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 new file mode 100644 index 00000000..a1290bc7 --- /dev/null +++ b/petab/_models/bngl_model.py @@ -0,0 +1,404 @@ +"""BNGL (BioNetGen Language) model support for PEtab. + +Adds a ``bngl`` model type, so a PEtab problem declaring ``language: bngl`` +can be loaded and validated. + +:class:`BnglModel` is backed by :func:`parse_bngl`, a small, dependency-free +BNGL reader. It only reads a model's declared entities -- parameters, +observables, functions, molecule types, compartments, seed species -- which +is all PEtab validation needs; it never runs BNG2.pl or generates a reaction +network. The one exception is :meth:`BnglModel.is_valid`: if a ``BNG2.pl`` +is found (``BNGPATH`` or ``PATH``), it runs ``BNG2.pl --check`` (a +parse/semantic check, no network generation); otherwise the model is +assumed valid. + +Two things worth knowing if a model doesn't parse the way you expect: + +* Symbols usable in an observable formula are parameters, observables, and + functions -- *not* compartments. +* The reader accepts line continuations (a trailing ``\\``), ``begin + species`` as an alias for ``begin seed species``, line labels (both the + numeric ``1 L0 1`` and named ``CD14: ...`` forms), and a leading ``$`` + (fixed-concentration) marker on a seed species. + +Examples +-------- + +For example BNGL PEtab v2 problems, see the `PyBioNetFit +`_ `tutorials +`_. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path + +from .._utils import _generate_path +from ..v1.lint import is_valid_identifier +from . import MODEL_TYPE_BNGL +from .model import Model + +__all__ = ["BnglEntities", "BnglModel", "parse_bngl"] + +#: The three keywords that open an observable declaration line. +_OBS_KEYWORDS = frozenset({"Molecules", "Species", "Counter"}) + +#: Short spellings BNG2.pl accepts for a block's canonical (long) name; either +#: spelling opens and closes the same block. The grammar doc +#: (``BNG_vscode_extension/docs/bngl-grammar.md``) also lists ``molecules`` and +#: ``rules``, but BNG2.pl 2.9.3 -- the reference this reader targets -- rejects +#: both ("Could not process block type"), so honoring them would accept models +#: BNG2.pl refuses. Only ``species`` (for ``seed species``, also BNG2.pl's own +#: canonical output spelling) is real. +_BLOCK_ALIASES = { + "seed species": ("species",), +} + + +@dataclass(frozen=True) +class BnglEntities: + """The named entities of a BNGL model that the PEtab layer reads. + + :ivar text: The verbatim BNGL model text. + :ivar parameters: Maps a parameter name to its raw right-hand side -- a + number (``"5"``, ``"6.02e23"``) or an expression (``"2*base"``), + kept verbatim; numeric coercion is the caller's job. + :ivar observable_names: Bare observable names. + :ivar function_names: Bare global-function names (without ``()``). + :ivar molecule_type_names: Bare molecule-type names. + :ivar seed_species: Concrete seed-species pattern strings (verbatim). + :ivar compartment_names: Bare compartment names. + """ + + text: str + parameters: dict[str, str] + observable_names: frozenset[str] + function_names: frozenset[str] + molecule_type_names: frozenset[str] + seed_species: frozenset[str] + compartment_names: frozenset[str] + + +def parse_bngl(text: str) -> BnglEntities: + """Parse BNGL ``text`` into a :class:`BnglEntities`. + + A stdlib ``begin``/``end `` scanner -- no BNG2.pl, no network + generation. Sufficient for PEtab validation, which only introspects the + model's declared entities. + + :param text: The BNGL model text. + :returns: The model's named entities. + """ + parameters: dict[str, str] = {} + for line in _block_lines(text, "parameters"): + name_value = _parameter_name_value(line) + if name_value is not None: + parameters[name_value[0]] = name_value[1] + return BnglEntities( + text=text, + parameters=parameters, + observable_names=_names(text, "observables", _observable_name), + function_names=_names(text, "functions", _function_name), + molecule_type_names=_names( + text, "molecule types", _molecule_type_name + ), + seed_species=_names(text, "seed species", _seed_species_pattern), + compartment_names=_names(text, "compartments", _compartment_name), + ) + + +def _names(text: str, block_name: str, extractor) -> frozenset[str]: + """The non-empty names ``extractor`` yields over a block's lines.""" + return frozenset( + name + for name in ( + extractor(line) for line in _block_lines(text, block_name) + ) + if name + ) + + +def _logical_lines(text: str) -> list[str]: + """The comment-stripped *logical* lines of ``text`` -- physical lines with + BNGL line continuations joined. + + Mirrors BNG2.pl's ``readFile`` (``Perl2/BNGModel.pm``): strip the ``#`` + comment first, then while the line ends with ``\\`` (as its last + non-whitespace character) drop that ``\\`` and append the next + comment-stripped physical line *directly* -- no separating space, so a + token split across the break (``1e\\`` + ``3`` -> ``1e3``) rejoins. + Without this, a continued parameter / function / observable is truncated at + the ``\\`` (e.g. a ``k = \\`` line would read as the value ``"\\"``). + """ + raw_lines = text.splitlines() + out = [] + i, n = 0, len(raw_lines) + while i < n: + line = raw_lines[i].split("#", 1)[0] + i += 1 + while re.search(r"\\\s*$", line): + line = re.sub(r"\\\s*$", "", line) + if i >= n: + break # a dangling continuation at EOF + line += raw_lines[i].split("#", 1)[0] + i += 1 + out.append(line.strip()) + return out + + +def _block_lines(text: str, block_name: str) -> list[str]: + """The comment-stripped, non-blank lines inside ``begin``/``end``. + + ``block_name`` is the canonical (long) spelling; a BNG2.pl-accepted alias + for it (only ``species`` for ``seed species``; see :data:`_BLOCK_ALIASES`) + opens and closes the same block. Lines are logical lines -- continuations + joined (see :func:`_logical_lines`). + """ + names = "|".join( + re.escape(name) + for name in (block_name, *_BLOCK_ALIASES.get(block_name, ())) + ) + begin = re.compile(rf"^begin\s+(?:{names})\b", re.IGNORECASE) + end = re.compile(rf"^end\s+(?:{names})\b", re.IGNORECASE) + lines = [] + in_block = False + for line in _logical_lines(text): + if begin.match(line): + in_block = True + elif end.match(line): + in_block = False + elif in_block and line: + lines.append(line) + return lines + + +def _strip_line_label(line: str) -> str: + """Drop a leading BNGL line label so the entity, not the label, is read. + + ``LineLabel = {Digit}, WS | Name, ":", [WS]`` (grammar) -- either a numeric + index (the legacy ``.net``-style ``1 L0 1`` form) or a named label + (``CD14: CD14(...)``). A valid BNGL identifier starts with a letter, so a + leading digit-run is always an index; a compartment prefix is ``@Name:`` + (with the ``@``), so a bare ``Name:`` at line start is unambiguously a + label. + """ + match = re.match(r"^\d+\s+(.*)$", line) or re.match( + r"^[A-Za-z]\w*:\s+(.*)$", line + ) + return match.group(1) if match else line + + +def _parameter_name_value(line: str) -> tuple[str, str] | None: + """``(name, rhs)`` for a ``[LineLabel] Name (WS|"=") MathExpr`` line.""" + line = _strip_line_label(line) + match = re.match(r"^(\w+)\s*=\s*(.+)$", line) or re.match( + r"^(\w+)\s+(.+)$", line + ) + return (match.group(1), match.group(2).strip()) if match else None + + +def _observable_name(line: str) -> str | None: + """The name in a `` `` observable line.""" + tokens = line.split() + if len(tokens) >= 2 and tokens[0] in _OBS_KEYWORDS: + return tokens[1] + return None + + +def _function_name(line: str) -> str | None: + """The name in a ``() = ...`` global-function line.""" + match = re.match(r"(\w+)\s*\(", line) or re.match(r"(\w+)\s*=", line) + return match.group(1) if match else None + + +def _molecule_type_name(line: str) -> str | None: + """The name in a ``(...)`` molecule-type line.""" + match = re.match(r"(\w+)", line) + return match.group(1) if match else None + + +def _seed_species_pattern(line: str) -> str | None: + """The species pattern in a ``[LineLabel] ["$"] `` line. + + A leading line label (numeric index ``1 A() 100`` or named + ``CD14: CD14(...)``; see :func:`_strip_line_label`) is dropped first so the + label is not mistaken for the species. A leading ``$`` (the fixed/clamped- + concentration marker, ``SeedSpeciesDefn = ["$"], Species, WS, + MathExpression``) is a modifier, not part of the species identity, so it + too is stripped: ``$counter() 10`` + enumerates the state variable ``counter()``. + """ + line = _strip_line_label(line) + if line.startswith("$"): + line = line[1:].lstrip() + tokens = line.split() + return tokens[0] if tokens else None + + +def _compartment_name(line: str) -> str | None: + """The name in a `` [outside]`` line.""" + tokens = line.split() + return tokens[0] if tokens else None + + +class BnglModel(Model): + """PEtab wrapper for BNGL models.""" + + type_id = MODEL_TYPE_BNGL + + def __init__( + self, + model: BnglEntities, + model_id: str | None = None, + rel_path: Path | str | None = None, + base_path: str | Path | None = None, + ): + super().__init__() + + self.rel_path = rel_path + self.base_path = base_path + + self.model = model + self._model_id = model_id + + if not is_valid_identifier(self._model_id): + raise ValueError( + f"Model ID '{self._model_id}' is not a valid identifier. " + "Either provide a valid identifier or rename the model file " + "to a valid PEtab model identifier." + ) + + @staticmethod + def from_file( + filepath_or_buffer, + model_id: str | None = None, + base_path: str | Path | None = None, + ) -> BnglModel: + path = Path(_generate_path(filepath_or_buffer, base_path)) + text = path.read_text(encoding="utf-8", errors="replace") + return BnglModel( + model=parse_bngl(text), + model_id=model_id or path.stem, + rel_path=filepath_or_buffer, + base_path=base_path, + ) + + def to_file(self, filename: str | Path | None = None) -> None: + target = filename or _generate_path(self.rel_path, self.base_path) + with open(target, "w", encoding="utf-8") as f: + f.write(self.model.text) + + @property + def model_id(self): + return self._model_id + + @model_id.setter + def model_id(self, model_id): + self._model_id = model_id + + def get_parameter_ids(self) -> Iterable[str]: + return list(self.model.parameters) + + def get_parameter_value(self, id_: str) -> float: + try: + rhs = self.model.parameters[id_] + except KeyError as e: + raise ValueError(f"Parameter {id_} does not exist.") from e + try: + return float(rhs) + except ValueError as e: + raise NotImplementedError( + f"Parameter '{id_}' has an expression value '{rhs}'. " + "Evaluating a BNGL parameter expression requires BNG2.pl / " + "network generation, which is out of scope for the " + "introspection-only BnglModel." + ) from e + + def get_free_parameter_ids_with_values( + self, + ) -> Iterable[tuple[str, float]]: + out = [] + for name, rhs in self.model.parameters.items(): + try: + out.append((name, float(rhs))) + except ValueError: + # An expression-valued parameter has no introspection-grade + # value; skip it rather than evaluate the expression. + continue + return out + + def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: + # All parameters are allowed in the parameter table. + return list(self.model.parameters) + + def has_entity_with_id(self, entity_id) -> bool: + # The full declared-identifier namespace. + return ( + entity_id in self.model.parameters + or entity_id in self.model.observable_names + or entity_id in self.model.function_names + or entity_id in self.model.molecule_type_names + or entity_id in self.model.compartment_names + or entity_id in self.model.seed_species + ) + + def get_valid_ids_for_condition_table(self) -> Iterable[str]: + return list(self.model.parameters) + list(self.model.compartment_names) + + def symbol_allowed_in_observable_formula(self, id_: str) -> bool: + # The BNG ParamList: parameters, observables, global functions only. + return ( + id_ in self.model.parameters + or id_ in self.model.observable_names + or id_ in self.model.function_names + ) + + def is_state_variable(self, id_: str) -> bool: + # At introspection grade only the concrete seed species are known; + # the full species set is a network-generation product. + return id_ in self.model.seed_species + + def is_valid(self) -> bool: + # Real BNG2.pl --check (parse/semantic validation, no network + # generation) when locatable, else True -- never a false failure + # where no BNG backend is available. + bng2 = _locate_bng2() + if bng2 is None or self.rel_path is None: + return True + path = Path(_generate_path(self.rel_path, self.base_path)) + if not path.is_file(): + # No local model file to check (e.g. a buffer-loaded model). + return True + # Resolve to an absolute path so BNG2.pl finds the model regardless + # of the working directory it runs in (its output stays next to the + # model via ``cwd``). + path = path.resolve() + try: + result = subprocess.run( # noqa: S603 + [bng2, "--check", str(path)], + capture_output=True, + text=True, + timeout=120, + cwd=str(path.parent), + check=False, + ) + except (OSError, subprocess.SubprocessError): + # A tooling hiccup must not masquerade as an invalid model. + return True + return result.returncode == 0 + + +def _locate_bng2() -> str | None: + """A path to ``BNG2.pl`` via ``BNGPATH`` or ``PATH``, else ``None``.""" + bngpath = os.environ.get("BNGPATH") + if bngpath: + candidate = Path(bngpath) / "BNG2.pl" + if candidate.is_file(): + return str(candidate) + return shutil.which("BNG2.pl") diff --git a/petab/_models/model.py b/petab/_models/model.py new file mode 100644 index 00000000..57c991dc --- /dev/null +++ b/petab/_models/model.py @@ -0,0 +1,188 @@ +"""PEtab model abstraction""" + +from __future__ import annotations + +import abc +from collections.abc import Iterable +from pathlib import Path +from typing import Any + +__all__ = ["Model", "model_factory"] + + +class Model(abc.ABC): + """Base class for wrappers for any PEtab-supported model type""" + + @abc.abstractmethod + def __init__(self): ... + + def __repr__(self): + return f"<{self.__class__.__name__} {self.model_id!r}>" + + @staticmethod + @abc.abstractmethod + def from_file( + filepath_or_buffer: Any, + model_id: str, + base_path: str | Path | None = None, + ) -> Model: + """Load the model from the given path/URL + + :param filepath_or_buffer: + Absolute or relative path/URL to the model file. + If relative, it is interpreted relative to `base_path`, if given. + :param base_path: Base path for relative paths in the model file. + :param model_id: Model ID + :returns: A ``Model`` instance holding the given model + """ + ... + + @abc.abstractmethod + def to_file(self, filename: str | Path | None = None): + """Save the model to the given file + + :param filename: Destination filename + """ + ... + + @classmethod + @property + @abc.abstractmethod + def type_id(cls): ... + + @property + @abc.abstractmethod + def model_id(self): ... + + @abc.abstractmethod + def get_parameter_value(self, id_: str) -> float: + """Get a parameter value + + :param id_: ID of the parameter whose value is to be returned + :raises ValueError: If no parameter with the given ID exists + :returns: The value of the given parameter as specified in the model + """ + ... + + @abc.abstractmethod + def get_free_parameter_ids_with_values( + self, + ) -> Iterable[tuple[str, float]]: + """Get free model parameters along with their values + + Returns: + Iterator over tuples of (parameter_id, parameter_value) + """ + ... + + @abc.abstractmethod + def get_parameter_ids(self) -> Iterable[str]: + """Get all parameter IDs from this model + + :returns: Iterator over model parameter IDs + """ + ... + + @abc.abstractmethod + def has_entity_with_id(self, entity_id) -> bool: + """Check if there is a model entity with the given ID + + :param entity_id: ID to check for + :returns: + ``True``, if there is an entity with the given ID, + ``False`` otherwise + """ + ... + + @abc.abstractmethod + def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: + """Get IDs of all parameters that are allowed to occur in the PEtab + parameters table + + :returns: Iterator over parameter IDs + """ + ... + + @abc.abstractmethod + def get_valid_ids_for_condition_table(self) -> Iterable[str]: + """Get IDs of all model entities that are allowed to occur as columns + in the PEtab conditions table. + + :returns: Iterator over model entity IDs + """ + ... + + @abc.abstractmethod + def symbol_allowed_in_observable_formula(self, id_: str) -> bool: + """Check if the given ID is allowed to be used in observable and noise + formulas + + :returns: ``True``, if allowed, ``False`` otherwise + """ + ... + + @abc.abstractmethod + def is_valid(self) -> bool: + """Validate this model + + :returns: + `True` if the model is valid, `False` if there are errors in + this model + """ + ... + + @abc.abstractmethod + def is_state_variable(self, id_: str) -> bool: + """Check whether the given ID corresponds to a model state variable""" + ... + + +def model_factory( + filepath_or_buffer: Any, + model_language: str, + model_id: str | None = None, + base_path: str | Path | None = None, +) -> Model: + """Create a PEtab model instance from the given model + + :param filepath_or_buffer: Path/URL of the model. + Absolute or relative to `base_path` if given. + :param base_path: Base path for relative paths in the model file. + :param model_language: PEtab model language ID for the given model + :param model_id: PEtab model ID for the given model + :returns: A :py:class:`Model` instance representing the given model + """ + from . import ( + MODEL_TYPE_BNGL, + MODEL_TYPE_PYSB, + MODEL_TYPE_SBML, + known_model_types, + ) + + if model_language == MODEL_TYPE_SBML: + from .sbml_model import SbmlModel + + return SbmlModel.from_file( + filepath_or_buffer, model_id=model_id, base_path=base_path + ) + + if model_language == MODEL_TYPE_PYSB: + from .pysb_model import PySBModel + + return PySBModel.from_file( + filepath_or_buffer, model_id=model_id, base_path=base_path + ) + + if model_language == MODEL_TYPE_BNGL: + from .bngl_model import BnglModel + + return BnglModel.from_file( + filepath_or_buffer, model_id=model_id, base_path=base_path + ) + + if model_language in known_model_types: + raise NotImplementedError( + f"Unsupported model format: {model_language}" + ) + + raise ValueError(f"Unknown model format: {model_language}") diff --git a/petab/_models/pysb_model.py b/petab/_models/pysb_model.py new file mode 100644 index 00000000..0fa4be66 --- /dev/null +++ b/petab/_models/pysb_model.py @@ -0,0 +1,364 @@ +"""Functions for handling PySB models""" + +from __future__ import annotations + +import ast +import itertools +import re +import sys +from collections import Counter +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import Any + +import pysb + +from .._utils import _generate_path +from ..v1.lint import is_valid_identifier +from . import MODEL_TYPE_PYSB +from .model import Model + +__all__ = ["PySBModel", "parse_species_name", "pattern_from_string"] + + +def _pysb_model_from_path(pysb_model_file: str | Path) -> pysb.Model: + """Load a pysb model module and return the :class:`pysb.Model` instance + + :param pysb_model_file: Full or relative path to the PySB model module + :return: The pysb Model instance + """ + pysb_model_file = Path(pysb_model_file) + pysb_model_module_name = pysb_model_file.with_suffix("").name + + import importlib.util + + spec = importlib.util.spec_from_file_location( + pysb_model_module_name, pysb_model_file + ) + module = importlib.util.module_from_spec(spec) + sys.modules[pysb_model_module_name] = module + spec.loader.exec_module(module) + + # find a pysb.Model instance in the module + # 1) check if module.model exists and is a pysb.Model + model = getattr(module, "model", None) + if model: + return model + + # 2) check if there is any other pysb.Model instance + for x in dir(module): + attr = getattr(module, x) + if isinstance(attr, pysb.Model): + return attr + + raise ValueError(f"Could not find any pysb.Model in {pysb_model_file}.") + + +class PySBModel(Model): + """PEtab wrapper for PySB models""" + + type_id = MODEL_TYPE_PYSB + + def __init__( + self, + model: pysb.Model, + model_id: str | None = None, + rel_path: Path | str | None = None, + base_path: str | Path | None = None, + ): + super().__init__() + + self.rel_path = rel_path + self.base_path = base_path + + self.model = model + self._model_id = model_id or self.model.name + + if not is_valid_identifier(self._model_id): + raise ValueError( + f"Model ID '{self._model_id}' is not a valid identifier. " + "Either provide a valid identifier or change the model name " + "to a valid PEtab model identifier." + ) + + @staticmethod + def from_file( + filepath_or_buffer, + model_id: str | None = None, + base_path: str | Path | None = None, + ) -> PySBModel: + return PySBModel( + model=_pysb_model_from_path( + _generate_path(filepath_or_buffer, base_path) + ), + model_id=model_id, + rel_path=filepath_or_buffer, + base_path=base_path, + ) + + def to_file(self, filename: str | Path | None = None) -> None: + model_source = self.to_str() + + with open( + filename or _generate_path(self.rel_path, self.base_path), "w" + ) as f: + f.write(model_source) + + def to_str(self) -> str: + """Get the PySB model Python code as a string.""" + from pysb.export import export + + return export(self.model, "pysb_flat") + + @property + def model_id(self): + return self._model_id + + @model_id.setter + def model_id(self, model_id): + self._model_id = model_id + + def get_parameter_ids(self) -> Iterable[str]: + return (p.name for p in self.model.parameters) + + def get_parameter_value(self, id_: str) -> float: + try: + return self.model.parameters[id_].value + except KeyError as e: + raise ValueError(f"Parameter {id_} does not exist.") from e + + def get_free_parameter_ids_with_values( + self, + ) -> Iterable[tuple[str, float]]: + return ((p.name, p.value) for p in self.model.parameters) + + def has_entity_with_id(self, entity_id) -> bool: + try: + _ = self.model.components[entity_id] + return True + except KeyError: + return False + + def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: + # all parameters are allowed in the parameter table + return self.get_parameter_ids() + + def get_valid_ids_for_condition_table(self) -> Iterable[str]: + return itertools.chain( + self.get_parameter_ids(), self.get_compartment_ids() + ) + + def symbol_allowed_in_observable_formula(self, id_: str) -> bool: + return id_ in ( + x.name + for x in itertools.chain( + self.model.parameters, + self.model.observables, + self.model.expressions, + ) + ) + + def is_valid(self) -> bool: + # PySB models are always valid + return True + + def is_state_variable(self, id_: str) -> bool: + """Check whether the given ID is a plausible PySB species name. + + The ID has to be a species pattern (e.g., ``A(b=1, s='u') % B(a=1)``) + with all sites of all monomers specified and all bonds paired. + Compartments are optional, even if the model has compartments. + This does not check whether the species is actually generated by + the model's rules, or whether all monomers of a complex are + connected. + """ + # If there is a component with that name, it's not a state variable + # (there are no dynamically-sized compartments) + if self.model.components.get(id_, None): + return False + + try: + pattern = pattern_from_string(id_, self.model) + except ValueError: + return False + + for mp in pattern.monomer_patterns: + if not mp.is_site_concrete(): + return False + # is_site_concrete() doesn't check this for duplicate sites + for site, count in Counter(mp.monomer.sites).items(): + if site not in mp.site_conditions: + return False + site_value = mp.site_conditions[site] + if ( + isinstance(site_value, pysb.MultiState) + and len(site_value) != count + ): + return False + + # each bond has to connect exactly two sites + bond_counts = Counter( + bond + for mp in pattern.monomer_patterns + for site_value in mp.site_conditions.values() + for bond in _iter_bonds(site_value) + ) + return all(count == 2 for count in bond_counts.values()) + + def get_compartment_ids(self) -> Iterable[str]: + return (compartment.name for compartment in self.model.compartments) + + +def parse_species_name( + name: str, +) -> list[tuple[str, str | None, dict[str, Any]]]: + """Parse a PySB species name + + Site values in the form of ``(state, bond)`` tuples and + :class:`pysb.MultiState` are not supported. + See :func:`pattern_from_string` for a more complete parser. + + :param name: Species name to parse + :returns: List of species, representing complex constituents, each as + a tuple of the monomer name, the compartment name, and a dict of sites + mapping to site states. + :raises ValueError: In case this is not a valid ID + """ + if "=MultiState(" in name: + raise NotImplementedError("MultiState is not yet supported.") + + complex_constituent_pattern = re.compile( + r"^(?P\w+)\((?P.*)\)" + r"( \*\* (?P.*))?$" + ) + result = [] + complex_constituents = name.split(" % ") + + for complex_constituent in complex_constituents: + match = complex_constituent_pattern.match(complex_constituent) + if not match: + raise ValueError( + f"Invalid species name: '{name}' ('{complex_constituent}')" + ) + monomer = match.groupdict()["monomer"] + site_config_str = match.groupdict()["site_config"] + compartment = match.groupdict()["compartment"] + + site_config = {} + for site_str in site_config_str.split(", "): + if not site_str: + continue + site, config = site_str.split("=") + if config == "None": + config = None + elif config.startswith("'"): + if not config.endswith("'"): + raise ValueError( + f"Invalid species name: '{name}' ('{config}')" + ) + # strip quotes + config = config[1:-1] + else: + config = int(config) + site_config[site] = config + result.append( + (monomer, compartment, site_config), + ) + + return result + + +def pattern_from_string(string: str, model: pysb.Model) -> pysb.ComplexPattern: + """Convert a pattern string to a pattern of the given model. + + The string has to be in the format of ``str(pysb.ComplexPattern)``, + e.g., ``A(b=1, s=('u', 2)) ** c % B(a=1, c=2)``. + Site values may be ``None``, bond numbers, lists of bond numbers, + state strings, ``(state, bond)`` tuples, or ``MultiState(...)``. + Wildcards such as ``ANY`` or ``WILD`` are not supported. + + :param string: The pattern string. + :param model: The model that defines the monomers and compartments. + :returns: The pattern. + :raises ValueError: If the string is not a valid pattern for this model. + """ + + class InvalidPattern(ValueError): + pass + + def invalid(node: ast.AST | None = None) -> InvalidPattern: + detail = f" ('{ast.unparse(node)}')" if node is not None else "" + return InvalidPattern(f"Invalid species name: '{string}'{detail}") + + def convert_site_value(node: ast.expr): + """Convert the AST of a site value to the PySB site condition.""" + if isinstance(node, ast.Constant) and ( + node.value is None or type(node.value) in (int, str) + ): + return node.value + if isinstance(node, ast.Tuple): + return tuple(convert_site_value(e) for e in node.elts) + if isinstance(node, ast.List): + return [convert_site_value(e) for e in node.elts] + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "MultiState" + and not node.keywords + ): + return pysb.MultiState(*map(convert_site_value, node.args)) + raise invalid(node) + + def convert(node: ast.expr): + """Convert the AST of a (complex/monomer) pattern to a PySB pattern.""" + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + monomer = model.monomers.get(node.func.id) + if monomer is None or node.args: + raise invalid(node) + sites = [kw.arg for kw in node.keywords] + if ( + None in sites + or len(set(sites)) != len(sites) + or set(sites) - set(monomer.sites) + ): + raise invalid(node) + site_conditions = { + kw.arg: convert_site_value(kw.value) for kw in node.keywords + } + # not `monomer(**site_conditions)`, which fails for a site + # named `conditions` + return pysb.MonomerPattern(monomer, site_conditions, None) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): + return convert(node.left) % convert(node.right) + if ( + isinstance(node, ast.BinOp) + and isinstance(node.op, ast.Pow) + and isinstance(node.right, ast.Name) + and (compartment := model.compartments.get(node.right.id)) + ): + return convert(node.left) ** compartment + raise invalid(node) + + try: + tree = ast.parse(string, mode="eval") + except (SyntaxError, RecursionError, MemoryError) as e: + # RecursionError / MemoryError for too deeply nested expressions + raise invalid() from e + + try: + return pysb.as_complex_pattern(convert(tree.body)) + except InvalidPattern: + raise + except Exception as e: + # PySB raises ValueError, KeyError, or bare Exception + # for invalid patterns + raise invalid() from e + + +def _iter_bonds(site_value) -> Iterator[int]: + """Iterate over the bond numbers in a site value.""" + if isinstance(site_value, int): + yield site_value + elif isinstance(site_value, tuple | list | pysb.MultiState): + for x in site_value: + yield from _iter_bonds(x) diff --git a/petab/_models/sbml_model.py b/petab/_models/sbml_model.py new file mode 100644 index 00000000..ce791ec5 --- /dev/null +++ b/petab/_models/sbml_model.py @@ -0,0 +1,359 @@ +"""Functions for handling SBML models""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterable +from pathlib import Path + +import libsbml +import sympy as sp +from sbmlmath import sbml_math_to_sympy + +from .._utils import _generate_path +from ..v1.sbml import ( + get_sbml_model, + is_sbml_consistent, + load_sbml_from_string, + write_sbml, +) +from . import MODEL_TYPE_SBML +from .model import Model + +__all__ = ["SbmlModel"] + + +class SbmlModel(Model): + """PEtab wrapper for SBML models""" + + type_id = MODEL_TYPE_SBML + + def __init__( + self, + sbml_model: libsbml.Model = None, + sbml_reader: libsbml.SBMLReader = None, + sbml_document: libsbml.SBMLDocument = None, + model_id: str | None = None, + rel_path: Path | str | None = None, + base_path: str | Path | None = None, + ): + """Constructor. + + :param sbml_model: SBML model. Optional if `sbml_document` is given. + :param sbml_reader: SBML reader. Optional. + :param sbml_document: SBML document. Optional if `sbml_model` is given. + :param model_id: Model ID. Defaults to the SBML model ID.""" + super().__init__() + + self.rel_path = rel_path + self.base_path = base_path + + if sbml_model is None and sbml_document is None: + raise ValueError( + "Either sbml_model or sbml_document must be given." + ) + + if sbml_model is None: + sbml_model = sbml_document.getModel() + + if sbml_document is None: + sbml_document = sbml_model.getSBMLDocument() + + self.sbml_reader: libsbml.SBMLReader | None = sbml_reader + self.sbml_document: libsbml.SBMLDocument | None = sbml_document + self.sbml_model: libsbml.Model | None = sbml_model + + self._model_id = model_id or sbml_model.getIdAttribute() + + def __getstate__(self): + """Return state for pickling""" + state = self.__dict__.copy() + + # libsbml stuff cannot be serialized directly + if self.sbml_model: + state["sbml_string"] = self.to_sbml_str() + + exclude = ["sbml_reader", "sbml_document", "sbml_model"] + for key in exclude: + state.pop(key) + + return state + + def __setstate__(self, state): + """Set state after unpickling""" + # load SBML model from pickled string + sbml_string = state.pop("sbml_string", None) + if sbml_string: + ( + self.sbml_reader, + self.sbml_document, + self.sbml_model, + ) = load_sbml_from_string(sbml_string) + + self.__dict__.update(state) + + @staticmethod + def from_file( + filepath_or_buffer, + model_id: str | None = None, + base_path: str | Path | None = None, + ) -> SbmlModel: + sbml_reader, sbml_document, sbml_model = get_sbml_model( + _generate_path(filepath_or_buffer, base_path=base_path) + ) + return SbmlModel( + sbml_model=sbml_model, + sbml_reader=sbml_reader, + sbml_document=sbml_document, + model_id=model_id, + rel_path=filepath_or_buffer, + base_path=base_path, + ) + + @staticmethod + def from_string(sbml_string, model_id: str | None = None) -> SbmlModel: + """Create SBML model from an SBML string. + + :param sbml_string: SBML model as string. + :param model_id: Model ID. Defaults to the SBML model ID. + """ + sbml_reader, sbml_document, sbml_model = load_sbml_from_string( + sbml_string + ) + + if not model_id: + model_id = sbml_model.getIdAttribute() + + return SbmlModel( + sbml_model=sbml_model, + sbml_reader=sbml_reader, + sbml_document=sbml_document, + model_id=model_id, + ) + + @staticmethod + def from_antimony(ant_model: str | Path, **kwargs) -> SbmlModel: + """Create SBML model from an Antimony model. + + Requires the `antimony` package (https://github.com/sys-bio/antimony). + + :param ant_model: Antimony model as string or path to file. + Strings are interpreted as Antimony model strings. + :param kwargs: Additional keyword arguments passed to + :meth:`SbmlModel.from_string`. + """ + sbml_str = antimony2sbml(ant_model) + return SbmlModel.from_string(sbml_str, **kwargs) + + def to_antimony(self) -> str: + """Convert the SBML model to an Antimony string.""" + import antimony as ant + + sbml_str = self.to_sbml_str() + + ant.clearPreviousLoads() + ant.freeAll() + + if ant.loadSBMLString(sbml_str) < 0: + raise RuntimeError(ant.getLastError()) + + return ant.getAntimonyString() + + def to_sbml_str(self) -> str: + """Convert the SBML model to an SBML/XML string.""" + sbml_document = self.sbml_model.getSBMLDocument() + sbml_writer = libsbml.SBMLWriter() + return sbml_writer.writeSBMLToString(sbml_document) + + @property + def model_id(self): + return self._model_id + + @model_id.setter + def model_id(self, model_id): + self._model_id = model_id + + def to_file(self, filename: str | Path | None = None) -> None: + write_sbml( + self.sbml_document or self.sbml_model.getSBMLDocument(), + filename or _generate_path(self.rel_path, self.base_path), + ) + + def get_parameter_value(self, id_: str) -> float: + parameter = self.sbml_model.getParameter(id_) + if not parameter: + raise ValueError(f"Parameter {id_} does not exist.") + return parameter.getValue() + + def get_free_parameter_ids_with_values( + self, + ) -> Iterable[tuple[str, float]]: + rule_targets = { + ar.getVariable() for ar in self.sbml_model.getListOfRules() + } + + def get_initial(p): + # return the initial assignment value if there is one, and it is a + # number; `None`, if there is a non-numeric initial assignment; + # otherwise, the parameter value + if ia := self.sbml_model.getInitialAssignmentBySymbol(p.getId()): + sym_expr = sympify_sbml(ia.getMath()) + return ( + float(sym_expr.evalf()) + if sym_expr.evalf().is_Number + else None + ) + return p.getValue() + + return ( + (p.getId(), initial) + for p in self.sbml_model.getListOfParameters() + if p.getId() not in rule_targets + and (initial := get_initial(p)) is not None + ) + + def get_parameter_ids(self) -> Iterable[str]: + rule_targets = { + ar.getVariable() for ar in self.sbml_model.getListOfRules() + } + + return ( + p.getId() + for p in self.sbml_model.getListOfParameters() + if p.getId() not in rule_targets + ) + + def get_parameter_ids_with_values(self) -> Iterable[tuple[str, float]]: + rule_targets = { + ar.getVariable() for ar in self.sbml_model.getListOfRules() + } + + return ( + (p.getId(), p.getValue()) + for p in self.sbml_model.getListOfParameters() + if p.getId() not in rule_targets + ) + + def has_entity_with_id(self, entity_id) -> bool: + return self.sbml_model.getElementBySId(entity_id) is not None + + def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: + # All parameters except rule-targets + disallowed_set = { + ar.getVariable() for ar in self.sbml_model.getListOfRules() + } + + return ( + p.getId() + for p in self.sbml_model.getListOfParameters() + if p.getId() not in disallowed_set + ) + + def get_valid_ids_for_condition_table(self) -> Iterable[str]: + return ( + x.getId() + for x in itertools.chain( + self.sbml_model.getListOfParameters(), + self.sbml_model.getListOfSpecies(), + self.sbml_model.getListOfCompartments(), + ) + ) + + def symbol_allowed_in_observable_formula(self, id_: str) -> bool: + return self.sbml_model.getElementBySId(id_) or id_ == "time" + + def get_referenced_ids(self) -> set[str]: + """Get the IDs that the model refers to. + + These are the IDs in the math of any model element (e.g., kinetic + laws, rules, initial assignments, events), and those referred to as + conversion factors. IDs that are only defined, but not referred to, + are not included. + """ + ids = set() + for element in self.sbml_model.getListOfAllElements(): + if not (hasattr(element, "isSetMath") and element.isSetMath()): + continue + nodes = [element.getMath()] + while nodes: + node = nodes.pop() + if node.getType() == libsbml.AST_NAME: + ids.add(node.getName()) + nodes += [ + node.getChild(i) for i in range(node.getNumChildren()) + ] + # conversion factors refer to parameters by attribute, not in math + ids |= { + element.getConversionFactor() + for element in [ + self.sbml_model, + *self.sbml_model.getListOfSpecies(), + ] + if element.isSetConversionFactor() + } + return ids + + def is_valid(self) -> bool: + return is_sbml_consistent(self.sbml_model.getSBMLDocument()) + + def is_state_variable(self, id_: str) -> bool: + return ( + self.sbml_model.getSpecies(id_) is not None + or self.sbml_model.getCompartment(id_) is not None + or self.sbml_model.getRuleByVariable(id_) is not None + ) + + +def sympify_sbml(sbml_obj: libsbml.ASTNode | libsbml.SBase) -> sp.Expr: + """Convert SBML math expression to sympy expression. + + Parameters + ---------- + sbml_obj: + SBML math element or an SBML object with a math element. + + Returns + ------- + The sympy expression corresponding to ``sbml_obj``. + """ + return sbml_math_to_sympy(sbml_obj) + + +def antimony2sbml(ant_model: str | Path) -> str: + """Convert Antimony model to SBML. + + :param ant_model: Antimony model as string or path to file. + Strings are interpreted as Antimony model strings. + + :returns: + The SBML model as string. + """ + import antimony as ant + + # Unload everything / free memory + ant.clearPreviousLoads() + ant.freeAll() + + try: + # potentially fails because of too long file name + is_file = ant_model and Path(ant_model).exists() + except OSError: + is_file = False + + if is_file: + status = ant.loadAntimonyFile(str(ant_model)) + else: + status = ant.loadAntimonyString(ant_model) + if status < 0: + raise RuntimeError( + f"Antimony model could not be loaded: {ant.getLastError()}" + ) + + if (main_module_name := ant.getMainModuleName()) is None: + raise AssertionError("There is no Antimony module.") + + sbml_str = ant.getSBMLString(main_module_name) + if not sbml_str: + raise ValueError("Antimony model could not be converted to SBML.") + + return sbml_str 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 index 2f8cef39..4cfd804c 100644 --- a/petab/v1/models/bngl_model.py +++ b/petab/v1/models/bngl_model.py @@ -1,404 +1,12 @@ -"""BNGL (BioNetGen Language) model support for PEtab. +"""Deprecated: use :mod:`petab.v2.models.bngl_model`. -Adds a ``bngl`` model type, so a PEtab problem declaring ``language: bngl`` -can be loaded and validated. - -:class:`BnglModel` is backed by :func:`parse_bngl`, a small, dependency-free -BNGL reader. It only reads a model's declared entities -- parameters, -observables, functions, molecule types, compartments, seed species -- which -is all PEtab validation needs; it never runs BNG2.pl or generates a reaction -network. The one exception is :meth:`BnglModel.is_valid`: if a ``BNG2.pl`` -is found (``BNGPATH`` or ``PATH``), it runs ``BNG2.pl --check`` (a -parse/semantic check, no network generation); otherwise the model is -assumed valid. - -Two things worth knowing if a model doesn't parse the way you expect: - -* Symbols usable in an observable formula are parameters, observables, and - functions -- *not* compartments. -* The reader accepts line continuations (a trailing ``\\``), ``begin - species`` as an alias for ``begin seed species``, line labels (both the - numeric ``1 L0 1`` and named ``CD14: ...`` forms), and a leading ``$`` - (fixed-concentration) marker on a seed species. - -Examples --------- - -For example BNGL PEtab v2 problems, see the `PyBioNetFit -`_ `tutorials -`_. +BNGL models are only supported with PEtab v2. """ -from __future__ import annotations - -import os -import re -import shutil -import subprocess -from collections.abc import Iterable -from dataclasses import dataclass -from pathlib import Path - -from ..._utils import _generate_path -from .. import is_valid_identifier -from . import MODEL_TYPE_BNGL -from .model import Model - -__all__ = ["BnglEntities", "BnglModel", "parse_bngl"] - -#: The three keywords that open an observable declaration line. -_OBS_KEYWORDS = frozenset({"Molecules", "Species", "Counter"}) - -#: Short spellings BNG2.pl accepts for a block's canonical (long) name; either -#: spelling opens and closes the same block. The grammar doc -#: (``BNG_vscode_extension/docs/bngl-grammar.md``) also lists ``molecules`` and -#: ``rules``, but BNG2.pl 2.9.3 -- the reference this reader targets -- rejects -#: both ("Could not process block type"), so honoring them would accept models -#: BNG2.pl refuses. Only ``species`` (for ``seed species``, also BNG2.pl's own -#: canonical output spelling) is real. -_BLOCK_ALIASES = { - "seed species": ("species",), -} - - -@dataclass(frozen=True) -class BnglEntities: - """The named entities of a BNGL model that the PEtab layer reads. - - :ivar text: The verbatim BNGL model text. - :ivar parameters: Maps a parameter name to its raw right-hand side -- a - number (``"5"``, ``"6.02e23"``) or an expression (``"2*base"``), - kept verbatim; numeric coercion is the caller's job. - :ivar observable_names: Bare observable names. - :ivar function_names: Bare global-function names (without ``()``). - :ivar molecule_type_names: Bare molecule-type names. - :ivar seed_species: Concrete seed-species pattern strings (verbatim). - :ivar compartment_names: Bare compartment names. - """ - - text: str - parameters: dict[str, str] - observable_names: frozenset[str] - function_names: frozenset[str] - molecule_type_names: frozenset[str] - seed_species: frozenset[str] - compartment_names: frozenset[str] - - -def parse_bngl(text: str) -> BnglEntities: - """Parse BNGL ``text`` into a :class:`BnglEntities`. - - A stdlib ``begin``/``end `` scanner -- no BNG2.pl, no network - generation. Sufficient for PEtab validation, which only introspects the - model's declared entities. - - :param text: The BNGL model text. - :returns: The model's named entities. - """ - parameters: dict[str, str] = {} - for line in _block_lines(text, "parameters"): - name_value = _parameter_name_value(line) - if name_value is not None: - parameters[name_value[0]] = name_value[1] - return BnglEntities( - text=text, - parameters=parameters, - observable_names=_names(text, "observables", _observable_name), - function_names=_names(text, "functions", _function_name), - molecule_type_names=_names( - text, "molecule types", _molecule_type_name - ), - seed_species=_names(text, "seed species", _seed_species_pattern), - compartment_names=_names(text, "compartments", _compartment_name), - ) - - -def _names(text: str, block_name: str, extractor) -> frozenset[str]: - """The non-empty names ``extractor`` yields over a block's lines.""" - return frozenset( - name - for name in ( - extractor(line) for line in _block_lines(text, block_name) - ) - if name - ) - - -def _logical_lines(text: str) -> list[str]: - """The comment-stripped *logical* lines of ``text`` -- physical lines with - BNGL line continuations joined. - - Mirrors BNG2.pl's ``readFile`` (``Perl2/BNGModel.pm``): strip the ``#`` - comment first, then while the line ends with ``\\`` (as its last - non-whitespace character) drop that ``\\`` and append the next - comment-stripped physical line *directly* -- no separating space, so a - token split across the break (``1e\\`` + ``3`` -> ``1e3``) rejoins. - Without this, a continued parameter / function / observable is truncated at - the ``\\`` (e.g. a ``k = \\`` line would read as the value ``"\\"``). - """ - raw_lines = text.splitlines() - out = [] - i, n = 0, len(raw_lines) - while i < n: - line = raw_lines[i].split("#", 1)[0] - i += 1 - while re.search(r"\\\s*$", line): - line = re.sub(r"\\\s*$", "", line) - if i >= n: - break # a dangling continuation at EOF - line += raw_lines[i].split("#", 1)[0] - i += 1 - out.append(line.strip()) - return out - - -def _block_lines(text: str, block_name: str) -> list[str]: - """The comment-stripped, non-blank lines inside ``begin``/``end``. - - ``block_name`` is the canonical (long) spelling; a BNG2.pl-accepted alias - for it (only ``species`` for ``seed species``; see :data:`_BLOCK_ALIASES`) - opens and closes the same block. Lines are logical lines -- continuations - joined (see :func:`_logical_lines`). - """ - names = "|".join( - re.escape(name) - for name in (block_name, *_BLOCK_ALIASES.get(block_name, ())) - ) - begin = re.compile(rf"^begin\s+(?:{names})\b", re.IGNORECASE) - end = re.compile(rf"^end\s+(?:{names})\b", re.IGNORECASE) - lines = [] - in_block = False - for line in _logical_lines(text): - if begin.match(line): - in_block = True - elif end.match(line): - in_block = False - elif in_block and line: - lines.append(line) - return lines - - -def _strip_line_label(line: str) -> str: - """Drop a leading BNGL line label so the entity, not the label, is read. - - ``LineLabel = {Digit}, WS | Name, ":", [WS]`` (grammar) -- either a numeric - index (the legacy ``.net``-style ``1 L0 1`` form) or a named label - (``CD14: CD14(...)``). A valid BNGL identifier starts with a letter, so a - leading digit-run is always an index; a compartment prefix is ``@Name:`` - (with the ``@``), so a bare ``Name:`` at line start is unambiguously a - label. - """ - match = re.match(r"^\d+\s+(.*)$", line) or re.match( - r"^[A-Za-z]\w*:\s+(.*)$", line - ) - return match.group(1) if match else line - - -def _parameter_name_value(line: str) -> tuple[str, str] | None: - """``(name, rhs)`` for a ``[LineLabel] Name (WS|"=") MathExpr`` line.""" - line = _strip_line_label(line) - match = re.match(r"^(\w+)\s*=\s*(.+)$", line) or re.match( - r"^(\w+)\s+(.+)$", line - ) - return (match.group(1), match.group(2).strip()) if match else None - - -def _observable_name(line: str) -> str | None: - """The name in a `` `` observable line.""" - tokens = line.split() - if len(tokens) >= 2 and tokens[0] in _OBS_KEYWORDS: - return tokens[1] - return None - - -def _function_name(line: str) -> str | None: - """The name in a ``() = ...`` global-function line.""" - match = re.match(r"(\w+)\s*\(", line) or re.match(r"(\w+)\s*=", line) - return match.group(1) if match else None - - -def _molecule_type_name(line: str) -> str | None: - """The name in a ``(...)`` molecule-type line.""" - match = re.match(r"(\w+)", line) - return match.group(1) if match else None - - -def _seed_species_pattern(line: str) -> str | None: - """The species pattern in a ``[LineLabel] ["$"] `` line. - - A leading line label (numeric index ``1 A() 100`` or named - ``CD14: CD14(...)``; see :func:`_strip_line_label`) is dropped first so the - label is not mistaken for the species. A leading ``$`` (the fixed/clamped- - concentration marker, ``SeedSpeciesDefn = ["$"], Species, WS, - MathExpression``) is a modifier, not part of the species identity, so it - too is stripped: ``$counter() 10`` - enumerates the state variable ``counter()``. - """ - line = _strip_line_label(line) - if line.startswith("$"): - line = line[1:].lstrip() - tokens = line.split() - return tokens[0] if tokens else None - - -def _compartment_name(line: str) -> str | None: - """The name in a `` [outside]`` line.""" - tokens = line.split() - return tokens[0] if tokens else None - - -class BnglModel(Model): - """PEtab wrapper for BNGL models.""" - - type_id = MODEL_TYPE_BNGL - - def __init__( - self, - model: BnglEntities, - model_id: str | None = None, - rel_path: Path | str | None = None, - base_path: str | Path | None = None, - ): - super().__init__() - - self.rel_path = rel_path - self.base_path = base_path - - self.model = model - self._model_id = model_id - - if not is_valid_identifier(self._model_id): - raise ValueError( - f"Model ID '{self._model_id}' is not a valid identifier. " - "Either provide a valid identifier or rename the model file " - "to a valid PEtab model identifier." - ) - - @staticmethod - def from_file( - filepath_or_buffer, - model_id: str | None = None, - base_path: str | Path | None = None, - ) -> BnglModel: - path = Path(_generate_path(filepath_or_buffer, base_path)) - text = path.read_text(encoding="utf-8", errors="replace") - return BnglModel( - model=parse_bngl(text), - model_id=model_id or path.stem, - rel_path=filepath_or_buffer, - base_path=base_path, - ) - - def to_file(self, filename: str | Path | None = None) -> None: - target = filename or _generate_path(self.rel_path, self.base_path) - with open(target, "w", encoding="utf-8") as f: - f.write(self.model.text) - - @property - def model_id(self): - return self._model_id - - @model_id.setter - def model_id(self, model_id): - self._model_id = model_id - - def get_parameter_ids(self) -> Iterable[str]: - return list(self.model.parameters) - - def get_parameter_value(self, id_: str) -> float: - try: - rhs = self.model.parameters[id_] - except KeyError as e: - raise ValueError(f"Parameter {id_} does not exist.") from e - try: - return float(rhs) - except ValueError as e: - raise NotImplementedError( - f"Parameter '{id_}' has an expression value '{rhs}'. " - "Evaluating a BNGL parameter expression requires BNG2.pl / " - "network generation, which is out of scope for the " - "introspection-only BnglModel." - ) from e - - def get_free_parameter_ids_with_values( - self, - ) -> Iterable[tuple[str, float]]: - out = [] - for name, rhs in self.model.parameters.items(): - try: - out.append((name, float(rhs))) - except ValueError: - # An expression-valued parameter has no introspection-grade - # value; skip it rather than evaluate the expression. - continue - return out - - def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: - # All parameters are allowed in the parameter table. - return list(self.model.parameters) - - def has_entity_with_id(self, entity_id) -> bool: - # The full declared-identifier namespace. - return ( - entity_id in self.model.parameters - or entity_id in self.model.observable_names - or entity_id in self.model.function_names - or entity_id in self.model.molecule_type_names - or entity_id in self.model.compartment_names - or entity_id in self.model.seed_species - ) - - def get_valid_ids_for_condition_table(self) -> Iterable[str]: - return list(self.model.parameters) + list(self.model.compartment_names) - - def symbol_allowed_in_observable_formula(self, id_: str) -> bool: - # The BNG ParamList: parameters, observables, global functions only. - return ( - id_ in self.model.parameters - or id_ in self.model.observable_names - or id_ in self.model.function_names - ) - - def is_state_variable(self, id_: str) -> bool: - # At introspection grade only the concrete seed species are known; - # the full species set is a network-generation product. - return id_ in self.model.seed_species - - def is_valid(self) -> bool: - # Real BNG2.pl --check (parse/semantic validation, no network - # generation) when locatable, else True -- never a false failure - # where no BNG backend is available. - bng2 = _locate_bng2() - if bng2 is None or self.rel_path is None: - return True - path = Path(_generate_path(self.rel_path, self.base_path)) - if not path.is_file(): - # No local model file to check (e.g. a buffer-loaded model). - return True - # Resolve to an absolute path so BNG2.pl finds the model regardless - # of the working directory it runs in (its output stays next to the - # model via ``cwd``). - path = path.resolve() - try: - result = subprocess.run( # noqa: S603 - [bng2, "--check", str(path)], - capture_output=True, - text=True, - timeout=120, - cwd=str(path.parent), - check=False, - ) - except (OSError, subprocess.SubprocessError): - # A tooling hiccup must not masquerade as an invalid model. - return True - return result.returncode == 0 +from ..._models import bngl_model as _impl +from ..._models.bngl_model import * +from ..._models.bngl_model import __all__ # noqa: F401 -def _locate_bng2() -> str | None: - """A path to ``BNG2.pl`` via ``BNGPATH`` or ``PATH``, else ``None``.""" - bngpath = os.environ.get("BNGPATH") - if bngpath: - candidate = Path(bngpath) / "BNG2.pl" - if candidate.is_file(): - return str(candidate) - return shutil.which("BNG2.pl") +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/model.py b/petab/v1/models/model.py index 57c991dc..124b4426 100644 --- a/petab/v1/models/model.py +++ b/petab/v1/models/model.py @@ -1,188 +1,9 @@ """PEtab model abstraction""" -from __future__ import annotations +from ..._models import model as _impl +from ..._models.model import * +from ..._models.model import __all__ # noqa: F401 -import abc -from collections.abc import Iterable -from pathlib import Path -from typing import Any -__all__ = ["Model", "model_factory"] - - -class Model(abc.ABC): - """Base class for wrappers for any PEtab-supported model type""" - - @abc.abstractmethod - def __init__(self): ... - - def __repr__(self): - return f"<{self.__class__.__name__} {self.model_id!r}>" - - @staticmethod - @abc.abstractmethod - def from_file( - filepath_or_buffer: Any, - model_id: str, - base_path: str | Path | None = None, - ) -> Model: - """Load the model from the given path/URL - - :param filepath_or_buffer: - Absolute or relative path/URL to the model file. - If relative, it is interpreted relative to `base_path`, if given. - :param base_path: Base path for relative paths in the model file. - :param model_id: Model ID - :returns: A ``Model`` instance holding the given model - """ - ... - - @abc.abstractmethod - def to_file(self, filename: str | Path | None = None): - """Save the model to the given file - - :param filename: Destination filename - """ - ... - - @classmethod - @property - @abc.abstractmethod - def type_id(cls): ... - - @property - @abc.abstractmethod - def model_id(self): ... - - @abc.abstractmethod - def get_parameter_value(self, id_: str) -> float: - """Get a parameter value - - :param id_: ID of the parameter whose value is to be returned - :raises ValueError: If no parameter with the given ID exists - :returns: The value of the given parameter as specified in the model - """ - ... - - @abc.abstractmethod - def get_free_parameter_ids_with_values( - self, - ) -> Iterable[tuple[str, float]]: - """Get free model parameters along with their values - - Returns: - Iterator over tuples of (parameter_id, parameter_value) - """ - ... - - @abc.abstractmethod - def get_parameter_ids(self) -> Iterable[str]: - """Get all parameter IDs from this model - - :returns: Iterator over model parameter IDs - """ - ... - - @abc.abstractmethod - def has_entity_with_id(self, entity_id) -> bool: - """Check if there is a model entity with the given ID - - :param entity_id: ID to check for - :returns: - ``True``, if there is an entity with the given ID, - ``False`` otherwise - """ - ... - - @abc.abstractmethod - def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: - """Get IDs of all parameters that are allowed to occur in the PEtab - parameters table - - :returns: Iterator over parameter IDs - """ - ... - - @abc.abstractmethod - def get_valid_ids_for_condition_table(self) -> Iterable[str]: - """Get IDs of all model entities that are allowed to occur as columns - in the PEtab conditions table. - - :returns: Iterator over model entity IDs - """ - ... - - @abc.abstractmethod - def symbol_allowed_in_observable_formula(self, id_: str) -> bool: - """Check if the given ID is allowed to be used in observable and noise - formulas - - :returns: ``True``, if allowed, ``False`` otherwise - """ - ... - - @abc.abstractmethod - def is_valid(self) -> bool: - """Validate this model - - :returns: - `True` if the model is valid, `False` if there are errors in - this model - """ - ... - - @abc.abstractmethod - def is_state_variable(self, id_: str) -> bool: - """Check whether the given ID corresponds to a model state variable""" - ... - - -def model_factory( - filepath_or_buffer: Any, - model_language: str, - model_id: str | None = None, - base_path: str | Path | None = None, -) -> Model: - """Create a PEtab model instance from the given model - - :param filepath_or_buffer: Path/URL of the model. - Absolute or relative to `base_path` if given. - :param base_path: Base path for relative paths in the model file. - :param model_language: PEtab model language ID for the given model - :param model_id: PEtab model ID for the given model - :returns: A :py:class:`Model` instance representing the given model - """ - from . import ( - MODEL_TYPE_BNGL, - MODEL_TYPE_PYSB, - MODEL_TYPE_SBML, - known_model_types, - ) - - if model_language == MODEL_TYPE_SBML: - from .sbml_model import SbmlModel - - return SbmlModel.from_file( - filepath_or_buffer, model_id=model_id, base_path=base_path - ) - - if model_language == MODEL_TYPE_PYSB: - from .pysb_model import PySBModel - - return PySBModel.from_file( - filepath_or_buffer, model_id=model_id, base_path=base_path - ) - - if model_language == MODEL_TYPE_BNGL: - from .bngl_model import BnglModel - - return BnglModel.from_file( - filepath_or_buffer, model_id=model_id, base_path=base_path - ) - - if model_language in known_model_types: - raise NotImplementedError( - f"Unsupported model format: {model_language}" - ) - - raise ValueError(f"Unknown model format: {model_language}") +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/pysb_model.py b/petab/v1/models/pysb_model.py index de1ce95c..38893741 100644 --- a/petab/v1/models/pysb_model.py +++ b/petab/v1/models/pysb_model.py @@ -1,364 +1,12 @@ -"""Functions for handling PySB models""" +"""Deprecated: use :mod:`petab.v2.models.pysb_model`. -from __future__ import annotations +PySB models are only supported with PEtab v2. +""" -import ast -import itertools -import re -import sys -from collections import Counter -from collections.abc import Iterable, Iterator -from pathlib import Path -from typing import Any +from ..._models import pysb_model as _impl +from ..._models.pysb_model import * +from ..._models.pysb_model import __all__ # noqa: F401 -import pysb -from ..._utils import _generate_path -from .. import is_valid_identifier -from . import MODEL_TYPE_PYSB -from .model import Model - -__all__ = ["PySBModel", "parse_species_name", "pattern_from_string"] - - -def _pysb_model_from_path(pysb_model_file: str | Path) -> pysb.Model: - """Load a pysb model module and return the :class:`pysb.Model` instance - - :param pysb_model_file: Full or relative path to the PySB model module - :return: The pysb Model instance - """ - pysb_model_file = Path(pysb_model_file) - pysb_model_module_name = pysb_model_file.with_suffix("").name - - import importlib.util - - spec = importlib.util.spec_from_file_location( - pysb_model_module_name, pysb_model_file - ) - module = importlib.util.module_from_spec(spec) - sys.modules[pysb_model_module_name] = module - spec.loader.exec_module(module) - - # find a pysb.Model instance in the module - # 1) check if module.model exists and is a pysb.Model - model = getattr(module, "model", None) - if model: - return model - - # 2) check if there is any other pysb.Model instance - for x in dir(module): - attr = getattr(module, x) - if isinstance(attr, pysb.Model): - return attr - - raise ValueError(f"Could not find any pysb.Model in {pysb_model_file}.") - - -class PySBModel(Model): - """PEtab wrapper for PySB models""" - - type_id = MODEL_TYPE_PYSB - - def __init__( - self, - model: pysb.Model, - model_id: str | None = None, - rel_path: Path | str | None = None, - base_path: str | Path | None = None, - ): - super().__init__() - - self.rel_path = rel_path - self.base_path = base_path - - self.model = model - self._model_id = model_id or self.model.name - - if not is_valid_identifier(self._model_id): - raise ValueError( - f"Model ID '{self._model_id}' is not a valid identifier. " - "Either provide a valid identifier or change the model name " - "to a valid PEtab model identifier." - ) - - @staticmethod - def from_file( - filepath_or_buffer, - model_id: str | None = None, - base_path: str | Path | None = None, - ) -> PySBModel: - return PySBModel( - model=_pysb_model_from_path( - _generate_path(filepath_or_buffer, base_path) - ), - model_id=model_id, - rel_path=filepath_or_buffer, - base_path=base_path, - ) - - def to_file(self, filename: str | Path | None = None) -> None: - model_source = self.to_str() - - with open( - filename or _generate_path(self.rel_path, self.base_path), "w" - ) as f: - f.write(model_source) - - def to_str(self) -> str: - """Get the PySB model Python code as a string.""" - from pysb.export import export - - return export(self.model, "pysb_flat") - - @property - def model_id(self): - return self._model_id - - @model_id.setter - def model_id(self, model_id): - self._model_id = model_id - - def get_parameter_ids(self) -> Iterable[str]: - return (p.name for p in self.model.parameters) - - def get_parameter_value(self, id_: str) -> float: - try: - return self.model.parameters[id_].value - except KeyError as e: - raise ValueError(f"Parameter {id_} does not exist.") from e - - def get_free_parameter_ids_with_values( - self, - ) -> Iterable[tuple[str, float]]: - return ((p.name, p.value) for p in self.model.parameters) - - def has_entity_with_id(self, entity_id) -> bool: - try: - _ = self.model.components[entity_id] - return True - except KeyError: - return False - - def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: - # all parameters are allowed in the parameter table - return self.get_parameter_ids() - - def get_valid_ids_for_condition_table(self) -> Iterable[str]: - return itertools.chain( - self.get_parameter_ids(), self.get_compartment_ids() - ) - - def symbol_allowed_in_observable_formula(self, id_: str) -> bool: - return id_ in ( - x.name - for x in itertools.chain( - self.model.parameters, - self.model.observables, - self.model.expressions, - ) - ) - - def is_valid(self) -> bool: - # PySB models are always valid - return True - - def is_state_variable(self, id_: str) -> bool: - """Check whether the given ID is a plausible PySB species name. - - The ID has to be a species pattern (e.g., ``A(b=1, s='u') % B(a=1)``) - with all sites of all monomers specified and all bonds paired. - Compartments are optional, even if the model has compartments. - This does not check whether the species is actually generated by - the model's rules, or whether all monomers of a complex are - connected. - """ - # If there is a component with that name, it's not a state variable - # (there are no dynamically-sized compartments) - if self.model.components.get(id_, None): - return False - - try: - pattern = pattern_from_string(id_, self.model) - except ValueError: - return False - - for mp in pattern.monomer_patterns: - if not mp.is_site_concrete(): - return False - # is_site_concrete() doesn't check this for duplicate sites - for site, count in Counter(mp.monomer.sites).items(): - if site not in mp.site_conditions: - return False - site_value = mp.site_conditions[site] - if ( - isinstance(site_value, pysb.MultiState) - and len(site_value) != count - ): - return False - - # each bond has to connect exactly two sites - bond_counts = Counter( - bond - for mp in pattern.monomer_patterns - for site_value in mp.site_conditions.values() - for bond in _iter_bonds(site_value) - ) - return all(count == 2 for count in bond_counts.values()) - - def get_compartment_ids(self) -> Iterable[str]: - return (compartment.name for compartment in self.model.compartments) - - -def parse_species_name( - name: str, -) -> list[tuple[str, str | None, dict[str, Any]]]: - """Parse a PySB species name - - Site values in the form of ``(state, bond)`` tuples and - :class:`pysb.MultiState` are not supported. - See :func:`pattern_from_string` for a more complete parser. - - :param name: Species name to parse - :returns: List of species, representing complex constituents, each as - a tuple of the monomer name, the compartment name, and a dict of sites - mapping to site states. - :raises ValueError: In case this is not a valid ID - """ - if "=MultiState(" in name: - raise NotImplementedError("MultiState is not yet supported.") - - complex_constituent_pattern = re.compile( - r"^(?P\w+)\((?P.*)\)" - r"( \*\* (?P.*))?$" - ) - result = [] - complex_constituents = name.split(" % ") - - for complex_constituent in complex_constituents: - match = complex_constituent_pattern.match(complex_constituent) - if not match: - raise ValueError( - f"Invalid species name: '{name}' ('{complex_constituent}')" - ) - monomer = match.groupdict()["monomer"] - site_config_str = match.groupdict()["site_config"] - compartment = match.groupdict()["compartment"] - - site_config = {} - for site_str in site_config_str.split(", "): - if not site_str: - continue - site, config = site_str.split("=") - if config == "None": - config = None - elif config.startswith("'"): - if not config.endswith("'"): - raise ValueError( - f"Invalid species name: '{name}' ('{config}')" - ) - # strip quotes - config = config[1:-1] - else: - config = int(config) - site_config[site] = config - result.append( - (monomer, compartment, site_config), - ) - - return result - - -def pattern_from_string(string: str, model: pysb.Model) -> pysb.ComplexPattern: - """Convert a pattern string to a pattern of the given model. - - The string has to be in the format of ``str(pysb.ComplexPattern)``, - e.g., ``A(b=1, s=('u', 2)) ** c % B(a=1, c=2)``. - Site values may be ``None``, bond numbers, lists of bond numbers, - state strings, ``(state, bond)`` tuples, or ``MultiState(...)``. - Wildcards such as ``ANY`` or ``WILD`` are not supported. - - :param string: The pattern string. - :param model: The model that defines the monomers and compartments. - :returns: The pattern. - :raises ValueError: If the string is not a valid pattern for this model. - """ - - class InvalidPattern(ValueError): - pass - - def invalid(node: ast.AST | None = None) -> InvalidPattern: - detail = f" ('{ast.unparse(node)}')" if node is not None else "" - return InvalidPattern(f"Invalid species name: '{string}'{detail}") - - def convert_site_value(node: ast.expr): - """Convert the AST of a site value to the PySB site condition.""" - if isinstance(node, ast.Constant) and ( - node.value is None or type(node.value) in (int, str) - ): - return node.value - if isinstance(node, ast.Tuple): - return tuple(convert_site_value(e) for e in node.elts) - if isinstance(node, ast.List): - return [convert_site_value(e) for e in node.elts] - if ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "MultiState" - and not node.keywords - ): - return pysb.MultiState(*map(convert_site_value, node.args)) - raise invalid(node) - - def convert(node: ast.expr): - """Convert the AST of a (complex/monomer) pattern to a PySB pattern.""" - if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): - monomer = model.monomers.get(node.func.id) - if monomer is None or node.args: - raise invalid(node) - sites = [kw.arg for kw in node.keywords] - if ( - None in sites - or len(set(sites)) != len(sites) - or set(sites) - set(monomer.sites) - ): - raise invalid(node) - site_conditions = { - kw.arg: convert_site_value(kw.value) for kw in node.keywords - } - # not `monomer(**site_conditions)`, which fails for a site - # named `conditions` - return pysb.MonomerPattern(monomer, site_conditions, None) - if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): - return convert(node.left) % convert(node.right) - if ( - isinstance(node, ast.BinOp) - and isinstance(node.op, ast.Pow) - and isinstance(node.right, ast.Name) - and (compartment := model.compartments.get(node.right.id)) - ): - return convert(node.left) ** compartment - raise invalid(node) - - try: - tree = ast.parse(string, mode="eval") - except (SyntaxError, RecursionError, MemoryError) as e: - # RecursionError / MemoryError for too deeply nested expressions - raise invalid() from e - - try: - return pysb.as_complex_pattern(convert(tree.body)) - except InvalidPattern: - raise - except Exception as e: - # PySB raises ValueError, KeyError, or bare Exception - # for invalid patterns - raise invalid() from e - - -def _iter_bonds(site_value) -> Iterator[int]: - """Iterate over the bond numbers in a site value.""" - if isinstance(site_value, int): - yield site_value - elif isinstance(site_value, tuple | list | pysb.MultiState): - for x in site_value: - yield from _iter_bonds(x) +def __getattr__(name): + return getattr(_impl, name) diff --git a/petab/v1/models/sbml_model.py b/petab/v1/models/sbml_model.py index 831a42e3..7f06cc67 100644 --- a/petab/v1/models/sbml_model.py +++ b/petab/v1/models/sbml_model.py @@ -1,359 +1,9 @@ """Functions for handling SBML models""" -from __future__ import annotations +from ..._models import sbml_model as _impl +from ..._models.sbml_model import * +from ..._models.sbml_model import __all__ # noqa: F401 -import itertools -from collections.abc import Iterable -from pathlib import Path -import libsbml -import sympy as sp -from sbmlmath import sbml_math_to_sympy - -from ..._utils import _generate_path -from ..sbml import ( - get_sbml_model, - is_sbml_consistent, - load_sbml_from_string, - write_sbml, -) -from . import MODEL_TYPE_SBML -from .model import Model - -__all__ = ["SbmlModel"] - - -class SbmlModel(Model): - """PEtab wrapper for SBML models""" - - type_id = MODEL_TYPE_SBML - - def __init__( - self, - sbml_model: libsbml.Model = None, - sbml_reader: libsbml.SBMLReader = None, - sbml_document: libsbml.SBMLDocument = None, - model_id: str | None = None, - rel_path: Path | str | None = None, - base_path: str | Path | None = None, - ): - """Constructor. - - :param sbml_model: SBML model. Optional if `sbml_document` is given. - :param sbml_reader: SBML reader. Optional. - :param sbml_document: SBML document. Optional if `sbml_model` is given. - :param model_id: Model ID. Defaults to the SBML model ID.""" - super().__init__() - - self.rel_path = rel_path - self.base_path = base_path - - if sbml_model is None and sbml_document is None: - raise ValueError( - "Either sbml_model or sbml_document must be given." - ) - - if sbml_model is None: - sbml_model = sbml_document.getModel() - - if sbml_document is None: - sbml_document = sbml_model.getSBMLDocument() - - self.sbml_reader: libsbml.SBMLReader | None = sbml_reader - self.sbml_document: libsbml.SBMLDocument | None = sbml_document - self.sbml_model: libsbml.Model | None = sbml_model - - self._model_id = model_id or sbml_model.getIdAttribute() - - def __getstate__(self): - """Return state for pickling""" - state = self.__dict__.copy() - - # libsbml stuff cannot be serialized directly - if self.sbml_model: - state["sbml_string"] = self.to_sbml_str() - - exclude = ["sbml_reader", "sbml_document", "sbml_model"] - for key in exclude: - state.pop(key) - - return state - - def __setstate__(self, state): - """Set state after unpickling""" - # load SBML model from pickled string - sbml_string = state.pop("sbml_string", None) - if sbml_string: - ( - self.sbml_reader, - self.sbml_document, - self.sbml_model, - ) = load_sbml_from_string(sbml_string) - - self.__dict__.update(state) - - @staticmethod - def from_file( - filepath_or_buffer, - model_id: str | None = None, - base_path: str | Path | None = None, - ) -> SbmlModel: - sbml_reader, sbml_document, sbml_model = get_sbml_model( - _generate_path(filepath_or_buffer, base_path=base_path) - ) - return SbmlModel( - sbml_model=sbml_model, - sbml_reader=sbml_reader, - sbml_document=sbml_document, - model_id=model_id, - rel_path=filepath_or_buffer, - base_path=base_path, - ) - - @staticmethod - def from_string(sbml_string, model_id: str | None = None) -> SbmlModel: - """Create SBML model from an SBML string. - - :param sbml_string: SBML model as string. - :param model_id: Model ID. Defaults to the SBML model ID. - """ - sbml_reader, sbml_document, sbml_model = load_sbml_from_string( - sbml_string - ) - - if not model_id: - model_id = sbml_model.getIdAttribute() - - return SbmlModel( - sbml_model=sbml_model, - sbml_reader=sbml_reader, - sbml_document=sbml_document, - model_id=model_id, - ) - - @staticmethod - def from_antimony(ant_model: str | Path, **kwargs) -> SbmlModel: - """Create SBML model from an Antimony model. - - Requires the `antimony` package (https://github.com/sys-bio/antimony). - - :param ant_model: Antimony model as string or path to file. - Strings are interpreted as Antimony model strings. - :param kwargs: Additional keyword arguments passed to - :meth:`SbmlModel.from_string`. - """ - sbml_str = antimony2sbml(ant_model) - return SbmlModel.from_string(sbml_str, **kwargs) - - def to_antimony(self) -> str: - """Convert the SBML model to an Antimony string.""" - import antimony as ant - - sbml_str = self.to_sbml_str() - - ant.clearPreviousLoads() - ant.freeAll() - - if ant.loadSBMLString(sbml_str) < 0: - raise RuntimeError(ant.getLastError()) - - return ant.getAntimonyString() - - def to_sbml_str(self) -> str: - """Convert the SBML model to an SBML/XML string.""" - sbml_document = self.sbml_model.getSBMLDocument() - sbml_writer = libsbml.SBMLWriter() - return sbml_writer.writeSBMLToString(sbml_document) - - @property - def model_id(self): - return self._model_id - - @model_id.setter - def model_id(self, model_id): - self._model_id = model_id - - def to_file(self, filename: str | Path | None = None) -> None: - write_sbml( - self.sbml_document or self.sbml_model.getSBMLDocument(), - filename or _generate_path(self.rel_path, self.base_path), - ) - - def get_parameter_value(self, id_: str) -> float: - parameter = self.sbml_model.getParameter(id_) - if not parameter: - raise ValueError(f"Parameter {id_} does not exist.") - return parameter.getValue() - - def get_free_parameter_ids_with_values( - self, - ) -> Iterable[tuple[str, float]]: - rule_targets = { - ar.getVariable() for ar in self.sbml_model.getListOfRules() - } - - def get_initial(p): - # return the initial assignment value if there is one, and it is a - # number; `None`, if there is a non-numeric initial assignment; - # otherwise, the parameter value - if ia := self.sbml_model.getInitialAssignmentBySymbol(p.getId()): - sym_expr = sympify_sbml(ia.getMath()) - return ( - float(sym_expr.evalf()) - if sym_expr.evalf().is_Number - else None - ) - return p.getValue() - - return ( - (p.getId(), initial) - for p in self.sbml_model.getListOfParameters() - if p.getId() not in rule_targets - and (initial := get_initial(p)) is not None - ) - - def get_parameter_ids(self) -> Iterable[str]: - rule_targets = { - ar.getVariable() for ar in self.sbml_model.getListOfRules() - } - - return ( - p.getId() - for p in self.sbml_model.getListOfParameters() - if p.getId() not in rule_targets - ) - - def get_parameter_ids_with_values(self) -> Iterable[tuple[str, float]]: - rule_targets = { - ar.getVariable() for ar in self.sbml_model.getListOfRules() - } - - return ( - (p.getId(), p.getValue()) - for p in self.sbml_model.getListOfParameters() - if p.getId() not in rule_targets - ) - - def has_entity_with_id(self, entity_id) -> bool: - return self.sbml_model.getElementBySId(entity_id) is not None - - def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: - # All parameters except rule-targets - disallowed_set = { - ar.getVariable() for ar in self.sbml_model.getListOfRules() - } - - return ( - p.getId() - for p in self.sbml_model.getListOfParameters() - if p.getId() not in disallowed_set - ) - - def get_valid_ids_for_condition_table(self) -> Iterable[str]: - return ( - x.getId() - for x in itertools.chain( - self.sbml_model.getListOfParameters(), - self.sbml_model.getListOfSpecies(), - self.sbml_model.getListOfCompartments(), - ) - ) - - def symbol_allowed_in_observable_formula(self, id_: str) -> bool: - return self.sbml_model.getElementBySId(id_) or id_ == "time" - - def get_referenced_ids(self) -> set[str]: - """Get the IDs that the model refers to. - - These are the IDs in the math of any model element (e.g., kinetic - laws, rules, initial assignments, events), and those referred to as - conversion factors. IDs that are only defined, but not referred to, - are not included. - """ - ids = set() - for element in self.sbml_model.getListOfAllElements(): - if not (hasattr(element, "isSetMath") and element.isSetMath()): - continue - nodes = [element.getMath()] - while nodes: - node = nodes.pop() - if node.getType() == libsbml.AST_NAME: - ids.add(node.getName()) - nodes += [ - node.getChild(i) for i in range(node.getNumChildren()) - ] - # conversion factors refer to parameters by attribute, not in math - ids |= { - element.getConversionFactor() - for element in [ - self.sbml_model, - *self.sbml_model.getListOfSpecies(), - ] - if element.isSetConversionFactor() - } - return ids - - def is_valid(self) -> bool: - return is_sbml_consistent(self.sbml_model.getSBMLDocument()) - - def is_state_variable(self, id_: str) -> bool: - return ( - self.sbml_model.getSpecies(id_) is not None - or self.sbml_model.getCompartment(id_) is not None - or self.sbml_model.getRuleByVariable(id_) is not None - ) - - -def sympify_sbml(sbml_obj: libsbml.ASTNode | libsbml.SBase) -> sp.Expr: - """Convert SBML math expression to sympy expression. - - Parameters - ---------- - sbml_obj: - SBML math element or an SBML object with a math element. - - Returns - ------- - The sympy expression corresponding to ``sbml_obj``. - """ - return sbml_math_to_sympy(sbml_obj) - - -def antimony2sbml(ant_model: str | Path) -> str: - """Convert Antimony model to SBML. - - :param ant_model: Antimony model as string or path to file. - Strings are interpreted as Antimony model strings. - - :returns: - The SBML model as string. - """ - import antimony as ant - - # Unload everything / free memory - ant.clearPreviousLoads() - ant.freeAll() - - try: - # potentially fails because of too long file name - is_file = ant_model and Path(ant_model).exists() - except OSError: - is_file = False - - if is_file: - status = ant.loadAntimonyFile(str(ant_model)) - else: - status = ant.loadAntimonyString(ant_model) - if status < 0: - raise RuntimeError( - f"Antimony model could not be loaded: {ant.getLastError()}" - ) - - if (main_module_name := ant.getMainModuleName()) is None: - raise AssertionError("There is no Antimony module.") - - sbml_str = ant.getSBMLString(main_module_name) - if not sbml_str: - raise ValueError("Antimony model could not be converted to SBML.") - - return sbml_str +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/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 96% rename from tests/v1/bngl_corpus/README.md rename to tests/models/bngl_corpus/README.md index 2aee5db8..5550643d 100644 --- a/tests/v1/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/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 97% rename from tests/v1/fetch_bngl_corpus.py rename to tests/models/fetch_bngl_corpus.py index 21e9d721..6c41e486 100755 --- a/tests/v1/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/v1/test_bngl_corpus.py b/tests/models/test_bngl_corpus.py similarity index 94% rename from tests/v1/test_bngl_corpus.py rename to tests/models/test_bngl_corpus.py index aa49f7d3..82e88ee0 100644 --- a/tests/v1/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/v1/test_model_bngl.py b/tests/models/test_model_bngl.py similarity index 98% rename from tests/v1/test_model_bngl.py rename to tests/models/test_model_bngl.py index b4641faf..cd83c6a7 100644 --- a/tests/v1/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/v1/test_model_pysb.py b/tests/models/test_model_pysb.py similarity index 98% rename from tests/v1/test_model_pysb.py rename to tests/models/test_model_pysb.py index 48aa4481..6afebafd 100644 --- a/tests/v1/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,