diff --git a/petab/_models/pysb_model.py b/petab/_models/pysb_model.py index 0fa4be66..4a8b5031 100644 --- a/petab/_models/pysb_model.py +++ b/petab/_models/pysb_model.py @@ -16,6 +16,7 @@ from .._utils import _generate_path from ..v1.lint import is_valid_identifier from . import MODEL_TYPE_PYSB +from ._entities import EntityCategory, EntityDynamics, EntityInfo from .model import Model __all__ = ["PySBModel", "parse_species_name", "pattern_from_string"] @@ -182,28 +183,55 @@ def is_state_variable(self, id_: str) -> bool: 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()) + return _is_concrete_species(pattern) + + def _iter_entities( + self, ids: Iterable[str] | None = None + ) -> Iterator[EntityInfo]: + """Iterate over the entities of the model. + + Components are classified by their type: + parameters are model parameters, compartments are compartments, + observables and global expressions are algebraic quantities, + and monomers, rules, local expressions, and other components are + non-quantities. + + By default, the species included are those of the model's initial + conditions (:class:`pysb.Initial`), identified by their pattern. + If ``ids`` is given, any ID that is not the name of a component is + interpreted as a species pattern (see :func:`pattern_from_string`). + A pattern with all sites of all monomers specified and all bonds + paired is a species, whether or not the model's rules generate it. + It is constant if it is the pattern of a fixed initial condition, + and differential otherwise. + In a model with compartments, the pattern has to specify the + compartment. + + See :meth:`petab._models.model.Model._iter_entities`. + """ + if ids is None: + yield from map(_classify_pysb_component, self.model.components) + for initial in self.model.initials: + yield _species_entity(str(initial.pattern), initial.fixed) + return + + for id_ in dict.fromkeys(ids): + if (component := self.model.components.get(id_)) is not None: + yield _classify_pysb_component(component) + continue + try: + pattern = pattern_from_string(id_, self.model) + except ValueError: + continue + if not _is_concrete_species(pattern) or ( + self.model.compartments and not pattern.is_concrete() + ): + continue + fixed = any( + initial.fixed and initial.pattern.is_equivalent_to(pattern) + for initial in self.model.initials + ) + yield _species_entity(id_, fixed) def get_compartment_ids(self) -> Iterable[str]: return (compartment.name for compartment in self.model.compartments) @@ -355,6 +383,72 @@ def convert(node: ast.expr): raise invalid() from e +def _is_concrete_species(pattern: pysb.ComplexPattern) -> bool: + """Check whether a pattern specifies a single species. + + All sites of all monomers have to be specified, and each bond has to + connect exactly two sites. The compartment is not checked. + """ + 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 _species_entity(id_: str, fixed: bool) -> EntityInfo: + """Describe a species.""" + return EntityInfo( + id=id_, + category=EntityCategory.SPECIES, + dynamics=( + EntityDynamics.CONSTANT if fixed else EntityDynamics.DIFFERENTIAL + ), + native_type="pysb:species", + ) + + +def _classify_pysb_component(component: pysb.Component) -> EntityInfo: + """Describe a PySB model component.""" + if isinstance(component, pysb.Parameter): + category = EntityCategory.PARAMETER + dynamics = EntityDynamics.CONSTANT + elif isinstance(component, pysb.Compartment): + category = EntityCategory.COMPARTMENT + dynamics = EntityDynamics.CONSTANT + elif isinstance(component, pysb.Observable) or ( + isinstance(component, pysb.Expression) and not component.is_local + ): + category = EntityCategory.OTHER_QUANTITY + dynamics = EntityDynamics.ALGEBRAIC + else: + category = EntityCategory.NON_QUANTITY + dynamics = None + return EntityInfo( + id=component.name, + category=category, + dynamics=dynamics, + native_type=f"pysb:{type(component).__name__}", + ) + + def _iter_bonds(site_value) -> Iterator[int]: """Iterate over the bond numbers in a site value.""" if isinstance(site_value, int): diff --git a/tests/models/test_model_entities_pysb.py b/tests/models/test_model_entities_pysb.py new file mode 100644 index 00000000..35b4f425 --- /dev/null +++ b/tests/models/test_model_entities_pysb.py @@ -0,0 +1,188 @@ +"""Tests for the classification of PySB model entities.""" + +import pysb +import pytest + +from petab._models._entities import ( + EntityCategory, + EntityDynamics, + EntityInfo, +) +from petab.v2.models.bngl_model import _locate_bng2 +from petab.v2.models.pysb_model import PySBModel + +from .test_model_entities import assert_consistent + + +@pytest.fixture +def pysb_model(clean_pysb_exports) -> PySBModel: + model = pysb.Model(name="m") + A = pysb.Monomer("A", ["b", "s"], {"s": ["u", "p"]}) + B = pysb.Monomer("B", ["a"]) + C = pysb.Monomer("C", ["x", "x"], {"x": ["u", "p"]}) + c = pysb.Compartment("c", size=None) + vol = pysb.Parameter("vol", 2) + c2 = pysb.Compartment("c2", size=vol, parent=c, dimension=2) + A0 = pysb.Parameter("A0", 10) + k = pysb.Parameter("k", 1) + pysb.Expression("e", k * 2) + pysb.Initial(A(b=None, s="u") ** c, A0) + pysb.Initial(B(a=None) ** c, A0, fixed=True) + pysb.Initial(B(a=None) ** c2, A0) + pysb.Initial(C(x=pysb.MultiState("u", "p")) ** c, A0, fixed=True) + obs = pysb.Observable("obs", A()) + x = pysb.Tag("x") + pysb.Expression("loc", obs(x) * 2) + pysb.Rule( + "r", A(b=None) ** c + B(a=None) ** c | A(b=1) ** c % B(a=1) ** c, k, k + ) + return PySBModel(model=model, model_id="m") + + +@pytest.mark.parametrize( + "id_, category, dynamics, native_type", + [ + ("k", EntityCategory.PARAMETER, EntityDynamics.CONSTANT, "Parameter"), + ( + "vol", + EntityCategory.PARAMETER, + EntityDynamics.CONSTANT, + "Parameter", + ), + ( + "e", + EntityCategory.OTHER_QUANTITY, + EntityDynamics.ALGEBRAIC, + "Expression", + ), + ( + "obs", + EntityCategory.OTHER_QUANTITY, + EntityDynamics.ALGEBRAIC, + "Observable", + ), + ("loc", EntityCategory.NON_QUANTITY, None, "Expression"), + ( + "c", + EntityCategory.COMPARTMENT, + EntityDynamics.CONSTANT, + "Compartment", + ), + ( + "c2", + EntityCategory.COMPARTMENT, + EntityDynamics.CONSTANT, + "Compartment", + ), + ("A", EntityCategory.NON_QUANTITY, None, "Monomer"), + ("r", EntityCategory.NON_QUANTITY, None, "Rule"), + ("x", EntityCategory.NON_QUANTITY, None, "Tag"), + ], +) +def test_pysb_components(pysb_model, id_, category, dynamics, native_type): + assert pysb_model._get_entity(id_) == EntityInfo( + id=id_, + category=category, + dynamics=dynamics, + native_type=f"pysb:{native_type}", + ) + + +@pytest.mark.parametrize( + "id_, dynamics", + [ + # initial conditions + ("A(b=None, s='u') ** c", EntityDynamics.DIFFERENTIAL), + # site order does not matter + ("A(s='u', b=None) ** c", EntityDynamics.DIFFERENTIAL), + # fixed initial condition + ("B(a=None) ** c", EntityDynamics.CONSTANT), + ("B(a=None) ** c2", EntityDynamics.DIFFERENTIAL), + # no initial conditions + ("A(b=1, s='p') ** c % B(a=1) ** c", EntityDynamics.DIFFERENTIAL), + ("A(b=None, s='p') ** c2", EntityDynamics.DIFFERENTIAL), + # (state, bond) and MultiState + ( + "A(b=None, s=('p', 1)) ** c % B(a=1) ** c", + EntityDynamics.DIFFERENTIAL, + ), + ("C(x=MultiState('u', 'u')) ** c", EntityDynamics.DIFFERENTIAL), + # fixed initial condition, equivalent pattern + ("C(x=MultiState('p', 'u')) ** c", EntityDynamics.CONSTANT), + ], +) +def test_pysb_species(pysb_model, id_, dynamics): + assert pysb_model._get_entity(id_) == EntityInfo( + id=id_, + category=EntityCategory.SPECIES, + dynamics=dynamics, + native_type="pysb:species", + ) + + +@pytest.mark.parametrize( + "id_", + [ + # not concrete + "A(b=None)", + "C(x=MultiState('u'))", + # unpaired bond + "A(b=1, s='u') ** c", + # without compartment, although the model has compartments + "A(b=None, s='u')", + "B(a=None)", + "A(b=1, s='p') % B(a=1)", + # unknown monomer, compartment, or site + "D()", + "A(b=None, s='u') ** c3", + "A(b=None, s='u', z=None)", + "nonexistent", + ], +) +def test_pysb_non_entities(pysb_model, id_): + assert pysb_model._get_entity(id_) is None + + +def test_pysb_iter_entities(pysb_model): + entities = assert_consistent(pysb_model) + assert entities.keys() == { + component.name for component in pysb_model.model.components + } | { + "A(b=None, s='u') ** c", + "B(a=None) ** c", + "B(a=None) ** c2", + "C(x=MultiState('u', 'p')) ** c", + } + assert [ + e.id for e in pysb_model._iter_entities(["k", "B(a=None) ** c", "D()"]) + ] == ["k", "B(a=None) ** c"] + + +@pytest.mark.skipif(_locate_bng2() is None, reason="BioNetGen not available") +def test_pysb_independent_of_network_generation(pysb_model): + from pysb.bng import generate_equations + + ids = [ + "A(b=None, s='u') ** c", + "A(b=1, s='u') ** c % B(a=1) ** c", + "A(b=None, s='p') ** c", + ] + before = list(pysb_model._iter_entities(ids)) + generate_equations(pysb_model.model) + assert pysb_model.model.species + assert list(pysb_model._iter_entities(ids)) == before + + +def test_pysb_species_without_compartments(clean_pysb_exports): + model = pysb.Model(name="m") + A = pysb.Monomer("A", ["s"], {"s": ["u", "p"]}) + pysb.Initial(A(s="u"), pysb.Parameter("A0", 1)) + pysb_model = PySBModel(model=model, model_id="m") + for id_ in ("A(s='u')", "A(s='p')"): + assert pysb_model._get_entity(id_) == EntityInfo( + id=id_, + category=EntityCategory.SPECIES, + dynamics=EntityDynamics.DIFFERENTIAL, + native_type="pysb:species", + ) + assert pysb_model._get_entity("A(s='u') ** c") is None