From 15d71298116c95ab85a6d4bb1651321c84ad5a94 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Thu, 19 Nov 2026 13:39:13 +0100 Subject: [PATCH 1/5] fix: write the SBML id, gene products and SBO terms as RAVEN does exportModel writes each character of the model id outside [0-9_a-zA-Z] as ____ and importModel decodes it. cobra passes the id to libSBML unchanged, and libSBML writes no id attribute for an id that is not a valid SId, such as ecoliGEM_v1.0.7. exportModel also writes the protein as fbc:name, the gene short name or else the gene id as fbc:label, and SBO:0000243 on each gene product without a term of its own. importModel reads proteins from fbc:name, so RAVEN read the short name of each gene as its protein. --- CHANGELOG.md | 5 ++ src/raven_toolbox/io/git.py | 57 +++++++++++++++---- tests/test_io_git.py | 26 +++++++-- tests/test_io_git_raven_parity.py | 93 +++++++++++++++++++++++++++++++ 4 files changed, 165 insertions(+), 16 deletions(-) create mode 100644 tests/test_io_git_raven_parity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3ac5c..633cb5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ * `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). + +### 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`. ### Data diff --git a/src/raven_toolbox/io/git.py b/src/raven_toolbox/io/git.py index 1d46206..a0503a9 100644 --- a/src/raven_toolbox/io/git.py +++ b/src/raven_toolbox/io/git.py @@ -50,6 +50,19 @@ 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]") + +# 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) -> cobra.Model: """A copy of ``model`` shaped so RAVEN's importModel finds everything. @@ -63,10 +76,23 @@ 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 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()} @@ -132,19 +158,30 @@ def _for_sbml(model: cobra.Model) -> cobra.Model: 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. - - 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. + """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. """ cobra.io.write_sbml_model(_for_sbml(model), 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() + 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() libsbml.writeSBMLToFile(doc, str(path)) diff --git a/tests/test_io_git.py b/tests/test_io_git.py index 8655b7c..36843b1 100644 --- a/tests/test_io_git.py +++ b/tests/test_io_git.py @@ -235,7 +235,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 +247,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",)) diff --git a/tests/test_io_git_raven_parity.py b/tests/test_io_git_raven_parity.py new file mode 100644 index 0000000..9068c1c --- /dev/null +++ b/tests/test_io_git_raven_parity.py @@ -0,0 +1,93 @@ +"""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 cobra +import libsbml +import pytest + +from raven_toolbox.io import export_for_git + + +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"} From 7b8206f7a80e597685d7e1bf5a33bf92b4884e9b Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Thu, 19 Nov 2026 13:39:51 +0100 Subject: [PATCH 2/5] fix: sort the compartments in the xlsx, mat and SBML files cobra lists the compartments in the order in which the metabolites first mention them, so export_for_git wrote c, p, e where RAVEN's sortIdentifiers gives c, e, p. export_to_excel sorted them only with sort_ids=True and write_matlab_model never did. The SBML file is sorted after cobra writes it. The yml file was already sorted by cobra. --- CHANGELOG.md | 1 + src/raven_toolbox/io/excel.py | 7 +++--- src/raven_toolbox/io/git.py | 19 ++++++++++++++- src/raven_toolbox/io/mat.py | 3 ++- tests/test_io_git_raven_parity.py | 39 +++++++++++++++++++++++++++++++ 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 633cb5c..083b1a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ ### 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`). ### 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 a0503a9..154f56d 100644 --- a/src/raven_toolbox/io/git.py +++ b/src/raven_toolbox/io/git.py @@ -157,6 +157,21 @@ def _for_sbml(model: cobra.Model) -> cobra.Model: return out +def _sort_sbml_compartments(sbml_model: libsbml.Model) -> None: + """Order the compartments of ``sbml_model`` by id. + + cobra writes them in the order in which the metabolites first mention them. + """ + 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_sbml(model: cobra.Model, path: Path) -> None: """Write ``model`` as SBML in the shape of RAVEN's exportModel. @@ -164,7 +179,8 @@ def _write_sbml(model: cobra.Model, path: Path) -> None: 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. + does not change what cobra reads back. The compartments are ordered by id, as in + RAVEN's sortIdentifiers. """ cobra.io.write_sbml_model(_for_sbml(model), str(path)) doc = libsbml.readSBMLFromFile(str(path)) @@ -182,6 +198,7 @@ def _write_sbml(model: cobra.Model, path: Path) -> None: product.setName(str(protein)) else: product.unsetName() + _sort_sbml_compartments(sbml_model) libsbml.writeSBMLToFile(doc, str(path)) 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_raven_parity.py b/tests/test_io_git_raven_parity.py index 9068c1c..a05cfb6 100644 --- a/tests/test_io_git_raven_parity.py +++ b/tests/test_io_git_raven_parity.py @@ -3,9 +3,13 @@ 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 @@ -91,3 +95,38 @@ 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 From d9bfc8f32b7a49194de9a367f06b57126c1d7562 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Thu, 19 Nov 2026 13:40:29 +0100 Subject: [PATCH 3/5] fix: list the toolchain only in dependencies.txt unless asked exportForGit writes MATLAB, libSBML and RAVEN, and the fields of model.modelVersion, which nothing else in RAVEN sets. export_for_git added model_version and model_date, so every release changed the file. model_version_in_dependencies=True writes the two lines. --- CHANGELOG.md | 1 + src/raven_toolbox/io/git.py | 32 ++++++++++++++++++++++---------- tests/test_io_git.py | 15 +++++++++++---- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 083b1a0..29ce47e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * `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). ### Model I/O diff --git a/src/raven_toolbox/io/git.py b/src/raven_toolbox/io/git.py index 154f56d..ea18f64 100644 --- a/src/raven_toolbox/io/git.py +++ b/src/raven_toolbox/io/git.py @@ -236,11 +236,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()), @@ -251,10 +252,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") @@ -303,6 +305,7 @@ def export_for_git( varname: str | None = None, version: str | None = None, date: str | datetime.date | None = None, + model_version_in_dependencies: bool = False, ) -> Path: """Write ``model`` into a Standard-GEM repository layout. @@ -338,6 +341,10 @@ 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. Returns ------- @@ -347,9 +354,14 @@ 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`` or ``model_version_in_dependencies`` 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), + ): 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__}" @@ -385,6 +397,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/tests/test_io_git.py b/tests/test_io_git.py index 36843b1..7c08d3d 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,7 @@ 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"]) @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): @@ -392,7 +399,7 @@ 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"]) def test_export_for_git_accepts_numpy_booleans(model, tmp_path, flag): import numpy as np From 9e0704fbc20411447598d5327d1fc784edf10f68 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Thu, 19 Nov 2026 13:41:04 +0100 Subject: [PATCH 4/5] fix: write the SBML version and date notes only on request exportModel writes no model version and no date, and the two notes changed the SBML file of every release. model_version_in_sbml=True writes them. --- CHANGELOG.md | 1 + src/raven_toolbox/io/git.py | 39 ++++++++++++++++++------------- tests/test_io_git.py | 8 +++++-- tests/test_io_git_raven_parity.py | 19 +++++++++++++++ tests/test_io_metadata.py | 13 +++++++++-- 5 files changed, 60 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29ce47e..9a1df72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * `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). ### Model I/O diff --git a/src/raven_toolbox/io/git.py b/src/raven_toolbox/io/git.py index ea18f64..fe29b8b 100644 --- a/src/raven_toolbox/io/git.py +++ b/src/raven_toolbox/io/git.py @@ -64,7 +64,7 @@ def _sbml_id(identifier: str) -> str: return _SBML_ID_UNSAFE.sub(lambda match: f"__{ord(match.group())}__", identifier) -def _for_sbml(model: cobra.Model) -> cobra.Model: +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: @@ -78,7 +78,8 @@ def _for_sbml(model: cobra.Model) -> cobra.Model: 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``. + 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. """ @@ -111,15 +112,15 @@ def _for_sbml(model: cobra.Model) -> cobra.Model: # 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. + # look for both shapes. 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 @@ -172,7 +173,7 @@ def _sort_sbml_compartments(sbml_model: libsbml.Model) -> None: sbml_model.addCompartment(compartment) -def _write_sbml(model: cobra.Model, path: Path) -> None: +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 @@ -180,9 +181,9 @@ def _write_sbml(model: cobra.Model, path: Path) -> None: 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. + RAVEN's sortIdentifiers. The model version and date are notes only with ``model_version``. """ - cobra.io.write_sbml_model(_for_sbml(model), str(path)) + cobra.io.write_sbml_model(_for_sbml(model, model_version=model_version), str(path)) doc = libsbml.readSBMLFromFile(str(path)) sbml_model = doc.getModel() products = sbml_model.getPlugin("fbc").getListOfGeneProducts() @@ -306,6 +307,7 @@ def export_for_git( 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. @@ -345,6 +347,10 @@ def export_for_git( 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: ...

``). The default (False) writes neither, as RAVEN's + ``exportModel`` does; RAVEN keeps the version in the model id only. Returns ------- @@ -354,13 +360,14 @@ def export_for_git( Raises ------ TypeError - If ``main_branch_flag``, ``sub_dirs`` or ``model_version_in_dependencies`` 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), ("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( @@ -389,7 +396,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: diff --git a/tests/test_io_git.py b/tests/test_io_git.py index 7c08d3d..b5b21ca 100644 --- a/tests/test_io_git.py +++ b/tests/test_io_git.py @@ -114,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", "model_version_in_dependencies"]) +@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): @@ -399,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", "model_version_in_dependencies"]) +@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 index a05cfb6..22ac04f 100644 --- a/tests/test_io_git_raven_parity.py +++ b/tests/test_io_git_raven_parity.py @@ -12,6 +12,7 @@ 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: @@ -130,3 +131,21 @@ def test_compartment_order_of_the_caller_is_not_changed(tmp_path): 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 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 From 59fe6d9d411d66e7efc69263f1d8f61fe1c372b2 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Thu, 19 Nov 2026 14:30:35 +0100 Subject: [PATCH 5/5] fix: write the SBML model note in the body shape RAVEN reads exportModel writes the model note as a bare paragraph in a body element, and importModel reads a model note only from that shape. cobra wraps its notes in an html element, so importModel found no note in the SBML file of export_for_git. The note is now the first paragraph of a body element, and the other notes follow as key: value paragraphs, which cobra reads. cobra also writes notes without escaping them, so a model note that held &, < or > was dropped from the file and only logged as an error. The notes are written with escaping. --- CHANGELOG.md | 2 ++ src/raven_toolbox/io/git.py | 48 ++++++++++++++++++++++++------ tests/test_io_git_raven_parity.py | 49 +++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a1df72..8784e4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,13 @@ * 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/git.py b/src/raven_toolbox/io/git.py index fe29b8b..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 @@ -109,11 +110,9 @@ def _for_sbml(model: cobra.Model, *, model_version: bool = False) -> 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. RAVEN's exportModel writes no version and no date, - # so they are notes only on request. + # 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 {}) if meta.get("note") and "note" not in stamped: stamped["note"] = str(meta["note"]) @@ -173,6 +172,31 @@ def _sort_sbml_compartments(sbml_model: libsbml.Model) -> None: 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"" + 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. @@ -181,11 +205,16 @@ def _write_sbml(model: cobra.Model, path: Path, *, model_version: bool = False) 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 version and date are notes only with ``model_version``. + RAVEN's sortIdentifiers. The model notes are written by :func:`_write_model_notes`; the + model version and date are notes only with ``model_version``. """ - cobra.io.write_sbml_model(_for_sbml(model, model_version=model_version), str(path)) + 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)) sbml_model = doc.getModel() + _write_model_notes(sbml_model, notes) products = sbml_model.getPlugin("fbc").getListOfGeneProducts() if len(products) != len(model.genes): raise RuntimeError( @@ -349,8 +378,9 @@ def export_for_git( 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: ...

``). The default (False) writes neither, as RAVEN's - ``exportModel`` does; RAVEN keeps the version in the model id only. + (``

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 ------- diff --git a/tests/test_io_git_raven_parity.py b/tests/test_io_git_raven_parity.py index 22ac04f..bc37348 100644 --- a/tests/test_io_git_raven_parity.py +++ b/tests/test_io_git_raven_parity.py @@ -149,3 +149,52 @@ def test_model_version_and_date_are_notes_on_request(tmp_path): ) 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