Skip to content

Manipulation (Python)

raven-toolbox objects in raven_toolbox.manipulation, collected from the source of the tracked branch.

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.
constrain_reversible_reactions Constrain reversible reactions that can only carry flux one way.
convert_to_irreversible Split non-exchange reversible reactions 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_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.
set_variance_bounds Constrain reactions to a ±percent/2 band around measured values.

Reference

add_reactions_from_equations

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

Parameters:

Name Type Description Default
model Model

Target cobra.Model, mutated in place.

required
reactions Sequence[Mapping]

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.
required
mets_by str

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.

'id'
compartment str | None

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

None
allow_new_mets bool

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.

True
allow_new_genes bool

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.

True
new_met_prefix str

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

'm'

Returns:

Type Description
list of cobra.Reaction

The reactions added, in input order.

add_reactions_from_model

Copy reactions from source_model into model.

Parameters:

Name Type Description Default
model Model

Draft model to copy into (mutated in place).

required
source_model Model

Model to copy reactions from.

required
reactions str | Iterable[str]

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

required
genes bool | str | Iterable[str]

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.

False
note str | None

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

'Added via add_reactions_from_model()'
confidence int | None

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

None

Returns:

Type Description
list of cobra.Reaction

The reactions added, in input order.

add_transport_reactions

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

Parameters:

Name Type Description Default
from_compartment str

Source compartment id.

required
to_compartments str | Iterable[str]

Target compartment id(s).

required
metabolite_names str | Iterable[str] | None

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

None
reversible bool

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

True
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 (copying name/formula/charge/ annotation from the source) before adding the transport.

True
id_prefix str

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

'tr_'

Returns:

Type Description
list of cobra.Reaction

The transport reactions added, in creation order.

change_gene_reaction_rules

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:

Name Type Description Default
model Model

Target cobra.Model, mutated in place.

required
rules Mapping[str, str]

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

required
replace bool

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

True

Returns:

Type Description
list of cobra.Reaction

The reactions changed, in input order.

change_reaction_equations

Replace the stoichiometry of existing reactions.

Parameters:

Name Type Description Default
model Model

Target cobra.Model, mutated in place.

required
equations Mapping[str, str]

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

required
mets_by str

Metabolite-matching options, as in add_reactions_from_equations.

'id'
compartment str

Metabolite-matching options, as in add_reactions_from_equations.

'id'
allow_new_mets str

Metabolite-matching options, as in add_reactions_from_equations.

'id'
new_met_prefix str

Metabolite-matching options, as in add_reactions_from_equations.

'id'

Returns:

Type Description
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.

constrain_reversible_reactions

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.

convert_to_irreversible

Split non-exchange reversible reactions into a forward + reverse pair. For each non-exchange reaction with lb < 0:

  • 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) and the gene-protein rule of the original.

Exchange reactions (boundary reactions) are never split, regardless of their bounds, matching MATLAB behavior where exchange reactions are explicitly excluded from convertToIrrev.

Parameters:

Name Type Description Default
model Model

A cobra.Model, mutated in place.

required

Returns:

Type Description
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 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

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:

Name Type Description Default
model Model

A cobra.Model, mutated in place.

required

Returns:

Type Description
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

Return groups of reactions that share identical stoichiometry.

Detection-only counterpart to :func: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:

Name Type Description Default
ignore_direction bool

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

True

Returns:

Type Description
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

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

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. Mutates in place.

merge_compartments

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 :func:merge_compartments then :func:raven_toolbox.localization.predict_localization with the full reaction list).

Metabolites that already share a base id (e.g. glc__D_c and glc__D_e both map to glc__D) collapse into one entity in the merged compartment; their stoichiometric contributions are summed per reaction. Reactions that end up with only one metabolite (e.g. A[c] → A[m] becomes A → A = nothing) are deleted by default (RAVEN's deleteRxnsWithOneMet). Reactions that become identical after merging are deduplicated (one survives).

merge_models

Merge models into a single new model.

Parameters:

Name Type Description Default
models Iterable[Model]

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

required
match_by str

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.

'name'
track_origin bool

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

True

Returns:

Type Description
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_dead_end_reactions

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.

Returns (removed_reaction_ids, removed_metabolite_ids).

remove_duplicate_reactions

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.

remove_genes

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:

Type Description
list of str

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

remove_metabolites

Remove metabolites, optionally matching by name across all compartments.

Parameters:

Name Type Description Default
by_name bool

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.

False
destructive bool

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

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

set_variance_bounds

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:

Name Type Description Default
reactions str | Reaction | Iterable

Reaction IDs or objects.

required
values Number | Sequence[Number]

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

required
percent Number

Total band width as a percentage.

required

Returns:

Type Description
list of cobra.Reaction

The reactions affected.