diff --git a/changelog.d/1992.fixed.md b/changelog.d/1992.fixed.md new file mode 100644 index 000000000..3470acd03 --- /dev/null +++ b/changelog.d/1992.fixed.md @@ -0,0 +1 @@ +- **`sbml_to_net` and `sbml_to_bngl` wrote a compartment size the SBML model refuses to change as a free parameter.** A size in `Model.unwritable_compartment_size_params` (one an initialAssignment folds into another compartment's size, for one) is not in `Model.frozen_params`, so the converters' handling of frozen parameters passed it over: the model loaded from the written file took `set_param` on it, which could move a rate law that names the size and not what the size was folded into, held there as a number. In the issue's model `set_param("c1", 3)` gave A(2) = 0.0498 where the SBML model at that size gives 0.1353. Such a size is now written as a frozen parameter is: left out where nothing in the file reads it, so that a write to it is refused as a name the model has not, and marked `folded_at_load=` where something does, so that the model loaded from the file lists it in `frozen_params` and refuses the write. The conversion report names each in `folded_left_out` or `folded_marked`. diff --git a/docs/user-guide/interchange.md b/docs/user-guide/interchange.md index ee8024a46..abd3ca082 100644 --- a/docs/user-guide/interchange.md +++ b/docs/user-guide/interchange.md @@ -74,7 +74,12 @@ What to watch out for: read in a value (`setConcentration("A()", "f*0.5")`) stays as well, marked, so that the actions run. These parameters are listed under `bngsim_only`, and the report names both kinds in `folded_left_out` and `folded_marked`. To - change one, edit the SBML and convert again. The other direction does not + change one, edit the SBML and convert again. A compartment size the SBML + model refuses to change (`Model.unwritable_compartment_size_params`) is + written the same way: the file holds what the size was folded into as a + number, so a write can move a rate law that names the size and not that + number, and the converted model refuses it as the SBML model does. The + other direction does not carry the comment: `net_to_sbml` and `net_to_omex` write a marked parameter as an ordinary one. diff --git a/python/bngsim/_model.py b/python/bngsim/_model.py index eaa6a2117..d2ac8b1f0 100644 --- a/python/bngsim/_model.py +++ b/python/bngsim/_model.py @@ -2139,7 +2139,12 @@ def frozen_params(self) -> list[str]: which the written network or its actions still read, has ``folded_at_load=`` and what it was folded into in a comment on its line, and is listed again in the model loaded from the file. (One that nothing in the network - reads is left out of the file.) The comment may be written by hand + reads is left out of the file.) A compartment size of the SBML model + in :attr:`unwritable_compartment_size_params` is written the same way + (issue #1992), since the file holds what the size was folded into as + a number: a marked one is listed here on the model loaded from + the file, and a write to one left out is refused as a name the model + has not. The comment may be written by hand on a parameter line of either format, to the same effect; one on a line that declares no parameter of the model says nothing. In a ``.bngl`` it is read off the declaration as BNG2.pl reads it: a line @@ -2247,6 +2252,11 @@ def unwritable_compartment_size_params(self) -> list[str]: ``Model.from_sbml(..., compartment_sizes={...})``; that refuses a size an assignment rule sets, which moves with what the rule reads. + A ``.net`` or ``.bngl`` that ``sbml_to_net`` or ``sbml_to_bngl`` writes + leaves one out where nothing in it reads the size, and marks it + otherwise, so the model loaded from the file has it in + :attr:`frozen_params` (issue #1992). + Returns ------- list[str] diff --git a/python/bngsim/convert/__init__.py b/python/bngsim/convert/__init__.py index dc821f177..663eb4c96 100644 --- a/python/bngsim/convert/__init__.py +++ b/python/bngsim/convert/__init__.py @@ -176,9 +176,11 @@ class ConversionReport: # the protocol from its annotation. ``ok`` and ``lossy`` judge the network. sedml_lossy: list[str] = field(default_factory=list) # The parameters folded into a number when the source model loaded - # (Model.frozen_params), by what the written file does with each: left - # out, since nothing in it reads one, or marked with a folded_at_load - # comment (sbml_to_net and sbml_to_bngl, issue #1792). n_parameters is the + # (Model.frozen_params) and the compartment sizes it refuses to change + # (Model.unwritable_compartment_size_params, issue #1992), by what the + # written file does with each: left out, since nothing in it reads one, or + # marked with a folded_at_load comment (sbml_to_net and sbml_to_bngl, + # issue #1792). n_parameters is the # source model's count less the ones left out, which is the count the # structural check compares. New fields go after every older one, so a # report built by position keeps its meaning. @@ -380,7 +382,8 @@ def sbml_to_net( mirror of :func:`net_to_sbml`'s ``bngl=`` (avoids the blanket-grid stiff-hang and exercises the trajectory the modeller actually ran). The parsed :class:`~bngsim.convert.ProtocolSpec` is attached to the report. - A parameter folded at load that one of its actions reads in a value it + A parameter folded at load, or a compartment size the model refuses + to change (issue #1992), that one of its actions reads in a value it evaluates stays in the network, marked (issue #1792). read_by_actions : iterable of str Further names that actions to be run on the network read, as for diff --git a/python/bngsim/convert/_bngl_writer.py b/python/bngsim/convert/_bngl_writer.py index 88eaa3eb8..de5aba8a6 100644 --- a/python/bngsim/convert/_bngl_writer.py +++ b/python/bngsim/convert/_bngl_writer.py @@ -461,7 +461,7 @@ def _eg(names: list[Any]) -> str: # Issue #1792: a parameter folded at load is left out where nothing in the # model block reads it, and marked for bngsim's reader where something does. left_out, marked = _folded_parameters(model, read_by_actions) - gone, kept = _frozen.notes(left_out, marked) + gone, kept = _frozen.notes(left_out, marked, model) dropped += gone bngsim_only += kept @@ -471,7 +471,8 @@ def _eg(names: list[Any]) -> str: def _folded_parameters( model: Model, read_by_actions: Iterable[str] = () ) -> tuple[list[str], list[str]]: - """The frozen parameters :func:`write_bngl` leaves out, and the ones it + """The frozen parameters and refused compartment sizes (issue #1992) + :func:`write_bngl` leaves out, and the ones it marks, read off the model block it writes (:mod:`bngsim.convert._frozen`). *read_by_actions* names what the actions after the block read, which stays.""" @@ -618,7 +619,8 @@ def write_bngl( ``setConcentration`` state changes. Its ``StateChange.target`` is a *codegen species name*, which this writer translates to the compartment-qualified pattern (``@comp:Mol()``) the model declares. - A parameter folded at load is left out or marked by what the model + A parameter folded at load, or a compartment size the model refuses + to change (issue #1992), is left out or marked by what the model block reads and by what the actions read in a value to evaluate (``setConcentration("A()", "f*0.5")`` keeps ``f``, marked; issue #1792). What an action sets is no read: a ``setParameter`` on a diff --git a/python/bngsim/convert/_frozen.py b/python/bngsim/convert/_frozen.py index f251ec454..a16ab3196 100644 --- a/python/bngsim/convert/_frozen.py +++ b/python/bngsim/convert/_frozen.py @@ -20,6 +20,15 @@ ``Model.from_bngl`` read back into ``frozen_params``. Only bngsim reads the comment: any other reader of the file takes the parameter as free. +A compartment size the SBML model refuses to change +(:attr:`bngsim.Model.unwritable_compartment_size_params`, issue #1992) is +handled the same way. It is not in ``frozen_params``, which leaves it to the +size's own refusal, but the written file holds it as a parameter like any +other, and what the SBML model folded it into as a number. A write could move +a rate law that names the size and not that number, which is why the SBML +model refuses it; the file now refuses it too, also where the write would +have happened to move everything that reads the size. + A parameter BNG2.pl folded into the rate constants of a compartmental network (a ``unit_conversion=`` comment, issue #711) is not handled here: it is written as before. @@ -36,10 +45,38 @@ _INDEX = re.compile(r"(\s*)\d+(?=\s)") +def _size_reason(name: str) -> str: + """What a compartment size the model refuses to change was folded into + (issue #1992), for the comment on its line and the refusal of the model + loaded from the file.""" + return ( + f"what the SBML model fixed from the size of compartment {name}, a size it " + "cannot resolve to a live volume and refuses to change " + "(Model.unwritable_compartment_size_params of the SBML model)" + ) + + def _reasons(model: Any) -> dict[str, str]: - """What each frozen parameter this module handles was folded into.""" + """What each frozen parameter this module handles was folded into: the + model's frozen parameters, and the compartment sizes it refuses to change + (:attr:`bngsim.Model.unwritable_compartment_size_params`), which the + written file holds as parameters like any other (issue #1992).""" frozen = getattr(model, "_frozen_params", None) or {} - return {str(n): str(w) for n, w in frozen.items() if "unit_conversion=" not in str(w)} + reasons = {str(n): str(w) for n, w in frozen.items() if "unit_conversion=" not in str(w)} + # A stand-in with no such property (a test's) has no sizes; an error raised + # inside the property of a Model is its own, and is not taken for none. + if hasattr(type(model), "unwritable_compartment_size_params"): + for n in model.unwritable_compartment_size_params: + # A parameter frozen for its own reason keeps it, a unit_conversion= + # one too, which this module writes as before. + if str(n) not in frozen: + reasons[str(n)] = _size_reason(str(n)) + return reasons + + +def handled(model: Any) -> frozenset[str]: + """The parameters of *model* this module leaves out or marks.""" + return frozenset(_reasons(model)) def has_folded(model: Any) -> bool: @@ -165,16 +202,27 @@ def named(n: str, i: int) -> bool: ) -def notes(left_out: list[str], marked: list[str]) -> tuple[list[str], list[str]]: - """``(dropped, bngsim_only)`` notes for a capability report.""" +def notes( + left_out: list[str], marked: list[str], model: Any = None +) -> tuple[list[str], list[str]]: + """``(dropped, bngsim_only)`` notes for a capability report. With *model*, + the model written, a note on a compartment size among *left_out* names the + list it is in (issue #1992).""" dropped: list[str] = [] bngsim_only: list[str] = [] if left_out: + frozen = set(getattr(model, "_frozen_params", None) or ()) + where = ( + "Model.frozen_params of the model written" + if model is None or all(n in frozen for n in left_out) + else "Model.frozen_params, or Model.unwritable_compartment_size_params for a " + "compartment size, of the model written" + ) dropped.append( f"{len(left_out)} parameter(s) folded into a number when the model was " f"loaded, which nothing in the written network reads ({', '.join(left_out)}): " - "a write to one moved nothing, and is now refused as a name the model " - "has not (Model.frozen_params of the model written)" + f"a write to one moved nothing, and is now refused as a name the model " + f"has not ({where})" ) if marked: bngsim_only.append( diff --git a/python/bngsim/convert/_net_writer.py b/python/bngsim/convert/_net_writer.py index b23541b2e..c642a92ba 100644 --- a/python/bngsim/convert/_net_writer.py +++ b/python/bngsim/convert/_net_writer.py @@ -271,7 +271,7 @@ def _eg(names: list[str]) -> str: # Issue #1792: a parameter folded at load is left out where nothing in the # network reads it, and marked for bngsim's reader where something does. left_out, marked = _folded_parameters(model, read_by_actions) - gone, kept = _frozen.notes(left_out, marked) + gone, kept = _frozen.notes(left_out, marked, model) dropped += gone bngsim_only += kept @@ -281,7 +281,8 @@ def _eg(names: list[str]) -> str: def _folded_parameters( model: Model, read_by_actions: Iterable[str] = () ) -> tuple[list[str], list[str]]: - """The frozen parameters :func:`write_net` leaves out, and the ones it + """The frozen parameters and refused compartment sizes (issue #1992) + :func:`write_net` leaves out, and the ones it marks, read off the text it writes (:mod:`bngsim.convert._frozen`). *read_by_actions* names what actions run on the network read, which stays.""" @@ -737,9 +738,12 @@ def write_net( Names that actions to be run on the network read in a value to evaluate (:func:`bngsim.convert._frozen.names_read` of the protocol); a ``str`` is taken as one name. - A parameter folded at load (``Model.frozen_params``) that nothing in - the network reads is left out of it, unless it is among these: then it - stays, marked, so that the actions find it (issue #1792). + A parameter folded at load (``Model.frozen_params``), or a compartment + size the model refuses to change + (``Model.unwritable_compartment_size_params``, issue #1992), that + nothing in the network reads is left out of it, unless it is among + these: then it stays, marked, so that the actions find it (issue + #1792). Returns ------- diff --git a/python/bngsim/convert/_validate.py b/python/bngsim/convert/_validate.py index 1cf3c32c5..08c5dfc06 100644 --- a/python/bngsim/convert/_validate.py +++ b/python/bngsim/convert/_validate.py @@ -997,8 +997,12 @@ def _folded_left_out(src: Model, dst: Model) -> set[str]: no parameter the two are to agree on. A parameter lost any other way does not hide here: one that the network still reads and that it no longer declares stops *dst* from loading, and one whose readers went with it - moves the right-hand side, which the next level compares.""" - return set(getattr(src, "_frozen_params", None) or ()) - set(dst.param_names) + moves the right-hand side, which the next level compares. The compartment + sizes *src* refuses to change are left out on the same terms (issue + #1992).""" + from bngsim.convert._frozen import handled + + return (set(getattr(src, "_frozen_params", None) or ()) | handled(src)) - set(dst.param_names) def _structural_metrics(src: Model, dst: Model) -> dict: diff --git a/python/tests/test_convert_unwritable_compartment_size.py b/python/tests/test_convert_unwritable_compartment_size.py new file mode 100644 index 000000000..9e6a61ca7 --- /dev/null +++ b/python/tests/test_convert_unwritable_compartment_size.py @@ -0,0 +1,350 @@ +"""A compartment size the SBML model refuses to change is not written as a +free parameter (issue #1992). + +``Model.unwritable_compartment_size_params`` lists the compartment sizes of an +SBML model that ``set_param`` refuses: here, a size an initialAssignment folds +into another compartment's size (``c2 = 2*c1``), a quantity no parameter +holds. They are not in ``Model.frozen_params``, which the converters read +(issue #1792), so ``sbml_to_net`` and ``sbml_to_bngl`` wrote one as an ordinary +parameter, and the model loaded from the file took the write: it moved a rate +law that names the size and not the volume the species are divided by, which +the file holds as a number. + +Now such a size is handled as a frozen parameter is: left out of the file +where nothing in it reads the size, and marked ``folded_at_load=`` where +something does, so that the model loaded from the file refuses the write. + +Oracle: closed forms. ``A`` in ``c1`` (size 2), ``B`` in ``c2``, concentrations. + +* ``A -> B`` at ``k A c1`` (the issue's model): ``dA/dt = -k A``, so + ``A(t) = exp(-k t)`` and ``B(t) = (1 - exp(-k t)) c1 / c2 = (1 - exp(-k t)) / 2``, + whatever ``c1`` is, since ``c2 = 2 c1``. +* ``A -> 0`` at ``k A c1``: ``A(t) = exp(-k t)``. The file folds ``c1`` into + numbers and names it nowhere else. +* ``A -> 0`` at ``k A``: ``A(t) = exp(-k t / c1)``. The file reads ``c1`` in + the rate's volume ratio. +""" + +from __future__ import annotations + +import math +import shutil +import warnings +from pathlib import Path +from types import SimpleNamespace + +import bngsim +import pytest +from bngsim import ParameterError +from bngsim.convert import _frozen, sbml_to_bngl, sbml_to_net +from bngsim.convert._bng2 import find_bng2 + +needs_sbml = pytest.mark.skipif(not bngsim.HAS_LIBSBML, reason="SBML loading requires libsbml") + +_FOUND = find_bng2() +BNG2 = Path(_FOUND).resolve() if _FOUND else None +HAS_BNG2 = BNG2 is not None and BNG2.is_file() and bool(shutil.which("perl")) +needs_bng2 = pytest.mark.skipif(not HAS_BNG2, reason="BNG2.pl not found") + +K, C1 = 1.0, 2.0 +# As in test_convert_frozen_parameters.py: the solver's default tolerances are +# 1e-8, and 1e-6 is orders below the smallest effect tested (e^-2 against e^-3). +REL = 1e-6 +MATH = 'xmlns="http://www.w3.org/1998/Math/MathML"' +TIMES = "{}" + + +def _sbml(*, product: bool, law_reads_c1: bool) -> str: + """``A -> B`` (*product*) or ``A -> 0`` in ``c1``, with ``c2 = 2*c1`` set by + an initialAssignment, at ``k A c1`` or at ``k A``.""" + names = "kA" + ("c1" if law_reads_c1 else "") + products = ( + '' + "" + if product + else "" + ) + return f""" + + + + + + + + + + + + + + 2c1 + + + + + {products} + {TIMES.format(names)} + + + + +""" + + +WRITERS = [ + pytest.param(sbml_to_net, ".net", id="net"), + pytest.param(sbml_to_bngl, ".bngl", id="bngl", marks=needs_bng2), +] + + +def _source(tmp_path: Path, **shape) -> Path: + source = tmp_path / "s.xml" + source.write_text(_sbml(**shape), encoding="utf-8") + return source + + +def _convert(tmp_path: Path, writer, ext: str, **shape): + """The SBML written by *writer*: ``(report, file)``.""" + source = _source(tmp_path, **shape) + out = tmp_path / f"s{ext}" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = writer(str(source), str(out)) + return report, out + + +def _load(path: Path) -> bngsim.Model: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if path.suffix == ".net": + return bngsim.Model.from_net(str(path)) + return bngsim.Model.from_bngl(str(path), cache=False) + + +def _at(model: bngsim.Model, t: float) -> dict[str, float]: + result = bngsim.Simulator(model, method="ode").run(t_span=(0, t), n_points=3) + names = [n.split("::")[-1].split("(")[0].split(":")[-1] for n in result.species_names] + return {n: float(result.species[-1][i]) for i, n in enumerate(names)} + + +def _parameters(text: str) -> dict[str, str]: + """The parameters block of a written file: name -> the rest of its line.""" + block = text.split("begin parameters")[1].split("end parameters")[0] + lines = [line.split(None, 2) for line in block.splitlines() if line.strip()] + assert [int(index) for index, _, _ in lines] == list(range(1, len(lines) + 1)) + return {name: rest for _, name, rest in lines} + + +# --- the source model, as a control ----------------------------------------- + + +@needs_sbml +@pytest.mark.parametrize("law_reads_c1", [False, True]) +def test_the_sbml_model_refuses_the_write(tmp_path, law_reads_c1): + model = bngsim.Model.from_sbml( + str(_source(tmp_path, product=False, law_reads_c1=law_reads_c1)) + ) + assert model.unwritable_compartment_size_params == ["c1"] + assert model.frozen_params == [] + with pytest.raises(ValueError, match="cannot resolve to a live volume"): + model.set_param("c1", 3.0) + want = math.exp(-K * 2.0) if law_reads_c1 else math.exp(-K * 2.0 / C1) + assert _at(model, 2.0)["A"] == pytest.approx(want, rel=REL) + + +# --- the issue's model: the rate law reads the size, marked ------------------- + + +@needs_sbml +@needs_bng2 +def test_the_issues_model_marks_the_size_and_refuses_the_write(tmp_path): + # sbml_to_net refuses this model (a cross-compartment reaction between + # compartments of different sizes); sbml_to_bngl writes it. + report, out = _convert(tmp_path, sbml_to_bngl, ".bngl", product=True, law_reads_c1=True) + assert report.ok + assert (report.folded_left_out, report.folded_marked) == ([], ["c1"]) + (note,) = [n for n in report.bngsim_only if "folded" in n] + assert "(c1)" in note + line = _parameters(out.read_text(encoding="utf-8"))["c1"] + assert "folded_at_load=what the SBML model fixed from the size of compartment c1" in line + + model = _load(out) + assert model.frozen_params == ["c1"] + with pytest.raises(ParameterError, match="unwritable_compartment_size_params") as refused: + model.set_param("c1", 3.0) + assert "folded_at_load comment" in str(refused.value) + # The value it holds is no change, and is taken. + model.set_param("c1", C1) + at = _at(model, 2.0) + assert at["A"] == pytest.approx(math.exp(-2.0), rel=REL) + assert at["B"] == pytest.approx((1 - math.exp(-2.0)) / 2, rel=REL) + + +@needs_sbml +@needs_bng2 +def test_the_write_main_took_moved_the_rate_law_alone(tmp_path): + # What the refusal prevents, on the file with its mark taken off: the write + # gives A(2) = e^-3 where the SBML model at c1 = 3 gives e^-2. + _, out = _convert(tmp_path, sbml_to_bngl, ".bngl", product=True, law_reads_c1=True) + text = out.read_text(encoding="utf-8") + bare = tmp_path / "bare.bngl" + bare.write_text(text.replace(_frozen.MARKER, "note="), encoding="utf-8") + model = _load(bare) + assert model.frozen_params == [] + model.set_param("c1", 3.0) + assert _at(model, 2.0)["A"] == pytest.approx(math.exp(-3.0), rel=REL) + + +# --- the volume ratio reads the size: marked --------------------------------- + + +@needs_sbml +@pytest.mark.parametrize(("writer", "ext"), WRITERS) +def test_a_size_the_rate_ratio_reads_is_marked(tmp_path, writer, ext): + # The refusal is the SBML model's: here a write would have been whole (the + # file follows c1 in the rate's ratio, and nothing reads c2's folded + # volume), so it is refused to match the source, not because it is wrong. + report, out = _convert(tmp_path, writer, ext, product=False, law_reads_c1=False) + assert (report.folded_left_out, report.folded_marked) == ([], ["c1"]) + parameters = _parameters(out.read_text(encoding="utf-8")) + assert _frozen.MARKER in parameters["c1"] + # What still reads it: the mass-action scalar's ratio to the load size. + assert any("c1" in rest for name, rest in parameters.items() if name != "c1") + + model = _load(out) + assert model.frozen_params == ["c1"] + with pytest.raises(ParameterError, match="cannot be changed after the model is loaded"): + model.set_param("c1", 3.0) + assert _at(model, 2.0)["A"] == pytest.approx(math.exp(-2.0 / C1), rel=REL) + + +# --- nothing reads it: left out ----------------------------------------------- + + +@needs_sbml +@pytest.mark.parametrize(("writer", "ext"), WRITERS) +def test_a_size_nothing_reads_is_left_out(tmp_path, writer, ext): + report, out = _convert(tmp_path, writer, ext, product=False, law_reads_c1=True) + assert (report.folded_left_out, report.folded_marked) == (["c1"], []) + (note,) = [n for n in report.dropped if "folded" in n] + assert "(c1)" in note and "Model.unwritable_compartment_size_params" in note + assert report.ok and not report.bngsim_only + text = out.read_text(encoding="utf-8") + assert "c1" not in _parameters(text) + + model = _load(out) + assert "c1" not in model.param_names + with pytest.raises(ParameterError, match="'c1' not found"): + model.set_param("c1", 3.0) + assert _at(model, 2.0)["A"] == pytest.approx(math.exp(-2.0), rel=REL) + + +@needs_sbml +def test_the_round_trip_checks_pass_with_a_size_left_out(tmp_path): + # L1 compares the source's parameter count with the reloaded file's, less + # what the writer left out, a size among them. + source = _source(tmp_path, product=False, law_reads_c1=True) + out = tmp_path / "s.net" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = sbml_to_net(str(source), str(out), validate="L1") + assert report.folded_left_out == ["c1"] + assert report.structural is not None and report.structural.passed, report.structural + assert report.structural.n_parameters[0] == report.structural.n_parameters[1] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = sbml_to_net(str(source), str(out), validate="full") + assert report.validation is not None and report.ok, report.validation + first = report.validation.level("L1") + assert first is not None and first.status == "pass" + assert first.metrics["n_parameters"][0] == first.metrics["n_parameters"][1], first.metrics + + +# --- another kind of size: one mass-action scalar for two compartments --------- + +SHARED = f""" + + + + + + + + + + + + + + + + + + + + + {TIMES.format("kABc1")} + + + + + +""" + + +@needs_sbml +@pytest.mark.parametrize(("writer", "ext"), WRITERS) +def test_sizes_one_scalar_divides_by_are_left_out(tmp_path, writer, ext): + # A + B -> C across c1 and c2, both of size 1, by one mass-action scalar: + # the SBML model refuses both sizes, which the file folds into numbers. + # A' = B' = -k A B with A(0) = B(0) = 1, so A(t) = B(t) = 1/(1 + k t). + source = tmp_path / "shared.xml" + source.write_text(SHARED, encoding="utf-8") + model = bngsim.Model.from_sbml(str(source)) + assert model.unwritable_compartment_size_params == ["c1", "c2"] + out = tmp_path / f"shared{ext}" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = writer(str(source), str(out)) + assert (sorted(report.folded_left_out), report.folded_marked) == (["c1", "c2"], []) + assert report.ok + loaded = _load(out) + for size in ("c1", "c2"): + assert size not in loaded.param_names + with pytest.raises(ParameterError, match=f"'{size}' not found"): + loaded.set_param(size, 2.0) + at = _at(loaded, 2.0) + assert at["A"] == pytest.approx(1 / (1 + K * 2.0), rel=REL) + assert at["B"] == pytest.approx(1 / (1 + K * 2.0), rel=REL) + assert at["C"] == pytest.approx(1 - 1 / (1 + K * 2.0), rel=REL) + + +# --- the module's reading of a model -------------------------------------------- + + +def test_a_model_without_the_size_list_is_read_by_its_frozen_parameters(): + stand_in = SimpleNamespace(_frozen_params={"f": "a stoichiometry"}) + assert _frozen.handled(stand_in) == {"f"} + assert _frozen.has_folded(stand_in) + + +def test_a_unit_conversion_parameter_that_is_also_a_size_is_written_as_before(): + class Stand: + _frozen_params = {"c1": "unit_conversion=1/c1", "f": "a stoichiometry"} + unwritable_compartment_size_params = ["c1"] + + assert _frozen.handled(Stand()) == {"f"} + + +def test_the_note_on_a_frozen_parameter_left_out_is_unchanged(): + stand_in = SimpleNamespace(_frozen_params={"f": "a stoichiometry"}) + (note,), _ = _frozen.notes(["f"], [], stand_in) + assert note.endswith("(Model.frozen_params of the model written)") + (note,), _ = _frozen.notes(["f"], []) + assert note.endswith("(Model.frozen_params of the model written)")