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.

parse_name_comp

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

resolve_aggregators

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

sort_identifiers

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

subsystem_to_str

Coerce a reaction subsystem to cobra's canonical str form.

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.

ElementalBalance#

Balance result for one reaction.

Attributes

reaction_id

ID of the reaction.

status

"balanced" — elements balance; "unbalanced" — they do not (see imbalance); "unknown" — at least one metabolite has no formula, or a formula cobra cannot parse (e.g. the polymer (C5H8)n), so it cannot be determined (cobra would silently miscount the former and raise on the latter).

imbalance

Element → net coefficient (products − 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").

Uses cobra's GPR AST. Reactions with no GPR are skipped.

Returns

list of GPRIssue

One entry per flagged reaction, in model reaction order. Empty if all GPRs are simple OR-of-AND-complexes.

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, the prefix is stripped, and the numeric width and starting point are both taken from whatever the model already has for that prefix -- matching generateNewIds.m exactly, quirks included: the highest existing number is found by sorting the stripped ids as strings, not as integers, and num_length is overridden by the length of that string whenever at least one matching id already exists. For a model whose own ids for this prefix are all the same width (the normal case, e.g. every id zero-padded to 4 digits), a string sort of zero-padded numbers agrees with a numeric sort; it can disagree if a prefix mixes widths (rxn_1 alongside rxn_0002), the same as it would in RAVEN.

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, e.g. "s_" or "r_".

quantity

Number of new ids to generate.

num_length

Width of the zero-padded numeric part, e.g. 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, e.g. ["r_0001", "r_0002"].

get_elemental_balance#

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

Check whether reactions are elementally balanced.

Parameters

reactions

Reaction IDs/objects to check; default all reactions. (Boundary reactions exchange mass with the environment and will read as unbalanced — filter them out if that is not wanted.)

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 it 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 (e.g. 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

Requires that the existing formulas and reactions are correct, and warns if a metabolite would need inconsistent compositions from different reactions -- so it can also be used to check a model for such errors. Successful completion does not guarantee correctness if the pre-existing formulas were themselves wrong.

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 neither resolves the name nor blocks 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. An empty/None rule is trivially DNF.

Raises

ValueError

If a rule string is not valid (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, e.g. "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.

parse_name_comp#

parse_name_comp(token: str)

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

This is the one genuinely cobra-absent sliver of RAVEN getIndexes' metcomps mode and addRxns eqnType 3: resolving a metabolite written as its name plus a compartment in square brackets, e.g. "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.

sort_identifiers#

sort_identifiers(model: cobra.Model)

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

Returns the same (mutated) model for convenience. Compartments are a plain dict and are emitted sorted by writers as needed.

subsystem_to_str#

subsystem_to_str(value)

Coerce a reaction subsystem to cobra's canonical str form.

cobra defines Reaction.subsystem as a plain string, but RAVEN/MATLAB and "messy" YAML sometimes deliver a list/tuple of subsystem names (a reaction can belong to several). This collapses any such value to a single ;-joined string of its parts — losing no data, unlike taking only the first — and returns "" for an empty/None subsystem. Used wherever a subsystem is rendered or compared so the handling is identical across modules.

Examples

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