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/changelog.d/+v2-lint-entity-eligibility.breaking.md b/changelog.d/+v2-lint-entity-eligibility.breaking.md new file mode 100644 index 00000000..0522d632 --- /dev/null +++ b/changelog.d/+v2-lint-entity-eligibility.breaking.md @@ -0,0 +1,7 @@ +PEtab v2 validation: the new validation task `CheckModelEntityEligibility` +reports errors for model entities that the PEtab v2 specification does not +allow as condition targets (e.g., targets of assignment rules, reactions) or +in the parameter table (e.g., targets of assignment rules, rate rules, or +event assignments), and warnings for questionable but valid uses. +Currently implemented for SBML models +([#623](https://github.com/PEtab-dev/libpetab-python/pull/623)) 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/_entities.py b/petab/_models/_entities.py new file mode 100644 index 00000000..e07e4377 --- /dev/null +++ b/petab/_models/_entities.py @@ -0,0 +1,385 @@ +"""Classification of model entities. + +Each model wrapper (:class:`petab.v2.models.Model` subclass) describes the +entities of its model as :class:`EntityInfo` objects +(:meth:`petab.v2.models.Model._get_entity`, +:meth:`petab.v2.models.Model._iter_entities`). +The functions in this module answer PEtab-level questions about an entity, +e.g., whether it may be a condition target or a parameter-table row, +based on that description only. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from enum import StrEnum +from functools import cached_property +from typing import TYPE_CHECKING, Literal + +if TYPE_CHECKING: + import sympy as sp + +__all__ = [ + "Dynamics", + "EligibilityIssue", + "EntityCategory", + "EntityInfo", + "Initializer", + "InitializerKind", + "SpeciesQuantity", + "condition_target_issue", + "has_literal_default", + "is_constant_parameter", + "parameter_table_issue", +] + + +class EntityCategory(StrEnum): + """What a model entity is.""" + + #: A plain scalar quantity, e.g., an SBML parameter. + PARAMETER = "parameter" + #: An amount or concentration of a chemical species. + SPECIES = "species" + #: A compartment; its value is the compartment size. + COMPARTMENT = "compartment" + #: Any other quantity, e.g., a reaction rate, a stoichiometry, or an + #: observable or expression defined in the model. + #: Neither a valid condition target nor a parameter-table entry. + OTHER_QUANTITY = "other_quantity" + #: An identifier that does not denote a number, e.g., an event, + #: a function definition, or a molecule type. + NON_QUANTITY = "non_quantity" + + +class Dynamics(StrEnum): + """How the value of an entity evolves over time. + + This is the *entity type* defined by the PEtab v2 specification. + """ + + #: Constant, or piecewise constant if subject to event assignments. + CONSTANT = "constant" + #: Defined by a time derivative. + DIFFERENTIAL = "differential" + #: Determined by an algebraic equation that is in effect throughout the + #: simulation, e.g., the target of an SBML assignment rule, the + #: unknown of an SBML algebraic rule, a reaction rate, or a PySB + #: expression. + ALGEBRAIC = "algebraic" + + +class SpeciesQuantity(StrEnum): + """Whether the value of a species is an amount or a concentration.""" + + AMOUNT = "amount" + CONCENTRATION = "concentration" + + +class InitializerKind(StrEnum): + """How the model defines the initial value of an entity.""" + + #: A number, or an expression over numbers only. + LITERAL = "literal" + #: An expression over other model entities. + FORMULA = "formula" + #: No initial value, or not introspectable. + UNSPECIFIED = "unspecified" + + +@dataclass(frozen=True, kw_only=True) +class Initializer: + """The initial value of an entity, as defined by the model itself. + + This is the value before PEtab applies any parameter-table values or + condition changes. + Use :meth:`literal`, :meth:`formula`, or :meth:`unspecified` to create + instances. + + :ivar kind: How the initial value is defined. + :ivar value: The initial value, for ``LITERAL`` initializers only. + :ivar raw: The defining expression in the model's own syntax, + for ``FORMULA`` initializers only. + :ivar dependencies: IDs of the model entities and functions that + the defining expression refers to, for ``FORMULA`` initializers only. + """ + + kind: InitializerKind + value: float | None = None + raw: str | None = None + dependencies: frozenset[str] = frozenset() + _expression_factory: Callable[[], sp.Expr] | None = field( + default=None, compare=False, repr=False + ) + + @classmethod + def literal(cls, value: float) -> Initializer: + """Create an initializer for a numeric initial value.""" + return cls(kind=InitializerKind.LITERAL, value=float(value)) + + @classmethod + def formula( + cls, + raw: str, + dependencies: Iterable[str] = (), + expression: Callable[[], sp.Expr] | None = None, + ) -> Initializer: + """Create an initializer for an initial value defined by an + expression. + + :param raw: The expression in the model's own syntax. + :param dependencies: IDs the expression refers to. + :param expression: A function returning the expression as a sympy + expression; called at most once, when :attr:`expression` is + first accessed. + """ + return cls( + kind=InitializerKind.FORMULA, + raw=raw, + dependencies=frozenset(dependencies), + _expression_factory=expression, + ) + + @classmethod + def unspecified(cls) -> Initializer: + """Create an initializer for an entity without initial value.""" + return cls(kind=InitializerKind.UNSPECIFIED) + + @cached_property + def expression(self) -> sp.Expr | None: + """The defining expression as a sympy expression. + + ``None`` for non-``FORMULA`` initializers, and if the model type + does not support conversion to sympy. + """ + if self._expression_factory is None: + return None + return self._expression_factory() + + +@dataclass(frozen=True, kw_only=True) +class EntityInfo: + """Description of a model entity. + + :ivar id: The entity's ID in the model, or, for PySB and BNGL species, + the species pattern string. + :ivar category: What the entity is. + :ivar dynamics: How the entity's value evolves. + ``None`` for :attr:`EntityCategory.NON_QUANTITY` entities. + :ivar event_assigned: Whether the entity is the target of an event + assignment. A ``CONSTANT`` entity that is not event-assigned is + *truly constant* in the sense of the PEtab v2 specification. + :ivar initializer: How the model defines the entity's initial value. + :ivar usable_in_math: Whether the ID may be used as a symbol in PEtab + math expressions, e.g., in observable formulas. + :ivar native_type: The model-specific type of the entity, + e.g., ``"sbml:Species"``. For messages only. + :ivar species_quantity: Whether the value is an amount or a + concentration. For species only. + :ivar declared: Whether the model declares the entity. + ``False`` for PySB and BNGL species patterns that are valid, but + not declared by the model; the model's rules may or may not + generate such a species. + :ivar notes: Remarks about questionable aspects of the entity, + e.g., an ambiguous algebraic rule. Validation reports each as a + warning. + """ + + id: str + category: EntityCategory + dynamics: Dynamics | None + event_assigned: bool = False + initializer: Initializer = field(default_factory=Initializer.unspecified) + usable_in_math: bool = True + native_type: str = "" + species_quantity: SpeciesQuantity | None = None + declared: bool = True + notes: tuple[str, ...] = () + + +@dataclass(frozen=True) +class EligibilityIssue: + """A reason why an entity is not, or not unconditionally, eligible for + some use. + + :ivar message: Human-readable description, naming the model construct. + :ivar level: ``"error"`` if the use is invalid, ``"warning"`` if it is + allowed but questionable. + """ + + message: str + level: Literal["error", "warning"] + + +def is_constant_parameter(info: EntityInfo) -> bool: + """Check whether the entity is a parameter of constant type. + + Event-assigned parameters are included. + """ + return ( + info.category == EntityCategory.PARAMETER + and info.dynamics == Dynamics.CONSTANT + ) + + +def has_literal_default(info: EntityInfo) -> bool: + """Check whether the model defines a numeric initial value for the + entity.""" + return info.initializer.kind == InitializerKind.LITERAL + + +def _matches( + info: EntityInfo, + category: EntityCategory | None, + dynamics: Dynamics | None, +) -> bool: + """Check whether the entity matches the given filters.""" + return (category is None or info.category == category) and ( + dynamics is None or info.dynamics == dynamics + ) + + +def _describe(info: EntityInfo) -> str: + """Short description of an entity for messages.""" + if info.native_type: + return f"`{info.id}` ({info.native_type})" + return f"`{info.id}`" + + +def _notes_issue(info: EntityInfo) -> EligibilityIssue | None: + if not info.notes: + return None + return EligibilityIssue( + f"{_describe(info)}: " + " ".join(info.notes), "warning" + ) + + +def _check_petab_version(petab_version: int) -> None: + if petab_version not in (1, 2): + raise ValueError(f"Unsupported PEtab version: {petab_version}") + + +def condition_target_issue( + info: EntityInfo, *, petab_version: Literal[1, 2] +) -> EligibilityIssue | None: + """Check whether the entity may be changed by the condition table. + + :param info: The entity. + :param petab_version: The PEtab major version whose rules apply. + :returns: ``None`` if the entity is a valid condition target without + reservations, otherwise the most severe issue. + """ + _check_petab_version(petab_version) + what = _describe(info) + + if info.category not in ( + EntityCategory.PARAMETER, + EntityCategory.SPECIES, + EntityCategory.COMPARTMENT, + ): + return EligibilityIssue( + f"{what} cannot be changed by a condition: it is not a " + "parameter, species, or compartment.", + "error", + ) + + if info.dynamics == Dynamics.ALGEBRAIC: + if petab_version == 2: + return EligibilityIssue( + f"{what} is defined by an algebraic assignment (e.g., an " + "assignment rule) and cannot be changed by a condition.", + "error", + ) + return EligibilityIssue( + f"{what} is defined by an algebraic assignment (e.g., an " + "assignment rule). The assignment overrides any condition " + "value, so the condition has no effect.", + "warning", + ) + + # PEtab v2 specifies that the condition value replaces the model's + # definition, PEtab v1 does not + if ( + petab_version == 1 + and info.category == EntityCategory.PARAMETER + and info.initializer.kind == InitializerKind.FORMULA + ): + return EligibilityIssue( + f"{what} is defined in the model as `{info.initializer.raw}`. " + "The condition value replaces that definition; some " + "simulators ignore it.", + "warning", + ) + + if not info.declared: + return EligibilityIssue( + f"{what} is not declared in the model; it is a valid species " + "pattern, but it may not exist in the generated reaction " + "network.", + "warning", + ) + + return _notes_issue(info) + + +def parameter_table_issue( + info: EntityInfo, *, petab_version: Literal[1, 2] +) -> EligibilityIssue | None: + """Check whether the entity may be listed in the parameter table. + + :param info: The entity. + :param petab_version: The PEtab major version whose rules apply. + :returns: ``None`` if the entity is a valid parameter-table entry + without reservations, otherwise the most severe issue. + """ + _check_petab_version(petab_version) + what = _describe(info) + + if info.category != EntityCategory.PARAMETER: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: " + "it is not a parameter.", + "error", + ) + + if info.dynamics == Dynamics.ALGEBRAIC: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: it is " + "defined by an algebraic assignment (e.g., an assignment rule).", + "error", + ) + + if info.dynamics == Dynamics.DIFFERENTIAL: + msg = ( + f"{what} cannot be listed in the parameter table: it is defined " + "by a time derivative (e.g., a rate rule)." + ) + if petab_version == 1: + msg += " This is a restriction of this library." + return EligibilityIssue(msg, "error") + + if info.event_assigned: + if petab_version == 2: + return EligibilityIssue( + f"{what} cannot be listed in the parameter table: " + "it is the target of an event assignment.", + "error", + ) + return EligibilityIssue( + f"{what} is the target of an event assignment. This is allowed " + "in PEtab v1, but invalid in PEtab v2.", + "warning", + ) + + if info.initializer.kind == InitializerKind.FORMULA: + return EligibilityIssue( + f"{what} is defined in the model as `{info.initializer.raw}`. " + "In PEtab v2, the parameter-table value replaces that " + "definition; PEtab v1 does not specify this, and some " + "simulators keep the model definition and ignore the " + "parameter-table value.", + "warning", + ) + + return _notes_issue(info) diff --git a/petab/_models/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..6372d5ff --- /dev/null +++ b/petab/_models/model.py @@ -0,0 +1,228 @@ +"""PEtab model abstraction""" + +from __future__ import annotations + +import abc +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ._entities import Dynamics, EntityCategory, EntityInfo + +__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 _get_entity(self, id_: str) -> EntityInfo | None: + """Get the description of the model entity with the given ID. + + Private for now; the interface may still change. + + :param id_: The entity's ID in the model, or, for PySB and BNGL + models, a species pattern string. + :returns: The entity description, or ``None`` if the model has no + such entity. + :raises NotImplementedError: If the model type does not support + entity classification yet. + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement `_get_entity`." + ) + + def _iter_entities( + self, + category: EntityCategory | None = None, + dynamics: Dynamics | None = None, + ) -> Iterator[EntityInfo]: + """Iterate over the entities of the model. + + Private for now; the interface may still change. + Species that the model does not declare, e.g., species generated + by reaction rules, are not included. + + :param category: Only include entities of this category. + :param dynamics: Only include entities with this dynamics. + :returns: Iterator over entity descriptions. + :raises NotImplementedError: If the model type does not support + entity classification yet. + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement `_iter_entities`." + ) + + +def model_factory( + filepath_or_buffer: Any, + 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..6c7c85f4 --- /dev/null +++ b/petab/_models/sbml_model.py @@ -0,0 +1,851 @@ +"""Functions for handling SBML models""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterable, Iterator +from functools import cached_property +from math import isnan as math_isnan +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 ._entities import ( + Dynamics, + EntityCategory, + EntityInfo, + Initializer, + SpeciesQuantity, + _matches, +) +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 _get_entity(self, id_: str) -> EntityInfo | None: + """Get the description of the model entity with the given ID. + + Elements are classified as follows: + + * parameters, species, compartments, and species references + (stoichiometries): by their rules, event assignments, and + participation in reactions; + * reactions (their rates): read-only quantities; + * events and function definitions: non-quantities. + + Other elements with an ID, e.g., local parameters, unit definitions, + or elements of SBML packages, are not entities. + Of ``comp`` models, only the main model is considered. + Results reflect the current state of the SBML model. + + See :meth:`petab.v2.models.Model._get_entity`. + """ + element = self.sbml_model.getElementBySId(id_) + if ( + element is None + or element.getPackageName() != "core" + or element.getTypeCode() not in _SBML_ENTITY_TYPES + ): + return None + return _classify_sbml_element( + element, _SbmlModelIndex(self.sbml_model, single=True) + ) + + def _iter_entities( + self, + category: EntityCategory | None = None, + dynamics: Dynamics | None = None, + ) -> Iterator[EntityInfo]: + """Iterate over the entities of the model. + + See :meth:`_get_entity` and + :meth:`petab.v2.models.Model._iter_entities`. + """ + index = _SbmlModelIndex(self.sbml_model) + # Not `getListOfAllElements`, which is quadratic in the model size, + # and which would include local parameters of SBML L2 models. + elements = [ + element + for element in _iter_sbml_elements(self.sbml_model) + if element.isSetIdAttribute() + ] + + def generate(): + for element in elements: + info = _classify_sbml_element(element, index) + if info is not None and _matches(info, category, dynamics): + yield info + + return generate() + + +def _iter_sbml_elements(model: libsbml.Model) -> Iterator[libsbml.SBase]: + """Iterate over the SBML core elements of a model that may have an ID. + + Local parameters are not included. + """ + # Not rules, initial assignments, or event assignments: libsbml does not + # resolve their `id` attribute in `getElementBySId`. + yield from model.getListOfFunctionDefinitions() + yield from model.getListOfCompartments() + yield from model.getListOfSpecies() + yield from model.getListOfParameters() + for reaction in model.getListOfReactions(): + yield reaction + yield from reaction.getListOfReactants() + yield from reaction.getListOfProducts() + yield from reaction.getListOfModifiers() + yield from model.getListOfEvents() + + +def _iter_sbml_math(model: libsbml.Model) -> Iterator[libsbml.ASTNode]: + """Iterate over the math of all SBML core elements of a model.""" + for element in itertools.chain( + model.getListOfFunctionDefinitions(), + model.getListOfInitialAssignments(), + model.getListOfRules(), + model.getListOfConstraints(), + ( + reaction.getKineticLaw() + for reaction in model.getListOfReactions() + if reaction.isSetKineticLaw() + ), + *( + ( + event.getTrigger(), + event.getDelay(), + event.getPriority(), + *event.getListOfEventAssignments(), + ) + for event in model.getListOfEvents() + ), + ): + if element is not None and element.isSetMath(): + yield element.getMath() + + +#: Type codes of SBML elements whose value can be set or computed. +_SBML_VARIABLE_TYPES = { + libsbml.SBML_PARAMETER, + libsbml.SBML_SPECIES, + libsbml.SBML_COMPARTMENT, + libsbml.SBML_SPECIES_REFERENCE, +} + +#: Type codes of the SBML core elements that are entities +#: (see :func:`_iter_sbml_elements`). +_SBML_ENTITY_TYPES = { + *_SBML_VARIABLE_TYPES, + libsbml.SBML_FUNCTION_DEFINITION, + libsbml.SBML_REACTION, + libsbml.SBML_MODIFIER_SPECIES_REFERENCE, + libsbml.SBML_EVENT, +} + + +class _SbmlModelIndex: + """Model-wide information needed to classify SBML elements. + + In bulk mode, each aggregate is computed on first use, by one pass over + the model. In single mode (for classifying a single element), targeted + lookups are used where possible. + Only valid as long as the model is not modified. + """ + + def __init__(self, model: libsbml.Model, single: bool = False): + self.model = model + self.single = single + + def rule_type(self, id_: str) -> int | None: + """The type code of the assignment or rate rule for the given ID.""" + if not self.single: + return self.rule_types.get(id_) + rule = self.model.getRuleByVariable(id_) + if rule is None or rule.isAlgebraic(): + return None + return rule.getTypeCode() + + def initial_assignment(self, id_: str) -> libsbml.InitialAssignment | None: + if not self.single: + return self.initial_assignments.get(id_) + return self.model.getInitialAssignmentBySymbol(id_) + + def is_event_assigned(self, id_: str) -> bool: + if not self.single: + return id_ in self.event_assignment_targets + return any( + ea.getVariable() == id_ + for event in self.model.getListOfEvents() + for ea in event.getListOfEventAssignments() + ) + + def is_reactant_or_product(self, id_: str) -> bool: + if not self.single: + return id_ in self.reactants_and_products + return any( + species_ref.getSpecies() == id_ + for reaction in self.model.getListOfReactions() + for species_ref in itertools.chain( + reaction.getListOfReactants(), reaction.getListOfProducts() + ) + ) + + def algebraic_info(self, id_: str) -> tuple[bool, list[str]]: + """Whether the entity is determined by an algebraic rule, and notes. + + See :attr:`algebraic`. + """ + if self.single and not any( + node.getType() == libsbml.AST_NAME and node.getName() == id_ + for rule in self.model.getListOfRules() + if rule.isAlgebraic() and rule.isSetMath() + for node in _iter_ast(rule.getMath()) + ): + return False, [] + determined, notes = self.algebraic + return id_ in determined, notes.get(id_, []) + + @cached_property + def rule_types(self) -> dict[str, int]: + """Rule type codes by rule variable.""" + return { + rule.getVariable(): rule.getTypeCode() + for rule in self.model.getListOfRules() + if not rule.isAlgebraic() + } + + @cached_property + def event_assignment_targets(self) -> set[str]: + return { + ea.getVariable() + for event in self.model.getListOfEvents() + for ea in event.getListOfEventAssignments() + } + + @cached_property + def initial_assignments(self) -> dict[str, libsbml.InitialAssignment]: + return { + ia.getSymbol(): ia + for ia in self.model.getListOfInitialAssignments() + } + + @cached_property + def reactants_and_products(self) -> set[str]: + """IDs of species that are reactants or products of any reaction.""" + return { + species_ref.getSpecies() + for reaction in self.model.getListOfReactions() + for species_ref in itertools.chain( + reaction.getListOfReactants(), reaction.getListOfProducts() + ) + } + + @cached_property + def algebraic(self) -> tuple[set[str], dict[str, list[str]]]: + """Entities determined by algebraic rules. + + :returns: The IDs of entities that are the only candidate for being + determined by some algebraic rule, and notes for entities that + are one of several candidates. + """ + rules = [ + rule for rule in self.model.getListOfRules() if rule.isAlgebraic() + ] + if not rules: + return set(), {} + + rate_of_targets = { + node.getChild(0).getName() + for math in _iter_sbml_math(self.model) + for node in _iter_ast(math) + if node.getType() == libsbml.AST_FUNCTION_RATE_OF + and node.getNumChildren() == 1 + } + + def is_candidate(id_: str) -> bool: + element = self.model.getElementBySId(id_) + if ( + element is None + or element.getTypeCode() not in _SBML_VARIABLE_TYPES + or element.getConstant() + or self.rule_type(id_) is not None + or id_ in rate_of_targets + ): + return False + return not ( + element.getTypeCode() == libsbml.SBML_SPECIES + and not element.getBoundaryCondition() + and self.is_reactant_or_product(id_) + ) + + # (rule formula, candidates) for each rule not yet resolved + undecided = [ + ( + libsbml.formulaToL3String(rule.getMath()), + [ + c + for c in sorted( + { + node.getName() + for node in _iter_ast(rule.getMath()) + if node.getType() == libsbml.AST_NAME + } + ) + if is_candidate(c) + ], + ) + for rule in rules + if rule.isSetMath() + ] + # A rule with a single undetermined candidate determines it; + # repeat until no rule determines a new entity. + determined = set() + changed = True + while changed: + changed = False + still_undecided = [] + for formula, candidates in undecided: + remaining = [c for c in candidates if c not in determined] + if len(remaining) <= 1: + determined.update(remaining) + changed = True + else: + still_undecided.append((formula, remaining)) + undecided = still_undecided + + notes = {} + for formula, candidates in undecided: + for candidate in candidates: + notes.setdefault(candidate, []).append( + f"It may be determined by the algebraic rule " + f"`0 = {formula}`, which has several candidate " + f"variables ({', '.join(candidates)})." + ) + return determined, notes + + +def _iter_ast(node: libsbml.ASTNode) -> Iterator[libsbml.ASTNode]: + """Iterate over all nodes of an AST.""" + nodes = [node] + while nodes: + node = nodes.pop() + yield node + nodes.extend(node.getChild(i) for i in range(node.getNumChildren())) + + +#: AST node types that refer to the model state or time. +_AST_NON_CLOSED_TYPES = { + libsbml.AST_NAME, + libsbml.AST_NAME_TIME, + libsbml.AST_FUNCTION, + libsbml.AST_FUNCTION_DELAY, + libsbml.AST_FUNCTION_RATE_OF, +} + + +def _initializer_from_math(math: libsbml.ASTNode) -> Initializer: + """Classify an initial-assignment formula. + + Formulas over numbers only are evaluated; anything referring to model + entities, time, or function definitions is ``FORMULA``. + """ + dependencies = set() + closed = True + for node in _iter_ast(math): + if node.getType() in _AST_NON_CLOSED_TYPES: + closed = False + if node.getType() in (libsbml.AST_NAME, libsbml.AST_FUNCTION): + dependencies.add(node.getName()) + + if closed: + value = libsbml.SBMLTransforms.evaluateASTNode(math) + # libsbml returns NaN for anything it cannot evaluate + if not math_isnan(value) or math.isNaN(): + return Initializer.literal(value) + + math = math.deepCopy() + return Initializer.formula( + raw=libsbml.formulaToL3String(math), + dependencies=dependencies, + expression=lambda: sympify_sbml(math), + ) + + +def _formula_initializer( + formula: str, dependencies: set[str], model: libsbml.Model +) -> Initializer: + # with the model, so that IDs like `pi` or `time` are not taken as + # constants or csymbols + math = libsbml.parseL3FormulaWithModel(formula, model) + return Initializer.formula( + raw=formula, + dependencies=dependencies, + expression=lambda: sympify_sbml(math), + ) + + +def _attribute_initializer(element: libsbml.SBase) -> Initializer: + """The initial value given by the attributes of an element.""" + type_code = element.getTypeCode() + if type_code == libsbml.SBML_PARAMETER: + if element.isSetValue(): + return Initializer.literal(element.getValue()) + elif type_code == libsbml.SBML_COMPARTMENT: + if element.isSetSize(): + return Initializer.literal(element.getSize()) + elif type_code == libsbml.SBML_SPECIES_REFERENCE: + # defaults to 1 before SBML L3 + if element.isSetStoichiometry() or element.getLevel() < 3: + return Initializer.literal(element.getStoichiometry()) + elif type_code == libsbml.SBML_SPECIES: + compartment = element.getCompartment() + if element.getHasOnlySubstanceUnits(): + if element.isSetInitialAmount(): + return Initializer.literal(element.getInitialAmount()) + if element.isSetInitialConcentration(): + return _formula_initializer( + f"{element.getInitialConcentration()!r} * {compartment}", + {compartment}, + element.getModel(), + ) + else: + if element.isSetInitialConcentration(): + return Initializer.literal(element.getInitialConcentration()) + if element.isSetInitialAmount(): + return _formula_initializer( + f"{element.getInitialAmount()!r} / {compartment}", + {compartment}, + element.getModel(), + ) + return Initializer.unspecified() + + +def _classify_sbml_element( + element: libsbml.SBase, index: _SbmlModelIndex +) -> EntityInfo | None: + """Classify an SBML element with an ID.""" + type_code = element.getTypeCode() + id_ = element.getIdAttribute() + native_type = f"sbml:{type(element).__name__}" + + if type_code == libsbml.SBML_REACTION: + return EntityInfo( + id=id_, + category=EntityCategory.OTHER_QUANTITY, + dynamics=Dynamics.ALGEBRAIC, + native_type=native_type, + ) + + if type_code not in _SBML_VARIABLE_TYPES: + return EntityInfo( + id=id_, + category=EntityCategory.NON_QUANTITY, + dynamics=None, + usable_in_math=False, + native_type=native_type, + ) + + category = { + libsbml.SBML_PARAMETER: EntityCategory.PARAMETER, + libsbml.SBML_SPECIES: EntityCategory.SPECIES, + libsbml.SBML_COMPARTMENT: EntityCategory.COMPARTMENT, + libsbml.SBML_SPECIES_REFERENCE: EntityCategory.OTHER_QUANTITY, + }[type_code] + + rule_type = index.rule_type(id_) + algebraic_determined, algebraic_notes = ( + index.algebraic_info(id_) if rule_type is None else (False, []) + ) + if ( + rule_type == libsbml.SBML_ASSIGNMENT_RULE + or algebraic_determined + or ( + type_code == libsbml.SBML_SPECIES_REFERENCE + and element.isSetStoichiometryMath() + ) + ): + dynamics = Dynamics.ALGEBRAIC + elif rule_type == libsbml.SBML_RATE_RULE or ( + type_code == libsbml.SBML_SPECIES + and not element.getBoundaryCondition() + and not element.getConstant() + and index.is_reactant_or_product(id_) + ): + dynamics = Dynamics.DIFFERENTIAL + else: + dynamics = Dynamics.CONSTANT + + if dynamics == Dynamics.ALGEBRAIC: + initializer = Initializer.unspecified() + elif (ia := index.initial_assignment(id_)) is not None and ia.isSetMath(): + initializer = _initializer_from_math(ia.getMath()) + else: + initializer = _attribute_initializer(element) + + species_quantity = None + if type_code == libsbml.SBML_SPECIES: + species_quantity = ( + SpeciesQuantity.AMOUNT + if element.getHasOnlySubstanceUnits() + else SpeciesQuantity.CONCENTRATION + ) + + return EntityInfo( + id=id_, + category=category, + dynamics=dynamics, + event_assigned=index.is_event_assigned(id_), + initializer=initializer, + # species reference IDs only have a mathematical meaning since L3 + usable_in_math=element.getLevel() >= 3 + or type_code != libsbml.SBML_SPECIES_REFERENCE, + native_type=native_type, + species_quantity=species_quantity, + notes=tuple(algebraic_notes), + ) + + +def sympify_sbml(sbml_obj: libsbml.ASTNode | libsbml.SBase) -> sp.Expr: + """Convert SBML math expression to sympy expression. + + 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/lint.py b/petab/v2/lint.py index 3a995e66..96c7e506 100644 --- a/petab/v2/lint.py +++ b/petab/v2/lint.py @@ -14,7 +14,13 @@ import pandas as pd import sympy as sp +from .._models._entities import ( + EligibilityIssue, + condition_target_issue, + parameter_table_issue, +) from ..v2.C import * +from ._helpers import _matches_id_pattern from .core import PriorDistribution, Problem logger = logging.getLogger(__name__) @@ -31,6 +37,7 @@ "CheckMeasuredObservablesDefined", "CheckMeasurementModelId", "CheckModel", + "CheckModelEntityEligibility", "CheckNeuralNetworkModel", "CheckObservablesDoNotShadowModelEntities", "CheckOverridesMatchPlaceholders", @@ -615,6 +622,76 @@ def run(self, problem: Problem) -> ValidationIssue | None: return None +class CheckModelEntityEligibility(ValidationTask): + """Check that model entities are only changed by conditions and listed + in the parameter table where the PEtab specification allows it. + + For example, targets of assignment rules must not be condition targets, + and targets of event assignments must not be in the parameter table. + Condition targets and parameter-table IDs are resolved via the mapping + table. IDs that are not model entities are not checked here. + Models that do not support entity classification are skipped. + """ + + def run(self, problem: Problem) -> ValidationIssue | None: + model_ids = { + m.petab_id: m.model_id for m in problem.mappings if m.model_id + } + targets = { + change.target_id + for cond in problem.conditions + for change in cond.changes + } + checks = [ + *((id_, condition_target_issue) for id_ in sorted(targets)), + *( + (id_, parameter_table_issue) + for id_ in sorted({p.id for p in problem.parameters}) + ), + ] + + errors = [] + warnings = [] + for model in problem.models: + try: + entities = {e.id: e for e in model._iter_entities()} + except NotImplementedError: + continue + + for petab_id, check in checks: + model_id = model_ids.get(petab_id, petab_id) + if (info := entities.get(model_id)) is None: + # only species patterns may be missing from + # `_iter_entities`, and they are no valid identifiers + if _matches_id_pattern(model_id): + continue + if (info := model._get_entity(model_id)) is None: + continue + issue: EligibilityIssue | None = check(info, petab_version=2) + if issue is None: + continue + where = ( + "Condition table" + if check is condition_target_issue + else "Parameter table" + ) + alias = ( + f" (`{petab_id}` in the mapping table)" + if model_id != petab_id + else "" + ) + message = f"{where}{alias}: {issue.message}" + (errors if issue.level == "error" else warnings).append( + message + ) + + if errors: + return ValidationError("\n".join(errors)) + if warnings: + return ValidationWarning("\n".join(warnings)) + return None + + class CheckValidParameterInConditionOrParameterTable(ValidationTask): """A task to check that all required and only allowed model parameters are present in the condition or parameter table.""" @@ -1270,6 +1347,7 @@ def get_placeholders( CheckObservablesDoNotShadowModelEntities(), CheckAllParametersPresentInParameterTable(), CheckValidParameterInConditionOrParameterTable(), + CheckModelEntityEligibility(), CheckUnusedExperiments(), CheckUnusedConditions(), CheckUnusedPlaceholders(), diff --git a/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/models/test_model_entities.py b/tests/models/test_model_entities.py new file mode 100644 index 00000000..1f0701a9 --- /dev/null +++ b/tests/models/test_model_entities.py @@ -0,0 +1,548 @@ +"""Tests for the model entity classification (`petab._models._entities`).""" + +import libsbml +import pytest +import sympy as sp + +from petab._models._entities import ( + Dynamics, + EntityCategory, + EntityInfo, + Initializer, + InitializerKind, + SpeciesQuantity, + condition_target_issue, + has_literal_default, + is_constant_parameter, + parameter_table_issue, +) +from petab.v2.models.sbml_model import SbmlModel + +K = EntityCategory +T = Dynamics +LIT = Initializer.literal +UNSPECIFIED = Initializer.unspecified() + + +def kw(**kwargs): + """Keyword arguments as a dict.""" + return kwargs + + +def formula(raw, *dependencies): + return Initializer.formula(raw=raw, dependencies=dependencies) + + +def assert_consistent(model): + """`_iter_entities` and `_get_entity` agree.""" + entities = list(model._iter_entities()) + assert len({e.id for e in entities}) == len(entities) + for info in entities: + assert model._get_entity(info.id) == info + return {e.id: e for e in entities} + + +# --- _entities.py --- + + +def test_initializer(): + calls = [] + + def factory(): + calls.append(1) + return sp.Symbol("k") * 2 + + init = Initializer.formula( + raw="2*k", dependencies=["k"], expression=factory + ) + assert init.kind == InitializerKind.FORMULA + assert init.dependencies == {"k"} + assert not calls + assert init.expression == 2 * sp.Symbol("k") + assert init.expression == 2 * sp.Symbol("k") + assert calls == [1] + # the expression factory is not part of equality + assert init == Initializer.formula(raw="2*k", dependencies=["k"]) + assert Initializer.formula(raw="2*k").expression is None + + assert LIT(2) == Initializer(kind=InitializerKind.LITERAL, value=2.0) + assert LIT(2).expression is None + assert UNSPECIFIED.kind == InitializerKind.UNSPECIFIED + + +def _info(**kwargs): + defaults = kw(id="x", category=K.PARAMETER, dynamics=T.CONSTANT) + return EntityInfo(**(defaults | kwargs)) + + +@pytest.mark.parametrize( + "info, v1, v2", + [ + (_info(), None, None), + (_info(event_assigned=True), None, None), + (_info(dynamics=T.DIFFERENTIAL), None, None), + (_info(category=K.SPECIES, dynamics=T.DIFFERENTIAL), None, None), + ( + _info(category=K.SPECIES, initializer=formula("k", "k")), + None, + None, + ), + (_info(category=K.COMPARTMENT), None, None), + (_info(dynamics=T.ALGEBRAIC), "warning", "error"), + (_info(category=K.OTHER_QUANTITY), "error", "error"), + (_info(category=K.NON_QUANTITY, dynamics=None), "error", "error"), + (_info(initializer=formula("2*k", "k")), "warning", None), + ( + _info(category=K.SPECIES, declared=False), + "warning", + "warning", + ), + (_info(notes=("ambiguous",)), "warning", "warning"), + ], +) +def test_condition_target_issue(info, v1, v2): + for version, expected in ((1, v1), (2, v2)): + issue = condition_target_issue(info, petab_version=version) + assert (issue and issue.level) == expected + if issue: + assert "`x`" in issue.message + + +@pytest.mark.parametrize( + "info, v1, v2", + [ + (_info(), None, None), + (_info(event_assigned=True), "warning", "error"), + (_info(dynamics=T.DIFFERENTIAL), "error", "error"), + (_info(dynamics=T.ALGEBRAIC), "error", "error"), + (_info(category=K.SPECIES), "error", "error"), + (_info(category=K.COMPARTMENT), "error", "error"), + (_info(category=K.OTHER_QUANTITY), "error", "error"), + (_info(initializer=formula("2*k", "k")), "warning", "warning"), + (_info(notes=("ambiguous",)), "warning", "warning"), + ], +) +def test_parameter_table_issue(info, v1, v2): + for version, expected in ((1, v1), (2, v2)): + issue = parameter_table_issue(info, petab_version=version) + assert (issue and issue.level) == expected + + +def test_issue_functions_require_version(): + with pytest.raises(TypeError): + condition_target_issue(_info()) + with pytest.raises(ValueError): + parameter_table_issue(_info(), petab_version=3) + + +def test_predicates(): + assert is_constant_parameter(_info()) + assert is_constant_parameter(_info(event_assigned=True)) + assert not is_constant_parameter(_info(dynamics=T.DIFFERENTIAL)) + assert not is_constant_parameter(_info(category=K.SPECIES)) + assert has_literal_default(_info(initializer=LIT(1))) + assert not has_literal_default(_info()) + assert not has_literal_default(_info(initializer=formula("k", "k"))) + + +# --- SBML --- + + +@pytest.fixture +def sbml_model() -> SbmlModel: + model = SbmlModel.from_antimony(""" + function f(x) + 2 * x + end + + model m + compartment c = 2 + compartment c_unset + species S in c = 1 + species B in c + $B = 3 + species B_ev in c + $B_ev = 3 + species B_rate in c + $B_rate = 3 + species S_ar in c + species S_const in c + const S_const = 5 + species S_free in c + S_free = 4 + substanceOnly species S_amount in c = 6 + species S_ia in c + S_ia = 2 * k + + J0: S -> ; k * S + + k = 0.1 + k_ev = 1 + k_ar := 2 * k + S_ar := 2 * k + k_rate' = 1 + k_rate = 0 + B_rate' = 1 + k_ia = 2 * k + k_ia_num = 3^2 + k_ia_func = f(2) + + E1: at time > 1: k_ev = 2, B_ev = 1 + end + """) + parameter = model.sbml_model.createParameter() + parameter.setId("k_unset") + parameter.setConstant(True) + return model + + +@pytest.mark.parametrize( + "id_, expected", + [ + ( + "k", + kw( + category=K.PARAMETER, dynamics=T.CONSTANT, initializer=LIT(0.1) + ), + ), + ( + "k_ev", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + event_assigned=True, + initializer=LIT(1), + ), + ), + ("k_ar", kw(category=K.PARAMETER, dynamics=T.ALGEBRAIC)), + ( + "k_rate", + kw( + category=K.PARAMETER, + dynamics=T.DIFFERENTIAL, + initializer=LIT(0), + ), + ), + ( + "k_ia", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + initializer=formula("2 * k", "k"), + ), + ), + ( + "k_ia_num", + kw(category=K.PARAMETER, dynamics=T.CONSTANT, initializer=LIT(9)), + ), + ( + "k_ia_func", + kw( + category=K.PARAMETER, + dynamics=T.CONSTANT, + initializer=formula("f(2)", "f"), + ), + ), + ("k_unset", kw(category=K.PARAMETER, dynamics=T.CONSTANT)), + ( + "S", + kw( + category=K.SPECIES, + dynamics=T.DIFFERENTIAL, + initializer=LIT(1), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B_ev", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + event_assigned=True, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "B_rate", + kw( + category=K.SPECIES, + dynamics=T.DIFFERENTIAL, + initializer=LIT(3), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_ar", + kw( + category=K.SPECIES, + dynamics=T.ALGEBRAIC, + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_const", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(5), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + # in no reaction, no rule + "S_free", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(4), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "S_amount", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=LIT(6), + species_quantity=SpeciesQuantity.AMOUNT, + ), + ), + ( + "S_ia", + kw( + category=K.SPECIES, + dynamics=T.CONSTANT, + initializer=formula("2 * k", "k"), + species_quantity=SpeciesQuantity.CONCENTRATION, + ), + ), + ( + "c", + kw( + category=K.COMPARTMENT, dynamics=T.CONSTANT, initializer=LIT(2) + ), + ), + ("c_unset", kw(category=K.COMPARTMENT, dynamics=T.CONSTANT)), + ("J0", kw(category=K.OTHER_QUANTITY, dynamics=T.ALGEBRAIC)), + ( + "E1", + kw(category=K.NON_QUANTITY, dynamics=None, usable_in_math=False), + ), + ( + "f", + kw(category=K.NON_QUANTITY, dynamics=None, usable_in_math=False), + ), + ], +) +def test_sbml_entities(sbml_model, id_, expected): + element = sbml_model.sbml_model.getElementBySId(id_) + expected = EntityInfo( + id=id_, native_type=f"sbml:{type(element).__name__}", **expected + ) + assert sbml_model._get_entity(id_) == expected + + +def test_sbml_consistency(sbml_model): + entities = assert_consistent(sbml_model) + assert {"k", "S", "c", "J0", "E1", "f"} <= entities.keys() + assert sbml_model._get_entity("time") is None + assert sbml_model._get_entity("nonexistent") is None + + +def test_sbml_filter(sbml_model): + ids = { + e.id + for e in sbml_model._iter_entities( + category=K.PARAMETER, dynamics=T.CONSTANT + ) + } + assert ids == {"k", "k_ev", "k_ia", "k_ia_num", "k_ia_func", "k_unset"} + + +def test_sbml_initializer_expression(sbml_model): + expr = sbml_model._get_entity("k_ia").initializer.expression + assert {str(s) for s in expr.free_symbols} == {"k"} + assert float(expr.subs(dict.fromkeys(expr.free_symbols, 0.5))) == 1 + + +def test_sbml_species_other_form(): + """Initial amount for a concentration-based species.""" + model = SbmlModel.from_antimony(""" + compartment c = 2 + species S in c + S = 1 + """) + species = model.sbml_model.getSpecies("S") + species.unsetInitialConcentration() + species.setInitialAmount(4) + assert model._get_entity("S").initializer == formula("4.0 / c", "c") + expr = model._get_entity("S").initializer.expression + assert float(expr.subs(dict.fromkeys(expr.free_symbols, 2))) == 2 + + +def test_sbml_species_other_form_reserved_compartment_id(): + """A compartment ID that is a constant in L3 formulas is not one here.""" + model = SbmlModel.from_antimony(""" + compartment c = 2 + species S in c + S = 1 + """) + model.sbml_model.getCompartment("c").setId("pi") + species = model.sbml_model.getSpecies("S") + species.setCompartment("pi") + species.unsetInitialConcentration() + species.setInitialAmount(4) + expr = model._get_entity("S").initializer.expression + assert {str(s) for s in expr.free_symbols} == {"pi"} + + +def test_sbml_live_mutation(sbml_model): + sbml_model.sbml_model.getParameter("k").setValue(7) + assert sbml_model._get_entity("k").initializer == LIT(7) + rule = sbml_model.sbml_model.createAssignmentRule() + rule.setVariable("k") + rule.setMath(libsbml.parseL3Formula("1")) + assert sbml_model._get_entity("k").dynamics == T.ALGEBRAIC + assert sbml_model._get_entity("k").initializer == UNSPECIFIED + + +def _sbml_with_algebraic_rule(formula: str) -> SbmlModel: + model = SbmlModel.from_antimony(""" + compartment c = 1 + species S in c = 1 + x = 1 + y = 1 + J0: S -> ; S + """) + for id_ in ("x", "y"): + model.sbml_model.getParameter(id_).setConstant(False) + rule = model.sbml_model.createAlgebraicRule() + rule.setMath(libsbml.parseL3Formula(formula)) + return model + + +def test_sbml_algebraic_rule_single_candidate(): + # `S` is a non-boundary reactant, so `x` is the only candidate + model = _sbml_with_algebraic_rule("x - S") + assert model._get_entity("x").dynamics == T.ALGEBRAIC + assert model._get_entity("x").initializer == UNSPECIFIED + assert model._get_entity("x").notes == () + assert model._get_entity("S").dynamics == T.DIFFERENTIAL + assert model._get_entity("y").dynamics == T.CONSTANT + assert_consistent(model) + + +def test_sbml_algebraic_rule_several_candidates(): + model = _sbml_with_algebraic_rule("x + y - 1") + for id_ in ("x", "y"): + info = model._get_entity(id_) + assert info.dynamics == T.CONSTANT + assert len(info.notes) == 1 + assert "x, y" in info.notes[0] + assert condition_target_issue(info, petab_version=2).level == ( + "warning" + ) + assert_consistent(model) + + +def test_sbml_algebraic_rules_resolved_in_turn(): + # `0 = y - 2` determines `y`, leaving `x` as the only candidate of + # `0 = x + y - 1` + model = _sbml_with_algebraic_rule("x + y - 1") + rule = model.sbml_model.createAlgebraicRule() + rule.setMath(libsbml.parseL3Formula("y - 2")) + for id_ in ("x", "y"): + info = model._get_entity(id_) + assert info.dynamics == T.ALGEBRAIC + assert info.notes == () + assert_consistent(model) + + +def test_sbml_ids_of_rules(): + """IDs of rules and initial assignments are not entities. + + libsbml does not resolve them by ID. + """ + model = SbmlModel.from_antimony(""" + a = 1 + b := 2 * a + """) + model.sbml_model.getRuleByVariable("b").setIdAttribute("rule1") + assert model._get_entity("rule1") is None + assert "rule1" not in assert_consistent(model) + + +def test_sbml_ids_of_other_elements(): + """IDs of elements that are not enumerated are not entities.""" + model = SbmlModel.from_antimony(""" + S -> ; k * S + k = 1 + S = 1 + """) + reaction = model.sbml_model.getReaction(0) + reaction.getKineticLaw().setIdAttribute("kl") + assert model.sbml_model.getElementBySId("kl") is not None + assert model._get_entity("kl") is None + assert "kl" not in assert_consistent(model) + + +def test_sbml_species_reference_and_l2_local_parameter(): + document = libsbml.SBMLDocument(2, 4) + model = document.createModel() + model.setId("m") + c = model.createCompartment() + c.setId("c") + c.setSize(1) + s = model.createSpecies() + s.setId("S") + s.setCompartment("c") + s.setInitialConcentration(1) + reaction = model.createReaction() + reaction.setId("R") + reactant = reaction.createReactant() + reactant.setSpecies("S") + reactant.setId("sr") + reactant.setStoichiometry(2) + kinetic_law = reaction.createKineticLaw() + local = kinetic_law.createParameter() + local.setId("k_local") + local.setValue(1) + kinetic_law.setMath(libsbml.parseL3Formula("k_local * S")) + # no stoichiometry: 1 in SBML L2 + product = reaction.createProduct() + product.setSpecies("S") + product.setId("sp") + # stoichiometryMath + reactant2 = reaction.createReactant() + reactant2.setSpecies("S") + reactant2.setId("sr_math") + reactant2.createStoichiometryMath().setMath( + libsbml.parseL3Formula("2 * c") + ) + + sbml_model = SbmlModel(sbml_model=model) + assert not product.isSetStoichiometry() + assert sbml_model._get_entity("sp").initializer == LIT(1) + assert sbml_model._get_entity("sr_math").dynamics == T.ALGEBRAIC + assert sbml_model._get_entity("sr") == EntityInfo( + id="sr", + category=K.OTHER_QUANTITY, + dynamics=T.CONSTANT, + initializer=LIT(2), + # no mathematical meaning in SBML L2 + usable_in_math=False, + native_type="sbml:SpeciesReference", + ) + assert sbml_model._get_entity("k_local") is None + entities = assert_consistent(sbml_model) + assert "k_local" not in entities diff --git a/tests/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, diff --git a/tests/v2/test_lint.py b/tests/v2/test_lint.py index ea6c44f2..9141bc2f 100644 --- a/tests/v2/test_lint.py +++ b/tests/v2/test_lint.py @@ -320,3 +320,47 @@ def test_check_prior_distribution_infinite_bounds(): problem["p1"].prior_parameters = [0, float("inf")] assert (error := check.run(problem)) is not None assert "`p1` are invalid" in error.message + + +def test_check_model_entity_eligibility(): + problem = Problem() + problem.model = SbmlModel.from_antimony(""" + k = 1 + k_rule := 2 * k + k_event = 1 + at time > 1: k_event = 2 + k_ia = 2 * k + """) + problem.add_parameter("k", estimate=True, nominal_value=1, lb=0, ub=10) + check = CheckModelEntityEligibility() + assert check.run(problem) is None + + # parameter defined by an initial assignment: allowed, but questionable + problem.add_parameter("k_ia", estimate=False, nominal_value=1) + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.WARNING + assert "k_ia" in issue.message + + # event-assigned parameter in the parameter table + problem.add_parameter("k_event", estimate=False, nominal_value=1) + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.ERROR + assert "k_event" in issue.message + assert "k_ia" not in issue.message + + # assignment rule target as condition target + problem.parameter_tables[0].elements = [ + p for p in problem.parameters if p.id == "k" + ] + problem.add_condition("c1", k_rule="1") + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.ERROR + assert "Condition table: `k_rule`" in issue.message + assert "k_event" not in issue.message + + # models without entity classification are skipped + def not_implemented(*args, **kwargs): + raise NotImplementedError + + problem.model._iter_entities = not_implemented + assert check.run(problem) is None