Manipulation (Python)#

raven-toolbox objects in raven_toolbox.manipulation.

Functions#

Function

Summary

add_reactions_from_equations

Add reactions defined by equation strings, matching metabolites 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 of model with the exchange reactions closed.

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 in one direction.

convert_to_irreversible

Split every reversible reaction into a forward and a reverse reaction.

copy_to_compartment

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

expand_model

Split reactions with isozymes (OR in the 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 or 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 that can no longer 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 metabolites 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): for example "atp_c + h2o_c <=> adp_c + pi_c". <=> marks a reversible reaction; -->, -> and => mark an irreversible one.

  • name: reaction name.

  • bounds: (lower, upper) tuple; takes precedence over the arrow. Without bounds, the upper bound is the cobra default upper bound and the lower bound is the cobra default lower bound for a reversible reaction and 0 for an irreversible one.

  • gene_reaction_rule: GPR string. Read with raven_toolbox.utils.parse_gr_rule, the grammar of RAVEN.

  • subsystem: subsystem name.

mets_by

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

compartment

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

allow_new_mets

If True (default), metabolites that are not found are created. A new metabolite gets compartment (id mode) or an automatic ID m1, m2, ... (name mode). If False, an unknown metabolite raises ValueError.

allow_new_genes

If True (default), genes of a GPR that are not in the model are created and added to the model in sorted order, independent of the hash seed. If False, a GPR that references a gene not in the model raises ValueError.

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 (modified 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. A new metabolite keeps the id of the source metabolite unless that id is in use, in which case it gets an automatic ID m<N>.

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 added). New genes are created automatically.

note

Stored in the notes['note'] of each added reaction (None stores no note).

confidence

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

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

model : cobra.Model

Model the reactions are added to, in place.

from_compartment : str

Source compartment id.

to_compartments : str or Iterable of str

Target compartment id(s).

metabolite_names : str or Iterable of str or None

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

reversible : bool

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

only_to_existing : bool

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 (with name, formula, charge and annotation of the source) before adding the transport.

id_prefix : str

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.

Rules are read with raven_toolbox.utils.parse_gr_rule, the grammar of RAVEN's parseGrRule (G1&G2 is one gene id); a rule that the grammar does not accept is read with cobra's parser. New genes are created in the model. replace=False appends the rule as an isozyme, as RAVEN's changeGrRules with replace false does.

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) (new if the reaction has 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. The equation syntax is that of 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, as in RAVEN. Changing an equation from --> to <=> leaves the reaction irreversible until the bounds are set.

close_model#

close_model(model: cobra.Model)

Return a copy of model with the exchange reactions closed.

Every reaction with metabolites on only one side (no substrates or no products: an exchange, sink or demand reaction) gets the bounds (0, 0) and can no longer carry flux. RAVEN's closeModel closes the same reactions by balancing each one with a boundary metabolite. After closing, the inputs and outputs of a metabolic task are set by the task constraints only, as checkTasks assumes, and no open exchange reactions remain.

For a reaction with a single metabolite, the set equals cobra's Reaction.boundary; the set also includes a reaction that consumes or produces several metabolites without a balancing side.

The input model is not modified.

Parameters

model : cobra.Model

Model to close. It is copied and not modified.

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 in one direction.

Runs FVA on each reversible reaction. If a reaction can only carry forward flux, its lower bound is set to 0. If it can only carry reverse flux, it is turned into a forward reaction: the stoichiometry and the objective coefficient are negated and the bounds become (0, -lower_bound). Returns the IDs of the changed reactions. A bound counts as zero when |flux| < eps (default 1e-10, the threshold of RAVEN simplifyModel constrainReversible). A reaction with an infinite FVA range is not changed. Raises RuntimeError if the FVA fails or returns NaN ranges (an infeasible model).

RAVEN runs its FVA (getAllowedBounds → solveLP) at FeasibilityTol = 1e-9. The function sets the same feasibility tolerance, and the same optimality tolerance, on the solver when the solver exposes these Gurobi parameters. At the Gurobi default of 1e-6, a reaction with a tiny one-way flux is misclassified, which changes its reversibility and how group_linear_reactions merges it.

Parameters

model : cobra.Model

Model modified in place.

eps : float

A flux bound counts as zero when its absolute value is below eps. The default is 1e-10.

convert_to_irreversible#

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

Split every reversible reaction into a forward and a reverse reaction.

The split applies to each reaction with lb < 0, including exchange (boundary) reactions, as in RAVEN's convertToIrrev:

  • The original reaction is kept as the forward direction. Its lower bound is set 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 and its bounds are (0, -original_lb). It takes the name of the original (with " (reversible)" appended), the gene-protein rule, the subsystem, the annotations and the notes of the original. RAVEN's convertToIrrev copies the same per-reaction fields (eccodes, rxnMiriams, subSystems, rxnNotes, ...).

  • If the objective coefficient of the original reaction is negative, it is moved to the new reverse reaction (with the sign flipped to positive) and set to 0 on the forward reaction, so that a reversible reaction credited under the objective for reverse-direction flux keeps that credit after splitting. A non-negative coefficient stays on the forward reaction, and the objective coefficient of the reverse reaction is 0, as in RAVEN's convertToIrrev.

Parameters

model

The cobra.Model, modified in place.

rxns

Reaction IDs eligible for splitting. Reactions outside this set are left unchanged even if reversible. Defaults to every reaction in the model, as the rxns argument of RAVEN's convertToIrrev defaults to model.rxns.

Returns

list of str

Sorted IDs of newly added reverse reactions (the ones ending in _REV). The forward reactions keep 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). The input model is not modified. Use cases:

  • Build a dual-localised pathway (for example duplicate glycolysis into a peroxisome).

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

  • Prepare the input for a flux comparison between alternative compartmentalisations.

Each copied reaction gets the id "<orig_id>_<id_suffix>". Each metabolite of the reaction maps to its copy in target_compartment, which is created with the same suffix convention when it does not exist; a metabolite that is already in target_compartment is used unchanged. A reaction whose copy id is already in the model is skipped. With delete_original=True the original reactions are moved; their metabolites remain in the model.

Parameters

model : cobra.Model

Model to copy reactions in. It is copied and not modified.

reactions : Iterable[str]

Identifiers of the reactions to copy. An identifier that is not in the model raises ValueError.

target_compartment : str

Identifier of the compartment the copies are placed in. It is added to the model's compartments when missing.

target_compartment_name : str or None

Name stored for target_compartment when it is added. The default None uses the identifier as the name. The value is ignored when the compartment already exists.

delete_original : bool

With True, the original reactions are removed after copying. The default is False.

id_suffix : str or None

Suffix of the copied reaction and metabolite ids. The default None uses target_compartment.

expand_model#

expand_model(model: cobra.Model)

Split reactions with isozymes (OR in the 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 the ID suffix _EXP_1, _EXP_2, and so on. The _EXP_1 copy takes the position of the original reaction; the other copies are appended in the order of the originals, as RAVEN's expandModel does. Stoichiometry, bounds, name, subsystem, annotation and notes are copied from the original, and each copy gets the objective coefficient of the original. The GPR of a copy is the single AND-clause of its isozyme.

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

Parameters

model

The cobra.Model, modified 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.

This is the detection-only counterpart to remove_duplicate_reactions. Only the stoichiometry is compared; bounds, objective coefficients, GPRs and annotations are ignored, as in yeast-GEM findDuplicatedRxns. The groups are reactions that could be merged.

Parameters

model : cobra.Model

Model searched. It is not modified.

ignore_direction

When True (default), A → B and B → A are treated as duplicates (the convention of yeast-GEM). If False, identical orientation is required.

Returns

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

at least 2 reactions with the same stoichiometry. Reactions that have :

no duplicate are omitted. :

gpr_to_dnf#

gpr_to_dnf(gpr: GPR | str | None)

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

An empty GPR gives an empty list. A single clause (no OR anywhere) gives a list of length 1. An OR of ANDs gives one sublist per disjunct, each containing the gene names combined by AND.

AND is distributed over OR: g1 and (g2 or g3) becomes [[g1, g2], [g1, g3]].

Parameters

gpr

A cobra cobra.core.gene.GPR, a grRule string or None. A string is read with raven_toolbox.utils.parse_gr_rule, the grammar of RAVEN's parseGrRule, as RAVEN's grRuleToDNF reads it.

Raises

ValueError

If a rule string is malformed in that grammar (RAVEN raises RAVEN:badGrRule).

group_linear_reactions#

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

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

All gene-reaction rules are cleared and all genes are removed from the model, as in RAVEN. 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. Metabolites are visited in model order and the reaction with the lower index survives a merge, as in RAVEN's groupLinear, so the survivor of a chain is its first reaction. A reserved reaction is never merged away. The model is modified in place.

Parameters

model : cobra.Model

Model modified in place.

reserved : Iterable[str] or None

Reaction ids that are never merged away. The default None reserves none.

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=False, deduplicate_reactions: bool=True)

Merge every metabolite of model into one merged_id compartment.

Returns (merged_model, deleted_single_met_reactions, deduplicated_reactions). The input model is not modified. Use cases:

  • Check whether the network can produce or consume a metabolite at all, without compartment topology.

  • Simplify a model for visualisation or for an analysis that ignores compartments.

  • Prepare a localisation from scratch (call merge_compartments, then raven_toolbox.localization.predict_localization or raven_toolbox.localization.assign_compartments with the full reaction list).

Metabolites that share a key become one metabolite in the merged compartment, and their stoichiometric contributions are summed per reaction. A reaction whose metabolites all cancel (A[c] → A[m] becomes A → A) is always deleted. The objective is carried over to the returned model. deleted_single_met_reactions lists the reactions whose metabolites all cancelled and, with drop_single_metabolite_reactions=True, those reduced to one metabolite. RAVEN's deletedRxns lists only the latter, so it is empty with deleteRxnsWithOneMet off.

Each merged metabolite stores its base id in notes["merged_base_id"] (MERGED_BASE_ID_NOTE): the id of the kept copy without the suffix of the compartment it came from (ACCOA for ACCOA_c). The default metabolite key of raven_toolbox.localization.assign_compartments, raven_toolbox.localization.apply_assignment, raven_toolbox.localization.relocate_reactions and raven_toolbox.localization.curation_priority reads it, so the merged ACCOA_c in compartment s and ACCOA_m of a universal model are the same species there. When two merged metabolites would get the same base id (a base_metabolite that keeps X_c and X_m apart), both store their own id, so they remain distinct species. The note is kept by model.copy(), cobra's JSON and SBML files and raven_toolbox.io.write_yaml_model with raven_toolbox.io.read_yaml_model. RAVEN's readYAMLmodel shows it in metNotes, for example merged_base_id: ACCOA note: free text note for a metabolite that also has the free-text note free text note; no RAVEN function uses it. A round trip through RAVEN YAML (readYAMLmodel and writeYAMLmodel) or through a .mat file does not preserve the note: RAVEN joins the key and the free text into one string, which raven_toolbox.io.read_yaml_model reads back as the free-text note, and raven_toolbox.io.write_matlab_model and raven_toolbox.io.read_matlab_model carry no metabolite notes. The localisation functions then key the metabolite by its id without the suffix of its own compartment, so a merged ACCOA_c in compartment s gets the key ACCOA_c, and no error is raised.

Parameters

model : cobra.Model

Model to merge. It is copied and not modified.

merged_id : str

Identifier of the merged compartment. The default is "s" (RAVEN's "system").

merged_name : str

Name of the merged compartment, stored in compartments. The default is "system".

base_metabolite : Callable[[cobra.Metabolite], str] or None

Maps a metabolite to the compartment-independent key that decides which metabolites are the same species (two compartment copies with one key become one metabolite). The default None removes a trailing _<compartment> suffix from the id (glc__D_c and glc__D_e both give glc__D). A model that uses a different id per compartment for the same species, for example the s_#### ids of yeast-GEM, needs base_metabolite=lambda m: m.name (or an annotation key) to merge the compartments; the same callable is passed to raven_toolbox.localization.assign_compartments. The key decides the grouping only. The merged metabolite keeps the id, name, formula, charge, annotation and notes of one of its copies and never gets an id built from the key. The copy is the one already in merged_id if there is one, otherwise the copy whose id sorts first (ACCOA_c before ACCOA_m); among several copies in merged_id, the one whose id sorts first. RAVEN's mergeCompartments applies the same rule. The id can therefore name a compartment that no longer exists. A name-based key such as "1-acyl-sn-glycerol 3-phosphate (16:0)" merges the copies, and the merged id is still the id of one of them, so the characters of the key do not enter the id.

drop_single_metabolite_reactions : bool

With True (RAVEN's deleteRxnsWithOneMet; default False in both) a reaction that the merge reduces to one metabolite is deleted. A reaction with a single metabolite before the merge is an exchange (=> glucose) and is always kept, as in RAVEN, because dropping these reactions would remove the medium and the biomass reaction of the model.

deduplicate_reactions : bool

With True (the default), reactions that are identical after the merge (same stoichiometry and same reversibility) are reduced to the first one; the others are listed in deduplicated_reactions.

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 are ignored); "id" matches by metabolite ID. When matched metabolites have different formulas or charges, a warning is issued and the first metabolite is kept.

track_origin

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

Returns

cobra.Model

A new merged model (id="MERGED"). Reactions are not de-duplicated: as in RAVEN, every reaction from every model is kept, and a colliding ID is renamed id_<sourceid>. The objective direction is that of the first model.

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 or consume metabolites from nothing.

Modifies model in place.

Parameters

model:

Model to clean up. The search expects a model without uptake and excretion; it warns about open exchange reactions and continues. Close the model first with 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; otherwise it holds 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

The refModel option of RAVEN's removeBadRxns (checking that a deletion keeps a reference model feasible) is not available. RAVEN itself only warns that the feature "is currently not supported" and ignores it. When several reactions are candidates, the removed one is chosen at random with the random state of the standard library, so the result varies between runs unless that state is seeded.

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 (given the reaction directions) it can only be produced or only be consumed. Such a metabolite cannot carry steady-state flux, so the reactions that contain it are removed. The removal repeats until no dead end remains. A reserved reaction is kept even if it contains a dead-end metabolite.

Returns (removed_reaction_ids, removed_metabolite_ids).

Parameters

model : cobra.Model

Model modified in place.

reserved : Iterable[str] or None

Reaction ids that are never removed. The default None reserves none.

remove_duplicate_reactions#

remove_duplicate_reactions(model: cobra.Model, *, 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 and the same reversibility, as in RAVEN contractModel: reversible reactions are compared in the direction sort_model(sort_reversible=True) gives them, so A <=> B and B <=> A are duplicates. Bounds and objective coefficients may differ; the survivor takes the lowest lower bound, the highest upper bound and the highest objective coefficient of its group, with a warning where they differ (the values are taken as stored, not mirrored for a reaction written in the opposite direction). One reaction of each set is kept; there is no reserved-reaction option, as in contractModel. Returns the removed reaction IDs.

The survivor is the first reaction of the set in model.reactions order (as in RAVEN's contractModel). Its gene_reaction_rule becomes the union of the top-level OR-clauses of every duplicate, without repeated clauses, as in contractModel; an isozyme recorded on another duplicate is therefore kept. If every reaction in the set has an _EXP_<digits> suffix (the naming of raven_toolbox.manipulation.expand.expand_model), the suffix is removed from the id of the survivor, so that expand_model followed by remove_duplicate_reactions restores the original reaction id.

Parameters

model : cobra.Model

Model modified in place.

restrict_to_metabolites:

If given, only reactions that contain at least one of these metabolites are checked for duplicates; every other reaction is left unchanged even if it is a duplicate of another reaction (as the mets argument of contractModel; replace_metabolite uses it).

remove_genes#

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

Remove genes and handle reactions that can no longer carry flux.

cobra rewrites the GPRs (AND and OR semantics) and deletes the genes; this function adds a policy, set by blocked_reactions, for reactions whose GPR becomes empty (no enzyme left).

Requested genes that are not in the model are ignored. When none of the requested genes is in the model, the model is not changed and [] is returned. Otherwise, after the requested genes are removed, every gene that is not named in the GPR (before the removal) of any remaining reaction is deleted too, as in RAVEN's removeGenes. These are genes that no reaction uses (also when not requested) and, with "remove", genes used only by the deleted reactions. A gene whose only reaction is blocked and kept ("constrain" or "keep"), such as the other subunit of a complex that lost one, stays in model.genes.

Parameters

model : cobra.Model

Model the genes are removed from, in place.

genes : str or Gene or Iterable

Gene ids or cobra.Gene objects to remove.

blocked_reactions : str

Policy for reactions whose GPR becomes empty. One of the following; any other value raises ValueError.

  • "constrain" (default, as RAVEN's removeGenes): keep them with an empty GPR and bounds (0, 0).

  • "remove": delete them.

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

remove_orphans : bool

Relevant with blocked_reactions="remove" only. It is passed to cobra's remove_reactions, which also removes the metabolites left without a reaction. The default is False.

Returns

list of str

Sorted 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

model : cobra.Model

Model the metabolites are removed from, in place.

metabolites : str or Metabolite or Iterable

Metabolites to remove: names with by_name=True, otherwise ids or cobra.Metabolite objects.

by_name : bool

If True, metabolites are metabolite names; every metabolite with a matching name is removed, in any compartment (RAVEN isNames). If False, they are IDs or objects, resolved by cobra.

destructive : bool

Passed to cobra. If True, every reaction that contains the metabolite is removed as well.

Note

With by_name=False the function calls model.remove_metabolites. The deletion across compartments by name is the only addition to cobra.

remove_no_flux_reactions#

remove_no_flux_reactions(model: cobra.Model, *, open_exchanges: bool=True, reserved: Iterable[str] | None=None)

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

Runs FVA and removes every reaction whose minimum and maximum flux are both zero. A reaction that is blocked under the tested bounds stays blocked under any tighter bounds, so removing it before task discovery or the merge holds as long as no later step relaxes a sink, demand or internal bound. Every metabolite left without a reaction is removed; genes are kept, as in RAVEN removeReactions with its defaults. The model is modified in place; the function returns the removed reaction ids.

Parameters

model : cobra.Model

Model modified in place.

open_exchanges : bool

With True (the 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 False the current bounds are used, as in RAVEN's deleteMinMax, which can remove more reactions.

reserved : Iterable[str] or None

Reaction ids that are never removed. The default None reserves none.

remove_zero_interval_reactions#

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

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

This is the deleteZeroInterval mode of RAVEN simplifyModel. Such reactions cannot carry flux. Every metabolite left without a reaction is removed, including metabolites that had no reaction before. Genes are kept, as in RAVEN removeReactions with its defaults. The model is modified in place; the function returns the removed reaction ids.

Parameters

model : cobra.Model

Model modified in place.

reserved : Iterable[str] or None

Reaction ids that are never removed. The default None reserves none.

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 the RAVEN notes inchis, deltaG and metFrom) is copied onto every replaced metabolite when matching by name.

identifiers:

If True, metabolite and replacement are metabolite ids; by default they are names. Ids are unique, so the old metabolite is merged into the replacement, which keeps its own name, formula, charge, annotation and notes. Names are not unique: every metabolite named metabolite receives the identity of the first metabolite named replacement, and then every group of metabolites in the model that share a name and compartment with a replacement is merged into the first metabolite of the group (model order), including metabolites that were not named metabolite. This follows replaceMets.m, whose example is a model with both "oxygen" and "o2" as names.

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 that contain a surviving replacement metabolite are checked; duplicates elsewhere in the model are not changed.

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.

Corresponds to RAVEN setExchangeBounds. Exchange reactions are the boundary reactions of cobra (single metabolite). The function warns about every metabolite of the model that is exchanged by more than one reaction, whether or not it is in mets (RAVEN warns only about the metabolites in mets). The bounds are set on all exchange reactions of each metabolite in mets, as in RAVEN.

Parameters

model : cobra.Model

Model whose exchange-reaction bounds are set in place.

mets : str or Metabolite or Iterable or None

Metabolite objects, ids (exact) or names (case-insensitive), matched against the exchanged metabolites of the model only; a metabolite in the model that is not exchanged counts as unused, like one that does not exist. None (default) selects every exchanged metabolite, in which case lb and ub must each be a single value.

lb, ub : Number or Sequence of Number or None

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

close_others : bool

Close import on every exchange reaction not covered by mets; export is not changed. Default True. Set to False, with a warning, if the exchange reactions of the model do not agree on which sign of flux is import: closing import would then need a different bound (lb or ub) for each reaction, which this function does not do.

media_only : bool

Only consider exchange reactions whose metabolite is in the compartment named "extracellular" (in model.compartments, case-insensitive), which excludes, for example, sink and demand reactions of an intracellular metabolite. Raises ValueError if the model has no compartment with that name.

Returns

list of str or cobra.Metabolite

The entries of mets (as supplied: ids, names or metabolite objects) that were not found among the exchanged metabolites of the model.

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). percent is the total width, split into half above and half below. For a negative v the two are swapped so that lb <= ub. For example, percent=5 gives 97.5 % to 102.5 % of v.

Parameters

model : cobra.Model

Model whose reaction bounds are set in place.

reactions : str or Reaction or Iterable

Reaction IDs or objects.

values : Number or Sequence of Number

Measured value per reaction; a scalar applies to all reactions.

percent : Number

Total band width as a percentage.

Returns

list of cobra.Reaction

The reactions whose bounds were set.

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).

The function has the boolean-flag interface of RAVEN's simplifyModel, so a simplification is composed as in RAVEN (for example the first simplification of ftINIT is delete_zero_interval + delete_dead_end + delete_no_flux, and the second is constrain_reversible). Modes run in the order of RAVEN: duplicates, zero-interval, topological dead-end, no-flux (FVA deleteMinMax), constrain-reversible, then linear grouping, so reversible reactions that carry flux in one direction only are made irreversible before they are grouped. Each mode delegates to the function of this module with the same name. All modes operate in place.

RAVEN's deleteUnconstrained (boundary-metabolite removal) has no analogue here: cobra models have explicit boundary reactions and no unconstrained field.

Parameters

model : cobra.Model

Model modified in place.

delete_zero_interval : bool

Run remove_zero_interval_reactions. The default is False.

delete_dead_end : bool

Run remove_dead_end_reactions. The default is False.

delete_no_flux : bool

Run remove_no_flux_reactions. The default is False.

delete_duplicates : bool

Run remove_duplicate_reactions on the whole model. The default is False.

group_linear : bool

Run group_linear_reactions, which clears all gene-reaction rules and removes all genes. The default is False.

constrain_reversible : bool

Run constrain_reversible_reactions with its default eps. The default is False.

reserved : Iterable[str] or None

Reaction ids that are never removed by the zero-interval, dead-end, no-flux and group-linear modes (the duplicates mode ignores them, as in RAVEN). The default None reserves none.

open_exchanges : bool

Passed to the no-flux mode. The default is True.