Gap-filling (Python)#

raven-toolbox objects in raven_toolbox.gapfilling.

Functions#

Function

Summary

analyse_topology

BFS metabolite-producibility analysis.

connect_blocked_reactions

Add template reactions so blocked draft reactions can carry flux.

FastLPResult

Result of an LP-based gap-fill.

fill_gaps_fast_lp

LP-based gap-filling (fastGapFill / swiftGapFill).

fill_gaps_milp

Gap-fill to make the model objective (biomass) >= min_growth.

find_leak_metabolite

Find a metabolite that can be freely produced or consumed.

gap_report

Run a gap analysis on model.

GapFillResult

Result of a connectivity gap-fill.

GapReportResult

Outcome of a gap analysis.

LeakMetaboliteResult

Result of a leak search.

MILPGapFillResult

Outcome of a growth-floor MILP gap-fill.

MinToConnect

One entry of the minimal set of metabolites to connect.

print_gap_report

Print the result of gap_report and return it.

TopologicalAnalysisResult

Outcome of a topological gap analysis.

unique_templates

Copies of templates whose reaction ids are unique against model and each other.

Reference#

analyse_topology#

analyse_topology(model: cobra.Model, templates: cobra.Model | Iterable[cobra.Model], *, seeds: Iterable[str] | None=None, targets: Iterable[str] | None=None, verbose: bool=True)

BFS metabolite-producibility analysis.

Starting from seed metabolites (metabolites available in the medium), identifies which target metabolites in model cannot be produced by any sequence of draft reactions. For each unreachable target metabolite, lists the template reactions that produce it directly.

Parameters

model:

Draft model to analyse.

templates:

Universal database model(s) containing candidate reactions. Metabolite identifiers must match those in model.

seeds:

Metabolite IDs available from the medium. Default: the metabolites of every exchange reaction whose bounds let it supply them, as RAVEN's gapFillTopological picks them: a reaction with only substrates (met -->) and lower_bound < 0, or one with only products (--> met) and upper_bound > 0. An exchange reaction may have more than one metabolite. A UserWarning is issued when no such reaction exists.

targets:

Metabolite IDs to test for reachability. Default: every metabolite of the first objective reaction (in model order), substrates and products, as in RAVEN's gapFillTopological.

verbose:

Print a summary of the results.

Returns

TopologicalAnalysisResult :

Raises

ValueError

If targets is not given and the model has no objective reaction.

connect_blocked_reactions#

connect_blocked_reactions(model: cobra.Model, templates: cobra.Model | Iterable[cobra.Model], *, scores: dict[str, float] | None=None, penalty: float=1.0, allow_net_production: bool=False, threshold: float=1.0, min_flux: float=0.1)

Add template reactions so blocked draft reactions can carry flux.

Finds reactions that cannot carry a flux larger than threshold in model under its current bounds, then adds the minimum-penalty set of template reactions that lets the (irreversible) ones carry flux, and returns the filled model. Like RAVEN, only irreversible blocked reactions (lower_bound >= 0) are forced. A blocked reversible reaction is not forced and is listed in cannot_connect.

Unlike cobra.flux_analysis.gapfill, which adds reactions until the objective of the model is feasible and matches metabolites by id, this function connects blocked reactions and matches template metabolites to the draft by name[compartment].

The blocked reactions are determined under the bounds of the draft. A draft without exchange reactions for its nutrients has every reaction blocked that depends on those nutrients.

Parameters

model : cobra.Model

Draft model. It is not modified; the filled copy is in the result.

templates : cobra.Model or Iterable[cobra.Model]

One template model or several. Template metabolites are matched to the draft by name[compartment]. A template reaction whose id is already taken by the draft or by an earlier template is renamed <id>_<template id> (see raven_toolbox.gapfilling.templates.unique_templates).

scores : dict[str, float] or None

Maps a template reaction id to its score; a negative score is the penalty of adding that reaction, and penalty applies to a reaction without a score. A score that is not negative takes the penalty of the least negative score, or 0 when no score is negative. A score under the renamed id applies to that reaction; otherwise the score under the original id applies, so templates that share an id share that score unless the renamed id is given too. Default None, which gives every template reaction the penalty penalty.

penalty : float

Penalty of adding a template reaction that has no score. It must be greater than 0, otherwise ValueError is raised. Default 1.0.

allow_net_production : bool

Relaxes the steady-state balance from S @ v == 0 to S @ v >= 0 (metabolites may accumulate) in both flux checks and in the MILP. This can connect reactions that are blocked because a consumption pathway is missing. Default False.

threshold : float

Flux that a reaction must be able to exceed, in either direction, to count as unblocked, in the draft and, for a blocked reaction, with the templates added. Default 1.0.

min_flux : float

Lower bound set on each rescuable blocked reaction while the MILP is solved. Default 0.1.

Raises

ValueError

If penalty is not greater than 0.

RuntimeError

If the MILP over the reactions that pass the per-reaction rescue check is not optimal, for example when they cannot carry min_flux together or the solver stops for another reason. A blocked reaction that cannot carry flux even with all templates is listed in cannot_connect and does not raise.

FastLPResult#

Result of an LP-based gap-fill.

Parameters

added_reactions:

Template reaction IDs selected by the LP solver (union across all per-blocked-reaction LP solves).

newly_connected:

Draft reaction IDs that were blocked in the draft and can carry a flux above epsilon when all template reactions are added. The reactions in added_reactions alone are not checked for this flux.

cannot_connect:

Blocked draft reaction IDs that remain blocked even with the full template database added.

candidates_per_reaction:

Per blocked-reaction template reaction candidates (as returned by each individual LP solve).

model:

Draft model with added_reactions incorporated.

fill_gaps_fast_lp#

fill_gaps_fast_lp(model: cobra.Model, templates: cobra.Model | Iterable[cobra.Model], *, epsilon: float=0.0001, variant: Literal['fast', 'swift']='fast', verbose: bool=True, n_proc: int | None=None)

LP-based gap-filling (fastGapFill / swiftGapFill).

For each blocked draft reaction, runs a single LP that activates that reaction using a minimal ("fast") or maximal ("swift") set of template reactions. The union of all activated template reactions is returned.

Parameters

model:

Draft model to gap-fill.

templates:

Universal reaction database model(s).

epsilon:

Minimum flux threshold for a reaction to be considered active.

variant:

"fast": FASTCORE L1-norm LP (minimises the L1 norm of template fluxes). "swift": SWIFTCORE single LP (maximises the sum of the fluxes of the irreversible template reactions; results can differ between runs).

verbose:

Print progress messages.

n_proc:

Worker processes for solving each blocked reaction's LP in parallel. Defaults to cobra.Configuration().processes; 1 solves serially in this process. Each blocked reaction's LP depends only on the merged draft and template model (reverted after each solve via with working as m:) and never on the result of another blocked reaction. The LPs run in cobra.util.ProcessPool, which cobra's flux_variability_analysis also uses.

Returns

FastLPResult :

fill_gaps_milp#

fill_gaps_milp(model: cobra.Model, templates: cobra.Model | Iterable[cobra.Model], *, min_growth: float | None=None, big_m: float=1000.0, verbose: bool=True)

Gap-fill to make the model objective (biomass) >= min_growth.

Solves a global MILP that selects the fewest template reactions that make the model's objective (sum of coefficient times flux) reach min_growth. The draft reactions keep their bounds. A template reaction with a positive lower bound is only forced to carry that flux when it is selected.

Parameters

model:

Draft model to gap-fill. Must have a non-zero objective (biomass reaction).

templates:

Universal reaction database model(s).

min_growth:

Minimum required objective value. If None, runs FBA on the merged model and uses 10% of the maximum as the floor.

big_m:

Big-M constant for the coupling constraints of template reactions with an infinite bound. A finite bound is used as it is.

verbose:

Print progress messages.

Returns

MILPGapFillResult :

find_leak_metabolite#

find_leak_metabolite(model: cobra.Model, direction: Literal['produce', 'consume'], *, ignore_mets: Iterable[str] | None=None, is_names: bool=False, min_nr_fluxes: bool=False, allow_excretion: bool=True, ignore_int_bounds: bool=False)

Find a metabolite that can be freely produced or consumed.

Parameters

model:

Model to test. Never modified; the search runs on an internal copy. Its boundary reactions are used as they are: close every exchange, sink and demand reaction first (for r in model.boundary: r.bounds = (0, 0) on a copy), or an open uptake or excretion counts as a leak. Positive lower bounds (such as on a maintenance reaction) still apply and can make the search infeasible; the result then has status "infeasible", which does not show that the model is leak-free.

direction:

"produce" to look for freely excreted metabolites, or "consume" to look for freely consumed metabolites.

ignore_mets:

Metabolite ids (or names, with is_names=True) to exclude from the search. Unlike findLeakMetabolite.m, the argument accepts only ids or names, not a logical or index vector.

is_names:

If True, ignore_mets holds metabolite names (default: ids); every metabolite sharing one of those names, in any compartment, is excluded.

min_nr_fluxes:

Solve for the minimum number of active fluxes (raven_toolbox.analysis.get_min_nr_fluxes); the default is the minimum sum. Setting it true is slower, because the minimum number of fluxes is a MILP and the minimum sum is an LP. The MILP solution has the fewest active reactions; the LP solution can have more.

allow_excretion:

Allow every metabolite to freely accumulate. Only used when direction is "produce" (default True).

ignore_int_bounds:

Relax every non-boundary reaction to [-1000, 1000] before searching, to find leaks that are only possible once internal bounds (including reversibility) are ignored.

Returns

LeakMetaboliteResult :

gap_report#

gap_report(model: cobra.Model, *, template_models: cobra.Model | Iterable[cobra.Model] | None=None)

Run a gap analysis on model.

Parameters

model:

Model to analyse. The function does not modify it.

template_models:

Model(s) to gap-fill blocked reactions from (raven_toolbox.gapfilling.connect_blocked_reactions). If omitted, the gap-filling step is skipped and result.gap_fill is None.

Returns

GapReportResult :

Raises

ValueError

If model is infeasible under its own bounds, or once its boundary reactions are closed for can_produce_without_input and can_consume_without_output. The message lists the reactions with a forced flux (lower bound above zero or upper bound below zero), such as ATP maintenance with a positive lower bound. Setting the bounds of the forced reactions to zero before the call removes the cause.

GapFillResult#

Result of a connectivity gap-fill.

added_reactions are the template reaction ids added to model; newly_connected are draft reactions that were blocked but can now carry flux; cannot_connect are the blocked draft reactions that are not in newly_connected, including the reversible ones, which are not forced.

GapReportResult#

Outcome of a gap analysis.

Parameters

no_flux_reactions:

Reactions that cannot carry flux under the model's own constraints.

no_flux_reactions_relaxed:

Reactions that cannot carry flux even if every metabolite is allowed unconstrained net production.

subgraphs:

Metabolite ids in each isolated sub-network (two metabolites are connected if they share a reaction), largest first.

not_produced_metabolites:

Metabolites that cannot have net production.

needed_for_production:

Metabolite id to the ids of the not-produced metabolites that a free source of it makes producible, directly or transitively (see MinToConnect on when the list includes the metabolite itself).

min_to_connect:

Metabolites to give a free source, chosen greedily (most newly connected metabolites first). The selection stops when no remaining metabolite connects any remaining metabolite (a metabolite whose reach is only itself is still selected), so a not-produced metabolite that no selected metabolite connects is not covered.

can_produce_without_input:

Metabolites that can be produced with every boundary reaction closed.

can_consume_without_output:

Metabolites that can be consumed with every boundary reaction closed.

gap_fill:

Result of gap-filling against template_models, or None if no template models were given.

LeakMetaboliteResult#

Result of a leak search.

Parameters

fluxes:

Flux for every reaction in the original model (empty if no leak was found).

metabolites:

Ids of the metabolites implicated. More than one means that those metabolites can only be exchanged together.

status:

"optimal" if a leak was found, "infeasible" otherwise.

MILPGapFillResult#

Outcome of a growth-floor MILP gap-fill.

Parameters

added_reactions:

Template reaction IDs selected by the MILP.

model:

Draft model with added_reactions incorporated.

exit_status:

Solver status string (for example "optimal", "infeasible"), or "not_restored" when the solver reported a solution but the selected repairs do not bring the objective to min_growth in model. The selection is still returned for inspection.

MinToConnect#

One entry of the minimal set of metabolites to connect.

connects counts the not-produced metabolites that giving this one a free source makes producible, directly or transitively, and that no earlier entry of the set has connected. The count includes the metabolite itself only when the rest of the network can drain it once it has a source (for example, another reaction consumes it on net). A metabolite with no other reaction does not connect itself.

TopologicalAnalysisResult#

Outcome of a topological gap analysis.

Parameters

reachable_metabolites:

Metabolite IDs that can be produced from the seeds using the draft reactions.

blocked_metabolites:

Subset of targets that could not be reached from seeds.

candidate_reactions:

Blocked metabolite ID mapped to the IDs of the template reactions that produce that metabolite directly (matched by metabolite id).

pruning_fraction:

Fraction of template reactions (unique by id) that are not candidates for any blocked metabolite.

unique_templates#

unique_templates(model: cobra.Model, templates: list[cobra.Model], renames: dict[str, str] | None=None)

Copies of templates whose reaction ids are unique against model and each other.

A colliding id becomes <id>_<template id>, then <id>_<template id>_2, ... as in RAVEN's mergeModels. When renames is given, it receives new id -> original id for every renamed reaction.