From c5ba123c3fa8043a15a418a3a16f6178a7ae405d Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Mon, 30 Nov 2026 19:22:18 +0100 Subject: [PATCH] v2 lint: check model entities as condition targets and parameters Add a private classification of model entities (`petab._models._entities`, `Model._get_entity`, `Model._iter_entities`), implemented for SBML models: what an entity is (parameter, species, compartment, other quantity, non-quantity), how its value evolves (constant, differential, algebraic), and whether it is the target of an event assignment. Use it in the new v2 validation task `CheckModelEntityEligibility`, which reports errors for entities that PEtab v2 does not allow as condition targets or in the parameter table, e.g. targets of assignment rules or event assignments. To avoid duplicate errors, it skips IDs that `CheckValidConditionTargets` or `CheckValidParameterInConditionOrParameterTable` already reject. Models without classification support are skipped. Relates to #518. Co-Authored-By: Claude Opus 5.5 --- .../+v2-lint-entity-eligibility.breaking.md | 6 + petab/_models/_entities.py | 75 ++++++ petab/_models/model.py | 36 ++- petab/_models/sbml_model.py | 118 ++++++++- petab/v2/lint.py | 117 +++++++++ tests/models/test_model_entities.py | 231 ++++++++++++++++++ tests/v2/test_lint.py | 130 ++++++++++ 7 files changed, 710 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+v2-lint-entity-eligibility.breaking.md create mode 100644 petab/_models/_entities.py create mode 100644 tests/models/test_model_entities.py 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..b8ef82b8 --- /dev/null +++ b/changelog.d/+v2-lint-entity-eligibility.breaking.md @@ -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)) diff --git a/petab/_models/_entities.py b/petab/_models/_entities.py new file mode 100644 index 00000000..a7e4b7f3 --- /dev/null +++ b/petab/_models/_entities.py @@ -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 = "" diff --git a/petab/_models/model.py b/petab/_models/model.py index 57c991dc..618eaaac 100644 --- a/petab/_models/model.py +++ b/petab/_models/model.py @@ -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"] @@ -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, diff --git a/petab/_models/sbml_model.py b/petab/_models/sbml_model.py index 09404d18..a6656681 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 +from collections.abc import Iterable, Iterator from pathlib import Path import libsbml @@ -18,6 +18,7 @@ write_sbml, ) from . import MODEL_TYPE_SBML +from ._entities import EntityCategory, EntityDynamics, EntityInfo from .model import Model __all__ = ["SbmlModel"] @@ -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 = { diff --git a/petab/v2/lint.py b/petab/v2/lint.py index 4bf6ff98..91b7de38 100644 --- a/petab/v2/lint.py +++ b/petab/v2/lint.py @@ -15,6 +15,7 @@ import pandas as pd import sympy as sp +from .._models._entities import EntityCategory, EntityDynamics, EntityInfo from ..v2.C import * from .core import PriorDistribution, Problem @@ -33,6 +34,7 @@ "CheckMeasuredObservablesDefined", "CheckMeasurementModelId", "CheckModel", + "CheckModelEntityEligibility", "CheckNeuralNetworkModel", "CheckObservablesDoNotShadowModelEntities", "CheckOverridesMatchPlaceholders", @@ -851,6 +853,120 @@ def run(self, problem: Problem) -> ValidationIssue | None: return None +def _describe_entity(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 _condition_target_error(info: EntityInfo) -> str | None: + """Get the error that makes the entity invalid as a condition target. + + Only parameters, species, and compartments are valid, and only if + they are of constant or differential type. + + :param info: The entity. + :returns: The error message, or ``None`` if the entity is a valid + condition target. + """ + what = _describe_entity(info) + if info.category not in ( + EntityCategory.PARAMETER, + EntityCategory.SPECIES, + EntityCategory.COMPARTMENT, + ): + return ( + f"{what} cannot be a condition target: it is not a model " + "parameter, species, or compartment." + ) + if info.dynamics == EntityDynamics.ALGEBRAIC: + return ( + f"{what} cannot be a condition target: the model defines its " + "value algebraically." + ) + return None + + +def _parameter_table_entry_error(info: EntityInfo) -> str | None: + """Get the error that makes the entity invalid as a parameter-table + entry. + + Only truly constant model parameters are valid, i.e., model parameters + of constant type that are not the target of an event assignment. + + :param info: The entity. + :returns: The error message, or ``None`` if the entity is a valid + parameter-table entry. + """ + what = f"{_describe_entity(info)} cannot be listed in the parameter table" + if info.category != EntityCategory.PARAMETER: + return f"{what}: it is not a model parameter." + if info.dynamics == EntityDynamics.ALGEBRAIC: + return f"{what}: the model defines its value algebraically." + if info.dynamics == EntityDynamics.DIFFERENTIAL: + return f"{what}: the model defines its value by a time derivative." + if info.event_assigned: + return f"{what}: it is the target of an event assignment." + 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. + Most IDs that :class:`CheckValidConditionTargets` or + :class:`CheckValidParameterInConditionOrParameterTable` already reject, + and IDs that are not model entities, are not checked here. + Mapping-table aliases are not resolved. + Models that do not support entity classification are skipped. + """ + + def run(self, problem: Problem) -> ValidationIssue | None: + targets = { + change.target_id + for cond in problem.conditions + for change in cond.changes + } + parameters = {p.id for p in problem.parameters} + + errors = [] + for model in problem.models: + # Only IDs not rejected by other tasks. This filter can go once + # those tasks are based on the entity classification. + model_targets = targets & set( + model.get_valid_ids_for_condition_table() + ) + model_parameters = parameters & set( + model.get_valid_parameters_for_parameter_table() + ) + try: + entities = { + e.id: e + for e in model._iter_entities( + model_targets | model_parameters + ) + } + except NotImplementedError: + continue + + for ids, get_error in ( + (model_targets, _condition_target_error), + (model_parameters, _parameter_table_entry_error), + ): + for id_ in sorted(ids): + if (info := entities.get(id_)) is not None and ( + error := get_error(info) + ): + errors.append(error) + + if errors: + return ValidationError("\n".join(errors)) + 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.""" @@ -1485,6 +1601,7 @@ def get_placeholders( CheckPlaceholdersOnlyUsedInOwnObservable(), CheckAllParametersPresentInParameterTable(), CheckValidParameterInConditionOrParameterTable(), + CheckModelEntityEligibility(), CheckUnusedExperiments(), CheckUnusedConditions(), CheckUnusedPlaceholders(), diff --git a/tests/models/test_model_entities.py b/tests/models/test_model_entities.py new file mode 100644 index 00000000..9bb51524 --- /dev/null +++ b/tests/models/test_model_entities.py @@ -0,0 +1,231 @@ +"""Tests for the classification of model entities.""" + +import libsbml +import pytest + +from petab._models._entities import ( + EntityCategory, + EntityDynamics, + EntityInfo, +) +from petab.v2.models.sbml_model import SbmlModel + + +def assert_consistent(model): + """`_iter_entities` with and without IDs, 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} + + +@pytest.fixture +def sbml_model() -> SbmlModel: + return SbmlModel.from_antimony(""" + function f(x) + 2 * x + end + + model m + compartment c = 2 + 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 + + 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 + + E1: at time > 1: k_ev = 2, B_ev = 1 + end + """) + + +@pytest.mark.parametrize( + "id_, category, dynamics, event_assigned", + [ + ("k", EntityCategory.PARAMETER, EntityDynamics.CONSTANT, False), + ("k_ev", EntityCategory.PARAMETER, EntityDynamics.CONSTANT, True), + ("k_ar", EntityCategory.PARAMETER, EntityDynamics.ALGEBRAIC, False), + ( + "k_rate", + EntityCategory.PARAMETER, + EntityDynamics.DIFFERENTIAL, + False, + ), + ("k_ia", EntityCategory.PARAMETER, EntityDynamics.CONSTANT, False), + ("S", EntityCategory.SPECIES, EntityDynamics.DIFFERENTIAL, False), + # boundary species + ("B", EntityCategory.SPECIES, EntityDynamics.CONSTANT, False), + ("B_ev", EntityCategory.SPECIES, EntityDynamics.CONSTANT, True), + ("B_rate", EntityCategory.SPECIES, EntityDynamics.DIFFERENTIAL, False), + ("S_ar", EntityCategory.SPECIES, EntityDynamics.ALGEBRAIC, False), + ("S_const", EntityCategory.SPECIES, EntityDynamics.CONSTANT, False), + # in no reaction, no rule + ("S_free", EntityCategory.SPECIES, EntityDynamics.CONSTANT, False), + ("c", EntityCategory.COMPARTMENT, EntityDynamics.CONSTANT, False), + ("J0", EntityCategory.OTHER_QUANTITY, EntityDynamics.ALGEBRAIC, False), + ("E1", EntityCategory.NON_QUANTITY, None, False), + ("f", EntityCategory.NON_QUANTITY, None, False), + ], +) +def test_sbml_entities(sbml_model, id_, category, dynamics, event_assigned): + element = sbml_model.sbml_model.getElementBySId(id_) + assert sbml_model._get_entity(id_) == EntityInfo( + id=id_, + category=category, + dynamics=dynamics, + event_assigned=event_assigned, + native_type=f"sbml:{type(element).__name__}", + ) + + +def test_sbml_iter_entities(sbml_model): + entities = assert_consistent(sbml_model) + # elements without ID, e.g., species references of `J0`, are not + # included + assert entities.keys() == { + "f", + "c", + "S", + "B", + "B_ev", + "B_rate", + "S_ar", + "S_const", + "S_free", + "J0", + "k", + "k_ev", + "k_ar", + "k_rate", + "k_ia", + "E1", + } + assert sbml_model._get_entity("nonexistent") is None + assert { + e.id for e in sbml_model._iter_entities(["k", "S", "nonexistent"]) + } == {"k", "S"} + + +def test_sbml_live_mutation(sbml_model): + assert sbml_model._get_entity("k").dynamics == EntityDynamics.CONSTANT + rule = sbml_model.sbml_model.createAssignmentRule() + rule.setVariable("k") + rule.setMath(libsbml.parseL3Formula("1")) + assert sbml_model._get_entity("k").dynamics == EntityDynamics.ALGEBRAIC + + +def test_sbml_ids_of_rules_and_assignments(): + """IDs of rules, initial assignments, and event assignments are + non-quantity entities.""" + model = SbmlModel.from_antimony(""" + a = 1 + b := 2 * a + c = 2 * a + at time > 1: a = 2 + """) + sbml_model = model.sbml_model + sbml_model.getRuleByVariable("b").setIdAttribute("rule1") + sbml_model.getInitialAssignmentBySymbol("c").setIdAttribute("ia1") + sbml_model.getEvent(0).getEventAssignment(0).setIdAttribute("ea1") + entities = assert_consistent(model) + for id_, native_type in ( + ("rule1", "sbml:AssignmentRule"), + ("ia1", "sbml:InitialAssignment"), + ("ea1", "sbml:EventAssignment"), + ): + assert entities[id_] == EntityInfo( + id=id_, + category=EntityCategory.NON_QUANTITY, + dynamics=None, + native_type=native_type, + ) + + +def test_sbml_ids_of_rules_before_l3v2(): + """Before SBML L3V2, rules cannot have IDs; none are reported.""" + model = SbmlModel.from_antimony(""" + a = 1 + b := 2 * a + """) + assert model.sbml_model.getSBMLDocument().setLevelAndVersion(3, 1) + # libsbml accepts this in memory, but the ID would be invalid + rule = model.sbml_model.getRule(0) + rule.setIdAttribute("rule1") + assert rule.isSetIdAttribute() + assert "rule1" not in {e.id for e in model._iter_entities()} + + +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")) + reactant2 = reaction.createReactant() + reactant2.setSpecies("S") + reactant2.setId("sr_math") + reactant2.createStoichiometryMath().setMath( + libsbml.parseL3Formula("2 * c") + ) + + sbml_model = SbmlModel(sbml_model=model) + assert ( + sbml_model._get_entity("sr_math").dynamics == EntityDynamics.ALGEBRAIC + ) + assert sbml_model._get_entity("sr") == EntityInfo( + id="sr", + category=EntityCategory.OTHER_QUANTITY, + dynamics=EntityDynamics.CONSTANT, + native_type="sbml:SpeciesReference", + ) + assert sbml_model._get_entity("k_local") is None + assert "k_local" not in assert_consistent(sbml_model) diff --git a/tests/v2/test_lint.py b/tests/v2/test_lint.py index 8b6baeae..959ec072 100644 --- a/tests/v2/test_lint.py +++ b/tests/v2/test_lint.py @@ -6,10 +6,13 @@ import pytest import sympy as sp +from petab._models._entities import EntityCategory, EntityDynamics, EntityInfo from petab.v2 import Problem from petab.v2.C import LOG_NORMAL, NORMAL, TIME_SYMBOL, UNIFORM from petab.v2.lint import * from petab.v2.lint import ( + _condition_target_error, + _parameter_table_entry_error, get_required_parameters_for_parameter_table, get_valid_parameters_for_parameter_table, ) @@ -699,3 +702,130 @@ def test_check_placeholders_only_used_in_own_observable_duplicates(): def test_check_observables_do_not_shadow_model_entities_deprecated(): with pytest.deprecated_call(): CheckObservablesDoNotShadowModelEntities() + + +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 + R1: -> S; k + """) + problem.add_parameter("k", estimate=True, nominal_value=1, lb=0, ub=10) + # well-defined in PEtab v2: the parameter-table value replaces the + # initial assignment + problem.add_parameter("k_ia", estimate=False, nominal_value=1) + check = CheckModelEntityEligibility() + assert check.run(problem) is None + + # rejected by `CheckValidParameterInConditionOrParameterTable` + # and therefore not reported again + problem.add_parameter("k_rule", estimate=False, nominal_value=1) + assert ( + CheckValidParameterInConditionOrParameterTable().run(problem) + is not None + ) + assert check.run(problem) is None + problem.parameter_tables[0].elements = [ + p for p in problem.parameters if p.id != "k_rule" + ] + + # rejected by `CheckValidConditionTargets` + problem.add_condition("c0", R1="1") + assert CheckValidConditionTargets().run(problem) is not None + assert check.run(problem) is None + problem.condition_tables[0].elements = [] + + # event-assigned parameter in the parameter table, assignment rule + # target as condition target: both are reported + problem.add_parameter("k_event", estimate=False, nominal_value=1) + problem.add_condition("c1", k_rule="1") + assert CheckValidConditionTargets().run(problem) is None + assert (issue := check.run(problem)) is not None + assert issue.level == ValidationIssueSeverity.ERROR + assert issue.message.split("\n") == [ + ( + "`k_rule` (sbml:Parameter) cannot be a condition target: " + "the model defines its value algebraically." + ), + ( + "`k_event` (sbml:Parameter) cannot be listed in the parameter " + "table: it is the target of an event assignment." + ), + ] + + # 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 + + +def _entity(**kwargs): + return EntityInfo( + **( + { + "id": "x", + "category": EntityCategory.PARAMETER, + "dynamics": EntityDynamics.CONSTANT, + } + | kwargs + ) + ) + + +@pytest.mark.parametrize( + "info, valid", + [ + (_entity(), True), + (_entity(event_assigned=True), True), + (_entity(dynamics=EntityDynamics.DIFFERENTIAL), True), + ( + _entity( + category=EntityCategory.SPECIES, + dynamics=EntityDynamics.DIFFERENTIAL, + ), + True, + ), + (_entity(category=EntityCategory.COMPARTMENT), True), + (_entity(dynamics=EntityDynamics.ALGEBRAIC), False), + ( + _entity( + category=EntityCategory.SPECIES, + dynamics=EntityDynamics.ALGEBRAIC, + ), + False, + ), + (_entity(category=EntityCategory.OTHER_QUANTITY), False), + (_entity(category=EntityCategory.NON_QUANTITY, dynamics=None), False), + ], +) +def test_condition_target_error(info, valid): + message = _condition_target_error(info) + assert (message is None) == valid + if message: + assert "`x`" in message + + +@pytest.mark.parametrize( + "info, valid", + [ + (_entity(), True), + (_entity(event_assigned=True), False), + (_entity(dynamics=EntityDynamics.DIFFERENTIAL), False), + (_entity(dynamics=EntityDynamics.ALGEBRAIC), False), + (_entity(category=EntityCategory.SPECIES), False), + (_entity(category=EntityCategory.COMPARTMENT), False), + (_entity(category=EntityCategory.OTHER_QUANTITY), False), + (_entity(category=EntityCategory.NON_QUANTITY, dynamics=None), False), + ], +) +def test_parameter_table_entry_error(info, valid): + message = _parameter_table_entry_error(info) + assert (message is None) == valid + if message: + assert "`x`" in message