diff --git a/changelog.d/+v2-model-id-perf.perf.md b/changelog.d/+v2-model-id-perf.perf.md new file mode 100644 index 00000000..54eb9f14 --- /dev/null +++ b/changelog.d/+v2-model-id-perf.perf.md @@ -0,0 +1,4 @@ +`CheckGloballyUniqueIds`, `petab.v2.reparametrize_log`, and +`petab1to2(..., reparametrize=...)` are faster for large SBML models with +many PEtab IDs +([#655](https://github.com/PEtab-dev/libpetab-python/pull/655)) diff --git a/petab/_models/model.py b/petab/_models/model.py index 618eaaac..a834e121 100644 --- a/petab/_models/model.py +++ b/petab/_models/model.py @@ -3,7 +3,7 @@ from __future__ import annotations import abc -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from pathlib import Path from typing import TYPE_CHECKING, Any @@ -150,6 +150,15 @@ def _get_entity(self, id_: str) -> EntityInfo | None: """ return next(iter(self._iter_entities([id_])), None) + def _get_model_entity_checker(self) -> Callable[[str], bool]: + """Get a function that checks whether an ID is a model entity ID. + + Equivalent to :meth:`has_entity_with_id`, but possibly faster for + checking many IDs. The model must not be changed while the returned + function is used. + """ + return self.has_entity_with_id + def _iter_entities( self, ids: Iterable[str] | None = None ) -> Iterator[EntityInfo]: diff --git a/petab/_models/sbml_model.py b/petab/_models/sbml_model.py index a6656681..dfa37d2f 100644 --- a/petab/_models/sbml_model.py +++ b/petab/_models/sbml_model.py @@ -3,7 +3,7 @@ from __future__ import annotations import itertools -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from pathlib import Path import libsbml @@ -250,6 +250,16 @@ def _get_initial_assignment_values(self) -> dict[str, float | None]: def has_entity_with_id(self, entity_id) -> bool: return self.sbml_model.getElementBySId(entity_id) is not None + def _get_model_entity_checker(self) -> Callable[[str], bool]: + # `getElementBySId` scans the whole model, so it is only called for + # IDs that occur in the model at all + ids = { + element.getIdAttribute() + for element in self.sbml_model.getListOfAllElements() + if element.isSetIdAttribute() + } + return lambda id_: id_ in ids and self.has_entity_with_id(id_) + def get_valid_parameters_for_parameter_table(self) -> Iterable[str]: # All parameters except rule-targets disallowed_set = { diff --git a/petab/v2/core.py b/petab/v2/core.py index f3f294fc..92642f8b 100644 --- a/petab/v2/core.py +++ b/petab/v2/core.py @@ -8,7 +8,7 @@ import tempfile import traceback from abc import abstractmethod -from collections.abc import Collection, Sequence +from collections.abc import Callable, Collection, Sequence from enum import StrEnum from itertools import chain from math import nan @@ -2020,20 +2020,29 @@ def _get_unused_id( *, used_ids: Collection[str], exclude: Collection[str] = (), + model_entity_checkers: Collection[Callable[[str], bool]] | None = None, ) -> str: """Like :meth:`get_unused_id`, but with precomputed used IDs. For generating many IDs, compute `used_ids` once via :meth:`_get_used_ids` and add the generated IDs to it. + Likewise, pass `model_entity_checkers` from + ``Model._get_model_entity_checker`` for all models. """ if not is_valid_identifier(base): raise ValueError(f"`{base}' is not a valid identifier.") + if model_entity_checkers is None: + model_entity_checkers = [m.has_entity_with_id for m in self.models] + def is_used(id_: str) -> bool: return ( id_ in used_ids or id_ in exclude - or any(m.has_entity_with_id(id_) for m in self.models) + or any( + is_model_entity(id_) + for is_model_entity in model_entity_checkers + ) ) id_ = base diff --git a/petab/v2/lint.py b/petab/v2/lint.py index 91b7de38..14901f6e 100644 --- a/petab/v2/lint.py +++ b/petab/v2/lint.py @@ -605,12 +605,15 @@ def _add_model_entities( if len(problem.models) == 1 else f"entity of model `{model.model_id}`" ) - for id_ in sorted(ids_by_model.get(model, ())): + if not (ids := ids_by_model.get(model)): + continue + is_model_entity = model._get_model_entity_checker() + for id_ in sorted(ids): unmodeled = id_ in unmodeled_ids # a parameter table entry for a model entity is no clash if definitions.get(id_) == ["parameter ID"] and not unmodeled: continue - if not model.has_entity_with_id(id_): + if not is_model_entity(id_): continue if unmodeled and unmodeled_source not in definitions[id_]: definitions[id_].append(unmodeled_source) diff --git a/petab/v2/reparametrize.py b/petab/v2/reparametrize.py index ef04e6bd..503eeb57 100644 --- a/petab/v2/reparametrize.py +++ b/petab/v2/reparametrize.py @@ -301,10 +301,15 @@ def _reparametrize_log_inplace( # assign new IDs used_ids = problem._get_used_ids() + model_entity_checkers = [ + m._get_model_entity_checker() for m in problem.models + ] id_map = {} for p in parameter_ids: id_map[p] = new_parameters[p].id = problem._get_unused_id( - f"{prefix}{p}", used_ids=used_ids + f"{prefix}{p}", + used_ids=used_ids, + model_entity_checkers=model_entity_checkers, ) used_ids.add(id_map[p]) diff --git a/tests/models/test_model_entities.py b/tests/models/test_model_entities.py index 9bb51524..907aa829 100644 --- a/tests/models/test_model_entities.py +++ b/tests/models/test_model_entities.py @@ -229,3 +229,19 @@ def test_sbml_species_reference_and_l2_local_parameter(): ) assert sbml_model._get_entity("k_local") is None assert "k_local" not in assert_consistent(sbml_model) + + +def test_model_entity_checker(): + """The checker agrees with `has_entity_with_id`, also for IDs of SBML + elements other than parameters, species, etc., e.g., kinetic laws.""" + model = SbmlModel.from_antimony(""" + J0: S -> ; k * S + k = 1 + S = 1 + """) + model.sbml_model.getReaction(0).getKineticLaw().setIdAttribute("kl") + is_model_entity = model._get_model_entity_checker() + for id_ in ("k", "S", "J0", "kl", "nonexistent"): + assert is_model_entity(id_) == model.has_entity_with_id(id_) + assert is_model_entity("kl") + assert not is_model_entity("nonexistent")