Utilities (Python)#

raven-toolbox objects in raven_toolbox.utils.

Functions#

Function

Summary

check_model

Run curation checks on a model and return the issues found.

ElementalBalance

Balance result for one reaction.

find_non_dnf_grrules

Find reactions whose GPR is not in disjunctive normal form ("OR of AND-complexes").

generate_new_ids

Generate quantity new ids, sequentially numbered after the model's own.

get_elemental_balance

Check whether reactions are elementally balanced.

GPRIssue

A reaction whose GPR is flagged by the linter.

guess_composition

Infer missing metabolite formulas from elemental mass balance.

GuessCompositionResult

Result of guess_composition.

is_dnf

Return whether a GPR is in disjunctive normal form (OR of AND-complexes).

ModelIssue

One curation issue found in a model.

next_ids

The id sequence of generate_new_ids for a list of existing ids.

parse_gr_rule

Parse a grRule string in the grammar of RAVEN's parseGrRule.

parse_name_comp

Split a name[comp] token into (name, compartment).

resolve_aggregators

Validate the scoring-mode names and return (isozyme_fn, complex_fn).

reversible_orientation

-1 when a reversible reaction is written with its first metabolite (sorted by name and

rule_to_gpr

The cobra.core.gene.GPR of a rule string as parse_gr_rule reads it.

rule_tokens

Split a gene rule into (kind, text) pairs.

set_gene_rule

Give rxn a gene rule in RAVEN's grammar.

set_raven_tolerance

Set the solver tolerance of model to RAVEN's value.

sort_identifiers

Sort reactions, metabolites and genes alphabetically by ID, in place.

sort_model

Standardise the direction and order of reactions and metabolites, in place.

subsystem_order_scores

Order score of every subsystem with 2 to 250 reactions, in the current reaction order.

subsystem_to_str

Convert a reaction subsystem to a str.

Reference#

check_model#

check_model(model: cobra.Model)

Run curation checks on a model and return the issues found.

Does not raise; returns a possibly empty list of ModelIssue.

Parameters

model : cobra.Model

Model to check. It is not modified.

ElementalBalance#

Balance result for one reaction.

Attributes

reaction_id

ID of the reaction.

status

"balanced": the elements balance; "unbalanced": they do not (see imbalance); "unknown": the reaction has no metabolites, at least one metabolite has no formula, or a formula cobra cannot parse (for example the polymer (C5H8)n), so the balance cannot be determined (cobra treats a missing formula as empty and raises ValueError for an unparsable one).

imbalance

Element to net coefficient (products minus reactants), only for "unbalanced"; empty otherwise. Charge is not included.

find_non_dnf_grrules#

find_non_dnf_grrules(model: cobra.Model)

Find reactions whose GPR is not in disjunctive normal form ("OR of AND-complexes").

The check runs on cobra's GPR AST. Reactions with no GPR are skipped.

Parameters

model : cobra.Model

Model whose reactions are checked. It is not modified.

Returns

list of GPRIssue

One entry per flagged reaction, in model reaction order. Empty if all GPRs are in DNF.

generate_new_ids#

generate_new_ids(model: cobra.Model, entity_type: Literal['reactions', 'metabolites'], prefix: str, *, quantity: int=1, num_length: int=4)

Generate quantity new ids, sequentially numbered after the model's own.

Existing ids are filtered to those starting with prefix and the prefix is stripped. When any remainder reads as a finite whole number of absolute value below 2**52, the largest number is the starting point and its text length is the width. A remainder is read as a plain decimal number with an optional sign, fraction and e exponent; inf, nan, 2.5, 1e20, 1e400 and text do not count. MATLAB str2double reads more as numbers than this does (hexadecimal 0x10, a thousands separator 1,000, complex 3+0i), so ids with such suffixes are numbered differently by generateNewIds. When no remainder counts, the width is the length of the last remainder in string order and numbering starts at 1. num_length applies only when no id has the prefix. The numbering follows generateNewIds.m: r_9, r_10 and r_2 give r_11, and r_0003 beside r_abc gives r_0004.

Parameters

model

A cobra model.

entity_type

Which id namespace to look in and generate for: "reactions" or "metabolites".

prefix

Prefix for all generated ids, for example "s_" or "r_".

quantity

Number of new ids to generate.

num_length

Width of the zero-padded numeric part, for example 4 gives ids like r_0001. Ignored in favour of the model's own existing width whenever at least one id with this prefix is already present.

Returns

list[str]

The generated ids, for example ["r_0001", "r_0002"].

get_elemental_balance#

get_elemental_balance(model: cobra.Model, reactions=None)

Check whether reactions are elementally balanced.

Parameters

model : cobra.Model

Model whose reactions are checked. It is not modified.

reactions : str or Reaction or Iterable or None

Reaction IDs or reaction objects to check; default all reactions. Boundary reactions exchange mass with the environment and are reported as unbalanced.

Returns

list of ElementalBalance

One entry per checked reaction, in model order.

GPRIssue#

A reaction whose GPR is flagged by the linter.

Attributes

reaction_id

ID of the reaction.

gpr

The (already cobra-normalised) grRule string.

reason

Human-readable explanation of why the reaction was flagged.

guess_composition#

guess_composition(model: cobra.Model, *, print_results: bool=True)

Infer missing metabolite formulas from elemental mass balance.

Modifies model in place: resolved metabolites get their formula (and elements) set. Metabolites sharing a name (for example the same compound in different compartments) are resolved and assigned together, since composition does not depend on compartment.

Parameters

model:

Model to fill in formulas for.

print_results:

Print each resolved metabolite's name and guessed formula.

Returns

GuessCompositionResult :

Notes

The result is correct only if the existing formulas and reactions are correct. A warning is issued if a metabolite would need inconsistent compositions from different reactions, so the function can also check a model for such errors. Wrong pre-existing formulas are not detected by a successful completion.

Each pass resolves formulas using a snapshot of what was already known at the start of that pass: a metabolite resolved earlier in the same pass only helps resolve others starting from the next pass, matching the original algorithm's own once-per-pass formula parsing.

A metabolite instance that does not participate in any reaction contributes nothing either way: it does not resolve the name and does not block a resolution reached through a different compartment instance.

GuessCompositionResult#

Result of guess_composition.

Attributes

guessed

Metabolite names a formula was assigned to.

could_not_guess

Metabolite names that had no formula before the call and still have none afterwards: either no resolving reaction was found, or different reactions implied inconsistent compositions.

is_dnf#

is_dnf(gpr: GPR | str | None)

Return whether a GPR is in disjunctive normal form (OR of AND-complexes).

Parameters

gpr

A cobra cobra.core.gene.GPR, a grRule string, or None. A string is read with parse_gr_rule. An empty or None rule is in DNF.

Raises

ValueError

If a rule string is not valid in the grammar of parse_gr_rule (unbalanced parentheses, a dangling operator, two genes without an operator between them, ()).

Examples

>>> is_dnf("(G1 and G2) or G3")
True
>>> is_dnf("(G1 or G2) and G3")
False

ModelIssue#

One curation issue found in a model.

Attributes

category

Machine-readable kind, for example "orphan_metabolite", "empty_reaction", "orphan_gene", "duplicate_name_compartment", "empty_metabolite_name", "objective".

object_id

ID of the offending object, or None for model-level issues.

message

Human-readable description.

next_ids#

next_ids(existing_ids: Iterable[str], prefix: str, quantity: int=1, num_length: int=4, *, label: str='entity')

The id sequence of generate_new_ids for a list of existing ids.

parse_gr_rule#

parse_gr_rule(rule: str | None)

Parse a grRule string in the grammar of RAVEN's parseGrRule.

The grammar, with AND binding tighter than OR::

expr   := term ( OR term )*
term   := factor ( AND factor )*
factor := gene | '(' expr ')'

AND is and in any case, & or &&; OR is or in any case, | or ||. Operators and brackets are separated from gene ids by whitespace or a bracket; any other word is a gene id. curate_model_from_tables/batch_curate, is_dnf and raven_toolbox.manipulation.gpr_to_dnf all read rules with this parser, so they accept and refuse the same rules as RAVEN.

Parameters

rule

A grRule such as "(G1 and G2) or G3".

Returns

GPR or None

The parsed rule; None for None, an empty or an all-blank rule.

Raises

ValueError

If the rule is malformed: an operator without an operand, unbalanced or empty parentheses, or two genes without an operator between them. The messages are those of RAVEN's RAVEN:badGrRule error.

parse_name_comp#

parse_name_comp(token: str)

Split a name[comp] token into (name, compartment).

This covers the part of the metcomps mode of RAVEN getIndexes and of addRxns eqnType 3 that cobra lacks: reading a metabolite written as its name plus a compartment in square brackets, for example "ATP[c]".

Returns (name, None) when there is no trailing [...].

Examples

>>> parse_name_comp("ATP[c]")
('ATP', 'c')
>>> parse_name_comp("ATP")
('ATP', None)
>>> parse_name_comp("weird[name][m]")
('weird[name]', 'm')

resolve_aggregators#

resolve_aggregators(isozyme_scoring: str, complex_scoring: str)

Validate the scoring-mode names and return (isozyme_fn, complex_fn).

Raises ValueError naming the offending argument if either mode is not one of AGGREGATORS.

reversible_orientation#

reversible_orientation(rxn: cobra.Reaction, met_index: dict[str, int])

-1 when a reversible reaction is written with its first metabolite (sorted by name and

compartment) as a product, so sort_reversible would reverse it; 1 otherwise.

rule_to_gpr#

rule_to_gpr(rule: str | None)

The cobra.core.gene.GPR of a rule string as parse_gr_rule reads it.

An empty or None rule gives an empty GPR. A rule that parse_gr_rule rejects is read with cobra's GPR.from_string.

rule_tokens#

rule_tokens(rule: str)

Split a gene rule into (kind, text) pairs.

The kind is (, ), and, or or gene.

A word is everything up to whitespace or a bracket, whitespace being the characters for which MATLAB's isspace is true (not U+00A0, U+0085, U+2007 or U+202F). The operators are and/or in any case and the symbols &, &&, | and ||, each as a whole word, as RAVEN's parseGrRule reads them; every other word is a gene id, so G1&G2 is one gene.

set_gene_rule#

set_gene_rule(rxn: cobra.Reaction, rule: GPR | str | None)

Give rxn a gene rule in RAVEN's grammar.

A cobra.core.gene.GPR is copied as it is; a string is read with rule_to_gpr. Assigning a string to rxn.gene_reaction_rule reads it with cobra's grammar, which splits a gene id such as G1&G2 into G1 and G2.

Callers include the functions of raven_toolbox.manipulation (add, change, compartments, expand, irreversible, merge, transfer), raven_toolbox.localization.assign, raven_toolbox.io.yaml, raven_toolbox.io.mat, raven_toolbox.init.genes, raven_toolbox.init.taskfill, raven_toolbox.reconstruction.homology.homology and raven_toolbox.reconstruction.kegg.assemble. The duplicate merge and group_linear_reactions in raven_toolbox.manipulation.simplify assign gene_reaction_rule directly, and raven_toolbox.curation.batch assigns gpr directly.

set_raven_tolerance#

set_raven_tolerance(model: cobra.Model, tolerance: float=RAVEN_TOLERANCE)

Set the solver tolerance of model to RAVEN's value.

cobra.Model.tolerance stays on the model when its solver is replaced and when it is copied. The model is changed in place and returned.

sort_identifiers#

sort_identifiers(model: cobra.Model)

Sort reactions, metabolites and genes alphabetically by ID, in place.

Returns the same model object. Compartments are a plain dict, which this function leaves unchanged; writers sort them as needed.

Parameters

model : cobra.Model

Model sorted in place.

sort_model#

sort_model(model: cobra.Model, *, sort_reversible: bool=False, sort_met_name: bool=False, sort_reaction_order: bool=False, seed: int | None=None)

Standardise the direction and order of reactions and metabolites, in place.

Mirrors RAVEN's sortModel. Returns the same (mutated) model.

Parameters

model

The model to sort.

sort_reversible

Reverse the stoichiometry of each reversible reaction whose metabolite that is first in sorted order of name + compartment is a product; that metabolite then is a reactant. Bounds are not changed. Ignored when sort_reaction_order is true.

sort_met_name

Order the metabolites of the model by name[compartment].

sort_reaction_order

Reorder the reactions of each subsystem with 2 to 250 reactions, and reverse reversible reactions, to maximise the number of metabolites that are produced before they are consumed (see subsystem_order_scores). A reaction that lists several subsystems takes part in each of them in turn. Reactions without a subsystem are not moved.

seed

Seed of the random generator of the reaction-order search; None draws fresh entropy.

Notes

The reaction-order search is the random pair-swap search of sortModel.m, with the same score and stop rule. It draws from a numpy generator, so the same seed gives a different permutation than in MATLAB; their scores can be compared. RAVEN positions the reactions of a later subsystem with indices found before the first subsystem is reordered; here the positions are found again after each subsystem, which gives the same result when no reaction lists several subsystems.

subsystem_order_scores#

subsystem_order_scores(model: cobra.Model)

Order score of every subsystem with 2 to 250 reactions, in the current reaction order.

The score is the number of metabolites of the subsystem that are produced by a reaction before the first reaction that consumes them (reaction directions as stored). It is the quantity that sort_model(..., sort_reaction_order=True) maximises.

Parameters

model : cobra.Model

Model whose reaction order is scored. It is not modified.

subsystem_to_str#

subsystem_to_str(value)

Convert a reaction subsystem to a str.

cobra defines Reaction.subsystem as a string. RAVEN, MATLAB and YAML input can supply a list or tuple of subsystem names, since a reaction can belong to several. A list or tuple becomes one string of its non-blank parts joined by ;. None gives ""; any other value is converted with str. The modules that render or compare subsystems call this function, so they handle subsystems identically.

Examples

>>> subsystem_to_str("glycolysis")
'glycolysis'
>>> subsystem_to_str(["glycolysis", "TCA cycle"])
'glycolysis;TCA cycle'
>>> subsystem_to_str(None)
''