Input / output (Python)#
raven-toolbox objects in raven_toolbox.io.
Functions#
Function |
Summary |
|---|---|
Build an |
|
Serialise an |
|
Typed enzyme-constrained ecModel substructure attached as |
|
Write |
|
Write |
|
All metadata of the model as a plain dict (a copy). |
|
Build a |
|
Read a model structure from a MATLAB |
|
Read a RAVEN/cobrapy YAML model into a |
|
Set the version, date and descriptive fields that the YAML export writes, in place. |
|
Write |
|
Write a |
Reference#
ec_data_from_yaml_sections#
ec_data_from_yaml_sections(sections: dict)
Build an EcData from the ec-* top-level YAML sections.
Returns None when ec-rxns and ec-enzymes are both absent; the
caller then leaves model.ec = None. Raises ValueError when exactly one
of the two is present.
sections is the dict of foreign top-level keys captured by the YAML
loader. gecko_light defaults to False when the key is absent.
ec_data_to_yaml_sections#
ec_data_to_yaml_sections(ec: EcData)
Serialise an EcData to a dict suitable for YAML emission.
Returns a fresh dict with three keys: gecko_light (bool),
ec-rxns (list of mappings), ec-enzymes (list of mappings).
Values are native Python primitives (no numpy or ruamel scalars), so the YAML
writer can dump them directly.
Empty optional fields are omitted; the loader restores them.
EcData#
Typed enzyme-constrained ecModel substructure attached as model.ec.
Field semantics match MATLAB GECKO's model.ec struct one-to-one.
The fields form two parallel index spaces:
per-reaction arrays (
rxns,kcat,source,notes,eccodes) of lengthn_rxns;per-enzyme arrays (
genes,enzymes,mw,sequence,concs) of lengthn_enzymes.
The sparse rxn_enz_mat of shape (n_rxns, n_enzymes) connects the two spaces.
Its [i, j] entry is the subunit count of enzyme j in reaction i (0 or 1 for
single enzymes, above 1 for heteromeric complexes).
Sentinels (as in MATLAB GECKO):
kcat == 0means "no kcat assigned" (real turnover numbers are positive).mw == nanmeans "MW unknown" (the writer omits NaN mw entries).concs == nanmeans "not measured" (the writer omits NaN concs).empty strings in
source/notes/eccodes/sequenceare omitted on write and restored as""on load.
gecko_light marks the gecko-light layout: cobra reactions stay
singular, ec.rxns carries one entry per isozyme distinguished by a
###_ counter prefix, and the per-enzyme prot_<id> and usage reactions
are omitted in favour of the shared protein pool. False (default) is the
full layout, where ec.rxns matches cobra reactions
one-to-one after isozyme expansion.
export_for_git#
export_for_git(model: cobra.Model, path: str | Path='.', *, prefix: str='model', formats: Iterable[str]=_ALL_FORMATS, main_branch_flag: bool=False, sub_dirs: bool=True, varname: str | None=None, version: str | None=None, date: str | datetime.date | None=None)
Write model into a Standard-GEM repository layout.
Parameters
model: cobra.ModelModel to export. A sorted copy is written; the model passed in is not changed.
path: str or PathDirectory to populate.
prefix: strBase filename for every format (default
"model").formats: Iterable of strWhich formats to write; any of
"yml","xml","mat","xlsx","txt"(default: all five, as RAVEN'sexportForGit).main_branch_flag: boolA
bool. If True, raiseRuntimeErrorwhen raven_toolbox runs from a git checkout that is not onmainormaster(default False), as RAVEN'smainBranchFlag. The check passes when the package is not in a raven_toolbox checkout (for example a pip installation) and when git is missing or refuses the checkout (OSErroror a failinggitcall such assafe.directory). GECKO is not checked.sub_dirs: boolA
bool. If True (default), writemodel/<fmt>/<prefix>.<fmt>(standard-GEM layout); otherwise all files go directly inpath.varname: str or NoneVariable name for the MATLAB (
.mat) struct.None(default) lets cobra use its own default (the model id); set it when a repository pins a specific name (for example Human-GEM'shumanGEM).version: str or NoneVersion stamped into the exported copy's metadata (see
raven_toolbox.io.set_model_metadata); the model passed in is not changed. When not given, the model's own version is written.date: str or datetime.date or NoneDate stamped into the exported copy's metadata in the same way. When not given, the model's own date is written.
Returns
pathlib.PathThe root directory written to.
Raises
TypeErrorIf
main_branch_flagorsub_dirsis not aboolornumpy.bool_.
export_to_excel#
export_to_excel(model: cobra.Model, path: str | Path, *, sort_ids: bool=False)
Write model to a RAVEN-format .xlsx file.
For enzyme-constrained models (a populated raven_toolbox.io.EcData
on model.ec), two further export-only sheets are written: ENZYMES (one
row per enzyme) and ENZRXNS (one row per ec-reaction).
Parameters
model: cobra.ModelModel to export.
path: str or PathOutput file path; the workbook is saved to it (
strorpathlib.Path).sort_ids: boolIf True, write reactions, metabolites and genes sorted alphabetically by ID (the model itself is not modified); compartments are sorted by abbreviation. The ec sheets keep the order of the ec data.
get_model_metadata#
get_model_metadata(model: cobra.Model)
All metadata of the model as a plain dict (a copy).
The dict holds version, date and the descriptive fields, and any other entry that
read_yaml_model put in metaData (for example id, name and the
default bounds). version is taken from notes["version"], falling back to
notes["metaData"], the same order write_yaml_model uses. Fields the model
does not carry are absent.
Parameters
model: cobra.ModelModel whose
notesare read. The model is not changed.
model_from_yaml_data#
model_from_yaml_data(raw: dict)
Build a cobra.Model from an already-parsed RAVEN/cobrapy YAML dict.
Performs three jobs in order:
cobra-shaped portion: strips and restores RAVEN-only per-entry side-fields onto each entry's
.notes; liftsid/nameout of legacymetaData; preservesversionandmetaDataonmodel.notesfor round-trip.legacy quirks: lifts per-metabolite top-level
smilesintoannotation['smiles']and per-reaction top-leveleccodesintoannotation['ec-code'](older RAVEN/MATLAB GECKO files emitted these at the top level); flips the older reverse-directionusage_prot_*/prot_pool_exchangeconvention to the forward convention.GECKO ec sections: when
ec-rxns/ec-enzymesare present, parses them into a typedEcDataand attaches it asmodel.ec. Other unknown top-level keys land opaquely onmodel.notes['_yaml_sections']for round-trip.
raw is mutated in place — copy it first if the caller needs the
original.
read_matlab_model#
read_matlab_model(path: str | Path, *, varname: str | None=None)
Read a model structure from a MATLAB .mat file.
Reads a RAVEN structure natively. A COBRA Toolbox structure is recognised
and handed to cobra's own reader instead, so a file written by
save_matlab_model — Human-GEM 2.0.1 and 2.1.0 shipped one — is read
rather than silently coming back without its identifier, EC codes, gene
names and cross-references. A struct that is neither raises.
The inverse of write_matlab_model: RAVEN-only fields land where
read_yaml_model puts the same data, so a model read from either
format looks the same to the rest of raven-toolbox — cross-references in
annotation, metFrom/rxnFrom/notes/references/deltaG and
inchis in notes, and the model's own metadata in
notes["metaData"] and notes["version"].
Parameters
pathFile to read.
varnameName of the struct to read. Defaults to the file's only struct variable; required when the file holds more than one.
Returns
cobra.Model
:
read_yaml_model#
read_yaml_model(path: str | Path)
Read a RAVEN/cobrapy YAML model into a cobra.Model.
Convenience wrapper around model_from_yaml_data that opens the
file (transparently un-gzipping .gz) and parses the YAML. Callers
that need to pre-process the document (e.g. lift further non-standard
fields that cobra doesn't recognise) can read+normalise themselves and
call model_from_yaml_data with the resulting dict.
Accepts both the cobra !!omap shape and a very old RAVEN shape where
the document root is a bare - sequence of single-key mappings; the
latter is merged into one mapping before parsing.
Parameters
path: str or pathlib.PathPath of the YAML file. A path ending in
.gzis read as gzip-compressed text.
set_model_metadata#
set_model_metadata(model: cobra.Model, *, version: str | None=None, date: str | datetime.date | None=None, **fields: str)
Set the version, date and descriptive fields that the YAML export writes, in place.
Parameters
model: cobra.ModelModel whose
notes["version"]andnotes["metaData"]are updated in place.version: str or NoneModel version, for example
"1.2.0".date: str or datetime.date or NoneModel date, as
YYYY-MM-DDor adatetime.date(adatetimeis reduced to its date). Any other value raisesValueError. The YAML writer stamps today's date only when the model has none.**fields: strDescriptive
metaDatafields:givenName,familyName,authors,email,organization,taxonomy,noteandsourceUrl.
Arguments left out are not touched.
:
write_matlab_model#
write_matlab_model(model: cobra.Model, path: str | Path, *, varname: str | None=None)
Write model as a RAVEN model structure in a MATLAB .mat file.
Parameters
modelThe model to write.
pathDestination file.
varnameName of the struct inside the file. Defaults to the model's id; set it when a repository pins a specific name (Human-GEM's
humanGEM).
Returns
pathlib.PathThe file written.
write_yaml_model#
write_yaml_model(model: cobra.Model, path: str | Path, *, sort_ids: bool=False)
Write a cobra.Model to RAVEN/cobrapy (!!omap) YAML.
When model.ec is a populated EcData, the gecko_light
flag and the ec-rxns / ec-enzymes top-level sections are
emitted from it (numpy/ruamel scalars are coerced to plain Python
primitives en route, so the dumper never sees them).
With sort_ids=True metabolites/reactions/genes/compartments are
written in alphabetical order (diff-friendly), without modifying
model.
Parameters
model: cobra.ModelModel to write.
path: str or pathlib.PathOutput file path. A path ending in
.gzis written as gzip-compressed text.sort_ids: boolWhether to write entries in alphabetical order of their ids. The default is
False.