Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog.d/+v2-lint-entity-eligibility.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
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) or in the
parameter table (e.g., targets of event assignments).
Currently implemented for SBML models
([#623](https://github.com/PEtab-dev/libpetab-python/pull/623))
75 changes: 75 additions & 0 deletions petab/_models/_entities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Classification of model entities.

Each model class (subclass of :class:`petab._models.model.Model`)
describes the entities of its model as :class:`EntityInfo` objects
(:meth:`petab._models.model.Model._iter_entities`).
Checks of these descriptions against the rules of a PEtab version belong
to that version's validation code.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import StrEnum

__all__ = [
"EntityCategory",
"EntityDynamics",
"EntityInfo",
]


class EntityCategory(StrEnum):
"""What a model entity is."""

#: A model parameter, e.g., an SBML parameter.
#: Not necessarily constant; see :class:`EntityDynamics`.
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 or a stoichiometry.
OTHER_QUANTITY = "other_quantity"
#: An identifier that does not denote a number, e.g., an event or
#: a function definition.
NON_QUANTITY = "non_quantity"


class EntityDynamics(StrEnum):
"""How the value of an entity evolves over time.

This is the *entity type* defined by the PEtab v2 specification.
For species, it refers to the amount; the concentration of a
constant species changes with the size of its compartment.
"""

#: 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, or a
#: reaction rate.
ALGEBRAIC = "algebraic"


@dataclass(frozen=True, kw_only=True)
class EntityInfo:
"""Description of a model entity.

:ivar id: The entity's ID in the model.
: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.
:ivar native_type: The model-specific type of the entity,
e.g., ``"sbml:Species"``. For messages only.
"""

id: str
category: EntityCategory
dynamics: EntityDynamics | None
event_assigned: bool = False
native_type: str = ""
36 changes: 34 additions & 2 deletions petab/_models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
from __future__ import annotations

import abc
from collections.abc import Iterable
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from ._entities import EntityInfo

__all__ = ["Model", "model_factory"]

Expand Down Expand Up @@ -136,6 +139,35 @@ 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.

:param id_: The entity's ID in the model.
: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.
"""
return next(iter(self._iter_entities([id_])), None)

def _iter_entities(
self, ids: Iterable[str] | None = None
) -> Iterator[EntityInfo]:
"""Iterate over the entities of the model.

Private for now; the interface may still change.

:param ids: Only include the entities with these IDs.
IDs that are not model entities are ignored.
By default, all entities are included.
: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,
Expand Down
118 changes: 117 additions & 1 deletion petab/_models/sbml_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import itertools
from collections.abc import Iterable
from collections.abc import Iterable, Iterator
from pathlib import Path

import libsbml
Expand All @@ -18,6 +18,7 @@
write_sbml,
)
from . import MODEL_TYPE_SBML
from ._entities import EntityCategory, EntityDynamics, EntityInfo
from .model import Model

__all__ = ["SbmlModel"]
Expand Down Expand Up @@ -315,6 +316,121 @@ def is_state_variable(self, id_: str) -> bool:
or self.sbml_model.getRuleByVariable(id_) is not None
)

def _iter_entities(
self, ids: Iterable[str] | None = None
) -> Iterator[EntityInfo]:
"""Iterate over the entities of the model.

Elements are classified as follows:

* parameters, species, compartments, and species references
(stoichiometries): by their rules, event assignments, and
participation in reactions;
* reactions (their rates): algebraic quantities;
* events, function definitions, modifier species references, rules,
initial assignments, and event assignments: non-quantities.

Other elements with an ID, e.g., local parameters, unit definitions,
or elements of SBML packages, are not classified.
Of ``comp`` models, only the main model is considered.
Variables that are determined by algebraic rules are not detected
as algebraic.

See :meth:`petab._models.model.Model._iter_entities`.
"""
ids = None if ids is None else set(ids)
model = self.sbml_model
rule_types = {
rule.getVariable(): rule.getTypeCode()
for rule in model.getListOfRules()
if not rule.isAlgebraic()
}
event_assignment_targets = {
ea.getVariable()
for event in model.getListOfEvents()
for ea in event.getListOfEventAssignments()
}
reactants_and_products = {
species_ref.getSpecies()
for reaction in model.getListOfReactions()
for species_ref in itertools.chain(
reaction.getListOfReactants(), reaction.getListOfProducts()
)
}
# Not `getListOfAllElements`, which is quadratic in the model size,
# and which would include local parameters of SBML L2 models.
for element in _iter_sbml_elements(model):
if not element.isSetIdAttribute():
continue
id_ = element.getIdAttribute()
if ids is not None and id_ not in ids:
continue
type_code = element.getTypeCode()
rule_type = rule_types.get(id_)
if type_code == libsbml.SBML_REACTION:
category = EntityCategory.OTHER_QUANTITY
dynamics = EntityDynamics.ALGEBRAIC
elif (
category := _SBML_VARIABLE_CATEGORIES.get(type_code)
) is None:
category = EntityCategory.NON_QUANTITY
dynamics = None
elif rule_type == libsbml.SBML_ASSIGNMENT_RULE or (
type_code == libsbml.SBML_SPECIES_REFERENCE
and element.isSetStoichiometryMath()
):
dynamics = EntityDynamics.ALGEBRAIC
elif rule_type == libsbml.SBML_RATE_RULE or (
type_code == libsbml.SBML_SPECIES
and not element.getBoundaryCondition()
and not element.getConstant()
and id_ in reactants_and_products
):
dynamics = EntityDynamics.DIFFERENTIAL
else:
dynamics = EntityDynamics.CONSTANT
yield EntityInfo(
id=id_,
category=category,
dynamics=dynamics,
event_assigned=id_ in event_assignment_targets,
native_type=f"sbml:{type(element).__name__}",
)


#: Categories of SBML elements whose value can be set or computed,
#: by type code.
_SBML_VARIABLE_CATEGORIES = {
libsbml.SBML_PARAMETER: EntityCategory.PARAMETER,
libsbml.SBML_SPECIES: EntityCategory.SPECIES,
libsbml.SBML_COMPARTMENT: EntityCategory.COMPARTMENT,
libsbml.SBML_SPECIES_REFERENCE: EntityCategory.OTHER_QUANTITY,
}


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.
"""
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()
# Before SBML L3V2, the following elements cannot have IDs.
if (model.getLevel(), model.getVersion()) < (3, 2):
return
yield from model.getListOfRules()
yield from model.getListOfInitialAssignments()
for event in model.getListOfEvents():
yield from event.getListOfEventAssignments()


# AST node types that refer to model entities, function definitions, or time
_AST_NON_CLOSED_TYPES = {
Expand Down
Loading
Loading