Manipulation (Python)#
raven-toolbox objects in raven_toolbox.manipulation.
Functions#
Function |
Summary |
|---|---|
Add reactions defined by equation strings, matching metabolites by ID or name. |
|
Copy reactions from |
|
Add transport reactions from one compartment to one or more others. |
|
Set or append gene-reaction rules on existing reactions. |
|
Replace the stoichiometry of existing reactions. |
|
Return a copy of |
|
Close the boundary reactions of |
|
Constrain reversible reactions that can only carry flux in one direction. |
|
Split every reversible reaction into a forward and a reverse reaction. |
|
Copy a set of reactions into |
|
Split reactions with isozymes (OR in the GPR) into one reaction per isozyme. |
|
Return groups of reactions that share identical stoichiometry. |
|
Convert a GPR to disjunctive normal form (list of AND-clauses). |
|
Merge linear (single-producer, single-consumer) reaction chains. |
|
Merge every metabolite of |
|
Merge models into a single new model. |
|
Remove reactions that let |
|
Iteratively remove dead-end reactions and metabolites. |
|
Remove all but one of each set of duplicate reactions. |
|
Remove genes and handle reactions that can no longer carry flux. |
|
Remove metabolites, optionally matching by name across all compartments. |
|
Remove reactions that cannot carry flux under the tested bounds (RAVEN |
|
Remove reactions locked at zero flux ( |
|
Replace |
|
Set exchange-flux bounds for a chosen set of metabolites. |
|
Constrain reactions to a |
|
Reduce a model by the selected simplification modes (RAVEN |
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
modelTarget
cobra.Model, mutated in place.reactionsSequence 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. Withoutbounds, 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 withraven_toolbox.utils.parse_gr_rule, the grammar of RAVEN.subsystem: subsystem name.
mets_byHow bare equation tokens (without
[comp]) are matched:"id"(eqnType1 of RAVEN'saddRxns) or"name"(eqnType2). Aname[comp]token (eqnType3) is always matched by name and compartment.compartmentDefault compartment for new metabolites and for name-matched tokens without an explicit
[comp].allow_new_metsIf True (default), metabolites that are not found are created. A new metabolite gets
compartment(id mode) or an automatic IDm1,m2, ... (name mode). If False, an unknown metabolite raisesValueError.allow_new_genesIf 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_prefixPrefix for auto-generated metabolite IDs in name mode (default
"m").
Returns
list of cobra.ReactionThe 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
modelDraft model to copy into (modified in place).
source_modelModel to copy reactions from.
reactionsReaction ID(s) in
source_model. Reactions already present inmodel(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 IDm<N>.genesFalse(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.noteStored in the
notes['note']of each added reaction (Nonestores no note).confidenceIf given, stored in the
notes['confidence_score']of each added reaction.
Returns
list of cobra.ReactionThe 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.ModelModel the reactions are added to, in place.
from_compartment: strSource compartment id.
to_compartments: str or Iterable of strTarget compartment id(s).
metabolite_names: str or Iterable of str or NoneNames of metabolites to transport. Default: every metabolite in
from_compartment.reversible: boolIf True (default), bounds span the cobra configuration default (reversible); otherwise lower bound 0.
only_to_existing: boolIf 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: strPrefix for the sequential reaction IDs (
tr_0001, ...).
Returns
list of cobra.ReactionThe 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
modelTarget
cobra.Model, mutated in place.rulesMapping of
reaction_id -> GPR string. Every ID must already exist.replaceIf True (default), overwrite the existing GPR. If False, append the new rule as an isozyme:
(old) or (new)(newif the reaction has no GPR).
Returns
list of cobra.ReactionThe 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
modelTarget
cobra.Model, mutated in place.equationsMapping of
reaction_id -> equation string. Every ID must already exist in the model. The equation syntax is that ofraven_toolbox.manipulation.add.add_reactions_from_equations.mets_by, compartment, allow_new_mets, new_met_prefixMetabolite-matching options, as in
add_reactions_from_equations.
Returns
list of cobra.ReactionThe 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.ModelModel 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.ModelModel modified in place.
eps: floatA 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
_REVsuffix 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'sconvertToIrrevcopies 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
modelThe
cobra.Model, modified in place.rxnsReaction IDs eligible for splitting. Reactions outside this set are left unchanged even if reversible. Defaults to every reaction in the model, as the
rxnsargument of RAVEN'sconvertToIrrevdefaults tomodel.rxns.
Returns
list of strSorted 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.ModelModel 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: strIdentifier of the compartment the copies are placed in. It is added to the model's compartments when missing.
target_compartment_name: str or NoneName stored for
target_compartmentwhen it is added. The defaultNoneuses the identifier as the name. The value is ignored when the compartment already exists.delete_original: boolWith
True, the original reactions are removed after copying. The default isFalse.id_suffix: str or NoneSuffix of the copied reaction and metabolite ids. The default
Noneusestarget_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
modelThe
cobra.Model, modified in place.
Returns
list of strSorted IDs of newly added expanded reactions (those with
_EXP_Nsuffixes). 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.ModelModel searched. It is not modified.
ignore_directionWhen True (default),
A → BandB → Aare 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
gprA cobra
cobra.core.gene.GPR, a grRule string orNone. A string is read withraven_toolbox.utils.parse_gr_rule, the grammar of RAVEN'sparseGrRule, as RAVEN'sgrRuleToDNFreads it.
Raises
ValueErrorIf 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.ModelModel modified in place.
reserved: Iterable[str] or NoneReaction ids that are never merged away. The default
Nonereserves 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, thenraven_toolbox.localization.predict_localizationorraven_toolbox.localization.assign_compartmentswith 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.ModelModel to merge. It is copied and not modified.
merged_id: strIdentifier of the merged compartment. The default is
"s"(RAVEN's "system").merged_name: strName of the merged compartment, stored in
compartments. The default is"system".base_metabolite: Callable[[cobra.Metabolite], str] or NoneMaps 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
Noneremoves a trailing_<compartment>suffix from the id (glc__D_candglc__D_eboth giveglc__D). A model that uses a different id per compartment for the same species, for example thes_####ids of yeast-GEM, needsbase_metabolite=lambda m: m.name(or an annotation key) to merge the compartments; the same callable is passed toraven_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 inmerged_idif there is one, otherwise the copy whose id sorts first (ACCOA_cbeforeACCOA_m); among several copies inmerged_id, the one whose id sorts first. RAVEN'smergeCompartmentsapplies 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: boolWith
True(RAVEN'sdeleteRxnsWithOneMet; defaultFalsein 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: boolWith
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 indeduplicated_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
modelsThe models to merge (two or more). A single model is returned as a copy.
match_byHow 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_originIf True (default), record the
idof the source model in thenotes['origin']of each reaction, metabolite and gene.
Returns
cobra.ModelA 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 renamedid_<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 toraven_toolbox.gapfilling.find_leak_metabolite.is_names:If True,
ignore_metsholds 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
ValueErrorIf
modelis 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.ModelModel modified in place.
reserved: Iterable[str] or NoneReaction ids that are never removed. The default
Nonereserves 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.ModelModel 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
metsargument ofcontractModel;replace_metaboliteuses 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.ModelModel the genes are removed from, in place.
genes: str or Gene or IterableGene ids or
cobra.Geneobjects to remove.blocked_reactions: strPolicy for reactions whose GPR becomes empty. One of the following; any other value raises
ValueError."constrain"(default, as RAVEN'sremoveGenes): 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: boolRelevant with
blocked_reactions="remove"only. It is passed to cobra'sremove_reactions, which also removes the metabolites left without a reaction. The default isFalse.
Returns
list of strSorted 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.ModelModel the metabolites are removed from, in place.
metabolites: str or Metabolite or IterableMetabolites to remove: names with
by_name=True, otherwise ids orcobra.Metaboliteobjects.by_name: boolIf True,
metabolitesare metabolite names; every metabolite with a matching name is removed, in any compartment (RAVENisNames). If False, they are IDs or objects, resolved by cobra.destructive: boolPassed 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.ModelModel modified in place.
open_exchanges: boolWith
True(the default) the reactions inmodel.exchangesare 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. WithFalsethe current bounds are used, as in RAVEN'sdeleteMinMax, which can remove more reactions.reserved: Iterable[str] or NoneReaction ids that are never removed. The default
Nonereserves 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.ModelModel modified in place.
reserved: Iterable[str] or NoneReaction ids that are never removed. The default
Nonereserves 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,
metaboliteandreplacementare 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 namedmetabolitereceives the identity of the first metabolite namedreplacement, 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 namedmetabolite. This followsreplaceMets.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
ValueErrorIf
metaboliteorreplacementcannot 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.ModelModel whose exchange-reaction bounds are set in place.
mets: str or Metabolite or Iterable or NoneMetabolite 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 caselbandubmust each be a single value.lb, ub: Number or Sequence of Number or NoneA single value for every metabolite in
mets, or one value per metabolite. Default tocobra.Configuration().boundswhen not given.close_others: boolClose 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: boolOnly 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. RaisesValueErrorif the model has no compartment with that name.
Returns
list of str or cobra.MetaboliteThe 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.ModelModel whose reaction bounds are set in place.
reactions: str or Reaction or IterableReaction IDs or objects.
values: Number or Sequence of NumberMeasured value per reaction; a scalar applies to all reactions.
percent: NumberTotal band width as a percentage.
Returns
list of cobra.ReactionThe 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.ModelModel modified in place.
delete_zero_interval: boolRun
remove_zero_interval_reactions. The default isFalse.delete_dead_end: boolRun
remove_dead_end_reactions. The default isFalse.delete_no_flux: boolRun
remove_no_flux_reactions. The default isFalse.delete_duplicates: boolRun
remove_duplicate_reactionson the whole model. The default isFalse.group_linear: boolRun
group_linear_reactions, which clears all gene-reaction rules and removes all genes. The default isFalse.constrain_reversible: boolRun
constrain_reversible_reactionswith its defaulteps. The default isFalse.reserved: Iterable[str] or NoneReaction 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
Nonereserves none.open_exchanges: boolPassed to the no-flux mode. The default is
True.