From ca6c55af6306543baf198c0081caa4f20e2406f1 Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Mon, 23 Nov 2026 14:33:58 +0100 Subject: [PATCH 1/4] Move model modules and their tests (renames only) Move the model implementation from `petab/v1/models` to `petab/_models`, and the PySB and BNGL tests and fixtures from `tests/v1` to `tests/models`, without changes; the imports are fixed in the next commit. Co-Authored-By: Claude Opus 5.5 --- petab/{v1/models => _models}/bngl_model.py | 0 petab/{v1/models => _models}/model.py | 0 petab/{v1/models => _models}/pysb_model.py | 0 petab/{v1/models => _models}/sbml_model.py | 0 tests/{v1 => models}/bngl/parabola.bngl | 0 tests/{v1 => models}/bngl_corpus/README.md | 0 tests/{v1 => models}/bngl_corpus/golden.json | 0 tests/{v1 => models}/fetch_bngl_corpus.py | 0 tests/{v1 => models}/test_bngl_corpus.py | 0 tests/{v1 => models}/test_model_bngl.py | 0 tests/{v1 => models}/test_model_pysb.py | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename petab/{v1/models => _models}/bngl_model.py (100%) rename petab/{v1/models => _models}/model.py (100%) rename petab/{v1/models => _models}/pysb_model.py (100%) rename petab/{v1/models => _models}/sbml_model.py (100%) rename tests/{v1 => models}/bngl/parabola.bngl (100%) rename tests/{v1 => models}/bngl_corpus/README.md (100%) rename tests/{v1 => models}/bngl_corpus/golden.json (100%) rename tests/{v1 => models}/fetch_bngl_corpus.py (100%) rename tests/{v1 => models}/test_bngl_corpus.py (100%) rename tests/{v1 => models}/test_model_bngl.py (100%) rename tests/{v1 => models}/test_model_pysb.py (100%) diff --git a/petab/v1/models/bngl_model.py b/petab/_models/bngl_model.py similarity index 100% rename from petab/v1/models/bngl_model.py rename to petab/_models/bngl_model.py diff --git a/petab/v1/models/model.py b/petab/_models/model.py similarity index 100% rename from petab/v1/models/model.py rename to petab/_models/model.py diff --git a/petab/v1/models/pysb_model.py b/petab/_models/pysb_model.py similarity index 100% rename from petab/v1/models/pysb_model.py rename to petab/_models/pysb_model.py diff --git a/petab/v1/models/sbml_model.py b/petab/_models/sbml_model.py similarity index 100% rename from petab/v1/models/sbml_model.py rename to petab/_models/sbml_model.py diff --git a/tests/v1/bngl/parabola.bngl b/tests/models/bngl/parabola.bngl similarity index 100% rename from tests/v1/bngl/parabola.bngl rename to tests/models/bngl/parabola.bngl diff --git a/tests/v1/bngl_corpus/README.md b/tests/models/bngl_corpus/README.md similarity index 100% rename from tests/v1/bngl_corpus/README.md rename to tests/models/bngl_corpus/README.md diff --git a/tests/v1/bngl_corpus/golden.json b/tests/models/bngl_corpus/golden.json similarity index 100% rename from tests/v1/bngl_corpus/golden.json rename to tests/models/bngl_corpus/golden.json diff --git a/tests/v1/fetch_bngl_corpus.py b/tests/models/fetch_bngl_corpus.py similarity index 100% rename from tests/v1/fetch_bngl_corpus.py rename to tests/models/fetch_bngl_corpus.py diff --git a/tests/v1/test_bngl_corpus.py b/tests/models/test_bngl_corpus.py similarity index 100% rename from tests/v1/test_bngl_corpus.py rename to tests/models/test_bngl_corpus.py diff --git a/tests/v1/test_model_bngl.py b/tests/models/test_model_bngl.py similarity index 100% rename from tests/v1/test_model_bngl.py rename to tests/models/test_model_bngl.py diff --git a/tests/v1/test_model_pysb.py b/tests/models/test_model_pysb.py similarity index 100% rename from tests/v1/test_model_pysb.py rename to tests/models/test_model_pysb.py From 1365b1ab6d9ccffa5d68a3a268512efa7807ab19 Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Mon, 23 Nov 2026 14:34:04 +0100 Subject: [PATCH 2/4] Move model classes to a version-independent package The model classes serve both PEtab v1 and v2, but lived in `petab.v1.models`, with `petab.v2.models` re-exporting them. This suggested that PySB and BNGL models were supported with PEtab v1. Move the implementation to the private package `petab._models` (in the previous commit; here, only imports change). `petab.v1.models` and `petab.v2.models` re-export it. Deprecate (for now only in the changelog) the PySB and BNGL modules in `petab.v1.models`. Move the PySB and BNGL tests and fixtures to `tests/models`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci_tests.yml | 2 +- .gitignore | 4 +-- .../+v1-pysb-bngl-models.deprecation.md | 6 ++++ doc/development.rst | 2 +- petab/_models/__init__.py | 34 +++++++++++++++++++ petab/_models/bngl_model.py | 4 +-- petab/_models/pysb_model.py | 4 +-- petab/_models/sbml_model.py | 4 +-- petab/v1/models/__init__.py | 19 ++++------- petab/v1/models/bngl_model.py | 12 +++++++ petab/v1/models/model.py | 9 +++++ petab/v1/models/pysb_model.py | 12 +++++++ petab/v1/models/sbml_model.py | 9 +++++ petab/v2/core.py | 2 +- petab/v2/models/__init__.py | 3 +- petab/v2/models/bngl_model.py | 8 ++++- petab/v2/models/model.py | 8 ++++- petab/v2/models/pysb_model.py | 8 ++++- petab/v2/models/sbml_model.py | 8 ++++- tests/models/__init__.py | 0 tests/models/bngl_corpus/README.md | 4 +-- tests/models/fetch_bngl_corpus.py | 8 ++--- tests/models/test_bngl_corpus.py | 12 +++---- tests/models/test_model_bngl.py | 8 ++--- tests/models/test_model_pysb.py | 4 +-- 25 files changed, 147 insertions(+), 47 deletions(-) create mode 100644 changelog.d/+v1-pysb-bngl-models.deprecation.md create mode 100644 petab/_models/__init__.py create mode 100644 petab/v1/models/bngl_model.py create mode 100644 petab/v1/models/model.py create mode 100644 petab/v1/models/pysb_model.py create mode 100644 petab/v1/models/sbml_model.py create mode 100644 tests/models/__init__.py diff --git a/.github/workflows/ci_tests.yml b/.github/workflows/ci_tests.yml index 8070bab7..094ba697 100644 --- a/.github/workflows/ci_tests.yml +++ b/.github/workflows/ci_tests.yml @@ -37,7 +37,7 @@ jobs: if: matrix.platform == 'ubuntu-latest' - name: Fetch BNGL test corpus - run: uv run --no-project python -P tests/v1/fetch_bngl_corpus.py + run: uv run --no-project python -P tests/models/fetch_bngl_corpus.py - name: Unit tests run: | diff --git a/.gitignore b/.gitignore index d1431f9c..53f43239 100644 --- a/.gitignore +++ b/.gitignore @@ -115,8 +115,8 @@ venv.bak/ _untracked doc/_static/README.rst -# BNGL corpus fixtures are fetched on demand (tests/v1/fetch_bngl_corpus.py) -tests/v1/bngl_corpus/*.bngl +# BNGL corpus fixtures are fetched on demand (tests/models/fetch_bngl_corpus.py) +tests/models/bngl_corpus/*.bngl # CI resolves the latest dependency versions uv.lock diff --git a/changelog.d/+v1-pysb-bngl-models.deprecation.md b/changelog.d/+v1-pysb-bngl-models.deprecation.md new file mode 100644 index 00000000..0232eb6f --- /dev/null +++ b/changelog.d/+v1-pysb-bngl-models.deprecation.md @@ -0,0 +1,6 @@ +PySB and BNGL models are only supported with PEtab v2. +`petab.v1.models.pysb_model`, `petab.v1.models.bngl_model`, and loading +PySB or BNGL models via `petab.v1` are deprecated and will be removed in a +future release; use `petab.v2.models.pysb_model` and +`petab.v2.models.bngl_model` instead +([#622](https://github.com/PEtab-dev/libpetab-python/pull/622)) diff --git a/doc/development.rst b/doc/development.rst index 992616cc..0bb19598 100644 --- a/doc/development.rst +++ b/doc/development.rst @@ -77,7 +77,7 @@ have been downloaded via: .. code-block:: bash - uv run --no-project python -P tests/v1/fetch_bngl_corpus.py + uv run --no-project python -P tests/models/fetch_bngl_corpus.py Style guide ----------- diff --git a/petab/_models/__init__.py b/petab/_models/__init__.py new file mode 100644 index 00000000..1b67bb01 --- /dev/null +++ b/petab/_models/__init__.py @@ -0,0 +1,34 @@ +"""Model types supported by PEtab, shared by :mod:`petab.v1` and +:mod:`petab.v2`. + +Use :mod:`petab.v1.models` or :mod:`petab.v2.models` instead of importing +from here. +""" + +#: SBML model type as used in a PEtab v2 yaml file as `language`. +MODEL_TYPE_SBML = "sbml" +#: PySB model type as used in a PEtab v2 yaml file as `language`. +MODEL_TYPE_PYSB = "pysb" +#: BNGL model type as used in a PEtab v2 yaml file as `language`. +MODEL_TYPE_BNGL = "bngl" + +known_model_types = { + MODEL_TYPE_SBML, + MODEL_TYPE_PYSB, + MODEL_TYPE_BNGL, +} + +# The model modules use helpers from `petab.v1`, whose initialization +# imports `petab.v1.models` and thus this package; initialize `petab.v1` +# first to avoid a circular import. +import petab.v1 # noqa: E402, F401 + +from .model import Model # noqa: E402 + +__all__ = [ + "MODEL_TYPE_BNGL", + "MODEL_TYPE_PYSB", + "MODEL_TYPE_SBML", + "Model", + "known_model_types", +] diff --git a/petab/_models/bngl_model.py b/petab/_models/bngl_model.py index 2f8cef39..a1290bc7 100644 --- a/petab/_models/bngl_model.py +++ b/petab/_models/bngl_model.py @@ -39,8 +39,8 @@ from dataclasses import dataclass from pathlib import Path -from ..._utils import _generate_path -from .. import is_valid_identifier +from .._utils import _generate_path +from ..v1.lint import is_valid_identifier from . import MODEL_TYPE_BNGL from .model import Model diff --git a/petab/_models/pysb_model.py b/petab/_models/pysb_model.py index de1ce95c..0fa4be66 100644 --- a/petab/_models/pysb_model.py +++ b/petab/_models/pysb_model.py @@ -13,8 +13,8 @@ import pysb -from ..._utils import _generate_path -from .. import is_valid_identifier +from .._utils import _generate_path +from ..v1.lint import is_valid_identifier from . import MODEL_TYPE_PYSB from .model import Model diff --git a/petab/_models/sbml_model.py b/petab/_models/sbml_model.py index 831a42e3..ce791ec5 100644 --- a/petab/_models/sbml_model.py +++ b/petab/_models/sbml_model.py @@ -10,8 +10,8 @@ import sympy as sp from sbmlmath import sbml_math_to_sympy -from ..._utils import _generate_path -from ..sbml import ( +from .._utils import _generate_path +from ..v1.sbml import ( get_sbml_model, is_sbml_consistent, load_sbml_from_string, diff --git a/petab/v1/models/__init__.py b/petab/v1/models/__init__.py index 29c44a26..416c73ae 100644 --- a/petab/v1/models/__init__.py +++ b/petab/v1/models/__init__.py @@ -1,19 +1,12 @@ """Handling of different model types supported by PEtab.""" -#: SBML model type as used in a PEtab v2 yaml file as `language`. -MODEL_TYPE_SBML = "sbml" -#: PySB model type as used in a PEtab v2 yaml file as `language`. -MODEL_TYPE_PYSB = "pysb" -#: BNGL model type as used in a PEtab v2 yaml file as `language`. -MODEL_TYPE_BNGL = "bngl" - -known_model_types = { - MODEL_TYPE_SBML, - MODEL_TYPE_PYSB, +from ..._models import ( MODEL_TYPE_BNGL, -} - -from .model import Model # noqa F401 + MODEL_TYPE_PYSB, + MODEL_TYPE_SBML, + known_model_types, +) +from .model import Model __all__ = [ "MODEL_TYPE_BNGL", diff --git a/petab/v1/models/bngl_model.py b/petab/v1/models/bngl_model.py new file mode 100644 index 00000000..4cfd804c --- /dev/null +++ b/petab/v1/models/bngl_model.py @@ -0,0 +1,12 @@ +"""Deprecated: use :mod:`petab.v2.models.bngl_model`. + +BNGL models are only supported with PEtab v2. +""" + +from ..._models import bngl_model as _impl +from ..._models.bngl_model import * +from ..._models.bngl_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/model.py b/petab/v1/models/model.py new file mode 100644 index 00000000..124b4426 --- /dev/null +++ b/petab/v1/models/model.py @@ -0,0 +1,9 @@ +"""PEtab model abstraction""" + +from ..._models import model as _impl +from ..._models.model import * +from ..._models.model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/pysb_model.py b/petab/v1/models/pysb_model.py new file mode 100644 index 00000000..38893741 --- /dev/null +++ b/petab/v1/models/pysb_model.py @@ -0,0 +1,12 @@ +"""Deprecated: use :mod:`petab.v2.models.pysb_model`. + +PySB models are only supported with PEtab v2. +""" + +from ..._models import pysb_model as _impl +from ..._models.pysb_model import * +from ..._models.pysb_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/sbml_model.py b/petab/v1/models/sbml_model.py new file mode 100644 index 00000000..7f06cc67 --- /dev/null +++ b/petab/v1/models/sbml_model.py @@ -0,0 +1,9 @@ +"""Functions for handling SBML models""" + +from ..._models import sbml_model as _impl +from ..._models.sbml_model import * +from ..._models.sbml_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v2/core.py b/petab/v2/core.py index c719811a..9e782c37 100644 --- a/petab/v2/core.py +++ b/petab/v2/core.py @@ -50,12 +50,12 @@ ) from ..v1.distributions import * from ..v1.math import petab_math_str, sympify_petab -from ..v1.models.model import Model, model_factory from ..v1.yaml import get_path_prefix from ..versions import parse_version from . import C, get_observable_df from ._helpers import is_reserved_keyword, is_valid_identifier from .extensions import ExtensionConfig, parse_extension_config +from .models.model import Model, model_factory from .options import TableColumns, get_options if TYPE_CHECKING: diff --git a/petab/v2/models/__init__.py b/petab/v2/models/__init__.py index 7b66f4e6..49ecb8e3 100644 --- a/petab/v2/models/__init__.py +++ b/petab/v2/models/__init__.py @@ -1,3 +1,4 @@ """Handling of different model types supported by PEtab.""" -from ...v1.models import * +from ..._models import * +from ..._models import __all__ # noqa: F401 diff --git a/petab/v2/models/bngl_model.py b/petab/v2/models/bngl_model.py index 42df986d..c07727dc 100644 --- a/petab/v2/models/bngl_model.py +++ b/petab/v2/models/bngl_model.py @@ -1,3 +1,9 @@ """Functions for handling BNGL models""" -from ...v1.models.bngl_model import * +from ..._models import bngl_model as _impl +from ..._models.bngl_model import * +from ..._models.bngl_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v2/models/model.py b/petab/v2/models/model.py index 56c213bd..124b4426 100644 --- a/petab/v2/models/model.py +++ b/petab/v2/models/model.py @@ -1,3 +1,9 @@ """PEtab model abstraction""" -from ...v1.models.model import * +from ..._models import model as _impl +from ..._models.model import * +from ..._models.model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v2/models/pysb_model.py b/petab/v2/models/pysb_model.py index 1630f02c..171f3818 100644 --- a/petab/v2/models/pysb_model.py +++ b/petab/v2/models/pysb_model.py @@ -1,3 +1,9 @@ """Functions for handling PySB models""" -from ...v1.models.pysb_model import * +from ..._models import pysb_model as _impl +from ..._models.pysb_model import * +from ..._models.pysb_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v2/models/sbml_model.py b/petab/v2/models/sbml_model.py index e68b1581..7f06cc67 100644 --- a/petab/v2/models/sbml_model.py +++ b/petab/v2/models/sbml_model.py @@ -1,3 +1,9 @@ """Functions for handling SBML models""" -from ...v1.models.sbml_model import * +from ..._models import sbml_model as _impl +from ..._models.sbml_model import * +from ..._models.sbml_model import __all__ # noqa: F401 + + +def __getattr__(name): + return getattr(_impl, name) diff --git a/tests/models/__init__.py b/tests/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/models/bngl_corpus/README.md b/tests/models/bngl_corpus/README.md index 2aee5db8..5550643d 100644 --- a/tests/models/bngl_corpus/README.md +++ b/tests/models/bngl_corpus/README.md @@ -1,13 +1,13 @@ # Curated BNGL corpus fixtures Public community BNGL models, chosen for feature coverage, backing -`tests/v1/test_bngl_corpus.py`: it asserts `parse_bngl` enumerates the same +`tests/models/test_bngl_corpus.py`: it asserts `parse_bngl` enumerates the same model entities BNG2.pl does. The BNG2.pl answers are cached in `golden.json` (the entity name sets BNG2.pl emits from `writeModel`, its canonical parse), so the test needs **no BNG2.pl** -- it compares the reader against the frozen oracle. Regenerate the golden (needs BNG2.pl) with: - python tests/v1/test_bngl_corpus.py + python tests/models/test_bngl_corpus.py Vendored from public repos ([RuleWorld/RuleHub](https://github.com/RuleWorld/rulehub), diff --git a/tests/models/fetch_bngl_corpus.py b/tests/models/fetch_bngl_corpus.py index 21e9d721..6c41e486 100755 --- a/tests/models/fetch_bngl_corpus.py +++ b/tests/models/fetch_bngl_corpus.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Materialize the BNGL test corpus backing ``tests/v1/test_bngl_corpus.py``. +"""Materialize the BNGL test corpus for ``tests/models/test_bngl_corpus.py``. The corpus is 21 third-party ``.bngl`` fixture files. Rather than vendoring ~3200 lines of model text, this script fetches them on @@ -14,7 +14,7 @@ ``parity_checks/bng_parity/vendor_corpus.py``. Usage: - python tests/v1/fetch_bngl_corpus.py [--dest DIR] [--force] [--dry-run] + python tests/models/fetch_bngl_corpus.py [--dest DIR] [--force] [--dry-run] """ from __future__ import annotations @@ -47,7 +47,7 @@ # (dest filename, (repo, sha), upstream path, expected sha256 of the RAW # upstream bytes, optional (find, replace, expected_count) repair applied # after the hash check). Transcribed from -# tests/v1/bngl_corpus/README.md's provenance table. +# tests/models/bngl_corpus/README.md's provenance table. CORPUS = [ ( "An_2009.bngl", @@ -255,7 +255,7 @@ def main() -> int: type=Path, default=Path(__file__).parent / "bngl_corpus", help="directory to write fetched .bngl files into (default: " - "bngl_corpus/ next to this script, i.e. tests/v1/bngl_corpus)", + "bngl_corpus/ next to this script, i.e. tests/models/bngl_corpus)", ) ap.add_argument( "--force", diff --git a/tests/models/test_bngl_corpus.py b/tests/models/test_bngl_corpus.py index aa49f7d3..82e88ee0 100644 --- a/tests/models/test_bngl_corpus.py +++ b/tests/models/test_bngl_corpus.py @@ -1,6 +1,6 @@ """Corpus regression gate: the BNGL reader agrees with BNG2.pl on real models. -Asserts :func:`petab.v1.models.bngl_model.parse_bngl` enumerates the same model +Asserts :func:`petab.v2.models.bngl_model.parse_bngl` enumerates the same model entities BNG2.pl does, over a curated set of public community BNGL models under ``bngl_corpus/``. BNG2.pl's answers are cached in ``bngl_corpus/golden.json``: the entity name sets BNG2.pl emits from ``writeModel`` (its canonical parse, no @@ -13,7 +13,7 @@ Regenerate the golden after adding a fixture or changing the reader (needs a BNG2.pl on ``BNGPATH``/``PATH``) and review the diff:: - python tests/v1/test_bngl_corpus.py + python tests/models/test_bngl_corpus.py """ from __future__ import annotations @@ -28,14 +28,14 @@ import pytest -from petab.v1.models.bngl_model import parse_bngl +from petab.v2.models.bngl_model import parse_bngl _CORPUS = Path(__file__).parent / "bngl_corpus" _GOLDEN = _CORPUS / "golden.json" _MODELS = sorted(_CORPUS.glob("*.bngl")) _NO_CORPUS_REASON = ( - "no .bngl files in tests/v1/bngl_corpus/ -- fetch them first with " - "`python tests/v1/fetch_bngl_corpus.py`" + "no .bngl files in tests/models/bngl_corpus/ -- fetch them first with " + "`python tests/models/fetch_bngl_corpus.py`" ) @@ -170,7 +170,7 @@ def _canonical_bngl(model_text, bng2): def _regenerate(): - from petab.v1.models.bngl_model import _locate_bng2 + from petab.v2.models.bngl_model import _locate_bng2 bng2 = _locate_bng2() if bng2 is None: diff --git a/tests/models/test_model_bngl.py b/tests/models/test_model_bngl.py index b4641faf..cd83c6a7 100644 --- a/tests/models/test_model_bngl.py +++ b/tests/models/test_model_bngl.py @@ -1,10 +1,10 @@ -"""Tests for petab.v1.models.bngl_model""" +"""Tests for petab.v2.models.bngl_model""" from pathlib import Path import pytest -from petab.v1.models.bngl_model import BnglEntities, BnglModel, parse_bngl +from petab.v2.models.bngl_model import BnglEntities, BnglModel, parse_bngl #: A self-contained BNGL model exercising every entity kind read by the #: PEtab layer: parameters, a molecule type, a seed species, an observable, @@ -233,7 +233,7 @@ def test_is_valid(model): def test_is_valid_detects_broken_model_when_bng_available(tmp_path): - from petab.v1.models.bngl_model import _locate_bng2 + from petab.v2.models.bngl_model import _locate_bng2 if _locate_bng2() is None: pytest.skip("BNG2.pl not available; is_valid falls back to True") @@ -249,7 +249,7 @@ def test_is_valid_detects_broken_model_when_bng_available(tmp_path): def test_model_factory_routes_bngl(): - from petab.v1.models.model import model_factory + from petab.v2.models.model import model_factory model = model_factory(EXAMPLE_BNGL, "bngl") assert isinstance(model, BnglModel) diff --git a/tests/models/test_model_pysb.py b/tests/models/test_model_pysb.py index 48aa4481..6afebafd 100644 --- a/tests/models/test_model_pysb.py +++ b/tests/models/test_model_pysb.py @@ -1,9 +1,9 @@ -"""Test related to petab.models.model_pysb""" +"""Tests for petab.v2.models.pysb_model""" import pysb import pytest -from petab.v1.models.pysb_model import ( +from petab.v2.models.pysb_model import ( PySBModel, parse_species_name, pattern_from_string, From a491a76c249c60c201682065689d966481473c41 Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Mon, 23 Nov 2026 12:34:15 +0100 Subject: [PATCH 3/4] v2 lint: check model entities as condition targets and parameters Add a private classification of model entities (`petab._models._entities`, `Model._get_entity`, `Model._iter_entities`), implemented for SBML models: what an entity is (parameter, species, compartment, other quantity, non-quantity), how its value evolves (constant, differential, algebraic), and how the model defines its initial value. Use it in the new v2 validation task `CheckModelEntityEligibility`, which reports errors for entities that PEtab v2 does not allow as condition targets or in the parameter table, e.g. targets of assignment rules or event assignments, and warnings for questionable uses. Models without classification support are skipped. References #518. Co-Authored-By: Claude Opus 5.5 --- .../+v2-lint-entity-eligibility.breaking.md | 7 + petab/_models/_entities.py | 385 ++++++++++++ petab/_models/model.py | 44 +- petab/_models/sbml_model.py | 494 +++++++++++++++- petab/v2/lint.py | 78 +++ tests/models/test_model_entities.py | 548 ++++++++++++++++++ tests/v2/test_lint.py | 44 ++ 7 files changed, 1597 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+v2-lint-entity-eligibility.breaking.md create mode 100644 petab/_models/_entities.py create mode 100644 tests/models/test_model_entities.py diff --git a/changelog.d/+v2-lint-entity-eligibility.breaking.md b/changelog.d/+v2-lint-entity-eligibility.breaking.md new file mode 100644 index 00000000..3c9e75c4 --- /dev/null +++ b/changelog.d/+v2-lint-entity-eligibility.breaking.md @@ -0,0 +1,7 @@ +PEtab v2 validation: the new validation task `CheckModelEntityEligibility` +reports errors for model entities that the PEtab v2 specification does not +allow as condition targets (e.g., targets of assignment rules, reactions) or +in the parameter table (e.g., targets of assignment rules, rate rules, or +event assignments), and warnings for questionable but valid uses. +Currently implemented for SBML models +([#TODO](https://github.com/PEtab-dev/libpetab-python/pull/TODO)) diff --git a/petab/_models/_entities.py b/petab/_models/_entities.py new file mode 100644 index 00000000..e07e4377 --- /dev/null +++ b/petab/_models/_entities.py @@ -0,0 +1,385 @@ +"""Classification of model entities. + +Each model wrapper (:class:`petab.v2.models.Model` subclass) describes the +entities of its model as :class:`EntityInfo` objects +(:meth:`petab.v2.models.Model._get_entity`, +:meth:`petab.v2.models.Model._iter_entities`). +The functions in this module answer PEtab-level questions about an entity, +e.g., whether it may be a condition target or a parameter-table row, +based on that description only. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from enum import StrEnum +from functools import cached_property +from typing import TYPE_CHECKING, Literal + +if TYPE_CHECKING: + import sympy as sp + +__all__ = [ + "Dynamics", + "EligibilityIssue", + "EntityCategory", + "EntityInfo", + "Initializer", + "InitializerKind", + "SpeciesQuantity", + "condition_target_issue", + "has_literal_default", + "is_constant_parameter", + "parameter_table_issue", +] + + +class EntityCategory(StrEnum): + """What a model entity is.""" + + #: A plain scalar quantity, e.g., an SBML parameter. + PARAMETER = "parameter" + #: An amount or concentration of a chemical species. + SPECIES = "species" + #: A compartment; its value is the compartment size. + COMPARTMENT = "compartment" + #: Any other quantity, e.g., a reaction rate, a stoichiometry, or an + #: observable or expression defined in the model. + #: Neither a valid condition target nor a parameter-table entry. + OTHER_QUANTITY = "other_quantity" + #: An identifier that does not denote a number, e.g., an event, + #: a function definition, or a molecule type. + NON_QUANTITY = "non_quantity" + + +class Dynamics(StrEnum): + """How the value of an entity evolves over time. + + This is the *entity type* defined by the PEtab v2 specification. + """ + + #: Constant, or piecewise constant if subject to event assignments. + CONSTANT = "constant" + #: Defined by a time derivative. + DIFFERENTIAL = "differential" + #: Determined by an algebraic equation that is in effect throughout the + #: simulation, e.g., the target of an SBML assignment rule, the + #: unknown of an SBML algebraic rule, a reaction rate, or a PySB + #: expression. + ALGEBRAIC = "algebraic" + + +class SpeciesQuantity(StrEnum): + """Whether the value of a species is an amount or a concentration.""" + + AMOUNT = "amount" + CONCENTRATION = "concentration" + + +class InitializerKind(StrEnum): + """How the model defines the initial value of an entity.""" + + #: A number, or an expression over numbers only. + LITERAL = "literal" + #: An expression over other model entities. + FORMULA = "formula" + #: No initial value, or not introspectable. + UNSPECIFIED = "unspecified" + + +@dataclass(frozen=True, kw_only=True) +class Initializer: + """The initial value of an entity, as defined by the model itself. + + This is the value before PEtab applies any parameter-table values or + condition changes. + Use :meth:`literal`, :meth:`formula`, or :meth:`unspecified` to create + instances. + + :ivar kind: How the initial value is defined. + :ivar value: The initial value, for ``LITERAL`` initializers only. + :ivar raw: The defining expression in the model's own syntax, + for ``FORMULA`` initializers only. + :ivar dependencies: IDs of the model entities and functions that + the defining expression refers to, for ``FORMULA`` initializers only. + """ + + kind: InitializerKind + value: float | None = None + raw: str | None = None + dependencies: frozenset[str] = frozenset() + _expression_factory: Callable[[], sp.Expr] | None = field( + default=None, compare=False, repr=False + ) + + @classmethod + def literal(cls, value: float) -> Initializer: + """Create an initializer for a numeric initial value.""" + return cls(kind=InitializerKind.LITERAL, value=float(value)) + + @classmethod + def formula( + cls, + raw: str, + dependencies: Iterable[str] = (), + expression: Callable[[], sp.Expr] | None = None, + ) -> Initializer: + """Create an initializer for an initial value defined by an + expression. + + :param raw: The expression in the model's own syntax. + :param dependencies: IDs the expression refers to. + :param expression: A function returning the expression as a sympy + expression; called at most once, when :attr:`expression` is + first accessed. + """ + return cls( + kind=InitializerKind.FORMULA, + raw=raw, + dependencies=frozenset(dependencies), + _expression_factory=expression, + ) + + @classmethod + def unspecified(cls) -> Initializer: + """Create an initializer for an entity without initial value.""" + return cls(kind=InitializerKind.UNSPECIFIED) + + @cached_property + def expression(self) -> sp.Expr | None: + """The defining expression as a sympy expression. + + ``None`` for non-``FORMULA`` initializers, and if the model type + does not support conversion to sympy. + """ + if self._expression_factory is None: + return None + return self._expression_factory() + + +@dataclass(frozen=True, kw_only=True) +class EntityInfo: + """Description of a model entity. + + :ivar id: The entity's ID in the model, or, for PySB and BNGL species, + the species pattern string. + :ivar category: What the entity is. + :ivar dynamics: How the entity's value evolves. + ``None`` for :attr:`EntityCategory.NON_QUANTITY` entities. + :ivar event_assigned: Whether the entity is the target of an event + assignment. A ``CONSTANT`` entity that is not event-assigned is + *truly constant* in the sense of the PEtab v2 specification. + :ivar initializer: How the model defines the entity's initial value. + :ivar usable_in_math: Whether the ID may be used as a symbol in PEtab + math expressions, e.g., in observable formulas. + :ivar native_type: The model-specific type of the entity, + e.g., ``"sbml:Species"``. For messages only. + :ivar species_quantity: Whether the value is an amount or a + concentration. For species only. + :ivar declared: Whether the model declares the entity. + ``False`` for PySB and BNGL species patterns that are valid, but + not declared by the model; the model's rules may or may not + generate such a species. + :ivar notes: Remarks about questionable aspects of the entity, + e.g., an ambiguous algebraic rule. Validation reports each as a + warning. + """ + + id: str + category: EntityCategory + dynamics: Dynamics | None + event_assigned: bool = False + initializer: Initializer = field(default_factory=Initializer.unspecified) + usable_in_math: bool = True + native_type: str = "" + species_quantity: SpeciesQuantity | None = None + declared: bool = True + notes: tuple[str, ...] = () + + +@dataclass(frozen=True) +class EligibilityIssue: + """A reason why an entity is not, or not unconditionally, eligible for + some use. + + :ivar message: Human-readable description, naming the model construct. + :ivar level: ``"error"`` if the use is invalid, ``"warning"`` if it is + allowed but questionable. + """ + + message: str + level: Literal["error", "warning"] + + +def is_constant_parameter(info: EntityInfo) -> bool: + """Check whether the entity is a parameter of constant type. + + Event-assigned parameters are included. + """ + return ( + info.category == EntityCategory.PARAMETER + and info.dynamics == Dynamics.CONSTANT + ) + + +def has_literal_default(info: EntityInfo) -> bool: + """Check whether the model defines a numeric initial value for the + entity.""" + return info.initializer.kind == InitializerKind.LITERAL + + +def _matches( + info: EntityInfo, + category: EntityCategory | None, + dynamics: Dynamics | None, +) -> bool: + """Check whether the entity matches the given filters.""" + return (category is None or info.category == category) and ( + dynamics is None or info.dynamics == dynamics + ) + + +def _describe(info: EntityInfo) -> str: + """Short description of an entity for messages.""" + if info.native_type: + return f"`{info.id}` ({info.native_type})" + return f"`{info.id}`" + + +def _notes_issue(info: EntityInfo) -> EligibilityIssue | None: + if not info.notes: + return None + return EligibilityIssue( + f"{_describe(info)}: " + " ".join(info.notes), "warning" + ) + + +def _check_petab_version(petab_version: int) -> None: + if petab_version not in (1, 2): + raise ValueError(f"Unsupported PEtab version: {petab_version}") + + +def condition_target_issue( + info: EntityInfo, *, petab_version: Literal[1, 2] +) -> EligibilityIssue | None: + """Check whether the entity may be changed by the condition table. + + :param info: The entity. + :param petab_version: The PEtab major version whose rules apply. + :returns: ``None`` if the entity is a valid condition target without + reservations, otherwise the most severe issue. + """ + _check_petab_version(petab_version) + what = _describe(info) + + if info.category not in ( + EntityCategory.PARAMETER, + EntityCategory.SPECIES, + EntityCategory.COMPARTMENT, + ): + return EligibilityIssue( + f"{what} cannot be changed by a condition: it is not a " + "parameter, species, or compartment.", + "error", + ) + + if info.dynamics == Dynamics.ALGEBRAIC: + if petab_version == 2: + return EligibilityIssue( + f"{what} is defined by an algebraic assignment (e.g., an " + "assignment rule) and cannot be changed by a condition.", + "error", + ) + return EligibilityIssue( + f"{what} is defined by an algebraic assignment (e.g., an " + "assignment rule). The assignment overrides any condition " + "value, so the condition has no effect.", + "warning", + ) + + # PEtab v2 specifies that the condition value replaces the model's + # definition, PEtab v1 does not + if ( + petab_version == 1 + and info.category == EntityCategory.PARAMETER + and info.initializer.kind == InitializerKind.FORMULA + ): + return EligibilityIssue( + f"{what} is defined in the model as `{info.initializer.raw}`. " + "The condition value replaces that definition; some " + "simulators ignore it.", + "warning", + ) + + if not info.declared: + return EligibilityIssue( + f"{what} is not declared in the model; it is a valid species " + "pattern, but it may not exist in the generated reaction " + "network.", + "warning", + ) + + return _notes_issue(info) + + +def parameter_table_issue( + info: EntityInfo, *, petab_version: Literal[1, 2] +) -> EligibilityIssue | None: + """Check whether the entity may be listed in the parameter table. + + :param info: The entity. + :param petab_version: The PEtab major version whose rules apply. + :returns: ``None`` if the entity is a valid parameter-table entry + without reservations, otherwise the most severe issue. + """ + _check_petab_version(petab_version) + what = _describe(info) + + if info.category != EntityCategory.PARAMETER: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: " + "it is not a parameter.", + "error", + ) + + if info.dynamics == Dynamics.ALGEBRAIC: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: it is " + "defined by an algebraic assignment (e.g., an assignment rule).", + "error", + ) + + if info.dynamics == Dynamics.DIFFERENTIAL: + msg = ( + f"{what} cannot be listed in the parameter table: it is defined " + "by a time derivative (e.g., a rate rule)." + ) + if petab_version == 1: + msg += " This is a restriction of this library." + return EligibilityIssue(msg, "error") + + if info.event_assigned: + if petab_version == 2: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: " + "it is the target of an event assignment.", + "error", + ) + return EligibilityIssue( + f"{what} is the target of an event assignment. This is allowed " + "in PEtab v1, but invalid in PEtab v2.", + "warning", + ) + + if info.initializer.kind == InitializerKind.FORMULA: + return EligibilityIssue( + f"{what} is defined in the model as `{info.initializer.raw}`. " + "In PEtab v2, the parameter-table value replaces that " + "definition; PEtab v1 does not specify this, and some " + "simulators keep the model definition and ignore the " + "parameter-table value.", + "warning", + ) + + return _notes_issue(info) diff --git a/petab/_models/model.py b/petab/_models/model.py index 57c991dc..6372d5ff 100644 --- a/petab/_models/model.py +++ b/petab/_models/model.py @@ -3,9 +3,12 @@ from __future__ import annotations import abc -from collections.abc import Iterable +from collections.abc import Iterable, Iterator from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ._entities import Dynamics, EntityCategory, EntityInfo __all__ = ["Model", "model_factory"] @@ -136,6 +139,43 @@ def is_state_variable(self, id_: str) -> bool: """Check whether the given ID corresponds to a model state variable""" ... + def _get_entity(self, id_: str) -> EntityInfo | None: + """Get the description of the model entity with the given ID. + + Private for now; the interface may still change. + + :param id_: The entity's ID in the model, or, for PySB and BNGL + models, a species pattern string. + :returns: The entity description, or ``None`` if the model has no + such entity. + :raises NotImplementedError: If the model type does not support + entity classification yet. + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement `_get_entity`." + ) + + def _iter_entities( + self, + category: EntityCategory | None = None, + dynamics: Dynamics | None = None, + ) -> Iterator[EntityInfo]: + """Iterate over the entities of the model. + + Private for now; the interface may still change. + Species that the model does not declare, e.g., species generated + by reaction rules, are not included. + + :param category: Only include entities of this category. + :param dynamics: Only include entities with this dynamics. + :returns: Iterator over entity descriptions. + :raises NotImplementedError: If the model type does not support + entity classification yet. + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement `_iter_entities`." + ) + def model_factory( filepath_or_buffer: Any, diff --git a/petab/_models/sbml_model.py b/petab/_models/sbml_model.py index ce791ec5..6c7c85f4 100644 --- a/petab/_models/sbml_model.py +++ b/petab/_models/sbml_model.py @@ -3,7 +3,9 @@ from __future__ import annotations import itertools -from collections.abc import Iterable +from collections.abc import Iterable, Iterator +from functools import cached_property +from math import isnan as math_isnan from pathlib import Path import libsbml @@ -18,6 +20,14 @@ write_sbml, ) from . import MODEL_TYPE_SBML +from ._entities import ( + Dynamics, + EntityCategory, + EntityInfo, + Initializer, + SpeciesQuantity, + _matches, +) from .model import Model __all__ = ["SbmlModel"] @@ -303,6 +313,488 @@ def is_state_variable(self, id_: str) -> bool: or self.sbml_model.getRuleByVariable(id_) is not None ) + def _get_entity(self, id_: str) -> EntityInfo | None: + """Get the description of the model entity with the given ID. + + Elements are classified as follows: + + * parameters, species, compartments, and species references + (stoichiometries): by their rules, event assignments, and + participation in reactions; + * reactions (their rates): read-only quantities; + * events and function definitions: non-quantities. + + Other elements with an ID, e.g., local parameters, unit definitions, + or elements of SBML packages, are not entities. + Of ``comp`` models, only the main model is considered. + Results reflect the current state of the SBML model. + + See :meth:`petab.v2.models.Model._get_entity`. + """ + element = self.sbml_model.getElementBySId(id_) + if ( + element is None + or element.getPackageName() != "core" + or element.getTypeCode() not in _SBML_ENTITY_TYPES + ): + return None + return _classify_sbml_element( + element, _SbmlModelIndex(self.sbml_model, single=True) + ) + + def _iter_entities( + self, + category: EntityCategory | None = None, + dynamics: Dynamics | None = None, + ) -> Iterator[EntityInfo]: + """Iterate over the entities of the model. + + See :meth:`_get_entity` and + :meth:`petab.v2.models.Model._iter_entities`. + """ + index = _SbmlModelIndex(self.sbml_model) + # Not `getListOfAllElements`, which is quadratic in the model size, + # and which would include local parameters of SBML L2 models. + elements = [ + element + for element in _iter_sbml_elements(self.sbml_model) + if element.isSetIdAttribute() + ] + + def generate(): + for element in elements: + info = _classify_sbml_element(element, index) + if info is not None and _matches(info, category, dynamics): + yield info + + return generate() + + +def _iter_sbml_elements(model: libsbml.Model) -> Iterator[libsbml.SBase]: + """Iterate over the SBML core elements of a model that may have an ID. + + Local parameters are not included. + """ + # Not rules, initial assignments, or event assignments: libsbml does not + # resolve their `id` attribute in `getElementBySId`. + yield from model.getListOfFunctionDefinitions() + yield from model.getListOfCompartments() + yield from model.getListOfSpecies() + yield from model.getListOfParameters() + for reaction in model.getListOfReactions(): + yield reaction + yield from reaction.getListOfReactants() + yield from reaction.getListOfProducts() + yield from reaction.getListOfModifiers() + yield from model.getListOfEvents() + + +def _iter_sbml_math(model: libsbml.Model) -> Iterator[libsbml.ASTNode]: + """Iterate over the math of all SBML core elements of a model.""" + for element in itertools.chain( + model.getListOfFunctionDefinitions(), + model.getListOfInitialAssignments(), + model.getListOfRules(), + model.getListOfConstraints(), + ( + reaction.getKineticLaw() + for reaction in model.getListOfReactions() + if reaction.isSetKineticLaw() + ), + *( + ( + event.getTrigger(), + event.getDelay(), + event.getPriority(), + *event.getListOfEventAssignments(), + ) + for event in model.getListOfEvents() + ), + ): + if element is not None and element.isSetMath(): + yield element.getMath() + + +#: Type codes of SBML elements whose value can be set or computed. +_SBML_VARIABLE_TYPES = { + libsbml.SBML_PARAMETER, + libsbml.SBML_SPECIES, + libsbml.SBML_COMPARTMENT, + libsbml.SBML_SPECIES_REFERENCE, +} + +#: Type codes of the SBML core elements that are entities +#: (see :func:`_iter_sbml_elements`). +_SBML_ENTITY_TYPES = { + *_SBML_VARIABLE_TYPES, + libsbml.SBML_FUNCTION_DEFINITION, + libsbml.SBML_REACTION, + libsbml.SBML_MODIFIER_SPECIES_REFERENCE, + libsbml.SBML_EVENT, +} + + +class _SbmlModelIndex: + """Model-wide information needed to classify SBML elements. + + In bulk mode, each aggregate is computed on first use, by one pass over + the model. In single mode (for classifying a single element), targeted + lookups are used where possible. + Only valid as long as the model is not modified. + """ + + def __init__(self, model: libsbml.Model, single: bool = False): + self.model = model + self.single = single + + def rule_type(self, id_: str) -> int | None: + """The type code of the assignment or rate rule for the given ID.""" + if not self.single: + return self.rule_types.get(id_) + rule = self.model.getRuleByVariable(id_) + if rule is None or rule.isAlgebraic(): + return None + return rule.getTypeCode() + + def initial_assignment(self, id_: str) -> libsbml.InitialAssignment | None: + if not self.single: + return self.initial_assignments.get(id_) + return self.model.getInitialAssignmentBySymbol(id_) + + def is_event_assigned(self, id_: str) -> bool: + if not self.single: + return id_ in self.event_assignment_targets + return any( + ea.getVariable() == id_ + for event in self.model.getListOfEvents() + for ea in event.getListOfEventAssignments() + ) + + def is_reactant_or_product(self, id_: str) -> bool: + if not self.single: + return id_ in self.reactants_and_products + return any( + species_ref.getSpecies() == id_ + for reaction in self.model.getListOfReactions() + for species_ref in itertools.chain( + reaction.getListOfReactants(), reaction.getListOfProducts() + ) + ) + + def algebraic_info(self, id_: str) -> tuple[bool, list[str]]: + """Whether the entity is determined by an algebraic rule, and notes. + + See :attr:`algebraic`. + """ + if self.single and not any( + node.getType() == libsbml.AST_NAME and node.getName() == id_ + for rule in self.model.getListOfRules() + if rule.isAlgebraic() and rule.isSetMath() + for node in _iter_ast(rule.getMath()) + ): + return False, [] + determined, notes = self.algebraic + return id_ in determined, notes.get(id_, []) + + @cached_property + def rule_types(self) -> dict[str, int]: + """Rule type codes by rule variable.""" + return { + rule.getVariable(): rule.getTypeCode() + for rule in self.model.getListOfRules() + if not rule.isAlgebraic() + } + + @cached_property + def event_assignment_targets(self) -> set[str]: + return { + ea.getVariable() + for event in self.model.getListOfEvents() + for ea in event.getListOfEventAssignments() + } + + @cached_property + def initial_assignments(self) -> dict[str, libsbml.InitialAssignment]: + return { + ia.getSymbol(): ia + for ia in self.model.getListOfInitialAssignments() + } + + @cached_property + def reactants_and_products(self) -> set[str]: + """IDs of species that are reactants or products of any reaction.""" + return { + species_ref.getSpecies() + for reaction in self.model.getListOfReactions() + for species_ref in itertools.chain( + reaction.getListOfReactants(), reaction.getListOfProducts() + ) + } + + @cached_property + def algebraic(self) -> tuple[set[str], dict[str, list[str]]]: + """Entities determined by algebraic rules. + + :returns: The IDs of entities that are the only candidate for being + determined by some algebraic rule, and notes for entities that + are one of several candidates. + """ + rules = [ + rule for rule in self.model.getListOfRules() if rule.isAlgebraic() + ] + if not rules: + return set(), {} + + rate_of_targets = { + node.getChild(0).getName() + for math in _iter_sbml_math(self.model) + for node in _iter_ast(math) + if node.getType() == libsbml.AST_FUNCTION_RATE_OF + and node.getNumChildren() == 1 + } + + def is_candidate(id_: str) -> bool: + element = self.model.getElementBySId(id_) + if ( + element is None + or element.getTypeCode() not in _SBML_VARIABLE_TYPES + or element.getConstant() + or self.rule_type(id_) is not None + or id_ in rate_of_targets + ): + return False + return not ( + element.getTypeCode() == libsbml.SBML_SPECIES + and not element.getBoundaryCondition() + and self.is_reactant_or_product(id_) + ) + + # (rule formula, candidates) for each rule not yet resolved + undecided = [ + ( + libsbml.formulaToL3String(rule.getMath()), + [ + c + for c in sorted( + { + node.getName() + for node in _iter_ast(rule.getMath()) + if node.getType() == libsbml.AST_NAME + } + ) + if is_candidate(c) + ], + ) + for rule in rules + if rule.isSetMath() + ] + # A rule with a single undetermined candidate determines it; + # repeat until no rule determines a new entity. + determined = set() + changed = True + while changed: + changed = False + still_undecided = [] + for formula, candidates in undecided: + remaining = [c for c in candidates if c not in determined] + if len(remaining) <= 1: + determined.update(remaining) + changed = True + else: + still_undecided.append((formula, remaining)) + undecided = still_undecided + + notes = {} + for formula, candidates in undecided: + for candidate in candidates: + notes.setdefault(candidate, []).append( + f"It may be determined by the algebraic rule " + f"`0 = {formula}`, which has several candidate " + f"variables ({', '.join(candidates)})." + ) + return determined, notes + + +def _iter_ast(node: libsbml.ASTNode) -> Iterator[libsbml.ASTNode]: + """Iterate over all nodes of an AST.""" + nodes = [node] + while nodes: + node = nodes.pop() + yield node + nodes.extend(node.getChild(i) for i in range(node.getNumChildren())) + + +#: AST node types that refer to the model state or time. +_AST_NON_CLOSED_TYPES = { + libsbml.AST_NAME, + libsbml.AST_NAME_TIME, + libsbml.AST_FUNCTION, + libsbml.AST_FUNCTION_DELAY, + libsbml.AST_FUNCTION_RATE_OF, +} + + +def _initializer_from_math(math: libsbml.ASTNode) -> Initializer: + """Classify an initial-assignment formula. + + Formulas over numbers only are evaluated; anything referring to model + entities, time, or function definitions is ``FORMULA``. + """ + dependencies = set() + closed = True + for node in _iter_ast(math): + if node.getType() in _AST_NON_CLOSED_TYPES: + closed = False + if node.getType() in (libsbml.AST_NAME, libsbml.AST_FUNCTION): + dependencies.add(node.getName()) + + if closed: + value = libsbml.SBMLTransforms.evaluateASTNode(math) + # libsbml returns NaN for anything it cannot evaluate + if not math_isnan(value) or math.isNaN(): + return Initializer.literal(value) + + math = math.deepCopy() + return Initializer.formula( + raw=libsbml.formulaToL3String(math), + dependencies=dependencies, + expression=lambda: sympify_sbml(math), + ) + + +def _formula_initializer( + formula: str, dependencies: set[str], model: libsbml.Model +) -> Initializer: + # with the model, so that IDs like `pi` or `time` are not taken as + # constants or csymbols + math = libsbml.parseL3FormulaWithModel(formula, model) + return Initializer.formula( + raw=formula, + dependencies=dependencies, + expression=lambda: sympify_sbml(math), + ) + + +def _attribute_initializer(element: libsbml.SBase) -> Initializer: + """The initial value given by the attributes of an element.""" + type_code = element.getTypeCode() + if type_code == libsbml.SBML_PARAMETER: + if element.isSetValue(): + return Initializer.literal(element.getValue()) + elif type_code == libsbml.SBML_COMPARTMENT: + if element.isSetSize(): + return Initializer.literal(element.getSize()) + elif type_code == libsbml.SBML_SPECIES_REFERENCE: + # defaults to 1 before SBML L3 + if element.isSetStoichiometry() or element.getLevel() < 3: + return Initializer.literal(element.getStoichiometry()) + elif type_code == libsbml.SBML_SPECIES: + compartment = element.getCompartment() + if element.getHasOnlySubstanceUnits(): + if element.isSetInitialAmount(): + return Initializer.literal(element.getInitialAmount()) + if element.isSetInitialConcentration(): + return _formula_initializer( + f"{element.getInitialConcentration()!r} * {compartment}", + {compartment}, + element.getModel(), + ) + else: + if element.isSetInitialConcentration(): + return Initializer.literal(element.getInitialConcentration()) + if element.isSetInitialAmount(): + return _formula_initializer( + f"{element.getInitialAmount()!r} / {compartment}", + {compartment}, + element.getModel(), + ) + return Initializer.unspecified() + + +def _classify_sbml_element( + element: libsbml.SBase, index: _SbmlModelIndex +) -> EntityInfo | None: + """Classify an SBML element with an ID.""" + type_code = element.getTypeCode() + id_ = element.getIdAttribute() + native_type = f"sbml:{type(element).__name__}" + + if type_code == libsbml.SBML_REACTION: + return EntityInfo( + id=id_, + category=EntityCategory.OTHER_QUANTITY, + dynamics=Dynamics.ALGEBRAIC, + native_type=native_type, + ) + + if type_code not in _SBML_VARIABLE_TYPES: + return EntityInfo( + id=id_, + category=EntityCategory.NON_QUANTITY, + dynamics=None, + usable_in_math=False, + native_type=native_type, + ) + + category = { + libsbml.SBML_PARAMETER: EntityCategory.PARAMETER, + libsbml.SBML_SPECIES: EntityCategory.SPECIES, + libsbml.SBML_COMPARTMENT: EntityCategory.COMPARTMENT, + libsbml.SBML_SPECIES_REFERENCE: EntityCategory.OTHER_QUANTITY, + }[type_code] + + rule_type = index.rule_type(id_) + algebraic_determined, algebraic_notes = ( + index.algebraic_info(id_) if rule_type is None else (False, []) + ) + if ( + rule_type == libsbml.SBML_ASSIGNMENT_RULE + or algebraic_determined + or ( + type_code == libsbml.SBML_SPECIES_REFERENCE + and element.isSetStoichiometryMath() + ) + ): + dynamics = Dynamics.ALGEBRAIC + elif rule_type == libsbml.SBML_RATE_RULE or ( + type_code == libsbml.SBML_SPECIES + and not element.getBoundaryCondition() + and not element.getConstant() + and index.is_reactant_or_product(id_) + ): + dynamics = Dynamics.DIFFERENTIAL + else: + dynamics = Dynamics.CONSTANT + + if dynamics == Dynamics.ALGEBRAIC: + initializer = Initializer.unspecified() + elif (ia := index.initial_assignment(id_)) is not None and ia.isSetMath(): + initializer = _initializer_from_math(ia.getMath()) + else: + initializer = _attribute_initializer(element) + + species_quantity = None + if type_code == libsbml.SBML_SPECIES: + species_quantity = ( + SpeciesQuantity.AMOUNT + if element.getHasOnlySubstanceUnits() + else SpeciesQuantity.CONCENTRATION + ) + + return EntityInfo( + id=id_, + category=category, + dynamics=dynamics, + event_assigned=index.is_event_assigned(id_), + initializer=initializer, + # species reference IDs only have a mathematical meaning since L3 + usable_in_math=element.getLevel() >= 3 + or type_code != libsbml.SBML_SPECIES_REFERENCE, + native_type=native_type, + species_quantity=species_quantity, + notes=tuple(algebraic_notes), + ) + def sympify_sbml(sbml_obj: libsbml.ASTNode | libsbml.SBase) -> sp.Expr: """Convert SBML math expression to sympy expression. diff --git a/petab/v2/lint.py b/petab/v2/lint.py index 3a995e66..96c7e506 100644 --- a/petab/v2/lint.py +++ b/petab/v2/lint.py @@ -14,7 +14,13 @@ import pandas as pd import sympy as sp +from .._models._entities import ( + EligibilityIssue, + condition_target_issue, + parameter_table_issue, +) from ..v2.C import * +from ._helpers import _matches_id_pattern from .core import PriorDistribution, Problem logger = logging.getLogger(__name__) @@ -31,6 +37,7 @@ "CheckMeasuredObservablesDefined", "CheckMeasurementModelId", "CheckModel", + "CheckModelEntityEligibility", "CheckNeuralNetworkModel", "CheckObservablesDoNotShadowModelEntities", "CheckOverridesMatchPlaceholders", @@ -615,6 +622,76 @@ def run(self, problem: Problem) -> ValidationIssue | None: return None +class CheckModelEntityEligibility(ValidationTask): + """Check that model entities are only changed by conditions and listed + in the parameter table where the PEtab specification allows it. + + For example, targets of assignment rules must not be condition targets, + and targets of event assignments must not be in the parameter table. + Condition targets and parameter-table IDs are resolved via the mapping + table. IDs that are not model entities are not checked here. + Models that do not support entity classification are skipped. + """ + + def run(self, problem: Problem) -> ValidationIssue | None: + model_ids = { + m.petab_id: m.model_id for m in problem.mappings if m.model_id + } + targets = { + change.target_id + for cond in problem.conditions + for change in cond.changes + } + checks = [ + *((id_, condition_target_issue) for id_ in sorted(targets)), + *( + (id_, parameter_table_issue) + for id_ in sorted({p.id for p in problem.parameters}) + ), + ] + + errors = [] + warnings = [] + for model in problem.models: + try: + entities = {e.id: e for e in model._iter_entities()} + except NotImplementedError: + continue + + for petab_id, check in checks: + model_id = model_ids.get(petab_id, petab_id) + if (info := entities.get(model_id)) is None: + # only species patterns may be missing from + # `_iter_entities`, and they are no valid identifiers + if _matches_id_pattern(model_id): + continue + if (info := model._get_entity(model_id)) is None: + continue + issue: EligibilityIssue | None = check(info, petab_version=2) + if issue is None: + continue + where = ( + "Condition table" + if check is condition_target_issue + else "Parameter table" + ) + alias = ( + f" (`{petab_id}` in the mapping table)" + if model_id != petab_id + else "" + ) + message = f"{where}{alias}: {issue.message}" + (errors if issue.level == "error" else warnings).append( + message + ) + + if errors: + return ValidationError("\n".join(errors)) + if warnings: + return ValidationWarning("\n".join(warnings)) + return None + + class CheckValidParameterInConditionOrParameterTable(ValidationTask): """A task to check that all required and only allowed model parameters are present in the condition or parameter table.""" @@ -1270,6 +1347,7 @@ def get_placeholders( CheckObservablesDoNotShadowModelEntities(), CheckAllParametersPresentInParameterTable(), CheckValidParameterInConditionOrParameterTable(), + CheckModelEntityEligibility(), CheckUnusedExperiments(), CheckUnusedConditions(), CheckUnusedPlaceholders(), diff --git a/tests/models/test_model_entities.py b/tests/models/test_model_entities.py new file mode 100644 index 00000000..1f0701a9 --- /dev/null +++ b/tests/models/test_model_entities.py @@ -0,0 +1,548 @@ +"""Tests for the model entity classification (`petab._models._entities`).""" + +import libsbml +import pytest +import sympy as sp + +from petab._models._entities import ( + Dynamics, + EntityCategory, + EntityInfo, + Initializer, + InitializerKind, + SpeciesQuantity, + condition_target_issue, + has_literal_default, + is_constant_parameter, + parameter_table_issue, +) +from petab.v2.models.sbml_model import SbmlModel + +K = EntityCategory +T = Dynamics +LIT = Initializer.literal +UNSPECIFIED = Initializer.unspecified() + + +def kw(**kwargs): + """Keyword arguments as a dict.""" + return kwargs + + +def formula(raw, *dependencies): + return Initializer.formula(raw=raw, dependencies=dependencies) + + +def assert_consistent(model): + """`_iter_entities` and `_get_entity` agree.""" + entities = list(model._iter_entities()) + assert len({e.id for e in entities}) == len(entities) + for info in entities: + assert model._get_entity(info.id) == info + return {e.id: e for e in entities} + + +# --- _entities.py --- + + +def test_initializer(): + calls = [] + + def factory(): + calls.append(1) + return sp.Symbol("k") * 2 + + init = Initializer.formula( + raw="2*k", dependencies=["k"], expression=factory + ) + assert init.kind == InitializerKind.FORMULA + assert init.dependencies == {"k"} + assert not calls + assert init.expression == 2 * sp.Symbol("k") + assert init.expression == 2 * sp.Symbol("k") + assert calls == [1] + # the expression factory is not part of equality + assert init == Initializer.formula(raw="2*k", dependencies=["k"]) + assert Initializer.formula(raw="2*k").expression is None + + assert LIT(2) == Initializer(kind=InitializerKind.LITERAL, value=2.0) + assert LIT(2).expression is None + assert UNSPECIFIED.kind == InitializerKind.UNSPECIFIED + + +def _info(**kwargs): + defaults = kw(id="x", category=K.PARAMETER, dynamics=T.CONSTANT) + return EntityInfo(**(defaults | kwargs)) + + +@pytest.mark.parametrize( + "info, v1, v2", + [ + (_info(), None, None), + (_info(event_assigned=True), None, None), + (_info(dynamics=T.DIFFERENTIAL), None, None), + (_info(category=K.SPECIES, dynamics=T.DIFFERENTIAL), None, None), + ( + _info(category=K.SPECIES, initializer=formula("k", "k")), + None, + None, + ), + (_info(category=K.COMPARTMENT), None, None), + (_info(dynamics=T.ALGEBRAIC), "warning", "error"), + (_info(category=K.OTHER_QUANTITY), "error", "error"), + (_info(category=K.NON_QUANTITY, dynamics=None), "error", "error"), + (_info(initializer=formula("2*k", "k")), "warning", None), + ( + _info(category=K.SPECIES, declared=False), + "warning", + "warning", + ), + (_info(notes=("ambiguous",)), "warning", "warning"), + ], +) +def test_condition_target_issue(info, v1, v2): + for version, expected in ((1, v1), (2, v2)): + issue = condition_target_issue(info, petab_version=version) + assert (issue and issue.level) == expected + if issue: + assert "`x`" in issue.message + + +@pytest.mark.parametrize( + "info, v1, v2", + [ + (_info(), None, None), + (_info(event_assigned=True), "warning", "error"), + (_info(dynamics=T.DIFFERENTIAL), "error", "error"), + (_info(dynamics=T.ALGEBRAIC), "error", "error"), + (_info(category=K.SPECIES), "error", "error"), + (_info(category=K.COMPARTMENT), "error", "error"), + (_info(category=K.OTHER_QUANTITY), "error", "error"), + (_info(initializer=formula("2*k", "k")), "warning", "warning"), + (_info(notes=("ambiguous",)), "warning", "warning"), + ], +) +def test_parameter_table_issue(info, v1, v2): + for version, expected in ((1, v1), (2, v2)): + issue = parameter_table_issue(info, petab_version=version) + assert (issue and issue.level) == expected + + +def test_issue_functions_require_version(): + with pytest.raises(TypeError): + condition_target_issue(_info()) + with pytest.raises(ValueError): + parameter_table_issue(_info(), petab_version=3) + + +def test_predicates(): + assert is_constant_parameter(_info()) + assert is_constant_parameter(_info(event_assigned=True)) + assert not is_constant_parameter(_info(dynamics=T.DIFFERENTIAL)) + assert not is_constant_parameter(_info(category=K.SPECIES)) + assert has_literal_default(_info(initializer=LIT(1))) + assert not has_literal_default(_info()) + assert not has_literal_default(_info(initializer=formula("k", "k"))) + + +# --- SBML --- + + +@pytest.fixture +def sbml_model() -> SbmlModel: + model = SbmlModel.from_antimony(""" + function f(x) + 2 * x + end + + model m + compartment c = 2 + compartment c_unset + species S in c = 1 + species B in c + $B = 3 + species B_ev in c + $B_ev = 3 + species B_rate in c + $B_rate = 3 + species S_ar in c + species S_const in c + const S_const = 5 + species S_free in c + S_free = 4 + substanceOnly species S_amount in c = 6 + species S_ia in c + S_ia = 2 * k + + J0: S -> ; k * S + + k = 0.1 + k_ev = 1 + k_ar := 2 * k + S_ar := 2 * k + k_rate' = 1 + k_rate = 0 + B_rate' = 1 + k_ia = 2 * k + k_ia_num = 3^2 + k_ia_func = f(2) + + E1: at time > 1: k_ev = 2, B_ev = 1 + end + """) + parameter = model.sbml_model.createParameter() + parameter.setId("k_unset") + parameter.setConstant(True) + return model + + +@pytest.mark.parametrize( + "id_, expected", + [ + ( + "k", + kw( + category=K.PARAMETER, dynamics=T.CONSTANT, initializer=LIT(0.1) + ), + ), + ( + "k_ev", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + event_assigned=True, + initializer=LIT(1), + ), + ), + ("k_ar", kw(category=K.PARAMETER, dynamics=T.ALGEBRAIC)), + ( + "k_rate", + kw( + category=K.PARAMETER, + dynamics=T.DIFFERENTIAL, + initializer=LIT(0), + ), + ), + ( + "k_ia", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + initializer=formula("2 * k", "k"), + ), + ), + ( + "k_ia_num", + kw(category=K.PARAMETER, dynamics=T.CONSTANT, initializer=LIT(9)), + ), + ( + "k_ia_func", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + initializer=formula("f(2)", "f"), + ), + ), + ("k_unset", kw(category=K.PARAMETER, dynamics=T.CONSTANT)), + ( + "S", + kw( + category=K.SPECIES, + dynamics=T.DIFFERENTIAL, + initializer=LIT(1), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B_ev", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + event_assigned=True, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B_rate", + kw( + category=K.SPECIES, + dynamics=T.DIFFERENTIAL, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_ar", + kw( + category=K.SPECIES, + dynamics=T.ALGEBRAIC, + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_const", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(5), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + # in no reaction, no rule + "S_free", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(4), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_amount", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(6), + species_quantity=SpeciesQuantity.AMOUNT, + ), + ), + ( + "S_ia", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=formula("2 * k", "k"), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "c", + kw( + category=K.COMPARTMENT, dynamics=T.CONSTANT, initializer=LIT(2) + ), + ), + ("c_unset", kw(category=K.COMPARTMENT, dynamics=T.CONSTANT)), + ("J0", kw(category=K.OTHER_QUANTITY, dynamics=T.ALGEBRAIC)), + ( + "E1", + kw(category=K.NON_QUANTITY, dynamics=None, usable_in_math=False), + ), + ( + "f", + kw(category=K.NON_QUANTITY, dynamics=None, usable_in_math=False), + ), + ], +) +def test_sbml_entities(sbml_model, id_, expected): + element = sbml_model.sbml_model.getElementBySId(id_) + expected = EntityInfo( + id=id_, native_type=f"sbml:{type(element).__name__}", **expected + ) + assert sbml_model._get_entity(id_) == expected + + +def test_sbml_consistency(sbml_model): + entities = assert_consistent(sbml_model) + assert {"k", "S", "c", "J0", "E1", "f"} <= entities.keys() + assert sbml_model._get_entity("time") is None + assert sbml_model._get_entity("nonexistent") is None + + +def test_sbml_filter(sbml_model): + ids = { + e.id + for e in sbml_model._iter_entities( + category=K.PARAMETER, dynamics=T.CONSTANT + ) + } + assert ids == {"k", "k_ev", "k_ia", "k_ia_num", "k_ia_func", "k_unset"} + + +def test_sbml_initializer_expression(sbml_model): + expr = sbml_model._get_entity("k_ia").initializer.expression + assert {str(s) for s in expr.free_symbols} == {"k"} + assert float(expr.subs(dict.fromkeys(expr.free_symbols, 0.5))) == 1 + + +def test_sbml_species_other_form(): + """Initial amount for a concentration-based species.""" + model = SbmlModel.from_antimony(""" + compartment c = 2 + species S in c + S = 1 + """) + species = model.sbml_model.getSpecies("S") + species.unsetInitialConcentration() + species.setInitialAmount(4) + assert model._get_entity("S").initializer == formula("4.0 / c", "c") + expr = model._get_entity("S").initializer.expression + assert float(expr.subs(dict.fromkeys(expr.free_symbols, 2))) == 2 + + +def test_sbml_species_other_form_reserved_compartment_id(): + """A compartment ID that is a constant in L3 formulas is not one here.""" + model = SbmlModel.from_antimony(""" + compartment c = 2 + species S in c + S = 1 + """) + model.sbml_model.getCompartment("c").setId("pi") + species = model.sbml_model.getSpecies("S") + species.setCompartment("pi") + species.unsetInitialConcentration() + species.setInitialAmount(4) + expr = model._get_entity("S").initializer.expression + assert {str(s) for s in expr.free_symbols} == {"pi"} + + +def test_sbml_live_mutation(sbml_model): + sbml_model.sbml_model.getParameter("k").setValue(7) + assert sbml_model._get_entity("k").initializer == LIT(7) + rule = sbml_model.sbml_model.createAssignmentRule() + rule.setVariable("k") + rule.setMath(libsbml.parseL3Formula("1")) + assert sbml_model._get_entity("k").dynamics == T.ALGEBRAIC + assert sbml_model._get_entity("k").initializer == UNSPECIFIED + + +def _sbml_with_algebraic_rule(formula: str) -> SbmlModel: + model = SbmlModel.from_antimony(""" + compartment c = 1 + species S in c = 1 + x = 1 + y = 1 + J0: S -> ; S + """) + for id_ in ("x", "y"): + model.sbml_model.getParameter(id_).setConstant(False) + rule = model.sbml_model.createAlgebraicRule() + rule.setMath(libsbml.parseL3Formula(formula)) + return model + + +def test_sbml_algebraic_rule_single_candidate(): + # `S` is a non-boundary reactant, so `x` is the only candidate + model = _sbml_with_algebraic_rule("x - S") + assert model._get_entity("x").dynamics == T.ALGEBRAIC + assert model._get_entity("x").initializer == UNSPECIFIED + assert model._get_entity("x").notes == () + assert model._get_entity("S").dynamics == T.DIFFERENTIAL + assert model._get_entity("y").dynamics == T.CONSTANT + assert_consistent(model) + + +def test_sbml_algebraic_rule_several_candidates(): + model = _sbml_with_algebraic_rule("x + y - 1") + for id_ in ("x", "y"): + info = model._get_entity(id_) + assert info.dynamics == T.CONSTANT + assert len(info.notes) == 1 + assert "x, y" in info.notes[0] + assert condition_target_issue(info, petab_version=2).level == ( + "warning" + ) + assert_consistent(model) + + +def test_sbml_algebraic_rules_resolved_in_turn(): + # `0 = y - 2` determines `y`, leaving `x` as the only candidate of + # `0 = x + y - 1` + model = _sbml_with_algebraic_rule("x + y - 1") + rule = model.sbml_model.createAlgebraicRule() + rule.setMath(libsbml.parseL3Formula("y - 2")) + for id_ in ("x", "y"): + info = model._get_entity(id_) + assert info.dynamics == T.ALGEBRAIC + assert info.notes == () + assert_consistent(model) + + +def test_sbml_ids_of_rules(): + """IDs of rules and initial assignments are not entities. + + libsbml does not resolve them by ID. + """ + model = SbmlModel.from_antimony(""" + a = 1 + b := 2 * a + """) + model.sbml_model.getRuleByVariable("b").setIdAttribute("rule1") + assert model._get_entity("rule1") is None + assert "rule1" not in assert_consistent(model) + + +def test_sbml_ids_of_other_elements(): + """IDs of elements that are not enumerated are not entities.""" + model = SbmlModel.from_antimony(""" + S -> ; k * S + k = 1 + S = 1 + """) + reaction = model.sbml_model.getReaction(0) + reaction.getKineticLaw().setIdAttribute("kl") + assert model.sbml_model.getElementBySId("kl") is not None + assert model._get_entity("kl") is None + assert "kl" not in assert_consistent(model) + + +def test_sbml_species_reference_and_l2_local_parameter(): + document = libsbml.SBMLDocument(2, 4) + model = document.createModel() + model.setId("m") + c = model.createCompartment() + c.setId("c") + c.setSize(1) + s = model.createSpecies() + s.setId("S") + s.setCompartment("c") + s.setInitialConcentration(1) + reaction = model.createReaction() + reaction.setId("R") + reactant = reaction.createReactant() + reactant.setSpecies("S") + reactant.setId("sr") + reactant.setStoichiometry(2) + kinetic_law = reaction.createKineticLaw() + local = kinetic_law.createParameter() + local.setId("k_local") + local.setValue(1) + kinetic_law.setMath(libsbml.parseL3Formula("k_local * S")) + # no stoichiometry: 1 in SBML L2 + product = reaction.createProduct() + product.setSpecies("S") + product.setId("sp") + # stoichiometryMath + reactant2 = reaction.createReactant() + reactant2.setSpecies("S") + reactant2.setId("sr_math") + reactant2.createStoichiometryMath().setMath( + libsbml.parseL3Formula("2 * c") + ) + + sbml_model = SbmlModel(sbml_model=model) + assert not product.isSetStoichiometry() + assert sbml_model._get_entity("sp").initializer == LIT(1) + assert sbml_model._get_entity("sr_math").dynamics == T.ALGEBRAIC + assert sbml_model._get_entity("sr") == EntityInfo( + id="sr", + category=K.OTHER_QUANTITY, + dynamics=T.CONSTANT, + initializer=LIT(2), + # no mathematical meaning in SBML L2 + usable_in_math=False, + native_type="sbml:SpeciesReference", + ) + assert sbml_model._get_entity("k_local") is None + entities = assert_consistent(sbml_model) + assert "k_local" not in entities diff --git a/tests/v2/test_lint.py b/tests/v2/test_lint.py index ea6c44f2..9141bc2f 100644 --- a/tests/v2/test_lint.py +++ b/tests/v2/test_lint.py @@ -320,3 +320,47 @@ def test_check_prior_distribution_infinite_bounds(): problem["p1"].prior_parameters = [0, float("inf")] assert (error := check.run(problem)) is not None assert "`p1` are invalid" in error.message + + +def test_check_model_entity_eligibility(): + problem = Problem() + problem.model = SbmlModel.from_antimony(""" + k = 1 + k_rule := 2 * k + k_event = 1 + at time > 1: k_event = 2 + k_ia = 2 * k + """) + problem.add_parameter("k", estimate=True, nominal_value=1, lb=0, ub=10) + check = CheckModelEntityEligibility() + assert check.run(problem) is None + + # parameter defined by an initial assignment: allowed, but questionable + problem.add_parameter("k_ia", estimate=False, nominal_value=1) + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.WARNING + assert "k_ia" in issue.message + + # event-assigned parameter in the parameter table + problem.add_parameter("k_event", estimate=False, nominal_value=1) + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.ERROR + assert "k_event" in issue.message + assert "k_ia" not in issue.message + + # assignment rule target as condition target + problem.parameter_tables[0].elements = [ + p for p in problem.parameters if p.id == "k" + ] + problem.add_condition("c1", k_rule="1") + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.ERROR + assert "Condition table: `k_rule`" in issue.message + assert "k_event" not in issue.message + + # models without entity classification are skipped + def not_implemented(*args, **kwargs): + raise NotImplementedError + + problem.model._iter_entities = not_implemented + assert check.run(problem) is None From 7023be02cee531ac6da28a196f84195e10782c5c Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Mon, 23 Nov 2026 14:41:15 +0100 Subject: [PATCH 4/4] Add PR number to changelog entry Co-Authored-By: Claude Opus 5.5 --- changelog.d/+v2-lint-entity-eligibility.breaking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/+v2-lint-entity-eligibility.breaking.md b/changelog.d/+v2-lint-entity-eligibility.breaking.md index 3c9e75c4..0522d632 100644 --- a/changelog.d/+v2-lint-entity-eligibility.breaking.md +++ b/changelog.d/+v2-lint-entity-eligibility.breaking.md @@ -4,4 +4,4 @@ allow as condition targets (e.g., targets of assignment rules, reactions) or in the parameter table (e.g., targets of assignment rules, rate rules, or event assignments), and warnings for questionable but valid uses. Currently implemented for SBML models -([#TODO](https://github.com/PEtab-dev/libpetab-python/pull/TODO)) +([#623](https://github.com/PEtab-dev/libpetab-python/pull/623))