Manipulation (Python)#

raven-toolbox objects in raven_toolbox.manipulation.

Functions#

Function

Summary

add_reactions_from_equations

Add reactions defined by equation strings, matching mets by ID or name.

add_reactions_from_model

Copy reactions from source_model into model.

add_transport_reactions

Add transport reactions from one compartment to one or more others.

change_gene_reaction_rules

Set or append gene-reaction rules on existing reactions.

change_reaction_equations

Replace the stoichiometry of existing reactions.

close_model

Return a copy with the exchange reactions closed, RAVEN closeModel-style.

close_model_in_place

Close the boundary reactions of model in place; return their ids.

constrain_reversible_reactions

Constrain reversible reactions that can only carry flux one way.

convert_to_irreversible

Split every reversible reaction into a forward + reverse pair.

copy_to_compartment

Copy a set of reactions into target_compartment. RAVEN's copyToComps.

expand_model

Split reactions with isozymes (OR in GPR) into one reaction per isozyme.

find_duplicate_reactions

Return groups of reactions that share identical stoichiometry.

gpr_to_dnf

Convert a GPR to disjunctive normal form (list of AND-clauses).

group_linear_reactions

Merge linear (single-producer, single-consumer) reaction chains.

merge_compartments

Merge every metabolite of model into one merged_id compartment.

merge_models

Merge models into a single new model.

remove_bad_reactions

Remove reactions that let model produce/consume metabolites from nothing.

remove_dead_end_reactions

Iteratively remove dead-end reactions and metabolites.

remove_duplicate_reactions

Remove all-but-one of each set of duplicate reactions.

remove_genes

Remove genes and handle reactions left unable to carry flux.

remove_metabolites

Remove metabolites, optionally matching by name across all compartments.

remove_no_flux_reactions

Remove reactions that cannot carry flux under the tested bounds (RAVEN deleteMinMax).

remove_zero_interval_reactions

Remove reactions locked at zero flux (lb == ub == 0), pruning orphans.

replace_metabolite

Replace metabolite with replacement, an existing model metabolite.

set_exchange_bounds

Set exchange-flux bounds for a chosen set of metabolites.

set_variance_bounds

Constrain reactions to a ±percent/2 band around measured values.

simplify_model

Reduce a model by the selected simplification modes (RAVEN simplifyModel).

Reference#

add_reactions_from_equations#

add_reactions_from_equations(model: cobra.Model, reactions: Sequence[Mapping], *, mets_by: str='id', compartment: str | None=None, allow_new_mets: bool=True, allow_new_genes: bool=True, new_met_prefix: str='m')

Add reactions defined by equation strings, matching mets by ID or name.

Parameters

model

Target cobra.Model, mutated in place.

reactions

Sequence of mappings, one per reaction. Recognised keys:

  • id (required) — reaction ID; must not already exist.

  • equation (required) — e.g. "atp_c + h2o_c <=> adp_c + pi_c". Use <=> for reversible, -->/->/=> for irreversible.

  • name — reaction name.

  • bounds — (lower, upper) tuple; overrides the arrow.

  • gene_reaction_rule — GPR string.

  • subsystem — subsystem name.

mets_by

How bare equation tokens (without [comp]) are matched: "id" (RAVEN eqnType 1) or "name" (eqnType 2). A name[comp] token (eqnType 3) is always matched by name + compartment.

compartment

Default compartment for new metabolites and for name-matched tokens without an explicit [comp].

allow_new_mets

If True (default), create metabolites not found. New metabolites get compartment (id mode) or an auto ID m1, m2, ... (name mode). If False, an unknown metabolite raises.

allow_new_genes

If True (default), genes in a GPR are auto-created by cobra. If False, a GPR referencing a gene not already in the model raises.

new_met_prefix

Prefix for auto-generated metabolite IDs in name mode (default "m").

Returns

list of cobra.Reaction

The reactions added, in input order.

add_reactions_from_model#

add_reactions_from_model(model: cobra.Model, source_model: cobra.Model, reactions: str | Iterable[str], *, genes: bool | str | Iterable[str]=False, note: str | None='Added via add_reactions_from_model()', confidence: int | None=None)

Copy reactions from source_model into model.

Parameters

model

Draft model to copy into (mutated in place).

source_model

Model to copy reactions from.

reactions

Reaction ID(s) in source_model. Reactions already present in model (by ID) are skipped.

genes

False (default): add reactions without GPRs. True: copy each reaction's GPR from the source. A string: use it as the GPR for every added reaction. A list: per-reaction GPRs (matching the reactions that are actually added). New genes are created automatically.

note

Stored in each added reaction's notes['note'] (set None to skip).

confidence

If given, stored in each added reaction's notes['confidence_score'].

Returns

list of cobra.Reaction

The reactions added, in input order.

add_transport_reactions#

add_transport_reactions(model: cobra.Model, from_compartment: str, to_compartments: str | Iterable[str], metabolite_names: str | Iterable[str] | None=None, *, reversible: bool=True, only_to_existing: bool=True, id_prefix: str='tr_')

Add transport reactions from one compartment to one or more others.

Parameters

from_compartment

Source compartment id.

to_compartments

Target compartment id(s).

metabolite_names

Names of metabolites to transport. Default: every metabolite in from_compartment.

reversible

If True (default), bounds span the cobra configuration default (reversible); otherwise lower bound 0.

only_to_existing

If True (default), only transport a metabolite into a target compartment where a same-named metabolite already exists. If False, create the missing target metabolite (copying name/formula/charge/ annotation from the source) before adding the transport.

id_prefix

Prefix for the sequential reaction IDs (tr_0001, ...).

Returns

list of cobra.Reaction

The transport reactions added, in creation order.

change_gene_reaction_rules#

change_gene_reaction_rules(model: cobra.Model, rules: Mapping[str, str], *, replace: bool=True)

Set or append gene-reaction rules on existing reactions.

cobra already does the heavy lifting on assignment to reaction.gene_reaction_rule: it auto-creates any new Gene objects and normalises the rule. So the value here is batching plus RAVEN's replace option to append rather than overwrite.

Parameters

model

Target cobra.Model, mutated in place.

rules

Mapping of reaction_id -> GPR string. Every ID must already exist.

replace

If True (default), overwrite the existing GPR. If False, append the new rule as an isozyme: (old) or (new) (just new if the reaction had no GPR).

Returns

list of cobra.Reaction

The reactions changed, in input order.

change_reaction_equations#

change_reaction_equations(model: cobra.Model, equations: Mapping[str, str], *, mets_by: str='id', compartment: str | None=None, allow_new_mets: bool=True, new_met_prefix: str='m')

Replace the stoichiometry of existing reactions.

Parameters

model

Target cobra.Model, mutated in place.

equations

Mapping of reaction_id -> equation string. Every ID must already exist in the model. Equation syntax is identical to raven_toolbox.manipulation.add.add_reactions_from_equations.

mets_by, compartment, allow_new_mets, new_met_prefix

Metabolite-matching options, as in add_reactions_from_equations.

Returns

list of cobra.Reaction

The reactions changed, in input order.

Notes

Bounds are not modified, matching RAVEN. Changing an equation from --> to <=> does not by itself make the reaction reversible; adjust the bounds separately.

close_model#

close_model(model: cobra.Model)

Return a copy with the exchange reactions closed, RAVEN closeModel-style.

RAVEN's closeModel adds a boundary metabolite to every reaction with metabolites on only one side — no substrates or no products, an exchange / sink / demand reaction — balancing it against a boundary metabolite so it can no longer carry flux. After it, a metabolic task's inputs and outputs are defined solely by the task constraints (as checkTasks assumes), not by leftover open exchanges.

This closes exactly that set of reactions, which for a single-metabolite reaction is the same set as cobra's own Reaction.boundary, but also includes a reaction that consumes or produces several metabolites at once without a balancing side.

Modifies a copy; the original is untouched.

close_model_in_place#

close_model_in_place(model: cobra.Model)

Close the boundary reactions of model in place; return their ids.

In-place variant of close_model for callers that already hold a working copy.

constrain_reversible_reactions#

constrain_reversible_reactions(model: cobra.Model, *, eps: float=1e-10)

Constrain reversible reactions that can only carry flux one way.

Runs FVA on each reversible reaction; if it can only carry forward flux its lower bound is set to 0, and if it can only carry reverse flux it is flipped to a forward reaction (stoichiometry, bounds, and objective negated). Returns the changed reaction IDs.

Matches RAVEN simplifyModel's constrainReversible: it classifies a bound as zero at |flux| < 1e-10 and runs its FVA (getAllowedBounds → solveLP) at FeasibilityTol = 1e-9. We set the same feasibility tolerance on the solver so the FVA min/max are trustworthy at that 1e-10 threshold (at Gurobi's looser 1e-6 default a reaction with tiny one-way flux is mis-classified, changing its reversibility and, in turn, how group_linear_reactions merges it).

convert_to_irreversible#

convert_to_irreversible(model: cobra.Model, rxns: list[str] | None=None)

Split every reversible reaction into a forward + reverse pair.

For each reaction with lb < 0, including exchange (boundary) reactions -- MATLAB's convertToIrrev does not special-case them, so neither does this:

  • The original reaction is kept as the forward direction. Its lower bound is clamped to 0.

  • A new reaction with the same ID plus a _REV suffix is added, representing the reverse direction. Its stoichiometry is the negation of the original, its bounds are (0, -original_lb), and it inherits the name (with " (reversible)" appended), the gene-protein rule, the subsystem, the annotations and the notes of the original. MATLAB's convertToIrrev copies the same per-reaction fields across (eccodes, rxnMiriams, subSystems, rxnNotes, ...); dropping them would, among other things, leave the reverse reaction without an EC code and so without a kcat downstream.

  • If the original reaction's objective coefficient is negative, it is moved onto the new reverse reaction (sign-flipped positive) and zeroed on the forward reaction, so a reversible reaction credited under the objective for reverse-direction flux still gets that credit after splitting. A non-negative coefficient is left on the forward reaction unchanged, and the reverse reaction's is left at its default (0) -- matching MATLAB's convertToIrrev.

Parameters

model

A cobra.Model, mutated in place.

rxns

Reaction IDs eligible for splitting. Reactions outside this set are left untouched even if reversible. Defaults to every reaction in the model, matching MATLAB's convertToIrrev default (its rxns name-value argument defaults to model.rxns).

Returns

list of str

Sorted IDs of newly added reverse reactions (the ones ending in _REV). The forward reactions retain their original IDs.

copy_to_compartment#

copy_to_compartment(model: cobra.Model, reactions: Iterable[str], target_compartment: str, *, target_compartment_name: str | None=None, delete_original: bool=False, id_suffix: str | None=None)

Copy a set of reactions into target_compartment. RAVEN's copyToComps.

Returns (model_copy, new_reaction_ids, new_metabolite_ids). Use cases:

  • Build a dual-localised pathway (e.g. duplicate glycolysis into a peroxisome).

  • Mirror a curated subsystem into an additional compartment as a draft to refine.

  • Set up the input for a flux comparison between alternate compartmentalisations.

Each copied reaction is given the id "<orig_id>_<id_suffix>" (default id_suffix=target_compartment); each metabolite it touches is mapped to (or created in) target_compartment with the same suffix convention. delete_original=True moves the reactions instead of copying.

expand_model#

expand_model(model: cobra.Model)

Split reactions with isozymes (OR in GPR) into one reaction per isozyme.

For each reaction whose GPR contains at least one OR, the reaction is removed and replaced by one copy per disjunctive clause. The new reactions get ID suffix _EXP_1, _EXP_2, etc. All other fields (stoichiometry, bounds, name, subsystem) are copied verbatim; only the GPR is simplified to the single AND-clause for that isozyme.

Reactions with no GPR, or with a GPR that has no OR, are left untouched.

Parameters

model

A cobra.Model, mutated in place.

Returns

list of str

Sorted IDs of newly added expanded reactions (those with _EXP_N suffixes). The original reactions that were split are no longer in the model.

find_duplicate_reactions#

find_duplicate_reactions(model: cobra.Model, *, ignore_direction: bool=True)

Return groups of reactions that share identical stoichiometry.

Detection-only counterpart to remove_duplicate_reactions. Bounds, objective coefficients, GPRs and annotations are ignored — only stoichiometry is compared, mirroring the legacy yeast-GEM findDuplicatedRxns and matching the typical curation use case (find reactions that could be merged).

Parameters

ignore_direction

When True (default), A → B and B → A are treated as duplicates (yeast-GEM's convention). Set False to require identical orientation.

Returns

A list of duplicate groups. Each group is itself a list with :

≥ 2 reactions sharing the same stoichiometry. Reactions that have :

no duplicate are omitted. :

gpr_to_dnf#

gpr_to_dnf(gpr: GPR)

Convert a GPR to disjunctive normal form (list of AND-clauses).

An empty GPR yields an empty list. A single clause (no OR anywhere) yields a list of length 1. OR-of-ANDs yields one sublist per disjunct, each containing the gene names ANDed together.

Handles distributivity: g1 and (g2 or g3) becomes [[g1, g2], [g1, g3]].

group_linear_reactions#

group_linear_reactions(model: cobra.Model, *, reserved: Iterable[str] | None=None)

Merge linear (single-producer, single-consumer) reaction chains.

Lossy: gene-reaction associations are discarded (RAVEN does the same), since merged reactions have no meaningful combined GPR. The model is first made irreversible, then any metabolite that is produced by exactly one reaction and consumed by exactly one reaction is eliminated by merging the two reactions. reserved reaction ids are never merged away. Mutates in place.

merge_compartments#

merge_compartments(model: cobra.Model, *, merged_id: str=_MERGED_COMPARTMENT, merged_name: str='system', base_metabolite: Callable[[cobra.Metabolite], str] | None=None, drop_single_metabolite_reactions: bool=True, deduplicate_reactions: bool=True)

Merge every metabolite of model into one merged_id compartment.

Returns (model_copy, deleted_single_met_reactions, deduplicated_reactions). The returned model is a deep copy of the input. Use cases:

  • Check whether the network can produce/consume a metabolite at all (compartment topology is often what makes a model look blocked).

  • Simplify a model for visualisation or an analysis that doesn't care about compartments.

  • As a pre-step for localisation when the user does want RAVEN's "start from scratch" workflow (call merge_compartments then raven_toolbox.localization.predict_localization or raven_toolbox.localization.assign_compartments with the full reaction list).

base_metabolite maps a metabolite to the compartment-agnostic key that decides which metabolites are the same species (so two compartment copies collapse into one). The default strips a trailing _<compartment> id suffix (glc__D_c and glc__D_e both → glc__D). Models that key the same species to a different id per compartment — e.g. yeast-GEM's s_#### ids — need base_metabolite=lambda m: m.name (or an annotation key) so the compartments actually unify; pass the same callable to raven_toolbox.localization.assign_compartments. The key only decides grouping — the merged metabolite keeps an existing id (the copy already in merged_id, or an arbitrary member adapted to merged_id when none is there yet), never one minted from the key. So a name-based key like "1-acyl-sn-glycerol 3-phosphate (16:0)" unifies the copies while the merged id stays the model's own, already solver/SBML-safe identifier — no character sanitising. (cobra rejects an id containing whitespace when a model is built or loaded, so the source ids are solver-safe to begin with; this transform only ever inherits them.)

Metabolites that share a key collapse into one entity in the merged compartment; their stoichiometric contributions are summed per reaction. Reactions that become trivial through the merge (e.g. A[c] → A[m] becomes A → A = nothing) are deleted by default (RAVEN's deleteRxnsWithOneMet). A reaction that already had a single metabolite before merging is an exchange (=> glucose) and is always kept — dropping those would silently remove the model's medium and its biomass reaction. Reactions that become identical after merging are deduplicated (one survives). The objective is carried over to the returned model.

merge_models#

merge_models(models: Iterable[cobra.Model], *, match_by: str='name', track_origin: bool=True)

Merge models into a single new model.

Parameters

models

The models to merge (two or more). A single model is returned as a copy.

match_by

How metabolites are unified across models: "name" (default) treats metabolites with the same name and compartment as identical (IDs ignored); "id" matches by metabolite ID.

track_origin

If True (default), record the source model's id in each reaction's, metabolite's, and gene's notes['origin'].

Returns

cobra.Model

A new merged model (id="MERGED"). Reactions are not de-duplicated — matching RAVEN, every reaction from every model is kept, with ID collisions renamed id_<sourceid>.

remove_bad_reactions#

remove_bad_reactions(model: cobra.Model, *, rxn_rules: int=1, ignore_mets: Iterable[str] | None=None, is_names: bool=False, balance_elements: Iterable[str]=_DEFAULT_BALANCE_ELEMENTS, ignore_int_bounds: bool=False, print_report: bool=False)

Remove reactions that let model produce/consume metabolites from nothing.

Modifies model in place.

Parameters

model:

Model to clean up. Should not allow uptake/excretion for the search to be meaningful — import it closed, or close it first (see raven_toolbox.manipulation.close_model).

rxn_rules:

Which reactions may be removed (default 1):

  • 1: only reactions that are elementally unbalanced.

  • 2: also reactions whose balance could not be determined (missing or unparseable metabolite formulas).

  • 3: any flux-carrying reaction in the leak solution.

ignore_mets:

Metabolite ids (or names, with is_names=True) to exclude from the leak search; forwarded to raven_toolbox.gapfilling.find_leak_metabolite.

is_names:

If True, ignore_mets holds metabolite names rather than ids.

balance_elements:

Elements to check when deciding whether a reaction is unbalanced (default carbon, phosphorus, sulfur, nitrogen, oxygen). A reaction imbalanced only in an element outside this set is not treated as unbalanced.

ignore_int_bounds:

Forwarded to raven_toolbox.gapfilling.find_leak_metabolite.

print_report:

Print which metabolite triggered each iteration and which reaction was removed for it.

Returns

list[str]

Ids of the reactions removed, in removal order.

Raises

ValueError

If model is not feasible to begin with.

Notes

removeBadRxns.m's refModel option (checking that a deletion keeps a reference model feasible) is not ported: it is an unsupported stub in RAVEN itself, which only warns that the feature "is currently not supported" and otherwise ignores it. When more than one reaction ties for "the" culprit, the one removed is picked at random (via the standard library's shared random state, matching RAVEN's own use of its default random generator) — a real source of non-determinism inherited from the original algorithm, not introduced by this port.

remove_dead_end_reactions#

remove_dead_end_reactions(model: cobra.Model, *, reserved: Iterable[str] | None=None)

Iteratively remove dead-end reactions and metabolites.

A metabolite is a dead end if it participates in only one reaction, or if (accounting for reaction directionality) it can only be produced or only consumed — such metabolites cannot carry steady-state flux, so the reactions touching them are removed. Repeats until stable. reserved reaction ids are never removed, even if they touch a dead-end metabolite.

Returns (removed_reaction_ids, removed_metabolite_ids).

remove_duplicate_reactions#

remove_duplicate_reactions(model: cobra.Model, *, reserved: Iterable[str] | None=None, restrict_to_metabolites: Iterable[cobra.Metabolite] | None=None)

Remove all-but-one of each set of duplicate reactions.

Reactions are duplicates when they have identical stoichiometry, bounds, and objective coefficient. One of each set is kept (reserved reactions are never removed). Returns the removed reaction IDs.

The survivor is the first-encountered reaction in model.reactions order (matching RAVEN's contractModel). Its gene_reaction_rule becomes the union of every duplicate's top-level OR-clauses, deduplicated, rather than just its own — an isozyme relationship recorded on a different duplicate would otherwise be silently dropped, and contractModel merges this way. If every reaction in the group shares an _EXP_<digits> suffix (raven_toolbox.manipulation.expand.expand_model's naming), the model is assumed to have gone through expand_model, and the suffix is stripped from the survivor's id — so an expand-then-remove-duplicates round trip returns the original reaction id, not an arbitrarily-numbered expansion copy.

Parameters

restrict_to_metabolites:

If given, only reactions touching at least one of these metabolites are checked for duplicates; every other reaction is left alone even if it is already a duplicate of another (matching contractModel's mets argument, used internally by replace_metabolite).

remove_genes#

remove_genes(model: cobra.Model, genes: str | Gene | Iterable, *, blocked_reactions: str='remove', remove_orphans: bool=False)

Remove genes and handle reactions left unable to carry flux.

GPR rewriting (with correct AND/OR semantics) and gene deletion are done by cobra; this adds a policy for reactions whose GPR becomes empty (no enzyme left):

  • "remove" — delete them (cobra's default).

  • "constrain" — keep them but set bounds to (0, 0).

  • "keep" — leave them with an empty GPR and unchanged bounds.

remove_orphans (only meaningful with blocked_reactions="remove") passes through to cobra: drop metabolites and genes orphaned by the removal.

Returns

list of str

IDs of the reactions that became flux-blocked (had a GPR, now empty).

remove_metabolites#

remove_metabolites(model: cobra.Model, metabolites: str | Metabolite | Iterable, *, by_name: bool=False, destructive: bool=False)

Remove metabolites, optionally matching by name across all compartments.

Parameters

by_name

If True, metabolites are metabolite names; every metabolite with a matching name is removed, regardless of compartment (RAVEN isNames). If False, they are IDs/objects, resolved via cobra.

destructive

Passed to cobra: if True, also remove every reaction the metabolite participates in.

Note

With by_name=False this is just model.remove_metabolites — the by_name cross-compartment deletion is the only thing this adds over cobra.

remove_no_flux_reactions#

remove_no_flux_reactions(model: cobra.Model, *, open_exchanges: bool=True)

Remove reactions that cannot carry flux under the tested bounds (RAVEN deleteMinMax).

Runs FVA and drops every reaction whose minimum and maximum flux are both zero. With open_exchanges (default) the reactions in model.exchanges are first opened to at least (-1000, 1000); sink and demand reactions and all internal bounds keep their current values, so a reaction blocked only by one of those is still removed. With open_exchanges=False the current bounds are used, as RAVEN's deleteMinMax does, which can remove more. A reaction that is blocked under these bounds stays blocked under any tighter ones, so removing it before task discovery / the merge is safe as long as no later step relaxes a sink, demand or internal bound. Modifies in place; returns the removed reaction ids.

remove_zero_interval_reactions#

remove_zero_interval_reactions(model: cobra.Model)

Remove reactions locked at zero flux (lb == ub == 0), pruning orphans.

RAVEN simplifyModel's deleteZeroInterval mode — such reactions can never carry flux, so they only enlarge downstream problems. Modifies in place; returns the removed reaction ids.

replace_metabolite#

replace_metabolite(model: cobra.Model, metabolite: str, replacement: str, *, identifiers: bool=False, verbose: bool=False)

Replace metabolite with replacement, an existing model metabolite.

Parameters

model:

Model to modify in place.

metabolite:

Name (or id, with identifiers=True) of the metabolite to replace.

replacement:

Name (or id) of the metabolite to replace it with. Its identity (name, formula, charge, annotation, and RAVEN's inchi/deltaG/metFrom notes) is copied onto every replaced metabolite.

identifiers:

If True, metabolite/replacement are metabolite ids rather than names (default False). Ids are unique, so this is always a direct 1:1 merge, and the survivor (replacement) keeps its own existing identity unchanged — replaceMets.m copies the replacement's identity onto the old metabolite's row before deleting that row, which has no observable effect (it never survives to be seen), so this doesn't replicate that dead step. Names are not unique: every metabolite named metabolite is renamed to replacement's name, and then any metabolite in the model sharing a (name, compartment) with a renamed one is merged into it too — not just the ones being explicitly replaced, matching replaceMets.m exactly (its own docstring example: a model with both "oxygen" and "o2" as names). Here the identity copy is observable (a renamed metabolite that turns out not to collide with anything survives with the replacement's copied identity), so it is applied.

verbose:

Print the ids of reactions touching the to-be-replaced metabolite(s).

Returns

list[str]

Ids of duplicate reactions removed as a result of the merge (only reactions touching the replacement are checked — pre-existing duplicates elsewhere in the model are left alone).

Raises

ValueError

If metabolite or replacement cannot be found.

set_exchange_bounds#

set_exchange_bounds(model: cobra.Model, mets: str | Metabolite | Iterable[str | Metabolite] | None=None, lb: Number | Sequence[Number] | None=None, ub: Number | Sequence[Number] | None=None, *, close_others: bool=True, media_only: bool=False)

Set exchange-flux bounds for a chosen set of metabolites.

Port of RAVEN setExchangeBounds. Exchange reactions are cobra's own boundary reactions (single metabolite); a reaction where the same metabolite is exchanged more than once is warned about but still handled, matching RAVEN.

Parameters

mets

Metabolite objects, ids, or names (case-insensitive), matched against the model's exchanged metabolites specifically — a real metabolite that isn't exchanged counts as unused, same as one that doesn't exist. None (default) means every exchanged metabolite, in which case lb/ub must each be a single value, not a sequence.

lb, ub

A single value applied to every metabolite in mets, or one value per metabolite. Default to cobra.Configuration().bounds when not given.

close_others

Close import (only import — export is left alone) on every other exchange reaction not covered by mets. Forced off, with a warning, if the model's exchange reactions don't agree on which sign of flux is import: correctly closing "import" would then require a different bound (lb vs ub) reaction by reaction, which this function does not attempt.

media_only

Only consider exchange reactions whose metabolite is in the compartment named "extracellular" (by model.compartments, case-insensitive) — e.g. skips sink/demand reactions on an intracellular metabolite. Raises if the model has no compartment with that name.

Returns

list of cobra.Metabolite

Metabolites in mets that were not found among the model's exchanged metabolites.

set_variance_bounds#

set_variance_bounds(model: cobra.Model, reactions: str | Reaction | Iterable, values: Number | Sequence[Number], percent: Number)

Constrain reactions to a ±percent/2 band around measured values.

For a measured value v and percent p, the bounds become v * (1 - p/200) .. v * (1 + p/200) — i.e. percent is the total width, split half above and half below. For a negative v the two are swapped so that lb <= ub. E.g. percent=5 gives 97.5 %..102.5 % of v.

Parameters

reactions

Reaction IDs or objects.

values

Measured value per reaction; a scalar is broadcast to all reactions.

percent

Total band width as a percentage.

Returns

list of cobra.Reaction

The reactions affected.

simplify_model#

simplify_model(model: cobra.Model, *, delete_zero_interval: bool=False, delete_dead_end: bool=False, delete_no_flux: bool=False, delete_duplicates: bool=False, group_linear: bool=False, constrain_reversible: bool=False, reserved: Iterable[str] | None=None, open_exchanges: bool=True)

Reduce a model by the selected simplification modes (RAVEN simplifyModel).

A single entry point mirroring RAVEN's simplifyModel boolean-flag interface, so a caller composes a simplification the same way RAVEN does (e.g. ftINIT's first simplification = delete_zero_interval + delete_dead_end + delete_no_flux; its second = constrain_reversible). Modes run in RAVEN's order — zero-interval, topological dead-end, no-flux (FVA deleteMinMax), duplicates, linear grouping, then constrain-reversible — each delegating to the dedicated function in this module. All operate in place. reserved reaction ids are never removed by the dead-end / duplicate / group-linear modes; open_exchanges is forwarded to the no-flux pass.

RAVEN's deleteUnconstrained (boundary-metabolite removal) has no analogue here: cobra models use explicit boundary reactions rather than an unconstrained field.