### Install flowpaths from source (development) Source: https://github.com/algbio/flowpaths/blob/main/examples/README.md Install the package from the repository root for development, optionally with all dependencies. ```bash pip install -e . ``` ```bash pip install -e ".[dev]" ``` -------------------------------- ### Development setup commands Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Commands to fork, clone, set up a virtual environment, and install the package in editable mode with dev tools. Includes optional Gurobi solver installation and license configuration. ```bash git clone https://github.com/algbio/flowpaths.git cd flowpaths python3 -m venv .venv source .venv/bin/activate # zsh/bash pip install -e ".[dev]" # If you only want runtime deps, you can instead do: # pip install -e . pip install gurobipy # Obtain a (free for academic) license: https://www.gurobi.com/downloads/ # After placing your license file (e.g. ~/gurobi.lic) set this if not auto-detected: # export GRB_LICENSE_FILE=~/gurobi.lic # Quick check: # python -c "import gurobipy as gp; m = gp.Model(); print('Gurobi OK', gp.gurobi.version())" ``` -------------------------------- ### Run all examples at once Source: https://github.com/algbio/flowpaths/blob/main/examples/README.md Run all example files at once using the runall.sh script. ```bash bash examples/runall.sh ``` -------------------------------- ### Run example files from command line Source: https://github.com/algbio/flowpaths/blob/main/examples/README.md Run example files from the repository root using python or python3. ```bash python examples/min_flow_decomp.py python examples/min_path_error.py # ... or any other example file ``` ```bash python3 examples/min_flow_decomp.py ``` -------------------------------- ### Run example scripts Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Run any example directly from the examples/ directory. Some examples require an external solver like Gurobi, which is indicated via solver_options; otherwise the default HiGHS solver (highspy) is used. ```bash python examples/min_flow_decomp.py python examples/min_flow_decomp_cycles.py python examples/least_abs_errors.py ``` -------------------------------- ### Install documentation dependencies Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Install the required packages for building documentation with MkDocs, Material theme, and mkdocstrings into your active virtualenv. ```bash pip install \ mkdocs \ mkdocs-material \ mkdocs-material-extensions \ mkdocs-macros-plugin \ mkdocstrings-python \ mkdocs-autorefs \ pymdown-extensions \ mkdocs-get-deps \ black ``` -------------------------------- ### Minimum Flow Decomposition with MinFlowDecomp Source: https://github.com/algbio/flowpaths/blob/main/README.md Create a directed graph with flow attributes and solve a Minimum Flow Decomposition problem using the MinFlowDecomp solver. The example shows a simple DAG with two paths; the solution contains paths and their weights. ```python import flowpaths as fp import networkx as nx # Create a simple graph graph = nx.DiGraph() graph.add_edge("s", "a", flow=2) graph.add_edge("a", "t", flow=2) graph.add_edge("s", "b", flow=5) graph.add_edge("b", "t", flow=5) # ... # Create a Minimum Flow Decomposition solver mfd_solver = fp.MinFlowDecomp(graph, flow_attr="flow") mfd_solver.solve() # We solve it if mfd_solver.is_solved(): # We get the solution print(mfd_solver.get_solution()) # {'paths': [['s', 'b', 't'], ['s', 'a', 't']], 'weights': [5, 2]} ``` -------------------------------- ### Minimum Flow Decomposition with Cycles using MinFlowDecompCycles Source: https://github.com/algbio/flowpaths/blob/main/README.md Use the cyclic variant MinFlowDecompCycles for graphs with cycles, which returns walks rather than simple paths. The example shows a graph with a cycle between nodes 'a' and 'b'; the solution contains walks and their weights. ```python import flowpaths as fp import networkx as nx G = nx.DiGraph() G.add_edge("s", "a", flow=1) G.add_edge("a", "b", flow=2) # part of a cycle G.add_edge("b", "a", flow=2) # part of a cycle G.add_edge("a", "t", flow=1) mfd_solver = fp.MinFlowDecompCycles(G, flow_attr="flow") mfd_solver.solve() if mfd_solver.is_solved(): print(mfd_solver.get_solution()) # {'walks': [['s', 'a', 'b', 'a', 'b', 'a', 't']], 'weights': [1]} ``` -------------------------------- ### Serve documentation with live reload Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Start a local MkDocs server with live reload. Open the printed URL (usually http://127.0.0.1:8000/) to preview the docs. ```bash mkdocs serve ``` -------------------------------- ### Install flowpaths with pip Source: https://github.com/algbio/flowpaths/blob/main/README.md Install the flowpaths package from PyPI. Requires Python >= 3.8; dependencies (networkx, highspy, graphviz, numpy) are installed automatically. ```bash pip install flowpaths ``` -------------------------------- ### Create networkx DiGraph with edge flows Source: https://github.com/algbio/flowpaths/blob/main/docs/subpath-constraints.md Builds the directed acyclic graph used in the example. Each edge carries a 'flow' attribute that the solver will read. ```python import flowpaths as fp import networkx as nx graph = nx.DiGraph() graph.add_edge("s", "a", flow=6) graph.add_edge("s", "b", flow=7) graph.add_edge("a", "b", flow=2) graph.add_edge("a", "c", flow=4) graph.add_edge("b", "c", flow=9) graph.add_edge("c", "d", flow=6) graph.add_edge("c", "t", flow=7) graph.add_edge("d", "t", flow=6) ``` -------------------------------- ### Check Python version Source: https://github.com/algbio/flowpaths/blob/main/examples/README.md Check which Python version is used by the python command. ```bash python --version # or python3 --version ``` -------------------------------- ### Cyclic input graph example (Mermaid flowchart) Source: https://github.com/algbio/flowpaths/blob/main/docs/k-min-discordant-nodes-cycles.md Shows a cyclic directed graph with nodes s, a, b, t each having flow 5, and edges s->a, a->b, b->a, b->t. Used as an example input for the k-Minimum Discordant Nodes problem on general graphs. ```mermaid flowchart LR s((s:5)) a((a:5)) b((b:5)) t((t:5)) s --> a a --> b b --> a b --> t ``` -------------------------------- ### Sankey diagram file format examples Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Shows how the filename extension determines the static image format. The function always saves both HTML and static image. ```python # Saves both output.html and output.pdf fp.utils.draw(G, "output", paths=paths, weights=weights, draw_options={"style": "sankey"}) # Saves both flow.html and flow.png fp.utils.draw(G, "flow.png", paths=paths, weights=weights, draw_options={"style": "sankey"}) # Saves both diagram.html and diagram.svg fp.utils.draw(G, "diagram.svg", paths=paths, weights=weights, draw_options={"style": "sankey"}) ``` -------------------------------- ### Python example with additional starts and ends Source: https://github.com/algbio/flowpaths/blob/main/docs/additional-start-end-nodes.md Python code using fp.kMinPathError with additional_starts=['a'] and additional_ends=['d'] on a graph where the brown path has weight 10 instead of 20. The solution yields two paths from 'a' to 'd' with zero slack, illustrating that allowing additional starts and ends can produce unintended decompositions. ```python graph10 = nx.DiGraph() graph10.add_edge("s", "a", flow=6) graph10.add_edge("a", "b", flow=12) # graph10.add_edge("s", "b", flow=7) graph10.add_edge("a", "c", flow=4) graph10.add_edge("b", "c", flow=19) # graph10.add_edge("c", "d", flow=16) # graph10.add_edge("d", "t", flow=6) graph10.add_edge("c", "t", flow=7) mpe_model_10 = fp.kMinPathError( graph10, flow_attr="flow", k=4, weight_type=int, additional_starts=['a'], additional_ends=['d']) mpe_model_10.solve() if mpe_model_10.is_solved(): print(mpe_model_10.get_solution()) # {'paths': [ # ['s', 'b', 'c', 't'], # ['s', 'a', 'b', 'c', 'd', 't'], # ['a', 'c', 'd'], # ['a', 'b', 'c', 'd']], # 'weights': [7, 6, 4, 6], # 'slacks': [0, 0, 0, 0]} ``` -------------------------------- ### Get corrected graph and apply MinFlowDecomp Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-error-flow.md After solving the minimum error flow, retrieves the corrected graph and applies the minimum flow decomposition model (fp.MinFlowDecomp) on it. The solution prints paths and weights, e.g., {'paths': [['s', 'b', 'c', 't'], ['s', 'a', 'c', 'd', 't'], ['s', 'a', 'b', 'c', 'd', 't']], 'weights': [7.0, 4.0, 2.0]}. ```python if correction_model.is_solved(): corrected_graph = correction_model.get_corrected_graph() # This is equivalent to: corrected_graph = correction_model.get_solution()["graph"] mfd_model = fp.MinFlowDecomp(corrected_graph, flow_attr="flow") mfd_model.solve() if mfd_model.is_solved(): print(mfd_model.get_solution()) # {'paths': [ # ['s', 'b', 'c', 't'], # ['s', 'a', 'c', 'd', 't'], # ['s', 'a', 'b', 'c', 'd', 't']], # 'weights': [7.0, 4.0, 2.0]} ``` -------------------------------- ### Create and solve MinPathCoverCycles with networkx DiGraph Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-path-cover-cycles.md Builds a directed graph with cycles as a networkx DiGraph and solves the minimum path cover problem using fp.MinPathCoverCycles. The graph may have multiple sources or sinks; walks start in any source and end in any sink. ```python import flowpaths as fp import networkx as nx def test(): graph = nx.DiGraph() graph.add_edge("s", "a") graph.add_edge("a", "t") graph.add_edge("s", "b") graph.add_edge("b", "a") graph.add_edge("a", "h") graph.add_edge("h", "t") graph.add_edge("b", "c") graph.add_edge("c", "d") graph.add_edge("c", "h") graph.add_edge("d", "h") graph.add_edge("d", "e") graph.add_edge("e", "c") graph.add_edge("e", "f") graph.add_edge("f", "g") graph.add_edge("g", "e") mpc_model = fp.MinPathCoverCycles(G=graph) mpc_model.solve() ``` -------------------------------- ### Solve k-Minimum Discordant Nodes with flowpaths Source: https://github.com/algbio/flowpaths/blob/main/docs/k-min-discordant-nodes.md Constructs a directed graph with node flow attributes and solves the k-Minimum Discordant Nodes model using the flowpaths library. The example sets k=2 and discordance_tolerance=0.1, then prints the solution paths, weights, and discordant nodes if solved. ```python import flowpaths as fp import networkx as nx G = nx.DiGraph() G.add_node("s", flow=5) G.add_node("a", flow=10) G.add_node("b", flow=5) G.add_node("t", flow=5) G.add_edge("s", "a") G.add_edge("a", "b") G.add_edge("b", "t") model = fp.kMinDiscordantNodes( G=G, flow_attr="flow", k=2, discordance_tolerance=0.1, ) model.solve() if model.is_solved(): sol = model.get_solution() print(sol["paths"]) print(sol["weights"]) print(sol["discordant_nodes"]) ``` -------------------------------- ### stDiGraph.__init__ Source: https://github.com/algbio/flowpaths/blob/main/docs/stdigraph.md Constructor for the stDiGraph class, which wraps a directed graph with a global source and sink. It accepts an optional list of additional start nodes and additional end nodes. ```APIDOC ## stDiGraph.__init__ ### Description Constructor for the stDiGraph class, which wraps a directed graph with a global source and sink. It accepts an optional list of additional start nodes and additional end nodes. ### Method Constructor ### Signature ```python def __init__(self, base_graph: nx.DiGraph, additional_starts: Optional[list]=None, additional_ends: Optional[list]=None) ``` ### Parameters - **base_graph** (nx.DiGraph) - Required - The base directed graph to wrap. - **additional_starts** (Optional[list]) - Optional - List of additional start nodes. - **additional_ends** (Optional[list]) - Optional - List of additional end nodes. ### Returns - **stDiGraph** - An instance of the stDiGraph class. ``` -------------------------------- ### Repository structure layout Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Shows the top-level directory layout of the flowpaths repository, including the Python package, docs, examples, tests, and configuration files. ```text flowpaths/ # Python package source (imported as `flowpaths`) utils/ # Utilities (e.g., drawing, logging, graph helpers) __init__.py # Public API exports ... # Solvers and core modules docs/ # MkDocs site (Markdown pages, assets) examples/ # Small, runnable scripts demonstrating usage tests/ # Pytest suite (unit tests + tiny graph inputs) .github/ # GitHub workflows and repo meta (if present) mkdocs.yml # Docs site configuration and navigation pyproject.toml # Package metadata and runtime deps requirements.txt # Pinned runtime deps for local installs README.md, LICENSE # Project overview and license CONTRIBUTING.md # Contribution guide (this file) ``` -------------------------------- ### Solve Minimum Path Cover with MinPathCover Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-path-cover.md Creates a networkx DiGraph and solves the minimum path cover problem using flowpaths.MinPathCover. The graph may have multiple sources or sinks; solution paths start at any source and end at any sink. ```python import flowpaths as fp import networkx as nx graph = nx.DiGraph() graph.add_edge("s", "a") graph.add_edge("s", "b") graph.add_edge("a", "b") graph.add_edge("a", "c") graph.add_edge("b", "c") graph.add_edge("c", "d") graph.add_edge("c", "t") graph.add_edge("d", "t") mpc_model = fp.MinPathCover(graph) mpc_model.solve() ``` -------------------------------- ### Solve kMinPathError with default source/sink constraints Source: https://github.com/algbio/flowpaths/blob/main/docs/additional-start-end-nodes.md Solves the k-Minimum Path Error model on a graph with a single source 's' and sink 't', using k=4 paths. The solution has total slack 10 because paths must start at source and end at sink. ```python import flowpaths as fp import networkx as nx graph = nx.DiGraph() graph.add_edge("s", "a", flow=6) graph.add_edge("a", "b", flow=22) # graph.add_edge("s", "b", flow=7) graph.add_edge("a", "c", flow=4) graph.add_edge("b", "c", flow=29) # graph.add_edge("c", "d", flow=26) # graph.add_edge("d", "t", flow=6) graph.add_edge("c", "t", flow=7) mpe_model = fp.kMinPathError(graph, flow_attr="flow", k=4, weight_type=int) mpe_model.solve() if mpe_model.is_solved(): print(mpe_model.get_solution()) # {'paths': [ # ['s', 'a', 'b', 'c', 'd', 't'], # ['s', 'a', 'c', 'd', 't'], # ['s', 'b', 'c', 't'], # ['s', 'a', 'c', 'd', 't']], # 'weights': [12, 1, 7, 3], # 'slacks': [10, 0, 0, 0]} ``` -------------------------------- ### stDAG.__init__ Source: https://github.com/algbio/flowpaths/blob/main/docs/stdag.md Constructor for the stDAG class, which wraps a directed acyclic graph (DAG) with a unique global source and sink. It accepts an optional list of additional start and end nodes to augment the base graph. ```APIDOC ## [CONSTRUCTOR] stDAG.__init__ ### Description Initializes an augmented DAG with a global source and sink, wrapping the provided base graph. Optional additional start and end nodes can be specified to extend the graph's boundaries. ### Method Constructor ### Signature ```python stDAG(base_graph: nx.DiGraph, additional_starts: Optional[list]=None, additional_ends: Optional[list]=None) ``` ### Parameters - **base_graph** (nx.DiGraph) - Required - The directed acyclic graph to be wrapped. - **additional_starts** (Optional[list]) - Optional - List of additional start nodes. - **additional_ends** (Optional[list]) - Optional - List of additional end nodes. ``` -------------------------------- ### Solve kMinPathError with additional_starts and additional_ends Source: https://github.com/algbio/flowpaths/blob/main/docs/additional-start-end-nodes.md Solves the same k-Minimum Path Error model but allows paths to start at 'a' and end at 'd' via additional_starts and additional_ends. This recovers the path ['a','b','c','d'] with weight 20 and total slack 0. ```python mpe_model_2 = fp.kMinPathError( graph, flow_attr="flow", k=4, weight_type=int, additional_starts=['a'], additional_ends=['d']) mpe_model_2.solve() if mpe_model_2.is_solved(): print(mpe_model_2.get_solution()) # {'paths': [ # ['s', 'b', 'c', 't'], # ['s', 'a', 'b', 'c', 'd', 't'], # ['s', 'a', 'c', 'd', 't'], # ['a', 'b', 'c', 'd']], # 'weights': [7, 2, 4, 20], # 'slacks': [0, 0, 0, 0]} ``` -------------------------------- ### Build documentation once Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Perform a one-off static build of the documentation site. ```bash mkdocs build ``` -------------------------------- ### SolverWrapper.__init__ Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-wrapper.md Initializes a unified MILP/LP modelling convenience layer for HiGHS and Gurobi solvers. ```APIDOC ## SolverWrapper.__init__ ### Description Initializes a unified MILP/LP modelling convenience layer for HiGHS and Gurobi solvers. ### Method Constructor ### Signature ```python SolverWrapper(**kwargs) ``` ### Parameters - **kwargs** (dict) - Optional - Additional keyword arguments passed to the underlying solver. ``` -------------------------------- ### Set length coverage fraction with subpath_constraints_coverage_length Source: https://github.com/algbio/flowpaths/blob/main/docs/subpath-constraints.md Initialize the solver with `length_attr="length"` and `subpath_constraints_coverage_length=0.6` to require that 60% of the total edge length of each subpath constraint is covered by a solution path. For the constraint [('s','a'),('a','c'),('c','t')] with total length 36, at least 21.6 length units must be covered, so covering only edge ('s','a') (length 1) is insufficient. ```python mfd_model = fp.MinFlowDecomp( graph2, flow_attr="flow", length_attr="length", subpath_constraints=[[("s", "a"),("a", "c"),("c","t")]], subpath_constraints_coverage_length=0.6 ) ``` -------------------------------- ### Check solution and print paths and weights Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition.md Checks if the model was solved, then retrieves and prints the solution dictionary containing 'paths' and 'weights' keys. ```python if mfd_model.is_solved(): solution = mfd_model.get_solution() print(solution) # {'paths': [ # ['s', 'b', 'c', 't'], # ['s', 'a', 'c', 'd', 't'], # ['s', 'a', 'b', 'c', 'd', 't']], # 'weights': [7, 4, 2]} ``` -------------------------------- ### MinFlowDecomp.solve_time_elapsed Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition.md Returns the elapsed time since the start of the solve process. This property provides the time taken for the solving operation. ```APIDOC ## MinFlowDecomp.solve_time_elapsed ### Description Returns the elapsed time since the start of the solve process. This property provides the time taken for the solving operation. ### Method Property getter ### Signature ```python @property def MinFlowDecomp.solve_time_elapsed(self) ``` ### Parameters - **self** - The instance. ### Returns - **float** - The elapsed time in seconds. ``` -------------------------------- ### Check solution and retrieve walks and weights Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition-cycles.md Checks if the model was solved (it might not be due to time limits or other issues) and retrieves the solution dictionary. The solution contains keys 'walks' and 'weights', as shown in the commented output. ```python if mfd_model.is_solved(): solution = mfd_model.get_solution() print(solution) # {'walks': [ # ['s', 'b', 'c', 'd', 'e', 'f', 'g', 'e', 'f', 'g', 'e', 'c', 'h', 't'], # ['s', 'a', 't'], # ['s', 'b', 'a', 'h', 't']] # 'weights': [4, 3, 2]} ``` -------------------------------- ### HighsCustom.__init__ Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-wrapper.md Initializes a thin subclass of highspy.Highs that exposes a no-solve objective setter. ```APIDOC ## HighsCustom.__init__ ### Description Initializes a thin subclass of highspy.Highs that exposes a no-solve objective setter. ### Method Constructor ### Signature ```python HighsCustom() ``` ``` -------------------------------- ### Print solution walks from MinPathCoverCycles Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-path-cover-cycles.md After solving, retrieves the solution dictionary with key 'walks' containing the list of walks. The printed output shows four walks covering all edges. ```python if mpc_model.is_solved(): solution = mpc_model.get_solution() print(solution) # {'walks': [ # ['s', 'a', 't'], # ['s', 'b', 'a', 'h', 't'], # ['s', 'b', 'c', 'd', 'e', 'f', 'g', 'e', 'c', 'h', 't'], # ['s', 'b', 'c', 'd', 'h', 't']]} ``` -------------------------------- ### Configure console logging at INFO level Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Basic usage of fp.utils.configure_logging to enable console logging at INFO level. Use this to control verbosity and enable console/file logging. ```python import flowpaths as fp fp.utils.configure_logging( level=fp.utils.logging.INFO, log_to_console=True, ) ``` -------------------------------- ### Run all tests with pytest Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Runs the full test suite with verbose output, showing the 10 slowest tests and summary of failures/skips. ```bash pytest -vv -ra --durations=10 ``` -------------------------------- ### MILP solver options Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-options-optimizations.md Configure the Mixed Integer Linear Programming solver used by the AbstractPathModelDAG class. Pass a dictionary with keys such as threads, time_limit, presolve, log_to_console, external_solver, tolerance, and gurobi_params. ```APIDOC ## MILP solver options ### Description Configure the MILP solver by passing a dictionary `solver_options` to the model constructor. ### Parameters #### solver_options (dict) - `"threads"` (int) - Optional - Number of threads to use. Defaults to 4. - `"time_limit"` (int) - Optional - Time limit for solving in seconds. Defaults to Infinity. - `"presolve"` (str) - Optional - Presolve option. Defaults to `"choose"`. - `"log_to_console"` (str) - Optional - Log to console option. Defaults to `"false"`. - `"external_solver"` (str) - Optional - External solver to use. Defaults to `"highs"`. - `"tolerance"` (float) - Optional - Unified solver tolerance used for MIP gap, integrality tolerance, and feasibility tolerance. Defaults to `1e-9`. - `"gurobi_params"` (dict) - Optional - Extra Gurobi parameters passed to `gurobipy.Env.setParam(...)` when `"external_solver"` is `"gurobi"`. ### Request Example ``` python solver_options = { "threads": 8, "time_limit": 3600, } your_model = fp.kMinPathError( G=graph, k=5, flow_attr="flow", solver_options=solver_options, ) ``` ``` -------------------------------- ### Solve Minimum Flow Decomposition with MinFlowDecomp Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition.md Creates a MinFlowDecomp model with default settings, specifying the flow attribute, and calls solve() to solve it. The model is not solved until solve() is called. ```python mfd_model = fp.MinFlowDecomp(graph, flow_attr="flow") mfd_model.solve() ``` -------------------------------- ### Retrieve solution paths from MinPathCover Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-path-cover.md After solving, the solution is a dictionary with key 'paths' containing the list of source-to-sink paths. The printed output shows the expected structure. ```python if mpc_model.is_solved(): solution = mpc_model.get_solution() print(solution) # {'paths': [ # ['s', 'b', 'c', 't'], # ['s', 'a', 'b', 'c', 'd', 't'], # ['s', 'a', 'c', 't']]} ``` -------------------------------- ### Solve MinFlowDecomp with subpath_constraints Source: https://github.com/algbio/flowpaths/blob/main/docs/subpath-constraints.md Creates a Minimum Flow Decomposition solver with a single non-contiguous subpath constraint [("a","c"),("c","t")]. The constraint is passed as a list of edges, and the solver requires at least one path to contain that edge sequence. After solving, the solution is printed as paths and weights. ```python mfd_model = fp.MinFlowDecomp( graph, flow_attr="flow", subpath_constraints=[[("a", "c"),("c", "t")]]) mfd_model.solve() # We solve it if mfd_model.is_solved(): print(mfd_model.get_solution()) # {'paths': [['s', 'a', 'b', 'c', 't'], ['s', 'a', 'c', 't'], ['s', 'b', 'c', 't'], ['s', 'b', 'c', 'd', 't']], 'weights': [2.0, 4.0, 1.0, 6.0]} ``` -------------------------------- ### Draw graph with paths using fp.utils.draw Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Creates a PDF drawing of a graph with solution paths and weights. Requires a solved kMinPathError model. The draw_options control edge/path display. ```python import flowpaths as fp import networkx as nx # Create a simple graph graph = nx.DiGraph() graph.graph["id"] = "simple_graph" graph.add_edge("s", "a", flow=6) graph.add_edge("s", "b", flow=7) graph.add_edge("a", "b", flow=2) graph.add_edge("a", "c", flow=5) graph.add_edge("b", "c", flow=9) graph.add_edge("c", "d", flow=6) graph.add_edge("c", "t", flow=7) graph.add_edge("d", "t", flow=6) # Solve the minimum path error model mpe_model = fp.kMinPathError(graph, flow_attr="flow", k=3, weight_type=float) mpe_model.solve() # Draw the solution if mpe_model.is_solved(): solution = mpe_model.get_solution() fp.utils.draw( G=graph, filename="simple_graph.pdf", flow_attr="flow", paths=solution["paths"], weights=solution["weights"], draw_options={ "show_graph_edges": True, "show_edge_weights": False, "show_path_weights": False, "show_path_weight_on_first_edge": True, "pathwidth": 2, }) ``` -------------------------------- ### Configure optimization options with optimization_options dictionary Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-options-optimizations.md Pass a dictionary to the optimization_options parameter of fp.kMinPathError to control optimizations like safe paths and safe sequences. Defaults are optimize_with_safe_paths=True, optimize_with_flow_safe_paths=True (only for Minimum Flow Decomposition), optimize_with_safe_sequences=False, optimize_with_safe_zero_edges=False, optimize_with_symmetry_breaking=True. You cannot set both optimize_with_safe_paths and optimize_with_safe_sequences, and optimize_with_safe_zero_edges requires one of the safe path/sequence options. ```python optimization_options = { "optimize_with_safe_paths": False, "optimize_with_safe_sequences": True } your_model = fp.kMinPathError( G=graph, k=5, flow_attr="flow", optimization_options=optimization_options, ) ``` -------------------------------- ### Import libraries for Sankey diagram Source: https://github.com/algbio/flowpaths/blob/main/examples/sankey_demo.ipynb Imports networkx, flowpaths, and graphutils to create and visualize flow decompositions. ```python import networkx as nx import flowpaths as fp from flowpaths.utils import graphutils ``` -------------------------------- ### MinFlowDecomp constructor Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition.md Initializes a MinFlowDecomp instance to decompose a network flow on a directed acyclic graph into a minimum number of weighted paths. Accepts the graph, flow attribute, and various optional constraints and solver options. ```APIDOC ## MinFlowDecomp.__init__ ### Description Initializes a MinFlowDecomp instance to decompose a network flow on a directed acyclic graph into a minimum number of weighted paths. Accepts the graph, flow attribute, and various optional constraints and solver options. ### Method Constructor ### Signature ```python MinFlowDecomp(G: nx.DiGraph, flow_attr: str, flow_attr_origin: str='edge', weight_type: type=float, subpath_constraints: list=[], subpath_constraints_coverage: float=1.0, subpath_constraints_coverage_length: float=None, length_attr: str=None, elements_to_ignore: list=[], additional_starts: list=[], additional_ends: list=[], optimization_options: dict={}, solver_options: dict={}) ``` ### Parameters - **G** (nx.DiGraph) - Required - The directed acyclic graph representing the flow network. - **flow_attr** (str) - Required - The edge attribute name that stores the flow value. - **flow_attr_origin** (str) - Optional - Specifies whether the flow attribute is on edges (default 'edge') or nodes. - **weight_type** (type) - Optional - The numeric type used for weights (default float). - **subpath_constraints** (list) - Optional - List of subpath constraints to enforce. - **subpath_constraints_coverage** (float) - Optional - Coverage fraction for subpath constraints (default 1.0). - **subpath_constraints_coverage_length** (float) - Optional - Length-based coverage for subpath constraints. - **length_attr** (str) - Optional - Edge attribute name for length, used with coverage length. - **elements_to_ignore** (list) - Optional - List of elements to ignore during decomposition. - **additional_starts** (list) - Optional - Additional start nodes to consider. - **additional_ends** (list) - Optional - Additional end nodes to consider. - **optimization_options** (dict) - Optional - Options for the optimization model. - **solver_options** (dict) - Optional - Options for the solver. ### Returns - **MinFlowDecomp** - An instance of the class. ``` -------------------------------- ### Configure logging to file with append mode Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Extended usage of fp.utils.configure_logging to also log to a file in append mode. Default level is DEBUG; file_mode 'a' appends, 'w' overwrites. ```python fp.utils.configure_logging( level=fp.utils.logging.DEBUG, # default is DEBUG log_to_console=True, # show logs in terminal log_file="flowpaths.log", # write logs to this file file_mode="a", # "a" append (or "w" overwrite) ) ``` -------------------------------- ### Create and solve MinErrorFlow with default settings Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-error-flow.md Builds a directed graph with flow attributes and solves the minimum error flow problem using fp.MinErrorFlow. The graph has weights that do not satisfy flow conservation due to erroneous edges (shown in brown in the preceding diagram). After solving, the corrected graph can be retrieved. ```python import flowpaths as fp import networkx as nx graph = nx.DiGraph() graph.add_edge("s", "a", flow=7) graph.add_edge("s", "b", flow=7) graph.add_edge("a", "b", flow=2) graph.add_edge("a", "c", flow=4) graph.add_edge("b", "c", flow=9) graph.add_edge("c", "d", flow=7) graph.add_edge("c", "t", flow=7) graph.add_edge("d", "t", flow=6) # We create a the Minimum Error Flow solver with default settings correction_model = fp.MinErrorFlow(graph, flow_attr="flow") correction_model.solve() ``` -------------------------------- ### Configure MILP solver options with solver_options dictionary Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-options-optimizations.md Pass a dictionary to the solver_options parameter of fp.kMinPathError to set solver parameters like threads and time_limit. Defaults are threads=4, time_limit=Infinity, presolve="choose", log_to_console="false", external_solver="highs", tolerance=1e-9. If the time limit is exceeded, your_model.is_solved() returns False and get_model_status() may return "kTimeLimit". ```python solver_options = { "threads": 8, "time_limit": 3600, } your_model = fp.kMinPathError( G=graph, k=5, flow_attr="flow", solver_options=solver_options, ) ``` -------------------------------- ### Run a specific test file Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Runs all tests in the file tests/test_min_flow_decomp.py with verbose output. ```bash pytest -vv tests/test_min_flow_decomp.py ``` -------------------------------- ### Create graph with edge lengths for length-based coverage Source: https://github.com/algbio/flowpaths/blob/main/docs/subpath-constraints.md Build a directed graph with edge attributes `flow` and `length`. This graph is used with `length_attr="length"` to enable length-based coverage constraints. The edge lengths are used to compute the total length of a subpath constraint. ```python graph2 = nx.DiGraph() graph2.add_edge("s", "a", flow=6, length=1) # graph2.add_edge("s", "b", flow=7, length=2) graph2.add_edge("a", "b", flow=2, length=9) graph2.add_edge("a", "c", flow=4, length=20) # graph2.add_edge("b", "c", flow=9, length=9) graph2.add_edge("c", "d", flow=6, length=29) graph2.add_edge("c", "t", flow=7, length=15) # graph2.add_edge("d", "t", flow=6, length=1) ``` -------------------------------- ### Set edge coverage fraction with subpath_constraints_coverage Source: https://github.com/algbio/flowpaths/blob/main/docs/subpath-constraints.md Use this snippet to require that a fraction of the edges in a subpath constraint appear in a solution path. The parameter `subpath_constraints_coverage` is in [0,1]; here 0.75 means at least 75% of the constraint's edges must be covered. The constraint is given as a list of edge tuples. ```python mfd_model = fp.MinFlowDecomp( graph, flow_attr="flow", subpath_constraints=[[("s", "a"),("a", "c"),("c","t")]], subpath_constraints_coverage=0.75) ``` -------------------------------- ### Create simple DAG with flow values Source: https://github.com/algbio/flowpaths/blob/main/examples/sankey_demo.ipynb Builds a directed acyclic graph with flow attributes on edges, then prints node and edge counts. ```python # Create a simple DAG with flow values G = nx.DiGraph() G.add_edge('s', 'a', flow=10) G.add_edge('s', 'b', flow=5) G.add_edge('a', 'c', flow=6) G.add_edge('a', 'd', flow=4) G.add_edge('b', 'c', flow=3) G.add_edge('b', 'd', flow=2) G.add_edge('c', 't', flow=9) G.add_edge('d', 't', flow=6) print("Graph created with", G.number_of_nodes(), "nodes and", G.number_of_edges(), "edges") ``` ```text Output: Graph created with 6 nodes and 8 edges ``` -------------------------------- ### Create interactive Sankey diagram with fp.utils.draw Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Generates an interactive Sankey diagram for a DAG using plotly. Requires a solved MinFlowDecomp model. Saves HTML and static image. ```python import flowpaths as fp import networkx as nx # Create a sample DAG G = nx.DiGraph() G.add_edge('s', 'a', flow=10) G.add_edge('s', 'b', flow=5) G.add_edge('a', 'c', flow=6) G.add_edge('a', 'd', flow=4) G.add_edge('b', 'c', flow=3) G.add_edge('b', 'd', flow=2) G.add_edge('c', 't', flow=9) G.add_edge('d', 't', flow=6) # Compute minimum flow decomposition solver = fp.MinFlowDecomp(G, flow_attr='flow') solver.solve() solution = solver.get_solution() # Draw as interactive Sankey diagram fp.utils.draw( G=G, filename="flow_sankey.html", # saves as HTML (interactive) flow_attr='flow', paths=solution['paths'], weights=solution['weights'], draw_options={ "style": "sankey" } ) ``` -------------------------------- ### configure_logging Source: https://github.com/algbio/flowpaths/blob/main/docs/utils.md Configures logging for the flowpaths package, allowing control over verbosity, console/file logging, and file mode. ```APIDOC ## configure_logging ### Description Configures logging for the flowpaths package. Use it to control verbosity, enable console/file logging, and set file mode. ### Method Function call ### Signature ```python def configure_logging(level=logging.DEBUG, log_to_console=True, log_file=None, file_mode='w') ``` ### Parameters - `level` (int, optional) - Logging level (e.g., fp.utils.logging.DEBUG, fp.utils.logging.INFO). Default is fp.utils.logging.DEBUG. - `log_to_console` (bool, optional) - Whether to log to the console. Default is True. - `log_file` (str, optional) - File path to log to. If None, logging to a file is disabled. Default is None. If a file path is provided, the log will be written to that file. If the file already exists, it will be overwritten unless `file_mode` is set to "a". - `file_mode` (str, optional) - Mode for the log file. "a" (append) or "w" (overwrite). Default is "w". ### Example ```python import flowpaths as fp fp.utils.configure_logging( level=fp.utils.logging.INFO, log_to_console=True, ) ``` ```python fp.utils.configure_logging( level=fp.utils.logging.DEBUG, # default is DEBUG log_to_console=True, # show logs in terminal log_file="flowpaths.log", # write logs to this file file_mode="a", # "a" append (or "w" overwrite) ) ``` ``` -------------------------------- ### Create networkx DiGraph with flow attribute Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition-cycles.md Builds a directed graph with a 'flow' attribute on each edge, representing the flow value. This is the input graph for the Minimum Flow Decomposition solver. ```python import flowpaths as fp import networkx as nx graph = nx.DiGraph() graph.add_edge("s", "a", flow=3) graph.add_edge("a", "t", flow=3) graph.add_edge("s", "b", flow=6) graph.add_edge("b", "a", flow=2) graph.add_edge("a", "h", flow=2) graph.add_edge("h", "t", flow=6) graph.add_edge("b", "c", flow=4) graph.add_edge("c", "d", flow=4) graph.add_edge("c", "h", flow=4) graph.add_edge("d", "h", flow=0) graph.add_edge("d", "e", flow=4) graph.add_edge("e", "c", flow=4) graph.add_edge("e", "f", flow=8) graph.add_edge("f", "g", flow=8) graph.add_edge("g", "e", flow=8) ``` -------------------------------- ### Optimization options Source: https://github.com/algbio/flowpaths/blob/main/docs/solver-options-optimizations.md Configure optimizations that reduce the search space for solution paths while guaranteeing exact solutions. Pass a dictionary `optimization_options` to the model constructor. ```APIDOC ## Optimization options ### Description Configure optimizations by passing a dictionary `optimization_options` to the model constructor. ### Parameters #### optimization_options (dict) - `"optimize_with_safe_paths"` (bool) - Optional - Whether to optimize with safe paths. Defaults to `True`. - `"optimize_with_flow_safe_paths"` (bool) - Optional - Whether to optimize with flow-safe paths. This applies only to the Minimum Flow Decomposition problem and defaults to `True`. This overrides `"optimize_with_safe_paths"`. - `"optimize_with_safe_sequences"` (bool) - Optional - Whether to optimize with safe sequences. Defaults to `False`. At the moment, you cannot set both `"optimize_with_safe_paths"` and `"optimize_with_safe_sequences"`. - `"optimize_with_safe_zero_edges"` (bool) - Optional - Whether to optimize with safe zero edges. Defaults to `False`. You cannot set this without setting one of the above. - `"optimize_with_symmetry_breaking"` (bool) - Optional - Whether to break symmetries by adding relevant constraints to the model. Defaults to `True`. ### Request Example ``` python optimization_options = { "optimize_with_safe_paths": False, "optimize_with_safe_sequences": True } your_model = fp.kMinPathError( G=graph, k=5, flow_attr="flow", optimization_options=optimization_options, ) ``` ``` -------------------------------- ### Visualize simple graph as Sankey diagram Source: https://github.com/algbio/flowpaths/blob/main/examples/sankey_demo.ipynb Draws the Sankey diagram for the simple graph, saving it as example1_sankey.html. The diagram is interactive with hover, zoom, and pan. ```python # This will display the Sankey diagram inline and save it as HTML graphutils.draw( G, filename="example1_sankey", # Will save as example1_sankey.html flow_attr='flow', paths=paths, weights=weights, draw_options={ "style": "sankey" } ) ``` -------------------------------- ### Solve MinFlowDecompCycles model Source: https://github.com/algbio/flowpaths/blob/main/docs/minimum-flow-decomposition-cycles.md Creates a Minimum Flow Decomposition solver with default settings, specifying the edge flow attribute. Note that MinFlowDecompCycles only creates the model; you must call solve() to actually solve it. ```python mfd_model = fp.MinFlowDecompCycles(G=graph, flow_attr="flow") mfd_model.solve() ``` -------------------------------- ### Basic NumPathsOptimization for kFlowDecomp Source: https://github.com/algbio/flowpaths/blob/main/docs/numpathsoptimization.md Creates a NumPathsOptimization instance to automatically iterate over k values for a given model type (fp.kFlowDecomp). The stop_on_first_feasible=True flag stops at the first feasible k. Requires a graph and flow attribute. ```python mfd_model = fp.NumPathsOptimization( model_type = fp.kFlowDecomp, stop_on_first_feasible=True, G=graph, flow_attr="flow", ) ``` -------------------------------- ### Run tests with coverage Source: https://github.com/algbio/flowpaths/blob/main/CONTRIBUTING.md Runs the test suite with coverage measurement for the flowpaths package, showing missing lines in the terminal report. Requires pytest-cov, which is included in the dev extra. ```bash pytest --cov=flowpaths --cov-report=term-missing ```