From 4e79a64ab57b4370024c8058054fe1c5b197aca0 Mon Sep 17 00:00:00 2001 From: Nik Awtrey <46797896+nawtrey@users.noreply.github.com> Date: Fri, 9 Aug 2024 16:23:20 -0700 Subject: [PATCH] MAINT: Fix docstrings to follow NumPy formatting (#102) * MAINT: Fix docstrings to follow NumPy formatting * Fixes all function docstrings to consistently use NumPy RST syntax when referring to variables, giving examples, etc. * Misc fixes to docstrings including removal of returns/parameters that are no longer available --- kda/calculations.py | 226 ++++++++++++++++++++++++-------------------- kda/core.py | 12 +-- kda/diagrams.py | 120 +++++++++++------------ kda/exceptions.py | 2 +- kda/expressions.py | 19 ++-- kda/graph_utils.py | 86 +++++++++-------- kda/ode.py | 35 +++---- kda/plotting.py | 212 +++++++++++++++++++++-------------------- kda/svd.py | 35 ++++--- 9 files changed, 394 insertions(+), 353 deletions(-) diff --git a/kda/calculations.py b/kda/calculations.py index a6d79e9..a5261c9 100644 --- a/kda/calculations.py +++ b/kda/calculations.py @@ -35,14 +35,14 @@ def _get_ordered_cycle(G, input_cycle): """ Takes in arbitrary list of nodes and returns list of nodes in correct order. - Can be used in conjunction with `diagrams._construct_cycle_edges` to + Can be used in conjunction with ``diagrams._construct_cycle_edges`` to generate list of edge tuples for an arbitrary input cycle. Assumes input cycle only exists once in the input diagram G. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram input_cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter. @@ -107,19 +107,20 @@ def calc_sigma(G, dirpar_edges, key="name", output_strings=True): Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram dirpar_edges : list - List of all directional diagrams for the input diagram G. + List of all directional diagrams for the input diagram ``G``. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the normalization factor - using numbers. If True, this will assume the input - 'key' will return strings of variable names to join into the + is ``False``, which tells the function to calculate the normalization + factor using numbers. If ``True``, this will assume the input + ``'key'`` will return strings of variable names to join into the analytic cycle flux function. Returns @@ -128,7 +129,7 @@ def calc_sigma(G, dirpar_edges, key="name", output_strings=True): Normalization factor for state probabilities. sigma_str : str Sum of rate products of all directional diagrams for input - diagram G, in string form. + diagram ``G``, in string form. Notes ----- @@ -196,29 +197,31 @@ def calc_sigma(G, dirpar_edges, key="name", output_strings=True): def calc_sigma_K(G, cycle, flux_diags, key="name", output_strings=True): r""" Generates the expression for the path-based componenet of the - sum of flux diagrams for some `cycle` in kinetic diagram `G`. + sum of flux diagrams for some ``cycle`` in kinetic diagram ``G``. The sum of flux diagrams is used in calculating net cycle fluxes :footcite:`hill_free_1989`. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter but should not contain all nodes. flux_diags : list List of relevant directional flux diagrams for input cycle. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. + Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the sum of all - directional flux diagrams using numbers. If True, this will assume the - input 'key' will return strings of variable names to join into the - analytic function. + is ``False``, which tells the function to calculate the sum of all + directional flux diagrams using numbers. If ``True``, this will assume + the input ``'key'`` will return strings of variable names to join into + the analytic function. Returns ------- @@ -300,30 +303,33 @@ def calc_sigma_K(G, cycle, flux_diags, key="name", output_strings=True): def calc_pi_difference(G, cycle, order, key="name", output_strings=True): r""" Generates the expression for the cycle-based componenet of the - sum of flux diagrams for some `cycle` in kinetic diagram `G`. + sum of flux diagrams for some ``cycle`` in kinetic diagram ``G``. The sum of flux diagrams is used in calculating net cycle fluxes :footcite:`hill_free_1989`. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter unless your cycle contains all nodes. order : list of int - List of integers of length 2, where the integers must be nodes in the - input cycle. This pair of nodes is used to determine which direction is - CCW. + List of integers of length 2 (e.g. ``[0, 1]``), where the integers are + nodes in ``cycle``. The pair of nodes should be ordered such that + a counter-clockwise path is followed. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. + Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the difference using - numbers. If True, this will assume the input 'key' will return strings - of variable names to join into the analytic function. + is ``False``, which tells the function to calculate the difference + using numbers. If ``True``, this will assume the input ``'key'`` + will return strings of variable names to join into the analytic + function. Returns ------- @@ -390,38 +396,40 @@ def calc_pi_difference(G, cycle, order, key="name", output_strings=True): def calc_thermo_force(G, cycle, order, key="name", output_strings=True): r""" Generates the expression for the thermodynamic driving force - for some `cycle` in the kinetic diagram `G`. + for some ``cycle`` in the kinetic diagram ``G``. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter unless your cycle contains all nodes. order : list of int - List of integers of length 2, where the integers must be nodes in the - input cycle. This pair of nodes is used to determine which direction is - CCW. + List of integers of length 2 (e.g. ``[0, 1]``), where the integers are + nodes in ``cycle``. The pair of nodes should be ordered such that + a counter-clockwise path is followed. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. + Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the thermodynamic force - using numbers. If True, this will assume the input - 'key' will return strings of variable names to join into the + is ``False``, which tells the function to calculate the thermodynamic + force using numbers. If ``True``, this will assume the input + ``'key'`` will return strings of variable names to join into the analytic function. Returns ------- thermo_force : float The calculated thermodynamic force for the input cycle. This value is - unitless and should be multiplied by 'kT'. - parsed_thermo_force_str : SymPy function - The thermodynamic force equation in SymPy function form. Should be - multiplied by 'kT' to get actual thermodynamic force. + unitless and should be multiplied by ``kT``. + parsed_thermo_force_str : ``SymPy`` expression + Symbolic thermodynamic force expression. Should be + multiplied by ``kT`` to get actual thermodynamic force. Notes ----- @@ -485,25 +493,27 @@ def calc_state_probs(G, key="name", output_strings=True): Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the state - probabilities using numbers. If True, this will assume the input - 'key' will return strings of variable names to join into the + is ``False``, which tells the function to calculate the state + probabilities using numbers. If ``True``, this will assume the input + ``'key'`` will return strings of variable names to join into the analytic state multplicity and normalization function. Returns ------- - state_probs : NumPy array - Array of state probabilities for N states, [p1, p2, p3, ..., pN]. - state_probs_sympy : SymPy object - List of analytic SymPy state probability functions. + state_probs : ndarray + Array of state probabilities for ``N`` states + of the form ``[p1, p2, p3, ..., pN]``. + state_probs_sympy : ``SymPy`` expression + List of symbolic state probability expressions. Notes ----- @@ -539,31 +549,38 @@ def calc_state_probs(G, key="name", output_strings=True): def calc_net_cycle_flux(G, cycle, order, key="name", output_strings=True): r"""Generates the expression for the net cycle flux for - some `cycle` in kinetic diagram `G`. + some ``cycle`` in kinetic diagram ``G``. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter. + order : list of int + List of integers of length 2 (e.g. ``[0, 1]``), where the integers are + nodes in ``cycle``. The pair of nodes should be ordered such that + a counter-clockwise path is followed. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. + Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the cycle flux using - numbers. If True, this will assume the input 'key' will return strings - of variable names to join into the analytic cycle flux function. + is ``False``, which tells the function to calculate the cycle flux + using numbers. If ``True``, this will assume the input ``'key'`` + will return strings of variable names to join into the analytic + cycle flux function. Returns ------- net_cycle_flux : float Net cycle flux for input cycle. - net_cycle_flux_func : SymPy object - Analytic net cycle flux SymPy function. + net_cycle_flux_func : ``SymPy`` expression + Symbolic net cycle flux expression. Notes ----- @@ -613,30 +630,29 @@ def calc_state_probs_from_diags(G, dirpar_edges, key="name", output_strings=True Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram dirpar_edges : array Array of all directional diagram edges (made from 2-tuples). key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the state - probabilities using numbers. If True, this will assume the input - 'key' will return strings of variable names to join into the + is ``False``, which tells the function to calculate the state + probabilities using numbers. If ``True``, this will assume the input + ``'key'`` will return strings of variable names to join into the analytic state multplicity and normalization functions. Returns ------- - state_probabilities : NumPy array - Array of state probabilities for N states, [p1, p2, p3, ..., pN]. - state_mults : list - List of analytic state multiplicity functions in string form. - norm : str - Analytic state multiplicity function normalization function in - string form. This is the sum of all multiplicty functions. + state_probabilities : ndarray + Array of state probabilities for ``N`` states of + the form ``[p1, p2, p3, ..., pN]``. + state_mults : list of str + List of algebraic state multiplicity expressions. """ # get the number of nodes/states @@ -694,35 +710,41 @@ def calc_state_probs_from_diags(G, dirpar_edges, key="name", output_strings=True def calc_net_cycle_flux_from_diags( G, dirpar_edges, cycle, order, key="name", output_strings=True ): - """Generates the expression for the net cycle flux for some `cycle` - in kinetic diagram `G`. If directional diagram edges are already + """Generates the expression for the net cycle flux for some ``cycle`` + in kinetic diagram ``G``. If directional diagram edges are already generated this offers better performance than :func:`calc_net_cycle_flux`. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram. - dirpar_edges : array + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram + dirpar_edges : ndarray Array of all directional diagram edges (made from 2-tuples). cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter. + order : list of int + List of integers of length 2 (e.g. ``[0, 1]``), where the integers are + nodes in ``cycle``. The pair of nodes should be ordered such that + a counter-clockwise path is followed. key : str - Definition of key in NetworkX diagram edges, used to call edge rate - values or names. This needs to match the key used for the rate - constants names or values in the input diagram G. + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"name"``. output_strings : bool (optional) Used to denote whether values or strings will be combined. Default - is False, which tells the function to calculate the cycle flux using - numbers. If True, this will assume the input 'key' will return strings - of variable names to join into the analytic cycle flux function. + is ``False``, which tells the function to calculate the cycle flux + using numbers. If ``True``, this will assume the input ``'key'`` + will return strings of variable names to join into the analytic + cycle flux function. Returns ------- net_cycle_flux : float Net cycle flux for input cycle. - net_cycle_flux_func : SymPy object - Analytic net cycle flux SymPy function. + net_cycle_flux_func : ``SymPy`` expression + Symbolic net cycle flux expression. """ flux_diags = diagrams.generate_flux_diagrams(G, cycle) diff --git a/kda/core.py b/kda/core.py index 5c14786..554823e 100644 --- a/kda/core.py +++ b/kda/core.py @@ -37,20 +37,20 @@ class KineticModel(object): All cycles in the kinetic diagram. This attribute becomes available after running the :meth:`~kda.core.KineticModel.build_cycles` method. - partial_diagrams : array of Networkx Graphs + partial_diagrams : ndarray of ``Networkx.Graph`` The set of partial diagrams (i.e. spanning trees) for the kinetic diagram. This attribute becomes available after running the :meth:`~kda.core.KineticModel.build_partial_diagrams` method. - directional_diagrams : array of Networkx MultiDiGraphs + directional_diagrams : ndarray of ``Networkx.MultiDiGraph`` The set of directional diagrams for the kinetic diagram. This attribute becomes available after running the :meth:`~kda.core.KineticModel.build_directional_diagrams` method. - flux_diagrams : list of lists of Networkx MultiDiGraphs + flux_diagrams : list of lists of ``Networkx.MultiDiGraph`` The set of flux diagrams for each cycle in the kinetic diagram. This attribute becomes available after running the :meth:`~kda.core.KineticModel.build_flux_diagrams` method. - probabilities : array of floats or list of SymPy expressions + probabilities : array of floats or list of ``SymPy`` expressions The steady-state probabilities for all states in the kinetic diagram. Probabilities are either an array of numeric values or the algebraic expressions. This attribute becomes available @@ -69,8 +69,8 @@ def __init__(self, K=None, G=None): ``kij`` is the edge weight (i.e. transition rate constant). For example, for a 2-state model with ``k12=3`` and ``k21=4``, ``K=[[0, 3], [4, 0]]``. Default is ``None``. - G : NetworkX MultiDiGraph (optional) - Input diagram. Default is ``None``. + G : ``NetworkX.MultiDiGraph`` (optional) + A kinetic diagram. Default is ``None``. Raises ====== diff --git a/kda/diagrams.py b/kda/diagrams.py index 611525e..622712a 100644 --- a/kda/diagrams.py +++ b/kda/diagrams.py @@ -34,12 +34,12 @@ def _find_unique_edges(G): """ - Creates list of unique edges for input diagram G. Effectively removes - duplicate edges such as '(1, 0)' from [(0, 1), (1, 0)]. + Creates list of unique edges for input diagram ``G``. Effectively removes + duplicate edges such as ``(1, 0)`` from ``[(0, 1), (1, 0)]``. Parameters ---------- - G : NetworkX MultiDiGraph + G : ``NetworkX.MultiDiGraph`` Input diagram """ # since non-directional graphs cannot contain forward/reverse edges, @@ -68,15 +68,15 @@ def _get_neighbor_dict(target, unique_edges): ---------- target : int Index of target state - unique_edges : array + unique_edges : ndarray Array of edges (made from 2-tuples) that are unique - to the diagram, (i.e. [[0, 1], [1, 2], ...]). + to the diagram, (e.g. ``[[0, 1], [1, 2], ...]``). Returns ------- Dictionary of directional connections, where node indices are mapped to a list of their respective - neighbor node indices (i.e. {0: [1, 5], 1: [2], ...}). + neighbor node indices (e.g. ``{0: [1, 5], 1: [2], ...}``). """ # get the indices for each edge pair that contains the target state adj_idx = np.nonzero(unique_edges == target)[0] @@ -120,12 +120,12 @@ def _get_flux_path_edges(target, unique_edges): Target state. unique_edges : array Array of edges (made from 2-tuples) that are unique to the - diagram (i.e. `(1, 2)` and `(2, 1)` are considered the same). + diagram (e.g. ``(1, 2)`` and ``(2, 1)`` are considered the same). Returns ------- path_edges : list - List of edge tuples (i.e. [(0, 1, 0), (1, 2, 0), ...]). + List of edge tuples (e.g. ``[(0, 1, 0), (1, 2, 0), ...]``). """ neighbors = _get_neighbor_dict(target, unique_edges) path_edges = [(nbr, tgt, 0) for tgt in neighbors for nbr in neighbors[tgt]] @@ -139,8 +139,8 @@ def _collect_sources(G): Parameters ---------- - G : NetworkX MultiDiGraph - Partial diagram. + G : ``NetworkX.Graph`` + A partial diagram Returns ------- @@ -164,15 +164,15 @@ def _get_directional_path_edges(G, target): Parameters ---------- - G : NetworkX MultiDiGraph - Partial diagram. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram target : int Target state. Returns ------- path_edges : list - List of edge tuples (i.e. [(0, 1, 0), (1, 2, 0), ...]). + List of edge tuples (e.g. ``[(0, 1, 0), (1, 2, 0), ...]``). """ sources = _collect_sources(G) @@ -223,16 +223,16 @@ def _find_unique_uncommon_edges(G, cycle_edges): Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle_edges : list of tuples List of edge tuples for a cycle of interest. Both forward and - reverse edges should be included (i.e. `(1, 0)` and `(0, 1)`). + reverse edges should be included (e.g. ``(1, 0)`` and ``(0, 1)``). Returns ------- edges : list of tuples - List of uncommon edges between G and "cycle_edges". + List of uncommon edges between ``G`` and ``cycle_edges``. Since these should be unique edges (no reverse edges), these are the unique uncommon edges between two diagrams (normal use case). """ @@ -277,10 +277,12 @@ def _flux_edge_conditions(edge_list, n_flux_edges): def _append_reverse_edges(edge_list): """ Returns a list that contains original edges and reverse edges. + Parameters ---------- edge_list : list of edge tuples List of unidirectional edges to have reverse edges appended to. + Returns ------- new_edge_list : list of edge tuples @@ -293,17 +295,18 @@ def _append_reverse_edges(edge_list): def _get_cofactor_matrix(K_laplace): """ - Helper function for `enumerate_partial_diagrams()`. Uses singular value - decomposition to get the cofactor matrix for the input Laplacian matrix. + Helper function for :meth:`~kda.diagrams.enumerate_partial_diagrams()`. + Uses singular value decomposition to get the cofactor matrix for + the input Laplacian matrix. Parameters ---------- - K_laplace : array - `NxN` Laplacian matrix, where 'N' is the number of nodes. + K_laplace : ndarray + ``NxN`` Laplacian matrix, where ``N`` is the number of nodes. Returns ------- - K_cof : array + K_cof : ndarray Cofactor matrix for the input Laplacian matrix. """ U, w, Vt = np.linalg.svd(K_laplace) @@ -319,12 +322,12 @@ def _get_cofactor_matrix(K_laplace): def enumerate_partial_diagrams(G): """ Quantifies the number of partial diagrams (undirected spanning - trees) that can be generated from an input kinetic diagram `G`. + trees) that can be generated from a kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram Returns ------- @@ -342,7 +345,7 @@ def enumerate_partial_diagrams(G): number of undirected spanning trees. A more sophistocated version of this function is available in - the `NetworkX` library :footcite:`hagberg_exploring_2008` + the ``NetworkX`` library :footcite:`hagberg_exploring_2008` (see `here `_). @@ -372,23 +375,24 @@ def enumerate_partial_diagrams(G): def generate_partial_diagrams(G, return_edges=False): """ Generates all partial diagrams (undirected spanning trees) - for kinetic diagram `G`. + for a kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram return_edges : bool - Binary used for determining whether to return NetworkX diagram objects - (primarily for plotting) or the edge tuples (generally for - calculations). + Binary used for determining whether to return ``NetworkX`` + diagram objects (primarily for plotting) or the edge + tuples (generally for calculations). Returns ------- - partials : array - Array of NetworkX MultiDiGraphs where each graph is a unique - partial diagram with no loops (return_edges=False), or a nested - array of unique edges for valid partial diagrams (return_edges=True). + partials : ndarray of ``NetworkX.Graph`` + Array of ``NetworkX.Graph`` where each graph is a unique + partial diagram with no loops (``return_edges=False``), or + a nested array of unique edges for valid partial diagrams + (``return_edges=True``). """ # calculate number of edges needed for each partial diagram n_edges = G.number_of_nodes() - 1 @@ -427,24 +431,22 @@ def generate_partial_diagrams(G, return_edges=False): def generate_directional_diagrams(G, return_edges=False): """ - Generates all directional diagrams for kinetic diagram `G`. + Generates all directional diagrams for a kinetic diagram. Parameters ---------- - partials : list - List of NetworkX MultiDiGraphs where each graph is a unique partial - diagram with no loops. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram return_edges : bool - Binary used for determining whether to return NetworkX diagram objects - (primarily for plotting) or the edge tuples (generally for - calculations). + Binary used for determining whether to return ``NetworkX`` graph + objects (primarily for plotting) or the edge tuples (generally + for calculations). Returns ------- - directional_partial_diagrams : list - List of all directional diagrams for a given set of partial - diagrams. - directional_partial_diagram_edges : array + directional_diagrams : ndarray of ``NetworkX.MultiDiGraph`` + Array of all directional diagrams for ``G``. + directional_diagram_edges : ndarray Array of edges (made from 2-tuples) for valid directional diagrams. """ @@ -481,22 +483,22 @@ def generate_directional_diagrams(G, return_edges=False): def generate_flux_diagrams(G, cycle): """ - Generates all flux diagrams for `cycle` in the kinetic diagram `G`. + Generates all flux diagrams for a specific cycle in the kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram cycle : list of int List of node indices for cycle of interest, index zero. Order of node indices does not matter. Returns ------- - flux_diagrams : list of NetworkX MultiDiGraph objects + flux_diagrams : list of ``NetworkX.MultiDiGraph`` List of flux diagrams. Diagrams contain the input cycle - where remaining edges follow path pointing to cycle. - Cycle nodes are labeled by attribute 'is_target'. + where remaining edges follow path pointing to ``cycle``. + Cycle nodes are labeled by attribute ``'is_target'``. """ if sorted(cycle) == sorted(G.nodes): print( @@ -541,18 +543,18 @@ def generate_flux_diagrams(G, cycle): def generate_all_flux_diagrams(G): """ - Generates all flux diagrams for the kinetic diagram `G`. + Generates all flux diagrams for a kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph Object - Input diagram + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram Returns ------- - all_flux_diagrams : list of lists of NetworkX MultiDiGraph objects - List of lists of flux diagrams, where each list is for a different cycle - in G. + all_flux_diagrams : list of lists of ``NetworkX.MultiDiGraph`` + List of lists of flux diagrams, where each list + is for a different cycle in ``G``. """ all_cycles = graph_utils.find_all_unique_cycles(G) n_nodes = G.number_of_nodes() diff --git a/kda/exceptions.py b/kda/exceptions.py index 3611558..3dbc088 100644 --- a/kda/exceptions.py +++ b/kda/exceptions.py @@ -6,7 +6,7 @@ """ Kinetic Diagram Analysis (kda) Exceptions ========================================================================= -This file contains a host of custom exception classes for kda.core. +This file contains a host of custom exception classes. """ diff --git a/kda/expressions.py b/kda/expressions.py index c777b44..eaeb473 100644 --- a/kda/expressions.py +++ b/kda/expressions.py @@ -6,8 +6,8 @@ """ Algebraic Expressions ========================================================================= -This file contains a host of functions aimed at creating SymPy/Python -functions from algebraic expressions in string form. +The :mod:`~kda.expressions` module contains code to convert KDA-generated +string expressions into SymPy symbolic expressions. .. autofunction:: construct_sympy_prob_funcs .. autofunction:: construct_sympy_net_cycle_flux_func @@ -27,16 +27,13 @@ def construct_sympy_prob_funcs(state_mult_funcs): Parameters ---------- state_mult_funcs : list of str - List of length 'N', where N is the number of states, that contains the - analytic multiplicity function for each state - norm_func : str - Sum of all state multiplicity functions, the normalization factor to - calculate the state probabilities + List of length ``N`` (``N`` is the number of states) which contains + the algebraic multiplicity expressions for each state. Returns ------- sympy_funcs : list - List of analytic state probability SymPy functions. + List of Sympy symbolic state probability expressions. """ # convert the state multiplicity strings into sympy expressions parsed_mult_funcs = [parse_expr(e) for e in state_mult_funcs] @@ -61,8 +58,8 @@ def construct_sympy_net_cycle_flux_func(pi_diff_str, sigma_K_str, sigma_str): Sum of rate products of directional flux diagram edges pointing to input cycle in string form. sigma_str : str - Sum of rate products of all directional diagrams for input - diagram G, in string form. + Sum of rate products of all directional diagrams for the kinetic + diagram, in string form. Returns ------- @@ -89,7 +86,7 @@ def construct_lambda_funcs(sympy_funcs, rate_names): List of SymPy functions. rate_names : list List of strings, where each element is the name of the variables for - the input probability functions, ["x12", "x21", "x23", ...]. + the input probability functions (e.g. ``["k12", "k21", "k23", ...]``). Returns ------- diff --git a/kda/graph_utils.py b/kda/graph_utils.py index ec57c28..8b9c82d 100644 --- a/kda/graph_utils.py +++ b/kda/graph_utils.py @@ -6,7 +6,7 @@ """ Graph Utilities ========================================================================= -This file contains a host of utility functions for NetworkX graphs. +This file contains a host of utility functions for ``NetworkX`` graphs. .. autofunction:: generate_edges .. autofunction:: find_all_unique_cycles @@ -31,14 +31,14 @@ def generate_K_string_matrix(N_states): Parameters ========== N_states : int - The number of states in a diagram used to create a `NxN` matrix of - strings. + The number of states in a diagram used to create a ``NxN`` + matrix of strings. Returns ======= - K_string : NumPy array - An `NxN` array of strings where `N` is the number of states in a - diagram and the diaganol values of the array are zeros. + K_string : ndarray + An ``NxN`` array of strings where ``N`` is the number of states + in a diagram and the diagonal values of the array are zeros. """ K_string = [] for i in range(N_states): @@ -51,25 +51,30 @@ def generate_K_string_matrix(N_states): def generate_edges(G, vals, names=None, val_key="val", name_key="name"): """ - Generate edges with attributes 'val' and 'name'. + Generate edges for an input kinetic diagram ``G``, where edges have + attributes ``"name"`` (for rate constant variable names, e.g. + ``"k12"``) and ``"val"`` (for the rate constant values, e.g. ``100``). Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram - vals : array - 'NxN' array where 'N' is the number of nodes in the diagram G. Contains - the values associated with the attribute names in 'names'. For example, - assuming k12 and k21 had already been assigned values, for a 2 state - diagram 'vals' = [[0, k12], [k21, 0]]. - names : array (optional) - 'NxN' array where 'N' is the number of nodes in the diagram G. Contains - the names of all of the attributes corresponding to the values in - 'vals' as strings, i.e. [[0, "k12"], ["k21", 0]]. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram + vals : ndarray + ``NxN`` array where ``N`` is the number of nodes in ``G``. Contains + the kinetic rate *values* for each transition in ``G``. For example, + assuming we have some values ``k12_val`` and ``k21_val``, for a + 2-state diagram ``vals = [[0, k12_val], [k21_val, 0]]``. + names : ndarray (optional) + ``NxN`` array where ``N`` is the number of nodes in ``G``. Contains + the kinetic rate *variable names* (as strings) for each transition + in ``G``. For example, for a 2-state diagram + ``names = [[0, "k12"], ["k21", 0]]``. val_key : str (optional) - Key used to retrieve variable values in 'vals'. Default is 'val'. + Attribute key used to retrieve kinetic rate *values* from the + edge data stored in ``G.edges``. The default is ``"val"``. name_key : str (optional) - Key used to retrieve variable names in 'names'. Default is 'name'. + Attribute key used to retrieve kinetic rate *variable names* from + the edge data stored in ``G.edges``. The default is ``"name"``. """ if names is None: names = generate_K_string_matrix(vals.shape[0]) @@ -90,20 +95,23 @@ def generate_edges(G, vals, names=None, val_key="val", name_key="name"): def retrieve_rate_matrix(G, key="val"): """ - Retrieves rate matrix from edge data stored in input diagram G. + Retrieves rate matrix from a kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph - Input diagram - val : str (optional) - Key used to retrieve values from edges. Default is 'val'. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram + key : str + Attribute key used to retrieve edge data from ``G.edges``. The default + ``NetworkX`` edge key is ``"weight"``, however the ``kda`` edge keys + are ``"name"`` (for rate constant names, e.g. ``"k12"``) and ``"val"`` + (for the rate constant values, e.g. ``100``). Default is ``"val"``. Returns ------- - rate_matrix : array - 'NxN' array where 'N' is the number of nodes/states in the diagram G. - Contains the values/rates for each edge. + rate_matrix : ndarray + ``NxN`` array where ``N`` is the number of nodes/states in the + diagram ``G``. Contains the values/rates for each edge. """ # get the number of states n_states = G.number_of_nodes() @@ -119,12 +127,12 @@ def retrieve_rate_matrix(G, key="val"): def find_all_unique_cycles(G): """ - Finds all unique cycles for an input diagram G. + Finds all unique cycles in a kinetic diagram. Parameters ---------- - G : NetworkX MultiDiGraph object - Diagram of interest. + G : ``NetworkX.MultiDiGraph`` + A kinetic diagram Returns ------- @@ -144,9 +152,10 @@ def find_all_unique_cycles(G): def _is_ccw(cycle, start, end): """ Function for determining if a cycle is CCW based on a pair of nodes in the - cycle. For example, for a cycle [0, 1, 2], if moving from node 0 to 1 was - in the CCW direction, one would input 'start=0' and 'end=1'. Function - returns a value of 'True' if the input cycle is in the CCW direction. + cycle. For example, for ``cycle = [0, 1, 2]``, if moving from node ``0`` + to ``1`` was in the CCW direction, one would input ``start=0`` and + ``end=1``. Function returns a value of ``True`` if the input cycle is + in the CCW direction. Parameters ---------- @@ -168,7 +177,8 @@ def _is_ccw(cycle, start, end): def get_ccw_cycle(cycle, order): """ Function used for obtaining the CCW version of an input cycle, primarily - used for kda.calculate_pi_difference() and kda.calculate_thermo_force(). + used for :meth:`~kda.calculations.calculate_pi_difference()` and + :meth:`~kda.calculations.calculate_thermo_force()`. Parameters ---------- @@ -176,9 +186,9 @@ def get_ccw_cycle(cycle, order): List of node indices for cycle of interest, index zero. Order of node indices does not matter. order : list of int - List of integers of length 2, where the integers must be nodes in the - input cycle. This pair of nodes is used to determine which direction is - CCW. + List of integers of length 2 (e.g. ``[0, 1]``), where the integers are + nodes in ``cycle``. The pair of nodes should be ordered such that + a counter-clockwise path is followed. """ if not all(i in cycle for i in order): raise CycleError(f"Input node indices {order} do not exist in cycle {cycle}") diff --git a/kda/ode.py b/kda/ode.py index 7ce86e4..dfb993a 100644 --- a/kda/ode.py +++ b/kda/ode.py @@ -24,24 +24,24 @@ def ode_solver(P, K, t_max, method="LSODA", tol=1e-16, **options): Parameters ---------- P : array - 'Nx1' matrix of initial state probabilities. - K : array - 'NxN' matrix, where N is the number of states. Element i, j represents - the rate constant from state i to state j. Diagonal elements should be - zero, but does not have to be in input k - matrix. + ``Nx1`` matrix of initial state probabilities. + K : ndarray + Adjacency matrix for the kinetic diagram where each element + ``kij`` is the edge weight (i.e. transition rate constant). + For example, for a 2-state model with ``k12=3`` and ``k21=4``, + ``K=[[0, 3], [4, 0]]``. t_max : int - Length of time for integrator to run, in seconds. + Length of time for integrator to run in seconds. method : str - Integration method used in `scipy.integrate.solve_ivp()`. Default is - LSODA since it has automatic stiffness detection, and generally - requires much less run time to reach convergence than RK45. + Integration method used in ``scipy.integrate.solve_ivp()``. Default is + ``"LSODA"`` since it has automatic stiffness detection, and generally + requires much less run time to reach convergence than ``"RK45"``. tol : float (optional) Tolerance value used as convergence criteria. Once all dp/dt values for each state are less than the tolerance the integrator will terminate. - Default is 1e-16. + Default is ``1e-16``. options - Options passed to scipy.integrate.solve_ivp(). + Options passed to ``scipy.integrate.solve_ivp()``. Returns ------- @@ -49,12 +49,13 @@ def ode_solver(P, K, t_max, method="LSODA", tol=1e-16, **options): t : ndarray, shape (n_points,) Time points. y : ndarray, shape (n, n_points) - Values of the solution at t. + Values of the solution at ``t``. - Note: - For all parameters and returns, view the SciPy.integrate.solve_ivp() - documentation: "https://docs.scipy.org/doc/scipy/reference/generated/ - scipy.integrate.solve_ivp.html" + Notes + ----- + For all parameters and returns, view the ``SciPy.integrate.solve_ivp()`` + documentation (see `here `_). """ def convert_K(K): diff --git a/kda/plotting.py b/kda/plotting.py index 5a5845a..26f3f0d 100644 --- a/kda/plotting.py +++ b/kda/plotting.py @@ -6,9 +6,10 @@ """ Diagram Plotting ========================================================================= -This file contains a host of functions used for plotting various diagrams, such -as partial, directional, and flux diagrams. Also contains a function to plot -results from `ode.ode_solver`. +The :mod:`~kda.plotting` module contains code to plot partial diagrams +(undirected spanning trees), directional diagrams, and flux diagrams, as +well as cycles and :meth:`~kda.ode.ode_solver` results. + .. autofunction:: draw_diagrams .. autofunction:: draw_cycles @@ -31,7 +32,7 @@ def _get_node_labels(node_list): Parameters ---------- node_list : list - List of node indices (i.e. [0, 2, 3, 1]) indicating + List of node indices (e.g. ``[0, 2, 3, 1]``) indicating which node labels should be made. Returns @@ -54,17 +55,17 @@ def _get_node_colors(cbt, obj): ---------- cbt : bool 'Color by target' option that paints target nodes with a - coral red when true. Typically used for plotting partial + coral red when ``True``. Typically used for plotting directional and flux diagrams. obj: object - `NetworkX.Graph`, `NetworkX.MultiDiGraph`, or list of nodes to - return color values for. If a graph object is input, only nodes - with attribute `is_target=True` will be colored coral red. + ``nx.Graph``, ``nx.MultiDiGraph``, or list of nodes to return color + values for. If a graph object is input, only nodes + with attribute ``is_target=True`` will be colored coral red. Returns ------- node_colors: list - List of strings of color values (i.e. `["0.8", "0.8",...]`). + List of strings of color values (e.g. ``["0.8", "0.8",...]``). """ base_color = "0.8" @@ -93,15 +94,17 @@ def _get_axis_limits(pos, scale_factor=1.4): Parameters ---------- pos : dict - Dictionary where keys are the indexed states (0, 1, 2, ..., N) - and the values are the x, y coordinates for each node. + Dictionary where keys are the indexed states (e.g. 0, 1, + 2, ..., ``N``) and the values are the x, y coordinates for + each node. scale_factor: float (optional) - Factor used to scale the x/y axis limits. Default is `1.4`. + Factor used to scale the x/y axis limits. Default is ``1.4``. Returns ------- - Tuple of the form ``(xlims, ylims)``, where `xlims` and `ylims` are lists - containing the scaled minimum and maximum x and y values, respectively. + Tuple of the form ``(xlims, ylims)``, where ``xlims`` + and ``ylims`` are lists containing the scaled minimum + and maximum x and y values, respectively. """ x = np.zeros(len(pos)) @@ -129,14 +132,15 @@ def _get_panel_dimensions(n_diagrams, rows, cols=None): Number of rows, typically based on the square root of the number of diagrams to generate. cols : int (optional) - Number of columns. Default is `None`, which results in the number + Number of columns. Default is ``None``, which results in the number of rows being determined based on the number of diagrams input. Returns ------- - Tuple of the form ``(rows, cols, excess_plots)``, where `rows` and `cols` - are the number of rows and columns in the panel, respectively, and - `excess_plots` is the number of extra graphs available in the panel. + Tuple of the form ``(rows, cols, excess_plots)``, where + ``rows`` and ``cols`` are the number of rows and columns in the + panel, respectively, and ``excess_plots`` is the number of extra + graphs available in the panel. """ if rows is None: @@ -169,53 +173,54 @@ def _plot_single_diagram( Parameters ---------- - diagram : `NetworkX.MultiDiGraph` or `NetworkX.Graph()` + diagram : ``NetworkX.MultiDiGraph`` or ``NetworkX.Graph`` Diagram to be plotted. pos : dict (optional) - Dictionary where keys are the indexed states (0, 1, 2, ..., N) - and the values are the x, y coordinates for each node. If - not specified, ``NetworkX.spring_layout()`` is used. + Dictionary where keys are the indexed states (e.g. 0, 1, 2, + ..., ``N``) and the values are the x, y coordinates for each + node. If not specified, ``NetworkX.spring_layout()`` is used. node_labels: dict (optional) Dictionary where keys are the node index (index-zero) and the keys are the node index string (index-one). If not specified, labels will be created for all nodes in the input diagram. node_list : list (optional) - List of node indices (i.e. [0, 2, 3, 1]) indicating + List of node indices (e.g. ``[0, 2, 3, 1]``) indicating which nodes to plot. If not specified, all nodes in the input diagram will be plotted. node_colors: list (optional) - List of strings of color values (i.e. `["0.8", "0.8",...]`) + List of strings of color values (e.g. ``["0.8", "0.8",...]``) used to color the nodes. If not specified, node colors will - be determined using the `cbt` parameter. + be determined using the ``cbt`` parameter. edge_list: list (optional) - List of edge tuples (i.e. `[(1, 0), (1, 2), ...]`) to plot. If not + List of edge tuples (e.g. ``[(1, 0), (1, 2), ...]``) to plot. If not specified, all edges will be plotted. font_size : int (optional) - Sets the font size for the figure. Default is `12`. + Sets the font size for the figure. Default is ``12``. figsize: tuple (optional) - Tuple of the form ``(x, y)``, where `x` and `y` are the x and y-axis - figure dimensions in inches. Default is `(3, 3)`. + Tuple of the form ``(x, y)``, where ``x`` and ``y`` are the + x and y-axis figure dimensions in inches. Default is ``(3, 3)``. node_size: int (optional) - Size of nodes used for `NetworkX` diagram. Default is `300`. + Size of nodes used for ``NetworkX`` diagram. Default is ``300``. arrow_width: float (optional) - Arrow width used for `NetworkX` diagram. Default is `1.5`. + Arrow width used for ``NetworkX`` diagram. Default is ``1.5``. arrow_size: int (optional) - Arrow size used for `NetworkX` diagram. Default is `12`. + Arrow size used for ``NetworkX`` diagram. Default is ``12``. arrow_style: str (optional) - Style of arrows used for `NetworkX` diagram. Default is "->". + Style of arrows used for ``NetworkX`` diagram. Default is ``"->"``. connection_style: str (optional) - Style of arrow connections for `NetworkX` diagram. Default is "arc3". - ax: `matplotlib` axis object (optional) + Style of arrow connections for ``NetworkX`` diagram. + Default is ``"arc3"``. + ax: ``matplotlib`` axis object (optional) Axis to place diagrams on. If not specified, a new figure - and axis will be created. Default is `None`. + and axis will be created. Default is ``None``. cbt : bool (optional) 'Color by target' option that paints target nodes with a coral red. Typically used for plotting directional and flux diagrams. - Default is `False`. + Default is ``False``. Returns ------- - fig: `matplotlib.pyplot.figure` object + fig: ``matplotlib.pyplot.figure`` object The plotted diagram. """ @@ -287,34 +292,34 @@ def _plot_panel( Parameters ---------- - diagrams : list of cycles or NetworkX graph objects + diagrams : list of cycles or ``NetworkX`` graph objects List of diagrams or single diagram to be plotted. rows : int (optional) - Number of rows. Default is `None`, which results in the number + Number of rows. Default is ``None``, which results in the number of rows being determined based on the number of diagrams input. cols : int (optional) - Number of columns. Default is `None`, which results in the number + Number of columns. Default is ``None``, which results in the number of columns being determined based on the number of diagrams input. pos : dict (optional) - Dictionary where keys are the indexed states (0, 1, 2, ..., N) - and the values are the x, y coordinates for each node. If - not specified, ``NetworkX.spring_layout()`` is used. + Dictionary where keys are the indexed states (e.g. 0, 1, 2, + ..., ``N``) and the values are the x, y coordinates for each + node. If not specified, ``NetworkX.spring_layout()`` is used. panel_scale : float (optional) - Parameter used to scale figure if `panel=True`. Linearly - scales figure height and width. Default is `2`. + Parameter used to scale figure if ``panel=True``. Linearly + scales figure height and width. Default is ``2``. font_size : int (optional) - Sets the font size for the figure. Default is `12`. + Sets the font size for the figure. Default is ``12``. cbt : bool (optional) 'Color by target' option that paints target nodes with a - coral red. Typically used for plotting partial and flux - diagrams. Default is `False`. + coral red. Typically used for plotting directional and flux + diagrams. Default is ``False``. curved_arrows: bool (optional) Switches on arrows with a slight curvature to separate double arrows - for directional diagrams. Default is `False`. + for directional diagrams. Default is ``False``. Returns ------- - fig: `matplotlib.pyplot.figure` object + fig: ``matplotlib.pyplot.figure`` object A panel of figures, where each figure is a plotted diagram or cycle. Notes @@ -376,47 +381,45 @@ def draw_diagrams( Parameters ---------- - diagrams : list of cycles or NetworkX graph objects + diagrams : list of cycles or ``NetworkX`` graph objects List of diagrams or single diagram to be plotted. pos : dict (optional) - Dictionary where keys are the indexed states (0, 1, 2, ..., N) - and the values are the x, y coordinates for each node. If - not specified, ``NetworkX.spring_layout()`` is used. + Dictionary where keys are the indexed states (e.g. 0, 1, 2, + ..., ``N``) and the values are the x, y coordinates for each + node. If not specified, ``NetworkX.spring_layout()`` is used. panel : bool (optional) - Tells the function to output diagrams as an 'NxM' matrix of subplots, - where 'N' and 'M' are the number of rows and columns, respectively. - True will output a panel figure, False will output each figure - individually. Default is `False`. + Tells the function to output diagrams as an ``NxM`` matrix of subplots, + where ``N`` and ``M`` are the number of rows and columns, respectively. + ``True`` will output a panel figure, ``False`` will output each figure + individually. Default is ``False``. panel_scale : float (optional) - Parameter used to scale figure if `panel=True`. Linearly - scales figure height and width. Default is `2`. + Parameter used to scale figure if ``panel=True``. Linearly + scales figure height and width. Default is ``2``. font_size : int (optional) - Sets the font size for the figure. Default is `12`. + Sets the font size for the figure. Default is ``12``. cbt : bool (optional) 'Color by target' option that paints target nodes with a - coral red. Typically used for plotting directional and - flux diagrams. Default is `False`. + coral red. Typically used for plotting directional and flux + diagrams. Default is ``False``. rows : int (optional) - Number of rows to output if `panel=True`. Default is `None`, which - results in the number of rows being determined based on the number of - diagrams input. + Number of rows. Default is ``None``, which results in the number + of rows being determined based on the number of diagrams input. cols : int (optional) - Number of columns to output if `panel=True`. Default is `None`, which - results in the number of columns being determined based on the number of - diagrams input. + Number of columns. Default is ``None``, which results in the number + of columns being determined based on the number of diagrams input. path : str (optional) String of save path for figure. If a path is specified the figure(s) - will be saved at the specified location. Default is `None`. + will be saved at the specified location. Default is ``None``. label : str (optional) - Figure label used to create unique filename if `path` is - input. Includes `.png` file extension. Default is `None`. + Figure label used to create unique filename if ``path`` is + input. Includes ``.png`` file extension. Default is ``None``. curved_arrows: bool (optional) Switches on arrows with a slight curvature to separate double arrows - for directional diagrams. Default is `False`. + for directional diagrams. Default is ``False``. Notes ----- - When using `panel=True`, if number of diagrams is not a perfect square, + When using ``panel=True``, if number of diagrams is not a perfect square, extra plots will be generated as empty coordinate axes. """ @@ -508,42 +511,42 @@ def draw_cycles( Parameters ---------- - G : NetworkX MultiDiGraph + G : ``NetworkX.MultiDiGraph`` Input diagram used for plotting the cycles. cycles : list of lists of int List of cycles or individual cycle to be plotted, index zero. Order of node indices does not matter. pos : dict (optional) - Dictionary where keys are the indexed states (0, 1, 2, ..., N) - and the values are the x, y coordinates for each node. If - not specified, ``NetworkX.spring_layout()`` is used. + Dictionary where keys are the indexed states (e.g. 0, 1, 2, + ..., ``N``) and the values are the x, y coordinates for each + node. If not specified, ``NetworkX.spring_layout()`` is used. panel : bool (optional) - Tells the function to output diagrams as an 'NxM' matrix of subplots, - where 'N' and 'M' are the number of rows and columns, respectively. - True will output a panel figure, False will output each figure - individually. Default is `False`. + Tells the function to output diagrams as an ``NxM`` matrix of subplots, + where ``N`` and ``M`` are the number of rows and columns, respectively. + ``True`` will output a panel figure, ``False`` will output each figure + individually. Default is ``False``. panel_scale : float (optional) - Parameter used to scale figure if `panel=True`. Linearly scales figure - height and width. Default is `2`. + Parameter used to scale figure if ``panel=True``. Linearly + scales figure height and width. Default is ``2``. font_size : int (optional) - Sets the font size for the figure. Default is `12`. + Sets the font size for the figure. Default is ``12``. cbt : bool (optional) 'Color by target' option that paints target nodes with a - coral red. Typically used for plotting directional and - flux diagrams. Default is `False`. + coral red. Typically used for plotting directional and flux + diagrams. Default is ``False``. curved_arrows: bool (optional) Switches on arrows with a slight curvature to separate double arrows - for directional diagrams. Default is `False`. + for directional diagrams. Default is ``False``. path : str (optional) String of save path for figure. If a path is specified the figure(s) - will be saved at the specified location. Default is `None`. + will be saved at the specified location. Default is ``None``. label : str (optional) - Figure label used to create unique filename if `path` is - input. Includes `.png` file extension. Default is `None`. + Figure label used to create unique filename if ``path`` is + input. Includes ``.png`` file extension. Default is ``None``. Notes ----- - When using `panel=True`, if number of diagrams is not a perfect square, + When using ``panel=True``, if number of diagrams is not a perfect square, extra plots will be generated as empty coordinate axes. """ @@ -667,28 +670,29 @@ def draw_ode_results( results, figsize=(5, 4), legendloc="best", bbox_coords=None, path=None, label=None ): """ - Plots probability time series for all states generated by `ode.ode_solver`. + Plots probability time series for all states generated + by :meth:`~kda.ode.ode_solver`. Parameters ---------- results : ``Bunch`` object - Contains time information (results.t) and function information - at time t (results.y), as well as various other fields. + Contains time information (``results.t``) and function information + at time ``t`` (``results.y``), as well as various other fields. figsize: tuple (optional) - Tuple of the form `(x, y)`, where `x` and `y` are the x and y-axis - figure dimensions in inches. Default is `(5, 4)`. + Tuple of the form ``(x, y)``, where ``x`` and ``y`` are the x and + y-axis figure dimensions in inches. Default is ``(5, 4)``. legendloc : str (optional) String passed to determine where to place the legend for the figure. - Default is 'best'. + Default is ``"best"``. bbox_coords : tuple (optional) - Tuple of the form `(x, y)`, where `x` and `y` are the x and y-axis - coordinates for the legend. Default is `None`. + Tuple of the form ``(x, y)``, where ``x`` and ``y`` are the x + and y-axis coordinates for the legend. Default is ``None``. path : str (optional) String of save path for figure. If a path is specified the figure - will be saved at the specified location. Default is `None`. + will be saved at the specified location. Default is ``None``. label : str (optional) - Figure label used to create unique filename if `path` is - input. Includes `.png` file extension. Default is `None`. + Figure label used to create unique filename if ``path`` is + input. Includes ``.png`` file extension. Default is ``None``. """ N = int(len(results.y)) diff --git a/kda/svd.py b/kda/svd.py index f78b6df..934cf49 100644 --- a/kda/svd.py +++ b/kda/svd.py @@ -6,8 +6,8 @@ """ SVD and Matrix Solvers ========================================================================= -This file contains a host of functions aimed at the analysis of biochemical -kinetic diagrams via singular value decomposition. +The :mod:`~kda.svd` module contains code to calculate steady-state +probabilities using matrix and singular value decomposition methods. .. autofunction:: svd_solver .. autofunction:: matrix_solver @@ -25,18 +25,21 @@ def svd_solver(K, tol=1e-12): Parameters ---------- - K : array - 'NxN' matrix, where N is the number of states. Element i, j represents - the rate constant from state i to state j. Diagonal elements should be - zero, but does not have to be in input K matrix. + K : ndarray + Adjacency matrix for the kinetic diagram where each element + ``kij`` is the edge weight (i.e. transition rate constant). + For example, for a 2-state model with ``k12=3`` and ``k21=4``, + ``K=[[0, 3], [4, 0]]``. tol : float (optional) - Tolerance used for singular value determination. Values are considered - singular if they are less than the input tolerance. Default is 1e-12. + Tolerance used for singular value determination. Values are + considered singular if they are less than the input tolerance. + Default is ``1e-12``. Returns ------- state_probs : NumPy array - Array of state probabilities for N states, [p1, p2, p3, ..., pN]. + Array of state probabilities for ``N`` states of the + form ``[p1, p2, p3, ..., pN]``. """ # get number of states N = K.shape[0] @@ -101,15 +104,17 @@ def matrix_solver(K): Parameters ---------- - K : array - 'NxN' matrix, where N is the number of states. Element i, j represents - the rate constant from state i to state j. Diagonal elements should be - zero, but does not have to be in input K matrix. + K : ndarray + Adjacency matrix for the kinetic diagram where each element + ``kij`` is the edge weight (i.e. transition rate constant). + For example, for a 2-state model with ``k12=3`` and ``k21=4``, + ``K=[[0, 3], [4, 0]]``. Returns ------- - state_probs : NumPy array - Array of state probabilities for N states, [p1, p2, p3, ..., pN]. + state_probs : ndarray + Array of state probabilities for ``N`` states + of the form ``[p1, p2, p3, ..., pN]``. """ # get number of states N = K.shape[0]