diff --git a/doc/conf.py b/doc/conf.py index 975cad03..41c41496 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -9,6 +9,8 @@ import sys import warnings +from pydantic import BaseModel + # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, @@ -126,6 +128,9 @@ def skip_some_objects(app, what, name, obj, skip, options): """Exclude some objects from the documentation""" if getattr(obj, "__module__", None) == "collections": return True + # Napoleon + Pydantic v2 bug: BaseModel itself triggers __getattr__ error + if obj is BaseModel: + return True def setup(app): diff --git a/lint.py b/lint.py new file mode 100644 index 00000000..e69de29b diff --git a/petab/v2/C.py b/petab/v2/C.py index e640ae5c..7b141b77 100644 --- a/petab/v2/C.py +++ b/petab/v2/C.py @@ -258,6 +258,8 @@ MAPPING_FILES = "mapping_files" #: Extensions key in the YAML file EXTENSIONS = "extensions" +#: PEtab SciML extension +SCIML = "sciml" # MAPPING diff --git a/petab/v2/base.py b/petab/v2/base.py new file mode 100644 index 00000000..3decff94 --- /dev/null +++ b/petab/v2/base.py @@ -0,0 +1,225 @@ +"""Base classes shared across petab.v2 to avoid circular imports.""" + +from __future__ import annotations + +import logging +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from enum import IntEnum +from pathlib import Path +from typing import TYPE_CHECKING, Generic, TypeVar, get_args + +import pandas as pd +from pydantic import AnyUrl, BaseModel, Field + +from .._utils import _generate_path + +if TYPE_CHECKING: + from .core import Problem + +logger = logging.getLogger(__name__) + + +class ValidationIssueSeverity(IntEnum): + """The severity of a validation issue.""" + + INFO = 10 + WARNING = 20 + ERROR = 30 + CRITICAL = 40 + + +@dataclass +class ValidationIssue: + """The result of a validation task.""" + + level: ValidationIssueSeverity + message: str + task: str | None = None + + def __post_init__(self): + if not isinstance(self.level, ValidationIssueSeverity): + raise TypeError( + "`level` must be an instance of ValidationIssueSeverity." + ) + + def __str__(self): + return f"{self.level.name}: {self.message}" + + @staticmethod + def _get_task_name() -> str | None: + """Get the name of the ValidationTask that raised this error.""" + import inspect + + for frame_info in inspect.stack(): + frame = frame_info.frame + if "self" in frame.f_locals: + task = frame.f_locals["self"] + if isinstance(task, ValidationTask): + return task.__class__.__name__ + return None + + +@dataclass +class ValidationError(ValidationIssue): + """A validation result with level ERROR.""" + + level: ValidationIssueSeverity = field( + default=ValidationIssueSeverity.ERROR, init=False + ) + + def __post_init__(self): + if self.task is None: + self.task = self._get_task_name() + + +@dataclass +class ValidationWarning(ValidationIssue): + """A validation result with level WARNING.""" + + level: ValidationIssueSeverity = field( + default=ValidationIssueSeverity.WARNING, init=False + ) + + def __post_init__(self): + if self.task is None: + self.task = self._get_task_name() + + +class ValidationResultList(list): + """A list of validation results.""" + + def log( + self, + *, + logger: logging.Logger = logger, + min_level: ValidationIssueSeverity = ValidationIssueSeverity.INFO, + max_level: ValidationIssueSeverity = ValidationIssueSeverity.CRITICAL, + ): + """Log the validation results.""" + for result in self: + if result.level < min_level or result.level > max_level: + continue + msg = f"{result.level.name}: {result.message} [{result.task}]" + if result.level == ValidationIssueSeverity.INFO: + logger.info(msg) + elif result.level == ValidationIssueSeverity.WARNING: + logger.warning(msg) + elif result.level >= ValidationIssueSeverity.ERROR: + logger.error(msg) + + if not self: + logger.info("PEtab format check completed successfully.") + + def has_errors(self) -> bool: + """Check if there are any errors in the validation results.""" + return any( + result.level >= ValidationIssueSeverity.ERROR for result in self + ) + + +class ValidationTask(ABC): + """A task to validate a PEtab problem.""" + + @abstractmethod + def run(self, problem: Problem) -> ValidationIssue | None: + """Run the validation task.""" + ... + + def __call__(self, *args, **kwargs): + return self.run(*args, **kwargs) + + +T = TypeVar("T", bound=BaseModel) + + +class BaseTable(BaseModel, Generic[T]): + """Base class for PEtab tables.""" + + #: The table elements + elements: list[T] + #: The path to the table file, if applicable. + #: Relative to the base path, if the base path is set and rel_path is not + #: an absolute path. + rel_path: AnyUrl | Path | None = Field(exclude=True, default=None) + #: The base path for the table file, if applicable. + #: This is usually the directory of the PEtab YAML file. + base_path: AnyUrl | Path | None = Field(exclude=True, default=None) + + def __init__(self, elements: list[T] = None, **kwargs) -> None: + """Initialize the BaseTable with a list of elements.""" + if elements is None: + elements = [] + super().__init__(elements=elements, **kwargs) + + def __getitem__(self, id_: str) -> T: + """Get an element by ID. + + :param id_: The ID of the element to retrieve. + :return: The element with the given ID. + :raises KeyError: If no element with the given ID exists. + :raises NotImplementedError: + If the element type does not have an ID attribute. + """ + if "id" not in self._element_class().model_fields: + raise NotImplementedError( + f"__getitem__ is not implemented for {self.__class__.__name__}" + ) + + for element in self.elements: + if element.id == id_: + return element + + raise KeyError(f"{T.__name__} ID {id_} not found") + + @classmethod + @abstractmethod + def from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]: + """Create a table from a DataFrame.""" + pass + + @abstractmethod + def to_df(self) -> pd.DataFrame: + """Convert the table to a DataFrame.""" + pass + + @classmethod + def from_tsv( + cls, file_path: str | Path, base_path: str | Path | None = None + ) -> BaseTable[T]: + """Create table from a TSV file.""" + df = pd.read_csv(_generate_path(file_path, base_path), sep="\t") + return cls.from_df(df, rel_path=file_path, base_path=base_path) + + def to_tsv(self, file_path: str | Path = None) -> None: + """Write the table to a TSV file.""" + df = self.to_df() + df.to_csv( + file_path or _generate_path(self.rel_path, self.base_path), + sep="\t", + index=not isinstance(df.index, pd.RangeIndex), + ) + + @classmethod + def _element_class(cls) -> type[T]: + """Get the class of the elements in the table.""" + return get_args(cls.model_fields["elements"].annotation)[0] + + def __add__(self, other: T) -> BaseTable[T]: + """Add an item to the table.""" + if not isinstance(other, self._element_class()): + raise TypeError( + f"Can only add {self._element_class().__name__} " + f"to {self.__class__.__name__}" + ) + return self.__class__(elements=self.elements + [other]) + + def __iadd__(self, other: T) -> BaseTable[T]: + """Add an item to the table in place.""" + if not isinstance(other, self._element_class()): + raise TypeError( + f"Can only add {self._element_class().__name__} " + f"to {self.__class__.__name__}" + ) + self.elements.append(other) + return self diff --git a/petab/v2/core.py b/petab/v2/core.py index fb206502..0d3211e4 100644 --- a/petab/v2/core.py +++ b/petab/v2/core.py @@ -7,7 +7,6 @@ import os import tempfile import traceback -from abc import abstractmethod from collections.abc import Sequence from enum import Enum from itertools import chain @@ -18,10 +17,8 @@ TYPE_CHECKING, Annotated, Any, - Generic, + Literal, Self, - TypeVar, - get_args, ) import numpy as np @@ -40,6 +37,16 @@ model_validator, ) +try: + from petab_sciml import ( + ArrayData, + ArrayDataStandard, + NNModel, + NNModelStandard, + ) +except ModuleNotFoundError: + pass + from .._utils import _generate_path from ..v1 import ( validate_yaml_syntax, @@ -52,6 +59,12 @@ from ..v1.yaml import get_path_prefix from ..versions import parse_version from . import C, get_observable_df +from .base import BaseTable +from .sciml.core import ( + Hybridization, + HybridizationTable, + SciMLConfig, +) if TYPE_CHECKING: from ..v2.lint import ValidationResultList, ValidationTask @@ -60,6 +73,7 @@ __all__ = [ "Problem", "ProblemConfig", + "SciMLConfig", "Observable", "ObservableTable", "NoiseDistribution", @@ -213,101 +227,6 @@ class PriorDistribution(str, Enum): ) -T = TypeVar("T", bound=BaseModel) - - -class BaseTable(BaseModel, Generic[T]): - """Base class for PEtab tables.""" - - #: The table elements - elements: list[T] - #: The path to the table file, if applicable. - #: Relative to the base path, if the base path is set and rel_path is not - #: an absolute path. - rel_path: AnyUrl | Path | None = Field(exclude=True, default=None) - #: The base path for the table file, if applicable. - #: This is usually the directory of the PEtab YAML file. - base_path: AnyUrl | Path | None = Field(exclude=True, default=None) - - def __init__(self, elements: list[T] = None, **kwargs) -> None: - """Initialize the BaseTable with a list of elements.""" - if elements is None: - elements = [] - super().__init__(elements=elements, **kwargs) - - def __getitem__(self, id_: str) -> T: - """Get an element by ID. - - :param id_: The ID of the element to retrieve. - :return: The element with the given ID. - :raises KeyError: If no element with the given ID exists. - :raises NotImplementedError: - If the element type does not have an ID attribute. - """ - if "id" not in self._element_class().model_fields: - raise NotImplementedError( - f"__getitem__ is not implemented for {self.__class__.__name__}" - ) - - for element in self.elements: - if element.id == id_: - return element - - raise KeyError(f"{T.__name__} ID {id_} not found") - - @classmethod - @abstractmethod - def from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]: - """Create a table from a DataFrame.""" - pass - - @abstractmethod - def to_df(self) -> pd.DataFrame: - """Convert the table to a DataFrame.""" - pass - - @classmethod - def from_tsv( - cls, file_path: str | Path, base_path: str | Path | None = None - ) -> BaseTable[T]: - """Create table from a TSV file.""" - df = pd.read_csv(_generate_path(file_path, base_path), sep="\t") - return cls.from_df(df, rel_path=file_path, base_path=base_path) - - def to_tsv(self, file_path: str | Path = None) -> None: - """Write the table to a TSV file.""" - df = self.to_df() - df.to_csv( - file_path or _generate_path(self.rel_path, self.base_path), - sep="\t", - index=not isinstance(df.index, pd.RangeIndex), - ) - - @classmethod - def _element_class(cls) -> type[T]: - """Get the class of the elements in the table.""" - return get_args(cls.model_fields["elements"].annotation)[0] - - def __add__(self, other: T) -> BaseTable[T]: - """Add an item to the table.""" - if not isinstance(other, self._element_class()): - raise TypeError( - f"Can only add {self._element_class().__name__} " - f"to {self.__class__.__name__}" - ) - return self.__class__(elements=self.elements + [other]) - - def __iadd__(self, other: T) -> BaseTable[T]: - """Add an item to the table in place.""" - if not isinstance(other, self._element_class()): - raise TypeError( - f"Can only add {self._element_class().__name__} " - f"to {self.__class__.__name__}" - ) - self.elements.append(other) - return self - - class Observable(BaseModel): """Observable definition.""" @@ -318,9 +237,9 @@ class Observable(BaseModel): #: Observable name. name: str | None = Field(alias=C.OBSERVABLE_NAME, default=None) #: Observable formula. - formula: sp.Basic | None = Field(alias=C.OBSERVABLE_FORMULA, default=None) + formula: sp.Basic = Field(alias=C.OBSERVABLE_FORMULA) #: Noise formula. - noise_formula: sp.Basic | None = Field(alias=C.NOISE_FORMULA, default=None) + noise_formula: sp.Basic = Field(alias=C.NOISE_FORMULA) #: Noise distribution. noise_distribution: NoiseDistribution = Field( alias=C.NOISE_DISTRIBUTION, default=NoiseDistribution.NORMAL @@ -926,7 +845,8 @@ class Parameter(BaseModel): ) #: Nominal value. nominal_value: Annotated[ - float | None, BeforeValidator(_convert_nan_to_none) + # PEtab SciML supports arrays via "array" nominal values + float | Literal["array"] | None, BeforeValidator(_convert_nan_to_none) ] = Field(alias=C.NOMINAL_VALUE, default=None) #: Is the parameter to be estimated? estimate: bool = Field(alias=C.ESTIMATE, default=True) @@ -1133,15 +1053,23 @@ def __init__( measurement_tables: list[MeasurementTable] = None, parameter_tables: list[ParameterTable] = None, mapping_tables: list[MappingTable] = None, + neural_networks: list[NNModel] | None = None, + hybridization_tables: list[HybridizationTable] | None = None, + array_data_files: list[ArrayData] | None = None, config: ProblemConfig = None, ): - from ..v2.lint import default_validation_tasks + from ..v2.lint import default_validation_tasks, sciml_validation_tasks self.config = config self.models: list[Model] = models or [] - self.validation_tasks: list[ValidationTask] = ( - default_validation_tasks.copy() - ) + if config and config.extensions and config.extensions[C.SCIML]: + self.validation_tasks: list[ValidationTask] = ( + sciml_validation_tasks.copy() + ) + else: + self.validation_tasks: list[ValidationTask] = ( + default_validation_tasks.copy() + ) self.observable_tables = observable_tables or [ObservableTable()] self.condition_tables = condition_tables or [ConditionTable()] @@ -1149,6 +1077,11 @@ def __init__( self.measurement_tables = measurement_tables or [MeasurementTable()] self.mapping_tables = mapping_tables or [MappingTable()] self.parameter_tables = parameter_tables or [ParameterTable()] + self.neural_networks = neural_networks or [] + self.hybridization_tables = hybridization_tables or [ + HybridizationTable() + ] + self.array_data_files = array_data_files or [] def __repr__(self): return f"<{self.__class__.__name__} id={self.id!r}>" @@ -1321,6 +1254,37 @@ def from_yaml( else None ) + neural_networks = None + hybridization_tables = None + array_data_files = None + if config.extensions and config.extensions[C.SCIML]: + # Neural network classes are constructed via pytorch for now to get + # the proper inputs + neural_networks = [ + NNModel.from_pytorch_module( + NNModelStandard.load_data( + _generate_path( + file_path=nn_config.location, + base_path=base_path, + ) + ).to_pytorch_module(), + nn_model_id=nn_id, + ) + for nn_id, nn_config in ( + config.extensions[C.SCIML].neural_networks or {} + ).items() + ] + + hybridization_tables = [ + HybridizationTable.from_tsv(f, base_path) + for f in config.extensions[C.SCIML].hybridization_files + ] + + array_data_files = [ + ArrayDataStandard.load_data(_generate_path(f, base_path)) + for f in config.extensions[C.SCIML].array_files + ] + return Problem( config=config, models=models, @@ -1330,6 +1294,9 @@ def from_yaml( measurement_tables=measurement_tables, parameter_tables=parameter_tables, mapping_tables=mapping_tables, + neural_networks=neural_networks, + hybridization_tables=hybridization_tables, + array_data_files=array_data_files, ) @staticmethod @@ -1636,6 +1603,34 @@ def id(self, value: str): self.config = ProblemConfig(format_version="2.0.0") self.config.id = value + @property + def hybridizations(self) -> list[Hybridization]: + """ + List of hybridizations in the hybridization table(s). + Note that hybridizations are specific to PEtab SciML problems. + """ + return list( + chain.from_iterable( + ht.hybridizations for ht in self.hybridization_tables + ) + ) + + @property + def hybridization_df(self) -> pd.DataFrame | None: + """ + Combined SciML hybridization tables as DataFrame. + Note that hybridizations are specific to PEtab SciML problems. + """ + return ( + HybridizationTable(hybridizations).to_df() + if (hybridizations := self.hybridizations) + else None + ) + + @hybridization_df.setter + def hybridization_df(self, value: pd.DataFrame): + self.hybridization_tables = [HybridizationTable.from_df(value)] + def get_optimization_parameters(self) -> list[str]: """ Get the list of optimization parameter IDs from parameter table. @@ -1940,14 +1935,21 @@ def validate( validation_results = ValidationResultList() - if self.config and self.config.extensions: - extensions = ",".join(self.config.extensions.keys()) + supported_extensions = {C.SCIML} + if ( + self.config + and self.config.extensions + and (self.config.extensions.keys() - supported_extensions) + ): + extensions_without_support = ",".join( + self.config.extensions.keys() - supported_extensions + ) validation_results.append( ValidationIssue( ValidationIssueSeverity.WARNING, - "Validation of PEtab extensions is not yet implemented, " - "but the given problem uses the following extensions: " - f"{extensions}", + "The given problem uses the following extensions for " + "which validation is not yet implemented: " + f"{extensions_without_support}", ) ) @@ -2245,6 +2247,73 @@ def add_experiment(self, id_: str, *args): Experiment(id=id_, periods=periods) ) + def add_hybridization(self, target_id: str, target_value: str): + """Add a SciML hybridization table entry to the problem. + + If there is more than one hybridization table, the hybridization + is added to the last table. Note that hybridizations are specific + to PEtab SciML problems. + + Arguments: + target_id: The ID of the target entity in the PEtab problem + or neural network model + target_value: The value that is assigned to the target id. + """ + if not self.hybridization_tables: + self.hybridization_tables.append(HybridizationTable()) + self.hybridization_tables[-1].hybridizations.append( + Hybridization(target_id=target_id, target_value=target_value) + ) + + def add_neural_network_from_dict(self, model_id: str, nn_dict: dict): + """ + Add a SciML neural net from a dictionary (or PEtab SciML problems). + """ + # from petab_sciml import NNModel + nn_model = NNModel.model_validate(nn_dict) + nn_model.nn_model_id = model_id + self.neural_networks.append(nn_model) + + def add_neural_network_from_yaml( + self, + model_id: str, + file_path: str | Path, + base_path: str | Path | None = None, + ): + """ + Add a SciML neural net from a yaml file (for PEtab SciML problems). + """ + # from petab_sciml import NNModelStandard + self.neural_networks.append( + NNModelStandard.load_data( + _generate_path( + file_path=file_path, + base_path=base_path, + ), + nn_model_id=model_id, + ) + ) + + def add_array_data_from_dict(self, array_data: dict): + """ + Add SciML array data from a dictionary (for PEtab SciML problems). + """ + # from petab_sciml import ArrayData + self.array_data_files.append(ArrayData.model_validate(array_data)) + + def add_array_data_from_hdf5( + self, + file_path: str | Path, + base_path: str | Path | None = None, + ): + """ + Add SciML array data from an hdf5 file (for PEtab SciML problems). + """ + # from petab_sciml import ArrayDataStandard + self.array_data_files.append( + ArrayDataStandard.load_data(_generate_path(file_path, base_path)) + ) + def __iadd__(self, other): """Add Observable, Parameter, Measurement, Condition, or Experiment""" from .core import ( @@ -2505,6 +2574,23 @@ class ProblemConfig(BaseModel): validate_assignment=True, ) + @field_validator("extensions", mode="before") + @classmethod + def _parse_extensions(cls, v): + """Parse extensions dict and convert known extensions to their specific + config classes.""" + if isinstance(v, dict): + parsed_extensions = {} + for ext_name, ext_config in v.items(): + if ext_name == C.SCIML: + # Convert sciml extension to SciMLConfig + parsed_extensions[ext_name] = SciMLConfig(**ext_config) + else: + # Keep other extensions as ExtensionConfig + parsed_extensions[ext_name] = ExtensionConfig(**ext_config) + return parsed_extensions + return v + # convert parameter_file to list @field_validator( "parameter_files", @@ -2542,12 +2628,22 @@ def to_yaml(self, filename: str | Path): for model_id in data.get("model_files", {}): data["model_files"][model_id][C.MODEL_LOCATION] = str( - data["model_files"][model_id]["location"] + data["model_files"][model_id][C.MODEL_LOCATION] ) if data["id"] is None: # The schema requires a valid id or no id field at all. del data["id"] + for ext_id, d_ext in data[C.EXTENSIONS].items(): + if ext_id == C.SCIML: + # convert Paths to strings + for key in ("array_files", "hybridization_files"): + d_ext[key] = list(map(str, d_ext[key])) + for nn in d_ext["neural_networks"]: + d_ext["neural_networks"][nn][C.MODEL_LOCATION] = str( + d_ext["neural_networks"][nn][C.MODEL_LOCATION] + ) + write_yaml(data, filename) @property diff --git a/petab/v2/lint.py b/petab/v2/lint.py index 687d58f2..d0c11900 100644 --- a/petab/v2/lint.py +++ b/petab/v2/lint.py @@ -3,18 +3,25 @@ from __future__ import annotations import logging -from abc import ABC, abstractmethod from collections import Counter, OrderedDict from collections.abc import Set -from dataclasses import dataclass, field -from enum import IntEnum from itertools import chain from pathlib import Path import pandas as pd import sympy as sp +from petab.v2.sciml.lint import CheckHybridizationTable + from ..v2.C import * +from .base import ( + ValidationError, + ValidationIssue, + ValidationIssueSeverity, + ValidationResultList, + ValidationTask, + ValidationWarning, +) from .core import PriorDistribution, Problem logger = logging.getLogger(__name__) @@ -44,131 +51,13 @@ "CheckPriorDistribution", "CheckUndefinedExperiments", "CheckInitialChangeSymbols", + "CheckMappingTable", + "CheckHybridizationTable", "lint_problem", "default_validation_tasks", ] -class ValidationIssueSeverity(IntEnum): - """The severity of a validation issue.""" - - # INFO: Informational message, no action required - INFO = 10 - # WARNING: Warning message, potential issues - WARNING = 20 - # ERROR: Error message, action required - ERROR = 30 - # CRITICAL: Critical error message, stops further validation - CRITICAL = 40 - - -@dataclass -class ValidationIssue: - """The result of a validation task. - - Attributes: - level: The level of the validation event. - message: The message of the validation event. - """ - - level: ValidationIssueSeverity - message: str - task: str | None = None - - def __post_init__(self): - if not isinstance(self.level, ValidationIssueSeverity): - raise TypeError( - "`level` must be an instance of ValidationIssueSeverity." - ) - - def __str__(self): - return f"{self.level.name}: {self.message}" - - @staticmethod - def _get_task_name() -> str | None: - """Get the name of the ValidationTask that raised this error. - - Expected to be called from below a `ValidationTask.run`. - """ - import inspect - - # walk up the stack until we find the ValidationTask.run method - for frame_info in inspect.stack(): - frame = frame_info.frame - if "self" in frame.f_locals: - task = frame.f_locals["self"] - if isinstance(task, ValidationTask): - return task.__class__.__name__ - return None - - -@dataclass -class ValidationError(ValidationIssue): - """A validation result with level ERROR.""" - - level: ValidationIssueSeverity = field( - default=ValidationIssueSeverity.ERROR, init=False - ) - - def __post_init__(self): - if self.task is None: - self.task = self._get_task_name() - - -@dataclass -class ValidationWarning(ValidationIssue): - """A validation result with level WARNING.""" - - level: ValidationIssueSeverity = field( - default=ValidationIssueSeverity.WARNING, init=False - ) - - def __post_init__(self): - if self.task is None: - self.task = self._get_task_name() - - -class ValidationResultList(list[ValidationIssue]): - """A list of validation results. - - Contains all issues found during the validation of a PEtab problem. - """ - - def log( - self, - *, - logger: logging.Logger = logger, - min_level: ValidationIssueSeverity = ValidationIssueSeverity.INFO, - max_level: ValidationIssueSeverity = ValidationIssueSeverity.CRITICAL, - ): - """Log the validation results. - - :param logger: The logger to use for logging. - Defaults to the module logger. - :param min_level: The minimum severity level to log. - :param max_level: The maximum severity level to log. - """ - for result in self: - if result.level < min_level or result.level > max_level: - continue - msg = f"{result.level.name}: {result.message} [{result.task}]" - if result.level == ValidationIssueSeverity.INFO: - logger.info(msg) - elif result.level == ValidationIssueSeverity.WARNING: - logger.warning(msg) - elif result.level >= ValidationIssueSeverity.ERROR: - logger.error(msg) - - if not self: - logger.info("PEtab format check completed successfully.") - - def has_errors(self) -> bool: - """Check if there are any errors in the validation results.""" - return any( - result.level >= ValidationIssueSeverity.ERROR for result in self - ) - - def lint_problem(problem: Problem | str | Path) -> ValidationResultList: """Validate a PEtab problem. @@ -185,24 +74,6 @@ def lint_problem(problem: Problem | str | Path) -> ValidationResultList: return problem.validate() -class ValidationTask(ABC): - """A task to validate a PEtab problem.""" - - @abstractmethod - def run(self, problem: Problem) -> ValidationIssue | None: - """Run the validation task. - - Arguments: - problem: PEtab problem to check. - Returns: - Validation results or ``None`` - """ - ... - - def __call__(self, *args, **kwargs): - return self.run(*args, **kwargs) - - class CheckProblemConfig(ValidationTask): """A task to validate the configuration of a PEtab problem. @@ -551,7 +422,8 @@ def run(self, problem: Problem) -> ValidationIssue | None: class CheckAllParametersPresentInParameterTable(ValidationTask): """Ensure all required parameters are contained in the parameter table - with no additional ones.""" + with no additional ones. This also ensures that the mapping table petab ids + are used in the PEtab problem.""" def run(self, problem: Problem) -> ValidationIssue | None: if problem.model is None: @@ -825,8 +697,8 @@ def run(self, problem: Problem) -> ValidationIssue | None: if parameter.prior_distribution not in PRIOR_DISTRIBUTIONS: messages.append( - f"Prior distribution `{parameter.prior_distribution}' " - f"for parameter `{parameter.id}' is not valid." + f"Prior distribution `{parameter.prior_distribution}` " + f"for parameter `{parameter.id}` is not valid." ) continue @@ -834,8 +706,8 @@ def run(self, problem: Problem) -> ValidationIssue | None: exp_num_par := self._num_pars[parameter.prior_distribution] ) != len(parameter.prior_parameters): messages.append( - f"Prior distribution `{parameter.prior_distribution}' " - f"for parameter `{parameter.id}' requires " + f"Prior distribution `{parameter.prior_distribution}` " + f"for parameter `{parameter.id}` requires " f"{exp_num_par} parameters, but got " f"{len(parameter.prior_parameters)} " f"({parameter.prior_parameters})." @@ -848,8 +720,8 @@ def run(self, problem: Problem) -> ValidationIssue | None: _ = parameter.prior_dist.sample(1) except Exception as e: messages.append( - f"Prior parameters `{parameter.prior_parameters}' " - f"for parameter `{parameter.id}' are invalid " + f"Prior parameters `{parameter.prior_parameters}` " + f"for parameter `{parameter.id}` are invalid " f"(hint: {e})." ) @@ -874,7 +746,7 @@ def run(self, problem: Problem) -> ValidationIssue | None: continue messages.append( - f"Measurement `{measurement}' does not have a model ID, " + f"Measurement `{measurement}` does not have a model ID, " "but there are multiple models available. " "Please specify the model ID in the measurement table." ) @@ -882,8 +754,8 @@ def run(self, problem: Problem) -> ValidationIssue | None: if measurement.model_id not in available_models: messages.append( - f"Measurement `{measurement}' has model ID " - f"`{measurement.model_id}' which does not match " + f"Measurement `{measurement}` has model ID " + f"`{measurement.model_id}` which does not match " "any of the available models: " f"{available_models}." ) @@ -894,6 +766,62 @@ def run(self, problem: Problem) -> ValidationIssue | None: return None +class CheckMappingTable(ValidationTask): + """Validate the mapping table.""" + + def run(self, problem: Problem) -> ValidationIssue | None: + messages = [] + + # Mapping table is optional + if problem.mappings: + # Check that each id only occurs once + counter = Counter( + [ + getattr(mapping, attr) + for mapping in problem.mappings + for attr in ["petab_id", "model_id"] + if getattr(mapping, attr) + ] + ) + non_unique = {id_ for id_, count in counter.items() if count > 1} + if non_unique: + return ValidationError( + f"Mapping table contains non-unique IDs: {non_unique}." + ) + + # petabEntityId is not defined elsewhere in the PEtab problem + petab_ids_mapping = {m.petab_id for m in problem.mappings} + defined_petab_ids = ( + {c.id for c in problem.conditions} + | {e.id for e in problem.experiments} + | {o.id for o in problem.observables} + ) + if petab_ids_mapping & defined_petab_ids: + messages.append( + f"PEtab IDs `{petab_ids_mapping & defined_petab_ids}` are " + "defined in the mapping table but also defined through " + "other PEtab tables." + ) + + for mapping in problem.mappings: + # petabEntityId is not referenced in any model + for model in problem.models: + if ( + model.has_entity_with_id(mapping.petab_id) + and mapping.petab_id != mapping.model_id + ): + messages.append( + f"`{mapping.petab_id}` is used in the mapping " + "table and referenced directly in the model " + f"`{model.model_id}`." + ) + + if messages: + return ValidationError("\n".join(messages)) + + return None + + def get_valid_parameters_for_parameter_table( problem: Problem, ) -> set[str]: @@ -933,9 +861,17 @@ def get_valid_parameters_for_parameter_table( if p not in invalid ) + # Add petab ids from mapping table if they are used for aliasing for mapping in problem.mappings: - if mapping.model_id and mapping.model_id in parameter_ids.keys(): + if mapping.petab_id not in invalid: parameter_ids[mapping.petab_id] = None + # An aliased model id is not a valid parameter id + if ( + mapping.model_id + and mapping.model_id != mapping.petab_id + and mapping.model_id in parameter_ids + ): + del parameter_ids[mapping.model_id] # add output parameters from observable table output_parameters = problem.get_output_parameters() @@ -977,20 +913,13 @@ def get_required_parameters_for_parameter_table( measurement table as well as all parametric condition table overrides that are not defined in the model. """ - parameter_ids = set() - condition_targets = { - change.target_id - for cond in problem.conditions - for change in cond.changes - } + # Start with mapping table petab ids + parameter_ids = {m.petab_id for m in problem.mappings} # Add parameters from measurement table, unless they are fixed parameters def append_overrides(overrides): parameter_ids.update( - str_p - for p in overrides - if isinstance(p, sp.Symbol) - and (str_p := str(p)) not in condition_targets + str(p) for p in overrides if isinstance(p, sp.Symbol) ) for m in problem.measurements: @@ -1033,9 +962,21 @@ def append_overrides(overrides): if not problem.model.has_entity_with_id(str(p)) ) - # parameters that are overridden via the condition table are not allowed + # Parameters that are overridden via the condition table are not allowed + condition_targets = { + change.target_id + for cond in problem.conditions + for change in cond.changes + } parameter_ids -= condition_targets + hybridization_targets = {hyb.target_id for hyb in problem.hybridizations} + parameter_ids -= hybridization_targets + hybridization_target_values = { + str(hyb.target_value) for hyb in problem.hybridizations + } + parameter_ids -= hybridization_target_values + return parameter_ids @@ -1090,5 +1031,10 @@ def get_placeholders( CheckUnusedConditions(), CheckPriorDistribution(), CheckInitialChangeSymbols(), - # TODO validate mapping table + CheckMappingTable(), +] + +#: Validation tasks that should be run PEtab SciML problems +sciml_validation_tasks = default_validation_tasks + [ + CheckHybridizationTable(), ] diff --git a/petab/v2/sciml/__init__.py b/petab/v2/sciml/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/petab/v2/sciml/core.py b/petab/v2/sciml/core.py new file mode 100644 index 00000000..e4c29a46 --- /dev/null +++ b/petab/v2/sciml/core.py @@ -0,0 +1,127 @@ +from pathlib import Path +from typing import Self + +import numpy as np +import pandas as pd +import sympy as sp +from pydantic import ( + AnyUrl, + BaseModel, + ConfigDict, + Field, + field_validator, +) + +import petab.v2.C as C + +from ...v1.math.sympify import sympify_petab +from ..base import BaseTable + +__all__ = [ + "Hybridization", + "HybridizationTable", + "NeuralNetConfig", + "SciMLConfig", +] + + +class Hybridization(BaseModel): + """Assigns PEtab SciML NN inputs and outputs.""" + + #: The target ID. + target_id: str = Field(alias=C.TARGET_ID) + #: The target value. + target_value: sp.Basic = Field(alias=C.TARGET_VALUE) + + #: :meta private: + model_config = ConfigDict( + arbitrary_types_allowed=True, + populate_by_name=True, + extra="allow", + validate_assignment=True, + ) + + @field_validator("target_value", mode="before") + @classmethod + def _sympify(cls, v): + if v is None or isinstance(v, sp.Basic): + return v + if isinstance(v, float) and np.isnan(v): + return None + + return sympify_petab(v) + + +class HybridizationTable(BaseTable[Hybridization]): + """PEtab SciML hybridization table.""" + + @property + def hybridizations(self) -> list[Hybridization]: + """List of hybridizations.""" + return self.elements + + @classmethod + def from_df(cls, df: pd.DataFrame, **kwargs) -> Self: + """Create a HybridizationTable from a DataFrame.""" + if df is None: + return cls(**kwargs) + + hybridizations = [ + Hybridization( + **row.to_dict(), + ) + for _, row in df.iterrows() + ] + + return cls(hybridizations, **kwargs) + + def to_df(self) -> pd.DataFrame: + """Convert the HybridizationTable to a DataFrame.""" + records = self.model_dump(by_alias=True)["elements"] + + return pd.DataFrame(records) + + def __getitem__(self, target_id: str) -> Hybridization: + """Get a hybridization by target ID.""" + for hybridization in self.hybridizations: + if hybridization.target_id == target_id: + return hybridization + raise KeyError(f"Target ID {target_id} not found") + + def get(self, target_id, default=None): + """Get a hybridization by target ID or return a default value.""" + try: + return self[target_id] + except KeyError: + return default + + +class NeuralNetConfig(BaseModel): + """A neural net in the PEtab SciML problem configuration.""" + + location: AnyUrl | Path + pre_initialization: bool + format: str + + model_config = ConfigDict( + validate_assignment=True, + ) + + +class SciMLConfig(BaseModel): + """The extended configuration of a PEtab SciML problem.""" + + #: The PEtab SciML format version. + version: str = "0.1.0" + #: The paths to the array data files. + # Absolute or relative to `base_path`. + array_files: list[AnyUrl | Path] = [] + #: The paths to the hybridization tables. + # Absolute or relative to `base_path`. + hybridization_files: list[AnyUrl | Path] = [] + #: The neural network IDs and info. + neural_networks: dict[str, NeuralNetConfig] | None = {} + + model_config = ConfigDict( + validate_assignment=True, + ) diff --git a/petab/v2/sciml/lint.py b/petab/v2/sciml/lint.py new file mode 100644 index 00000000..dc087a36 --- /dev/null +++ b/petab/v2/sciml/lint.py @@ -0,0 +1,36 @@ +from petab.v1.problem import Problem +from petab.v2.base import ValidationError, ValidationIssue, ValidationTask + + +class CheckHybridizationTable(ValidationTask): + """Validate the SciML hybridization table.""" + + def run(self, problem: Problem) -> ValidationIssue | None: + messages = [] + + condition_targets = { + c.target_id for ct in problem.conditions for c in ct.changes + } + nn_input_ids = { + inp.input_id for nn in problem.neural_networks for inp in nn.inputs + } + hyb_target_ids = {hyb.target_id for hyb in problem.hybridizations} + hyb_target_vals = {hyb.target_value for hyb in problem.hybridizations} + + # Hybridization targets are not also targets in the condition table + if culprits := (hyb_target_ids & condition_targets): + messages.append( + f"Hybridization target ids `{culprits}` are also " + "target ids in the condition table." + ) + # NN inputs are not used as target values + if culprits := (hyb_target_vals & nn_input_ids): + messages.append( + "The following neural net inputs were used as target values " + f"in the Hybridization table: `{culprits}`." + ) + + if messages: + return ValidationError("\n".join(messages)) + + return None diff --git a/pyproject.toml b/pyproject.toml index e0e665e3..9d28e405 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ maintainers = [ tests = [ "antimony>=3.1.0", "copasi-basico>=0.85", + "petab_sciml @ git+https://github.com/PEtab-dev/petab_sciml.git", "pysb", "pytest", "pytest-cov", @@ -71,6 +72,9 @@ vis = [ "seaborn", "scipy" ] +sciml = [ + "petab_sciml @ git+https://github.com/PEtab-dev/petab_sciml.git", +] [project.scripts] petablint = "petab.petablint:main" diff --git a/tests/v2/test_core.py b/tests/v2/test_core.py index 22dbf0e1..7b5ad420 100644 --- a/tests/v2/test_core.py +++ b/tests/v2/test_core.py @@ -181,7 +181,7 @@ def test_measurments(): def test_observable(): - Observable(id="obs1", formula=x + y) + Observable(id="obs1", formula=x + y, noiseFormula=1) Observable(id="obs1", formula="x + y", noise_formula="x + y") Observable(id="obs1", formula=1, noise_formula=2) Observable( @@ -198,9 +198,17 @@ def test_observable(): observable_parameters=[sp.Symbol("p1")], noise_parameters=[sp.Symbol("n1")], ) - assert Observable(id="obs1", formula="x + y", non_petab=1).non_petab == 1 + assert ( + Observable( + id="obs1", + formula="x + y", + noise_formula="x + y", + non_petab=1, + ).non_petab + == 1 + ) - o = Observable(id="obs1", formula=x + y) + o = Observable(id="obs1", formula=x + y, noise_formula=1) assert o.observable_placeholders == [] assert o.noise_placeholders == [] @@ -492,14 +500,14 @@ def test_modify_problem(): problem.condition_df, exp_condition_df, check_dtype=False ) - problem.add_observable("observable1", "1") + problem.add_observable("observable1", "1", noise_formula=1) problem.add_observable("observable2", "2", noise_formula=2.2) exp_observable_df = pd.DataFrame( data={ OBSERVABLE_ID: ["observable1", "observable2"], OBSERVABLE_FORMULA: [1, 2], - NOISE_FORMULA: [np.nan, 2.2], + NOISE_FORMULA: [1, 2.2], } ).set_index([OBSERVABLE_ID]) assert_frame_equal( diff --git a/tests/v2/test_lint.py b/tests/v2/test_lint.py index 7eb6dc91..2b26fd57 100644 --- a/tests/v2/test_lint.py +++ b/tests/v2/test_lint.py @@ -43,7 +43,7 @@ def test_invalid_model_id_in_measurements(): """Test that measurements with an invalid model ID are caught.""" problem = Problem() problem.models.append(SbmlModel.from_antimony("p1 = 1", model_id="model1")) - problem.add_observable("obs1", "A") + problem.add_observable("obs1", "A", 1) problem.add_measurement("obs1", experiment_id="e1", time=0, measurement=1) check = CheckMeasurementModelId() @@ -70,7 +70,7 @@ def test_undefined_experiment_id_in_measurements(): """Test that measurements with an undefined experiment ID are caught.""" problem = Problem() problem.add_experiment("e1", 0, "c1") - problem.add_observable("obs1", "A") + problem.add_observable("obs1", "A", 1) problem.add_measurement("obs1", experiment_id="e1", time=0, measurement=1) check = CheckUndefinedExperiments() @@ -107,3 +107,43 @@ def test_validate_initial_change_symbols(): problem.parameter_tables[0].parameters.remove(problem["p2"]) assert (error := check.run(problem)) is not None assert "contains additional symbols: {'p2'}" in error.message + + +def test_check_mapping_table(): + """Test checks related to the mapping table.""" + problem = Problem() + # PySB model from PEtab test suite + problem.model = SbmlModel.from_antimony("a.mean = 1") + problem.add_mapping( + petab_id="a_m", + model_id="a.mean", + name=None, + ) + problem.add_parameter( + "a_m", + estimate=True, + nominal_value=2, + lb=0, + ub=10, + ) + + check = CheckMappingTable() + assert check.run(problem) is None + + check = CheckAllParametersPresentInParameterTable() + assert check.run(problem) is None + + # add a petab id without model id but with name for annotation + problem.add_mapping(petab_id="p2", model_id=None, name="Parameter 2") + problem.add_parameter("p2", estimate=True, nominal_value=1, lb=0, ub=10) + + check = CheckMappingTable() + assert check.run(problem) is None + + # Invalid: petabEntityId is referenced in the model + problem.model = SbmlModel.from_antimony("a.mean = 1; a_m = 2") + assert (error := check.run(problem)) is not None + assert ( + "`a_m` is used in the mapping table and referenced directly" + in error.message + ) diff --git a/tests/v2/test_sciml.py b/tests/v2/test_sciml.py new file mode 100644 index 00000000..23737a0e --- /dev/null +++ b/tests/v2/test_sciml.py @@ -0,0 +1,139 @@ +import numpy as np +from pydantic import ConfigDict + +from petab.v2.core import * +from petab.v2.core import ModelFile +from petab.v2.lint import sciml_validation_tasks +from petab.v2.models.sbml_model import SbmlModel +from petab.v2.sciml.core import NeuralNetConfig + + +def _get_test_problem(): + problem = Problem() + problem.validation_tasks = sciml_validation_tasks + problem.config = ProblemConfig( + format_version="2.0.0", + model_files=ConfigDict( + {"lv": ModelFile(location="lv.xml", language="sbml")} + ), + parameter_files=["parameters.tsv"], + measurement_files=["measurements.tsv"], + observable_files=["observables.tsv"], + experiment_files=["experiments.tsv"], + mapping_files=["mappings.tsv"], + extensions={ + "sciml": { + "version": "0.1.0", + "array_files": ["net1_ps.hdf5"], + "hybridization_files": ["hybridizations.tsv"], + "neural_networks": { + "net1": NeuralNetConfig( + location="net1.yaml", + pre_initialization=False, + format="YAML", + ) + }, + } + }, + ) + problem.model = SbmlModel.from_antimony(""" + model lv + species A, B; + A = 0.442; + B = 4.63; + alpha = 1.3; + gamma_ = 0.8; + -> A; alpha * A; + B -> ; 1.8 * B; + A -> ; 0.9 * A * B; + -> B; gamma_; + end + """) + problem.add_experiment("e1", 0, "") + problem.add_mapping("net1_input1", "net1.inputs[0][0]") + problem.add_mapping("net1_input2", "net1.inputs[0][1]") + problem.add_mapping("net1_output1", "net1.outputs[0][0]") + problem.add_mapping("net1_ps", "net1.parameters") + problem.add_measurement("B_obs", time=1, measurement=1, experiment_id="e1") + problem.add_observable("B_obs", "B", noise_formula="0.05") + problem.add_parameter( + "alpha", estimate=True, lb=0, ub=15, nominal_value=1.3 + ) + problem.add_parameter( + "net1_ps", estimate=True, lb=-np.inf, ub=np.inf, nominal_value="array" + ) + problem.add_hybridization("net1_input1", "A") + problem.add_hybridization("net1_input2", "B") + problem.add_hybridization("gamma_", "net1_output1") + problem.add_neural_network_from_dict( + "net1", + nn_dict={ + "nn_model_id": "net1", + "inputs": [{"input_id": "input0"}], + "layers": [ + { + "layer_id": "layer1", + "layer_type": "Linear", + "args": { + "in_features": 2, + "out_features": 1, + "bias": True, + }, + } + ], + "forward": [ + { + "name": "net_input", + "op": "placeholder", + "target": "net_input", + }, + { + "name": "layer1", + "op": "call_module", + "target": "layer1", + "args": ["net_input"], + }, + { + "name": "tanh", + "op": "call_method", + "target": "tanh", + "args": ["layer1"], + }, + ], + }, + ) + + # array data + problem.add_array_data_from_dict( + { + "metadata": {"pytorch_format": True}, + "inputs": {}, + "parameters": { + "net1": { + "layer1": { + "bias": np.random.randn(2), + "weight": np.random.randn(2), + } + } + }, + } + ) + + # set the filenames + problem.config.filepath = "problem.yaml" + problem.model.rel_path = "lv.xml" + problem.experiment_tables[0].rel_path = "experiments.tsv" + problem.mapping_tables[0].rel_path = "mappings.tsv" + problem.measurement_tables[0].rel_path = "measurements.tsv" + problem.observable_tables[0].rel_path = "observables.tsv" + problem.parameter_tables[0].rel_path = "parameters.tsv" + problem.hybridization_tables[0].rel_path = "hybridizations.tsv" + # problem.neural_networks[0].rel_path = "net1.yaml" + # problem.array_data_files[0].rel_path = "net1_ps.hdf5" + + return problem + + +def test_lint(): + problem = _get_test_problem() + assert problem.validate() == []