diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3ac5c..8784e4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ * `get_model_from_homology` with `preferred_order` treats a template gene that maps to a gene an earlier template already maps as a subunit without an ortholog, and `complex_policy` decides what happens to it (was: the gene and every part of the rule that needs it were removed). For the rule `(a and b) or x` with `a` taken by an earlier template, `flag` gives `(OLD_T2_a and nb) or nx`, `keep` gives `nb or nx` and `drop` gives `nx`. A reaction that has genes, none of which keeps a mapping, is not transferred. * `get_model_from_homology` with `complex_policy="drop"` removes each complex that has a subunit without an ortholog, and removes the reaction only when no complex remains (was: the reaction was removed as soon as one subunit had no ortholog). For the rule `(A and B) or (C and D)` without an ortholog of `B`, the draft has `C and D`. * `manipulation.contract_model` is the new name of `remove_duplicate_reactions`, after RAVEN's `contractModel`, and the old name is removed. `contract_model` takes `dist_reverse` (default `True`), the `distReverse` option of `contractModel`: with `False`, reactions with the same metabolites and a different reversibility are duplicates. +* The SBML file of `export_for_git` writes the protein of a gene as `fbc:name` and the gene short name as `fbc:label`, as RAVEN's `exportModel` does, so cobra reads the protein as the gene name (was: the gene short name as both, and the protein as a note). +* `export_for_git` lists only the toolchain in `dependencies.txt`, as RAVEN's `exportForGit` does, and lists `model_version` and `model_date` only with `model_version_in_dependencies=True` (was: always). +* The SBML file of `export_for_git` holds the model version and date as notes only with `model_version_in_sbml=True`, because RAVEN's `exportModel` writes neither (was: always). +* The SBML file of `export_for_git` writes the model note as the first paragraph of a body element, without the `note:` label, as RAVEN's `exportModel` does, so RAVEN's `importModel` reads it as `annotation.note` and cobra no longer reads it as `notes["note"]` (was: `
note: ...
` in an html element, which `importModel` does not read). + +### Model I/O + +* The SBML file of `export_for_git` writes the model id as RAVEN's `exportModel` does, each character outside `[0-9_a-zA-Z]` as `____`, so an id such as `ecoliGEM_v1.0.7` is written (was: no `id` attribute for an id that is not a valid SBML SId). Each gene product that has no SBO term of its own gets `SBO:0000243`.
+* `export_to_excel`, `write_matlab_model` and the SBML file of `export_for_git` list the compartments sorted by abbreviation (was: in the order in which the metabolites first mention them; `export_to_excel` sorted them only with `sort_ids=True`).
+* The SBML file of `export_for_git` escapes `&`, `<` and `>` in the model notes (was: cobra dropped all model notes from the file when one of them held such a character, and only logged an error).
### Data
diff --git a/src/raven_toolbox/io/excel.py b/src/raven_toolbox/io/excel.py
index ff56bed..a738f32 100644
--- a/src/raven_toolbox/io/excel.py
+++ b/src/raven_toolbox/io/excel.py
@@ -140,8 +140,9 @@ def export_to_excel(
Output file path; the workbook is saved to it (``str`` or ``pathlib.Path``).
sort_ids : bool
If 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.
+ (the model itself is not modified). The compartments are always written sorted by
+ abbreviation, because cobra lists them in the order in which the metabolites first
+ mention them. The ec sheets keep the order of the ec data.
"""
try:
from openpyxl import Workbook
@@ -201,7 +202,7 @@ def export_to_excel(
# --- COMPS ---
ws = wb.create_sheet("COMPS")
ws.append(["#", "ABBREVIATION", "NAME", "INSIDE", "MIRIAM"])
- comps = sorted(model.compartments) if sort_ids else list(model.compartments)
+ comps = sorted(model.compartments)
for cid in comps:
ws.append([None, cid, model.compartments.get(cid, ""), None, None])
diff --git a/src/raven_toolbox/io/git.py b/src/raven_toolbox/io/git.py
index 1d46206..7d9c669 100644
--- a/src/raven_toolbox/io/git.py
+++ b/src/raven_toolbox/io/git.py
@@ -18,6 +18,7 @@
import subprocess
from collections.abc import Iterable
from pathlib import Path
+from xml.sax.saxutils import escape
import cobra
import libsbml
@@ -50,8 +51,21 @@ def _version(package: str) -> str:
"confidence_score": "Confidence Level",
}
+# RAVEN's exportModel writes each character of the model id outside [0-9_a-zA-Z] as
+# ____ and importModel decodes it again. cobra passes the model id to libSBML
+# unchanged, and libSBML writes no id attribute for an id that is not a valid SId.
+_SBML_ID_UNSAFE = re.compile(r"[^0-9_a-zA-Z]")
-def _for_sbml(model: cobra.Model) -> cobra.Model:
+# The SBO term RAVEN's exportModel gives every gene product that has no SBO term of its own.
+_SBO_GENE_PRODUCT = "SBO:0000243"
+
+
+def _sbml_id(identifier: str) -> str:
+ """``identifier`` with each character outside [0-9_a-zA-Z] written as ``____``."""
+ return _SBML_ID_UNSAFE.sub(lambda match: f"__{ord(match.group())}__", identifier)
+
+
+def _for_sbml(model: cobra.Model, *, model_version: bool = False) -> cobra.Model:
"""A copy of ``model`` shaped so RAVEN's importModel finds everything.
Two kinds of information would be missing from the SBML file otherwise:
@@ -63,10 +77,24 @@ def _for_sbml(model: cobra.Model) -> cobra.Model:
* **rxnNotes, rxnReferences and rxnConfidenceScores.** The file contains them under
cobra's key names, while RAVEN parses other labels.
+ The model id is escaped as in RAVEN's exportModel, each gene gets the SBO term
+ ``SBO:0000243`` unless it has one of its own, and the protein of a gene leaves the gene's
+ notes because :func:`_write_sbml` writes it as ``fbc:name``. The model version and date
+ become notes only with ``model_version``, because RAVEN's exportModel writes neither.
+
The model passed in is not changed.
"""
out = model.copy()
+ if out.id:
+ out.id = _sbml_id(out.id)
+
+ for gene in out.genes:
+ # model.copy() shares each gene's notes and annotation dicts with the original, so the
+ # copy gets new dicts instead of changes in place.
+ gene.annotation = {"sbo": _SBO_GENE_PRODUCT, **gene.annotation}
+ gene.notes = {key: value for key, value in (gene.notes or {}).items() if key != "protein"}
+
for rxn in out.reactions:
notes = rxn.notes or {}
renamed = {_SBML_NOTE_LABELS.get(key, key): value for key, value in notes.items()}
@@ -82,18 +110,16 @@ def _for_sbml(model: cobra.Model) -> cobra.Model:
annotation["taxonomy"] = str(taxonomy).replace("taxonomy/", "")
out.annotation = annotation
- # The model's own note goes in as its own notes entry, so cobra writes it
- # as "note: ...
". RAVEN's exportModel instead puts a bare note
- # inside a that cobra never emits, which is why importModel has to
- # look for both shapes.
- # The note, version and date go in as their own notes entries, so cobra
- # writes each as "key: value
". RAVEN's exportModel instead puts a
- # bare note inside a that cobra never emits, which is why
- # importModel has to look for both shapes; the version and date reached
- # the file only inside the metaData repr dropped below.
+ # The model's own note goes in as the notes entry "note", which _write_model_notes
+ # writes in the body shape that RAVEN's importModel reads. RAVEN's exportModel writes
+ # no version and no date, so they are notes only on request.
stamped = dict(out.notes or {})
- for key in ("note", "version", "date"):
- if meta.get(key) and key not in stamped:
+ if meta.get("note") and "note" not in stamped:
+ stamped["note"] = str(meta["note"])
+ for key in ("version", "date"):
+ if not model_version:
+ stamped.pop(key, None)
+ elif meta.get(key) and key not in stamped:
stamped[key] = str(meta[key])
out.notes = stamped
@@ -131,20 +157,78 @@ def _for_sbml(model: cobra.Model) -> cobra.Model:
return out
-def _write_sbml(model: cobra.Model, path: Path) -> None:
- """Write ``model`` as SBML with each gene product's fbc:label set to the gene name.
+def _sort_sbml_compartments(sbml_model: libsbml.Model) -> None:
+ """Order the compartments of ``sbml_model`` by id.
- cobra's writer sets fbc:label to the gene product id (``G_``), while RAVEN's
- exportModel writes the gene short name there, and RAVEN's importModel reads
- geneShortNames from fbc:label before fbc:name. cobra writes the gene name as
- fbc:name, or the id when the gene has no name, so copying fbc:name into fbc:label
- keeps the id as label for unnamed genes. cobra reads gene ids from fbc:id and
- names from fbc:name, so the label does not change what cobra reads back.
+ cobra writes them in the order in which the metabolites first mention them.
"""
- cobra.io.write_sbml_model(_for_sbml(model), str(path))
+ compartments = sorted(
+ (compartment.clone() for compartment in sbml_model.getListOfCompartments()),
+ key=lambda compartment: compartment.getId(),
+ )
+ while sbml_model.getNumCompartments():
+ sbml_model.removeCompartment(0)
+ for compartment in compartments:
+ sbml_model.addCompartment(compartment)
+
+
+def _write_model_notes(sbml_model: libsbml.Model, notes: dict[str, str]) -> None:
+ """Write the model notes the way RAVEN's exportModel and importModel handle them.
+
+ RAVEN's exportModel writes the model note as a bare paragraph in a body element, and
+ importModel reads a model note only from that shape, while cobra wraps its notes in an
+ html element and writes them without escaping. With a model note, the note is the first
+ paragraph in a body element, as RAVEN writes it, and the other notes follow as
+ ``key: value`` paragraphs, which cobra reads and RAVEN adds to its note. Without a model
+ note, the notes stay in cobra's html element, which RAVEN does not read as its note.
+ """
+ if not notes:
+ return
+ note = notes.get("note")
+ paragraphs = [f"{escape(key)}: {escape(value)}" for key, value in notes.items() if key != "note"]
+ if note:
+ paragraphs.insert(0, escape(note))
+ tag = "body"
+ else:
+ tag = "html"
+ xhtml = f'<{tag} xmlns="http://www.w3.org/1999/xhtml">'
+ xhtml += "".join(f"{paragraph}
" for paragraph in paragraphs) + f"{tag}>"
+ if sbml_model.setNotes(xhtml) != libsbml.LIBSBML_OPERATION_SUCCESS:
+ raise RuntimeError("libSBML did not accept the model notes")
+
+
+def _write_sbml(model: cobra.Model, path: Path, *, model_version: bool = False) -> None:
+ """Write ``model`` as SBML in the shape of RAVEN's exportModel.
+
+ Each gene product gets the protein as fbc:name, as RAVEN writes it, and no fbc:name
+ when the gene has no protein; RAVEN's importModel reads proteins from fbc:name. The
+ gene short name, or the gene id when there is none, goes into fbc:label, from which
+ importModel reads geneShortNames; cobra reads gene names from fbc:name, so the label
+ does not change what cobra reads back. The compartments are ordered by id, as in
+ RAVEN's sortIdentifiers. The model notes are written by :func:`_write_model_notes`; the
+ model version and date are notes only with ``model_version``.
+ """
+ shaped = _for_sbml(model, model_version=model_version)
+ notes = dict(shaped.notes or {})
+ shaped.notes = {} # cobra writes notes without escaping them
+ cobra.io.write_sbml_model(shaped, str(path))
doc = libsbml.readSBMLFromFile(str(path))
- for gene_product in doc.getModel().getPlugin("fbc").getListOfGeneProducts():
- gene_product.setLabel(gene_product.getName())
+ sbml_model = doc.getModel()
+ _write_model_notes(sbml_model, notes)
+ products = sbml_model.getPlugin("fbc").getListOfGeneProducts()
+ if len(products) != len(model.genes):
+ raise RuntimeError(
+ f"the SBML has {len(products)} gene products for {len(model.genes)} genes"
+ )
+ # cobra writes the gene products in the order of model.genes.
+ for gene, product in zip(model.genes, products, strict=True):
+ protein = (gene.notes or {}).get("protein")
+ product.setLabel(gene.name or gene.id)
+ if protein:
+ product.setName(str(protein))
+ else:
+ product.unsetName()
+ _sort_sbml_compartments(sbml_model)
libsbml.writeSBMLToFile(doc, str(path))
@@ -182,11 +266,12 @@ def _write_txt(model: cobra.Model, path: Path) -> None:
)
-def _write_dependencies(path: Path, model: cobra.Model) -> None:
- """Versions of everything that writes the files, then the model's own version and date.
+def _write_dependencies(path: Path, model: cobra.Model, *, model_version: bool = False) -> None:
+ """Versions of everything that writes the files, then optionally the model's version and date.
The order is fixed and nothing depends on the time of the export, so the same model
- exported twice gives the same file.
+ exported twice gives the same file. With ``model_version`` false the file lists the
+ toolchain only, as RAVEN's exportForGit does.
"""
lines = [
("python", platform.python_version()),
@@ -197,10 +282,11 @@ def _write_dependencies(path: Path, model: cobra.Model) -> None:
("openpyxl", _version("openpyxl")),
("raven_toolbox", _version("raven_toolbox")),
]
- meta = get_model_metadata(model)
- for key in ("version", "date"):
- if meta.get(key) is not None:
- lines.append((f"model_{key}", str(meta[key])))
+ if model_version:
+ meta = get_model_metadata(model)
+ for key in ("version", "date"):
+ if meta.get(key) is not None:
+ lines.append((f"model_{key}", str(meta[key])))
with open(path, "w", encoding="utf-8") as fh:
for name, value in lines:
fh.write(f"{name}\t{value}\n")
@@ -249,6 +335,8 @@ def export_for_git(
varname: str | None = None,
version: str | None = None,
date: str | datetime.date | None = None,
+ model_version_in_dependencies: bool = False,
+ model_version_in_sbml: bool = False,
) -> Path:
"""Write ``model`` into a Standard-GEM repository layout.
@@ -284,6 +372,15 @@ def export_for_git(
date : str or datetime.date or None
Date stamped into the exported copy's metadata in the same way. When not given, the
model's own date is written.
+ model_version_in_dependencies : bool
+ A ``bool``. If True, ``dependencies.txt`` also lists ``model_version`` and
+ ``model_date`` from the model metadata. The default (False) lists the toolchain
+ only, as RAVEN's ``exportForGit`` does.
+ model_version_in_sbml : bool
+ A ``bool``. If True, the SBML file also holds the model version and date as notes
+ (``version: ...
``), which cobra reads. The default (False) writes neither, as
+ RAVEN's ``exportModel`` does; RAVEN keeps the version in the model id only. With a
+ model note, RAVEN's ``importModel`` appends the two notes to its model note.
Returns
-------
@@ -293,9 +390,15 @@ def export_for_git(
Raises
------
TypeError
- If ``main_branch_flag`` or ``sub_dirs`` is not a ``bool`` or ``numpy.bool_``.
+ If ``main_branch_flag``, ``sub_dirs``, ``model_version_in_dependencies`` or
+ ``model_version_in_sbml`` is not a ``bool`` or ``numpy.bool_``.
"""
- for name, flag in (("main_branch_flag", main_branch_flag), ("sub_dirs", sub_dirs)):
+ for name, flag in (
+ ("main_branch_flag", main_branch_flag),
+ ("sub_dirs", sub_dirs),
+ ("model_version_in_dependencies", model_version_in_dependencies),
+ ("model_version_in_sbml", model_version_in_sbml),
+ ):
if not isinstance(flag, (bool, np.bool_)):
raise TypeError(
f"{name} must be a bool or numpy.bool_, got {type(flag).__module__}.{type(flag).__qualname__}"
@@ -323,7 +426,7 @@ def target(fmt: str) -> Path:
if "yml" in formats:
write_yaml_model(model, target("yml"))
if "xml" in formats:
- _write_sbml(model, target("xml"))
+ _write_sbml(model, target("xml"), model_version=model_version_in_sbml)
if "mat" in formats:
write_matlab_model(model, target("mat"), varname=varname)
if "xlsx" in formats:
@@ -331,6 +434,6 @@ def target(fmt: str) -> Path:
if "txt" in formats:
_write_txt(model, target("txt"))
- _write_dependencies(root / "dependencies.txt", model)
+ _write_dependencies(root / "dependencies.txt", model, model_version=model_version_in_dependencies)
return root
diff --git a/src/raven_toolbox/io/mat.py b/src/raven_toolbox/io/mat.py
index 98b04e7..aca9e1b 100644
--- a/src/raven_toolbox/io/mat.py
+++ b/src/raven_toolbox/io/mat.py
@@ -217,7 +217,8 @@ def _model_struct(model: cobra.Model) -> dict:
rxns = list(model.reactions)
mets = list(model.metabolites)
genes = list(model.genes)
- comps = list(model.compartments)
+ # cobra lists the compartments in the order in which the metabolites first mention them.
+ comps = sorted(model.compartments)
meta = get_model_metadata(model)
struct: dict = {}
diff --git a/tests/test_io_git.py b/tests/test_io_git.py
index 8655b7c..b5b21ca 100644
--- a/tests/test_io_git.py
+++ b/tests/test_io_git.py
@@ -93,10 +93,17 @@ def test_all_five_formats_are_written_by_default(model, tmp_path):
assert (root / fmt / f"model.{fmt}").exists()
+def test_dependencies_list_the_toolchain_only_by_default(model, tmp_path):
+ set_model_metadata(model, version="1.2.0", date="2026-10-05")
+ root = export_for_git(model, tmp_path, formats=("yml",))
+ names = [line.split("\t")[0] for line in (root / "dependencies.txt").read_text().splitlines()]
+ assert names == ["python", "cobra", "libSBML", "ruamel.yaml", "scipy", "openpyxl", "raven_toolbox"]
+
+
def test_dependencies_are_ordered_and_repeatable(model, tmp_path):
set_model_metadata(model, version="1.2.0", date="2026-10-05")
- first = export_for_git(model, tmp_path / "a", formats=("yml",))
- second = export_for_git(model, tmp_path / "b", formats=("yml",))
+ first = export_for_git(model, tmp_path / "a", formats=("yml",), model_version_in_dependencies=True)
+ second = export_for_git(model, tmp_path / "b", formats=("yml",), model_version_in_dependencies=True)
text = (first / "dependencies.txt").read_text()
assert text == (second / "dependencies.txt").read_text()
names = [line.split("\t")[0] for line in text.splitlines()]
@@ -107,7 +114,9 @@ def test_dependencies_are_ordered_and_repeatable(model, tmp_path):
assert "model_version\t1.2.0" in text
-@pytest.mark.parametrize("flag", ["main_branch_flag", "sub_dirs"])
+@pytest.mark.parametrize(
+ "flag", ["main_branch_flag", "sub_dirs", "model_version_in_dependencies", "model_version_in_sbml"]
+)
@pytest.mark.parametrize("value", ["false", "true", "", 0, 1, None])
def test_export_for_git_refuses_a_flag_that_is_not_a_bool(model, tmp_path, flag, value):
with pytest.raises(TypeError, match=flag):
@@ -235,7 +244,10 @@ def _consistency(path):
def test_sbml_gene_label_is_the_gene_name(model, tmp_path):
- """RAVEN's importModel reads geneShortNames from fbc:label before fbc:name."""
+ """RAVEN's importModel reads geneShortNames from fbc:label and proteins from fbc:name.
+
+ A gene without a protein has no fbc:name, and its label is the short name or the gene id.
+ """
model.reactions.R1.gene_reaction_rule = "ENSG1 or ENSG2"
model.genes.ENSG1.name = "DPM1"
root = export_for_git(model, tmp_path, formats=("xml",))
@@ -244,19 +256,30 @@ def test_sbml_gene_label_is_the_gene_name(model, tmp_path):
doc = libsbml.readSBMLFromFile(str(path))
products = doc.getModel().getPlugin("fbc").getListOfGeneProducts()
labels = {gp.getId(): (gp.getName(), gp.getLabel()) for gp in products}
- assert labels == {"G_ENSG1": ("DPM1", "DPM1"), "G_ENSG2": ("G_ENSG2", "G_ENSG2")}
+ assert labels == {"G_ENSG1": ("", "DPM1"), "G_ENSG2": ("", "ENSG2")}
plain = tmp_path / "plain.xml"
cobra.io.write_sbml_model(_for_sbml(model), str(plain))
assert _consistency(path) == _consistency(plain)
- back, plain_back = cobra.io.read_sbml_model(str(path)), cobra.io.read_sbml_model(str(plain))
- assert sorted((g.id, g.name) for g in back.genes) == sorted(
- (g.id, g.name) for g in plain_back.genes
- )
+ back = cobra.io.read_sbml_model(str(path))
+ assert sorted(g.id for g in back.genes) == ["ENSG1", "ENSG2"]
assert back.reactions.R1.gene_reaction_rule == "ENSG1 or ENSG2"
+def test_sbml_protein_is_the_gene_product_name(model, tmp_path):
+ model.reactions.R1.gene_reaction_rule = "ENSG1 or ENSG2"
+ model.genes.ENSG1.name = "DPM1"
+ model.genes.ENSG1.notes = {"protein": "dolichol-phosphate mannosyltransferase"}
+ root = export_for_git(model, tmp_path, formats=("xml",))
+ doc = libsbml.readSBMLFromFile(str(root / "xml" / "model.xml"))
+ products = {gp.getId(): gp for gp in doc.getModel().getPlugin("fbc").getListOfGeneProducts()}
+ assert products["G_ENSG1"].getName() == "dolichol-phosphate mannosyltransferase"
+ assert products["G_ENSG1"].getLabel() == "DPM1"
+ assert not products["G_ENSG2"].isSetName()
+ assert model.genes.ENSG1.notes == {"protein": "dolichol-phosphate mannosyltransferase"}
+
+
def test_equation_leaves_out_a_coefficient_of_one(model, tmp_path):
model.reactions.get_by_id("R1").add_metabolites({model.metabolites.atp_c: -1})
root = export_for_git(model, tmp_path, formats=("txt",))
@@ -378,7 +401,9 @@ def test_main_branch_check_raises_with_layout_and_project_name(tmp_path):
assert out.returncode != 0 and "feature" in out.stderr
-@pytest.mark.parametrize("flag", ["main_branch_flag", "sub_dirs"])
+@pytest.mark.parametrize(
+ "flag", ["main_branch_flag", "sub_dirs", "model_version_in_dependencies", "model_version_in_sbml"]
+)
def test_export_for_git_accepts_numpy_booleans(model, tmp_path, flag):
import numpy as np
diff --git a/tests/test_io_git_raven_parity.py b/tests/test_io_git_raven_parity.py
new file mode 100644
index 0000000..bc37348
--- /dev/null
+++ b/tests/test_io_git_raven_parity.py
@@ -0,0 +1,200 @@
+"""The files export_for_git writes follow RAVEN's exportForGit where RAVEN's importModel reads them.
+
+The toy model has a model id that is not a valid SBML SId, three genes (a protein and a short name,
+a short name only, neither) and compartments that cobra lists as c, p, e.
+"""
+import re
+
+import cobra
+import libsbml
+import openpyxl
+import pytest
+import scipy.io as sio
+
+from raven_toolbox.io import export_for_git
+from raven_toolbox.io.metadata import set_model_metadata
+
+
+def _model(model_id: str = "toy_v1.0.0") -> cobra.Model:
+ m = cobra.Model(model_id)
+ m.compartments = {"c": "cytosol", "e": "extracellular space", "p": "periplasm"}
+ x_c, x_p, y_e = (cobra.Metabolite(i, name=i[0], compartment=i[-1]) for i in ("x_c", "x_p", "y_e"))
+ r1, r2 = cobra.Reaction("R1"), cobra.Reaction("R2")
+ m.add_reactions([r1, r2])
+ r1.add_metabolites({x_c: -1, x_p: 1})
+ r2.add_metabolites({x_p: -1, y_e: 1})
+ r1.gene_reaction_rule = "g1 and (g2 or g3)"
+ g1, g2 = m.genes.get_by_id("g1"), m.genes.get_by_id("g2")
+ g1.name, g1.notes = "short1", {"protein": "Pg1"}
+ g2.name = "short2"
+ m.notes = {"version": "1.0.7"}
+ return m
+
+
+@pytest.fixture
+def out(tmp_path):
+ return export_for_git(_model(), tmp_path, prefix="toy", sub_dirs=False)
+
+
+# libSBML frees a model together with its document, so the document must outlive the test.
+_KEEP_ALIVE = []
+
+
+def _sbml(root):
+ doc = libsbml.readSBMLFromFile(str(root / "toy.xml"))
+ _KEEP_ALIVE.append(doc)
+ return doc.getModel()
+
+
+def _products(root):
+ return {p.getId(): p for p in _sbml(root).getPlugin("fbc").getListOfGeneProducts()}
+
+
+def test_model_id_is_escaped_as_in_ravens_exportmodel(out):
+ assert _sbml(out).getIdAttribute() == "toy_v1__46__0__46__0"
+
+
+def test_model_id_that_is_a_valid_sid_is_unchanged(tmp_path):
+ root = export_for_git(_model("plain_id"), tmp_path, prefix="toy", sub_dirs=False, formats=("xml",))
+ assert _sbml(root).getIdAttribute() == "plain_id"
+
+
+def test_gene_product_name_is_the_protein_and_label_the_short_name_or_gene_id(out):
+ products = _products(out)
+ assert (products["G_g1"].getName(), products["G_g1"].getLabel()) == ("Pg1", "short1")
+ assert (products["G_g2"].isSetName(), products["G_g2"].getLabel()) == (False, "short2")
+ assert (products["G_g3"].isSetName(), products["G_g3"].getLabel()) == (False, "g3")
+
+
+def test_protein_is_not_also_written_as_a_note(out):
+ assert "protein:" not in (out / "toy.xml").read_text(encoding="utf-8")
+
+
+def test_gene_products_carry_sbo_243(out):
+ assert {p.getSBOTermID() for p in _products(out).values()} == {"SBO:0000243"}
+
+
+def test_own_sbo_term_of_a_gene_is_kept(tmp_path):
+ m = _model()
+ m.genes.get_by_id("g2").annotation["sbo"] = "SBO:0000010"
+ root = export_for_git(m, tmp_path, prefix="toy", sub_dirs=False, formats=("xml",))
+ products = _products(root)
+ assert products["G_g2"].getSBOTermID() == "SBO:0000010"
+ assert products["G_g1"].getSBOTermID() == "SBO:0000243"
+
+
+def test_genes_and_id_of_the_caller_are_not_changed(tmp_path):
+ """cobra's Model.copy shares the gene notes and annotation dicts, so a change in place leaks."""
+ m = _model()
+ export_for_git(m, tmp_path, prefix="toy", sub_dirs=False)
+ assert m.genes.get_by_id("g1").notes == {"protein": "Pg1"}
+ assert all(not gene.annotation for gene in m.genes)
+ assert m.id == "toy_v1.0.0"
+
+
+def test_sbml_reads_back_with_cobra(out):
+ back = cobra.io.read_sbml_model(str(out / "toy.xml"))
+ assert (len(back.genes), len(back.reactions), len(back.metabolites)) == (3, 2, 3)
+ assert set(back.compartments) == {"c", "e", "p"}
+
+
+def _yml_compartments(root):
+ text = (root / "toy.yml").read_text(encoding="utf-8")
+ return re.findall(r"^\s*- ([A-Za-z0-9_]+):", text.split("compartments:", 1)[1], flags=re.MULTILINE)
+
+
+@pytest.mark.parametrize("fmt", ["xml", "xlsx", "mat", "yml"])
+def test_compartments_are_sorted_in_every_format(out, fmt):
+ if fmt == "xml":
+ found = [c.getIdAttribute() for c in _sbml(out).getListOfCompartments()]
+ elif fmt == "xlsx":
+ sheet = openpyxl.load_workbook(out / "toy.xlsx")["COMPS"]
+ found = [row[1] for row in sheet.iter_rows(min_row=2, values_only=True)]
+ elif fmt == "mat":
+ mat = sio.loadmat(out / "toy.mat", simplify_cells=True)
+ found = list(mat[next(k for k in mat if not k.startswith("__"))]["comps"])
+ else:
+ found = _yml_compartments(out)
+ assert found == ["c", "e", "p"]
+
+
+def test_mat_metcomps_follow_the_sorted_compartments(out):
+ mat = sio.loadmat(out / "toy.mat", simplify_cells=True)
+ struct = mat[next(k for k in mat if not k.startswith("__"))]
+ comps = list(struct["comps"])
+ by_met = {met: comps[int(i) - 1] for met, i in zip(struct["mets"], struct["metComps"], strict=True)}
+ assert by_met == {"x_c": "c", "x_p": "p", "y_e": "e"}
+
+
+def test_compartment_order_of_the_caller_is_not_changed(tmp_path):
+ m = _model()
+ before = list(m.compartments)
+ export_for_git(m, tmp_path, prefix="toy", sub_dirs=False)
+ assert list(m.compartments) == before
+
+
+def test_model_version_and_date_are_not_notes_by_default(tmp_path):
+ m = _model()
+ set_model_metadata(m, date="2026-11-01")
+ root = export_for_git(m, tmp_path, prefix="toy", sub_dirs=False, formats=("xml",))
+ xml = (root / "toy.xml").read_text(encoding="utf-8")
+ assert "version:" not in xml and "date:" not in xml
+
+
+def test_model_version_and_date_are_notes_on_request(tmp_path):
+ m = _model()
+ set_model_metadata(m, date="2026-11-01")
+ root = export_for_git(
+ m, tmp_path, prefix="toy", sub_dirs=False, formats=("xml",), model_version_in_sbml=True
+ )
+ xml = (root / "toy.xml").read_text(encoding="utf-8")
+ assert "version: 1.0.7
" in xml and "date: 2026-11-01
" in xml
+
+
+def _ravens_import_of_the_model_note(root):
+ """What importModel.m (lines 620 to 631) makes of the model notes: None when it reads none."""
+ notes = _sbml(root).getNotesString()
+ start, end = notes.find('xhtml">'), notes.find("")
+ if start < 0 or end < 0:
+ return None
+ return re.sub(r"| ", "", notes[start + 7 : end]).strip()
+
+
+def _export_with_note(tmp_path, note="a generic test cell", **kwargs):
+ m = _model()
+ set_model_metadata(m, note=note)
+ return export_for_git(m, tmp_path, prefix="toy", sub_dirs=False, formats=("xml",), **kwargs)
+
+
+def test_model_note_is_written_where_ravens_importmodel_reads_it(tmp_path):
+ root = _export_with_note(tmp_path)
+ assert _ravens_import_of_the_model_note(root) == "a generic test cell"
+
+
+def test_model_note_with_markup_characters_is_escaped(tmp_path):
+ root = _export_with_note(tmp_path, note="A & B < C")
+ assert _ravens_import_of_the_model_note(root) == "A & B < C"
+ assert cobra.io.read_sbml_model(str(root / "toy.xml")).id == "toy_v1__46__0__46__0"
+
+
+def test_other_notes_follow_the_model_note_and_cobra_reads_them(tmp_path):
+ root = _export_with_note(tmp_path, model_version_in_sbml=True)
+ assert _ravens_import_of_the_model_note(root).startswith("a generic test cell")
+ assert cobra.io.read_sbml_model(str(root / "toy.xml")).notes["version"] == "1.0.7"
+
+
+def test_cobra_does_not_read_the_bare_model_note_as_a_notes_entry(tmp_path):
+ root = _export_with_note(tmp_path)
+ assert "note" not in cobra.io.read_sbml_model(str(root / "toy.xml")).notes
+
+
+def test_notes_without_a_model_note_stay_out_of_ravens_reach(tmp_path):
+ root = export_for_git(
+ _model(), tmp_path, prefix="toy", sub_dirs=False, formats=("xml",), model_version_in_sbml=True
+ )
+ assert _ravens_import_of_the_model_note(root) is None
+ assert cobra.io.read_sbml_model(str(root / "toy.xml")).notes["version"] == "1.0.7"
+
+
+def test_no_model_note_is_read_by_ravens_importmodel_when_there_is_none(out):
+ assert _ravens_import_of_the_model_note(out) is None
diff --git a/tests/test_io_metadata.py b/tests/test_io_metadata.py
index 7db9ccb..791feb2 100644
--- a/tests/test_io_metadata.py
+++ b/tests/test_io_metadata.py
@@ -87,7 +87,16 @@ def test_notes_version_wins_over_metadata_version(model, tmp_path):
assert get_model_metadata(read_yaml_model(tmp_path / "m.yml"))["version"] == "2.0.0"
-def test_export_for_git_stamps_sbml_too(model, tmp_path):
- root = export_for_git(model, tmp_path, prefix="m", formats=("xml",), version="2.0.0", date="2026-10-06")
+def test_export_for_git_stamps_sbml_on_request(model, tmp_path):
+ root = export_for_git(
+ model, tmp_path, prefix="m", formats=("xml",), version="2.0.0", date="2026-10-06",
+ model_version_in_sbml=True,
+ )
xml = (root / "xml" / "m.xml").read_text()
assert "2.0.0" in xml and "2026-10-06" in xml
+
+
+def test_export_for_git_leaves_version_and_date_out_of_sbml_by_default(model, tmp_path):
+ root = export_for_git(model, tmp_path, prefix="m", formats=("xml",), version="2.0.0", date="2026-10-06")
+ xml = (root / "xml" / "m.xml").read_text()
+ assert "2.0.0" not in xml and "2026-10-06" not in xml