petab.v2

The PEtab 2.0 subpackage.

Contains all functionality related to handling PEtab 2.0 problems.

class petab.v2.Cauchy(loc: float, scale: float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

Cauchy distribution.

A (possibly truncated) Cauchy distribution.

Parameters:
  • loc – The location parameter of the distribution.

  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated. If the distribution is log-scaled, the truncation limits are expected to be on the same log scale.

  • log – If True, the distribution is transformed to a log-Cauchy distribution. If a float, the distribution is transformed to a log-Cauchy distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the location and scale parameters are the location and scale of the underlying Cauchy distribution.

property loc: float

The location parameter of the underlying distribution.

property scale: float

The scale parameter of the underlying distribution.

class petab.v2.Change(*, targetId: Annotated[str, AfterValidator(func=_valid_petab_id)], targetValue: Basic, **extra_data: Any)[source]

Bases: BaseModel

A change to the model or model state.

A change to the model or model state, corresponding to an individual row of the PEtab condition table.

>>> Change(
...     target_id="k1",
...     target_value="10",
... )
Change(target_id='k1', target_value=10.0000000000000)
target_id: Annotated[str, AfterValidator(_valid_petab_id)]

The ID of the target entity to change.

target_value: sp.Basic

The value to set the target entity to.

class petab.v2.ChiSquare(dof: int | float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

Chi-squared distribution.

A (possibly truncated) Chi-squared distribution.

Parameters:
  • dof – The degrees of freedom parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated. If the distribution is log-scaled, the truncation limits are expected to be on the same log scale.

  • log – If True, the distribution is transformed to a log-Chi-squared distribution. If a float, the distribution is transformed to a log-Chi-squared distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the degrees of freedom parameter is the degrees of freedom of the underlying Chi-squared distribution.

property dof: int

The degrees of freedom parameter.

class petab.v2.Condition(*, conditionId: Annotated[str, AfterValidator(func=_valid_petab_id)], changes: list[Change], **extra_data: Any)[source]

Bases: BaseModel

A set of changes to the model or model state.

A set of simultaneously occurring changes to the model or model state, corresponding to a perturbation of the underlying system. This corresponds to all rows of the PEtab condition table with the same condition ID.

>>> Condition(
...     id="condition1",
...     changes=[
...         Change(
...             target_id="k1",
...             target_value="10",
...         )
...     ],
... )
Condition(id='condition1',
changes=[Change(target_id='k1', target_value=10.0000000000000)])
changes: list[Change]

The changes associated with this condition.

id: Annotated[str, AfterValidator(_valid_petab_id)]

The condition ID.

class petab.v2.ConditionTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Condition]

PEtab condition table.

property conditions: list[Condition]

List of conditions.

property free_symbols: set[Symbol]

Get all free symbols in the condition table.

This includes all free symbols in the target values of the changes, independently of whether it is referenced by any experiment, or (indirectly) by any measurement.

classmethod from_df(df: DataFrame, **kwargs) ConditionTable[source]

Create a ConditionTable from a DataFrame.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

to_df() DataFrame[source]

Convert the ConditionTable to a DataFrame.

class petab.v2.Distribution(*, log: bool | float = False, trunc: tuple[float, float] = None)[source]

Bases: ABC

A univariate probability distribution.

This class provides a common interface for sampling from and evaluating the probability density function of a univariate probability distribution.

The distribution can be transformed by applying a logarithm to the samples and the PDF. This is useful, e.g., for log-normal distributions.

Parameters:
  • log – If True, the distribution is transformed to its corresponding log distribution (e.g., Normal -> LogNormal). If a float, the distribution is transformed to its corresponding log distribution with the given log-base (e.g., Normal -> Log10Normal). If False, no transformation is applied.

  • trunc – The truncation points (lower, upper) of the distribution or None if the distribution is not truncated. If the distribution is log-scaled, the truncation limits are expected to be on the same log scale.

cdf(x) ndarray | float[source]

Cumulative distribution function at x.

Parameters:

x – The value at which to evaluate the CDF.

Returns:

The value of the CDF at x.

property logbase: bool | float

The base of the log transformation.

If False, no transformation is applied.

pdf(x) ndarray | float[source]

Probability density function at x.

Parameters:

x – The value at which to evaluate the PDF.

Returns:

The value of the PDF at x. NaN, if x is outside the domain of the PDF.

ppf(q) ndarray | float[source]

Percent point function at q.

Parameters:

q – The quantile at which to evaluate the PPF.

Returns:

The value of the PPF at q.

sample(shape=None) ndarray | float[source]

Sample from the distribution.

Parameters:

shape – The shape of the sample.

Returns:

A sample from the distribution.

property trunc_high: float

The upper truncation limit of the transformed distribution.

property trunc_low: float

The lower truncation limit of the transformed distribution.

class petab.v2.Experiment(*, experimentId: Annotated[str, AfterValidator(func=_valid_petab_id)], periods: list[ExperimentPeriod] = [], **extra_data: Any)[source]

Bases: BaseModel

An experiment or a timecourse defined by an ID and a set of different periods.

Corresponds to a group of rows of the PEtab experiment table with the same experiment ID.

property has_preequilibration: bool

Check if the experiment has preequilibration enabled.

id: Annotated[str, AfterValidator(_valid_petab_id)]

The experiment ID.

periods: list[ExperimentPeriod]

The periods of the experiment.

sort_periods() None[source]

Sort the periods of the experiment by time.

property sorted_periods: list[ExperimentPeriod]

Get the periods of the experiment sorted by time.

class petab.v2.ExperimentPeriod(*, time: ~typing.Annotated[float, ~pydantic.functional_validators.AfterValidator(func=~petab.v2.core._is_finite_or_neg_inf)], condition_ids: list[str] = <factory>, **extra_data: ~typing.Any)[source]

Bases: BaseModel

A period of a timecourse or experiment defined by a start time and a list of condition IDs.

This corresponds to a row of the PEtab experiment table.

condition_ids: list[str]

The IDs of the conditions to be applied at the start time.

property is_preequilibration: bool

Check if this period is a preequilibration period.

time: Annotated[float, AfterValidator(_is_finite_or_neg_inf)]

The start time of the period in time units as defined in the model.

class petab.v2.ExperimentTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Experiment]

PEtab experiment table.

property experiments: list[Experiment]

List of experiments.

classmethod from_df(df: DataFrame, **kwargs) ExperimentTable[source]

Create an ExperimentTable from a DataFrame.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

to_df() DataFrame[source]

Convert the ExperimentTable to a DataFrame.

class petab.v2.Exponential(scale: float, trunc: tuple[float, float] | None = None)[source]

Bases: Distribution

Exponential distribution.

A (possibly truncated) Exponential distribution.

Parameters:
  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated.

property scale: float

The scale parameter of the underlying distribution.

class petab.v2.Gamma(shape: float, scale: float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

Gamma distribution.

A (possibly truncated) Gamma distribution.

Parameters:
  • shape – The shape parameter of the distribution.

  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated.

  • log – If True, the distribution is transformed to a log-Gamma distribution. If a float, the distribution is transformed to a log-Gamma distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the shape and scale parameters are the shape and scale of the underlying Gamma distribution.

property scale: float

The scale parameter of the underlying distribution.

property shape: float

The shape parameter of the underlying distribution.

class petab.v2.Laplace(loc: float, scale: float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

A (log-)Laplace distribution.

Parameters:
  • loc – The location parameter of the distribution.

  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated. If the distribution is log-scaled, the truncation limits are expected to be on the same log scale.

  • log – If True, the distribution is transformed to a log-Laplace distribution. If a float, the distribution is transformed to a log-Laplace distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the location and scale parameters are the location and scale of the underlying Laplace distribution.

property loc: float

The location parameter of the underlying distribution.

property scale: float

The scale parameter of the underlying distribution.

class petab.v2.LogUniform(low: float, high: float, trunc: tuple[float, float] | None = None)[source]

Bases: Distribution

A log-uniform or reciprocal distribution.

A random variable is log-uniformly distributed between low and high if its logarithm is uniformly distributed between log(low) and log(high).

Parameters:
  • low – The lower bound of the distribution.

  • high – The upper bound of the distribution.

  • trunc – The truncation limits of the distribution.

class petab.v2.Mapping(*, petabEntityId: Annotated[str, AfterValidator(func=_valid_petab_id)], modelEntityId: Annotated[str | None, BeforeValidator(func=_convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, name: Annotated[str | None, BeforeValidator(func=_convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, **extra_data: Any)[source]

Bases: BaseModel

Mapping PEtab entities to model entities.

model_id: Annotated[str | None, BeforeValidator(_convert_nan_to_none)]

Model entity ID.

name: Annotated[str | None, BeforeValidator(_convert_nan_to_none)]

Arbitrary name

petab_id: Annotated[str, AfterValidator(_valid_petab_id)]

PEtab entity ID.

class petab.v2.MappingTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Mapping]

PEtab mapping table.

classmethod from_df(df: DataFrame, **kwargs) MappingTable[source]

Create a MappingTable from a DataFrame.

get(petab_id, default=None)[source]

Get a mapping by PEtab ID or return a default value.

property mappings: list[Mapping]

List of mappings.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

to_df() DataFrame[source]

Convert the MappingTable to a DataFrame.

class petab.v2.Measurement(*, modelId: ~typing.Annotated[str | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._valid_petab_id_or_none, json_schema_input_type=PydanticUndefined)] = None, observableId: ~typing.Annotated[str, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._valid_petab_id, json_schema_input_type=PydanticUndefined)], experimentId: ~typing.Annotated[str | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._valid_petab_id_or_none, json_schema_input_type=PydanticUndefined)] = None, time: ~typing.Annotated[float, ~pydantic.functional_validators.AfterValidator(func=~petab.v2.core._is_finite_or_pos_inf)], measurement: ~typing.Annotated[float, ~pydantic.functional_validators.AfterValidator(func=~petab.v2.core._not_nan)], observableParameters: list[~sympy.core.basic.Basic] = <factory>, noiseParameters: list[~sympy.core.basic.Basic] = <factory>, **extra_data: ~typing.Any)[source]

Bases: BaseModel

A measurement.

A measurement of an observable at a specific time point in a specific experiment.

classmethod convert_nan_to_none(v, info: ValidationInfo)[source]
experiment_id: Annotated[str | None, BeforeValidator(_valid_petab_id_or_none)]

The experiment ID.

measurement: Annotated[float, AfterValidator(_not_nan)]

The measurement value.

model_id: Annotated[str | None, BeforeValidator(_valid_petab_id_or_none)]

The model ID.

noise_parameters: list[sp.Basic]

Values for placeholder parameters in the noise formula.

observable_id: Annotated[str, BeforeValidator(_valid_petab_id)]

The observable ID.

observable_parameters: list[sp.Basic]

Values for placeholder parameters in the observable formula.

time: Annotated[float, AfterValidator(_is_finite_or_pos_inf)]

The time point of the measurement in time units as defined in the model.

class petab.v2.MeasurementTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Measurement]

PEtab measurement table.

classmethod from_df(df: DataFrame, **kwargs) MeasurementTable[source]

Create a MeasurementTable from a DataFrame.

property measurements: list[Measurement]

List of measurements.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

to_df() DataFrame[source]

Convert the MeasurementTable to a DataFrame.

class petab.v2.Model[source]

Bases: ABC

Base class for wrappers for any PEtab-supported model type

abstractmethod static from_file(filepath_or_buffer: Any, model_id: str, base_path: str | Path = None) Model[source]

Load the model from the given path/URL

Parameters:
  • filepath_or_buffer – Absolute or relative path/URL to the model file. If relative, it is interpreted relative to base_path, if given.

  • base_path – Base path for relative paths in the model file.

  • model_id – Model ID

Returns:

A Model instance holding the given model

abstractmethod get_free_parameter_ids_with_values() Iterable[tuple[str, float]][source]

Get free model parameters along with their values

Returns:

Iterator over tuples of (parameter_id, parameter_value)

abstractmethod get_parameter_ids() Iterable[str][source]

Get all parameter IDs from this model

Returns:

Iterator over model parameter IDs

abstractmethod get_parameter_value(id_: str) float[source]

Get a parameter value

Parameters:

id – ID of the parameter whose value is to be returned

Raises:

ValueError – If no parameter with the given ID exists

Returns:

The value of the given parameter as specified in the model

abstractmethod get_valid_ids_for_condition_table() Iterable[str][source]

Get IDs of all model entities that are allowed to occur as columns in the PEtab conditions table.

Returns:

Iterator over model entity IDs

abstractmethod get_valid_parameters_for_parameter_table() Iterable[str][source]

Get IDs of all parameters that are allowed to occur in the PEtab parameters table

Returns:

Iterator over parameter IDs

abstractmethod has_entity_with_id(entity_id) bool[source]

Check if there is a model entity with the given ID

Parameters:

entity_id – ID to check for

Returns:

True, if there is an entity with the given ID, False otherwise

abstractmethod is_state_variable(id_: str) bool[source]

Check whether the given ID corresponds to a model state variable

abstractmethod is_valid() bool[source]

Validate this model

Returns:

True if the model is valid, False if there are errors in this model

abstract property model_id
abstractmethod symbol_allowed_in_observable_formula(id_: str) bool[source]

Check if the given ID is allowed to be used in observable and noise formulas

Returns:

True, if allowed, False otherwise

abstractmethod to_file(filename: str | Path | None = None)[source]

Save the model to the given file

Parameters:

filename – Destination filename

abstract class property type_id
class petab.v2.NoiseDistribution(*values)[source]

Bases: str, Enum

Noise distribution types.

Noise distributions as used in the PEtab observable table.

LAPLACE = 'laplace'

Laplace distribution

LOG_LAPLACE = 'log-laplace'

Log-Laplace distribution

LOG_NORMAL = 'log-normal'

Log-normal distribution

NORMAL = 'normal'

Normal distribution

class petab.v2.Normal(loc: float, scale: float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

A (log-)normal distribution.

Parameters:
  • loc – The location parameter of the distribution.

  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated. If the distribution is log-scaled, the truncation limits are expected to be on the same log scale.

  • log – If True, the distribution is transformed to a log-normal distribution. If a float, the distribution is transformed to a log-normal distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the location and scale parameters are the location and scale of the underlying normal distribution.

property loc: float

The location parameter of the underlying distribution.

property scale: float

The scale parameter of the underlying distribution.

class petab.v2.Observable(*, observableId: Annotated[str, AfterValidator(func=_valid_petab_id)], observableName: str | None = None, observableFormula: Basic | None = None, noiseFormula: Basic | None = None, noiseDistribution: NoiseDistribution = NoiseDistribution.NORMAL, observablePlaceholders: list[Symbol] = [], noisePlaceholders: list[Symbol] = [], **extra_data: Any)[source]

Bases: BaseModel

Observable definition.

formula: sp.Basic | None

Observable formula.

id: Annotated[str, AfterValidator(_valid_petab_id)]

Observable ID.

name: str | None

Observable name.

noise_distribution: NoiseDistribution

Noise distribution.

noise_formula: sp.Basic | None

Noise formula.

noise_placeholders: list[sp.Symbol]

Placeholder symbols for the noise formula.

observable_placeholders: list[sp.Symbol]

Placeholder symbols for the observable formula.

class petab.v2.ObservableTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Observable]

PEtab observable table.

classmethod from_df(df: DataFrame, **kwargs) ObservableTable[source]

Create an ObservableTable from a DataFrame.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property observables: list[Observable]

List of observables.

to_df() DataFrame[source]

Convert the ObservableTable to a DataFrame.

class petab.v2.Parameter(*, parameterId: ~typing.Annotated[str, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._valid_petab_id, json_schema_input_type=PydanticUndefined)], lowerBound: ~typing.Annotated[float | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, upperBound: ~typing.Annotated[float | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, nominalValue: ~typing.Annotated[float | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, estimate: bool = True, priorDistribution: ~typing.Annotated[~petab.v2.core.PriorDistribution | None, ~pydantic.functional_validators.BeforeValidator(func=~petab.v2.core._convert_nan_to_none, json_schema_input_type=PydanticUndefined)] = None, priorParameters: list[float] = <factory>, **extra_data: ~typing.Any)[source]

Bases: BaseModel

Parameter definition.

estimate: bool

Is the parameter to be estimated?

id: Annotated[str, BeforeValidator(_valid_petab_id)]

Parameter ID.

lb: Annotated[float | None, BeforeValidator(_convert_nan_to_none)]

Lower bound.

nominal_value: Annotated[float | None, BeforeValidator(_convert_nan_to_none)]

Nominal value.

property prior_dist: Distribution | None

Get the prior distribution of the parameter.

Returns:

The prior distribution of the parameter, or None if no prior distribution is set.

prior_distribution: Annotated[PriorDistribution | None, BeforeValidator(_convert_nan_to_none)]

Type of parameter prior distribution.

prior_parameters: list[float]

Prior distribution parameters.

ub: Annotated[float | None, BeforeValidator(_convert_nan_to_none)]

Upper bound.

class petab.v2.ParameterScale(*values)[source]

Bases: str, Enum

Parameter scales.

Parameter scales as used in the PEtab parameter table.

LIN = 'lin'
LOG = 'log'
LOG10 = 'log10'
class petab.v2.ParameterTable(elements: list[T] = None, *, rel_path: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None)[source]

Bases: BaseTable[Parameter]

PEtab parameter table.

classmethod from_df(df: DataFrame, **kwargs) ParameterTable[source]

Create a ParameterTable from a DataFrame.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property n_estimated: int

Number of estimated parameters.

property parameters: list[Parameter]

List of parameters.

to_df() DataFrame[source]

Convert the ParameterTable to a DataFrame.

class petab.v2.PriorDistribution(*values)[source]

Bases: str, Enum

Prior types.

Prior types as used in the PEtab parameter table.

CAUCHY = 'cauchy'

Cauchy distribution.

CHI_SQUARED = 'chisquare'

Chi-squared distribution.

EXPONENTIAL = 'exponential'

Exponential distribution.

GAMMA = 'gamma'

Gamma distribution.

LAPLACE = 'laplace'

Laplace distribution.

LOG_LAPLACE = 'log-laplace'

Log-Laplace distribution

LOG_NORMAL = 'log-normal'

Log-normal distribution.

LOG_UNIFORM = 'log-uniform'

Log-uniform distribution.

NORMAL = 'normal'

Normal distribution.

RAYLEIGH = 'rayleigh'

Rayleigh distribution.

UNIFORM = 'uniform'

Uniform distribution.

class petab.v2.Problem(models: list[Model] = None, condition_tables: list[ConditionTable] = None, experiment_tables: list[ExperimentTable] = None, observable_tables: list[ObservableTable] = None, measurement_tables: list[MeasurementTable] = None, parameter_tables: list[ParameterTable] = None, mapping_tables: list[MappingTable] = None, config: ProblemConfig = None)[source]

Bases: object

PEtab parameter estimation problem

A PEtab parameter estimation problem as defined by

  • models

  • condition tables

  • experiment tables

  • measurement tables

  • parameter tables

  • observable tables

  • mapping tables

See also PEtab data format specification 2.0.

add_condition(id_: str, name: str = None, **kwargs: Number | str | Expr)[source]

Add a simulation condition to the problem.

If there are more than one condition tables, the condition is added to the last one.

Parameters:
  • id – The condition id

  • name – The condition name. If given, this will be added to the last mapping table. If no mapping table exists, a new mapping table will be created.

  • kwargs – Entities to be added to the condition table in the form target_id=target_value.

add_experiment(id_: str, *args)[source]

Add an experiment to the problem.

If there are more than one experiment tables, the experiment is added to the last one.

Parameters:
  • id – The experiment ID.

  • args – Timepoints and associated conditions (single condition ID as string or multiple condition IDs as lists of strings).

Example:

>>> p = Problem()
>>> p.add_experiment(
...     "experiment1",
...     1,
...     "condition1",
...     2,
...     ["condition2a", "condition2b"],
... )
>>> p.experiments[0]
Experiment(id='experiment1', periods=[ExperimentPeriod(time=1.0, condition_ids=['condition1']), ExperimentPeriod(time=2.0, condition_ids=['condition2a', 'condition2b'])])
add_mapping(petab_id: str, model_id: str = None, name: str = None)[source]

Add a mapping table entry to the problem.

If there are more than one mapping tables, the mapping is added to the last one.

Parameters:
  • petab_id – The new PEtab-compatible ID mapping to model_id

  • model_id – The ID of some entity in the model

  • name – A name (any string) for the entity referenced by petab_id.

add_measurement(obs_id: str, *, time: float, measurement: float, experiment_id: str | None = None, observable_parameters: Sequence[str | float] | str | float = None, noise_parameters: Sequence[str | float] | str | float = None)[source]

Add a measurement to the problem.

If there are more than one measurement tables, the measurement is added to the last one.

Parameters:
  • obs_id – The observable ID

  • experiment_id – The experiment ID

  • time – The measurement time

  • measurement – The measurement value

  • observable_parameters – The observable parameters

  • noise_parameters – The noise parameters

add_observable(id_: str, formula: str, noise_formula: str | float | int = None, noise_distribution: str = None, observable_placeholders: list[str] = None, noise_placeholders: list[str] = None, name: str = None, **kwargs)[source]

Add an observable to the problem.

If there are more than one observable tables, the observable is added to the last one.

Parameters:
  • id – The observable id

  • formula – The observable formula

  • noise_formula – The noise formula

  • noise_distribution – The noise distribution

  • observable_placeholders – Placeholders for the observable formula

  • noise_placeholders – Placeholders for the noise formula

  • name – The observable name

  • kwargs – additional columns/values to add to the observable table

add_parameter(id_: str, estimate: bool | str = True, nominal_value: Number | None = None, lb: Number = None, ub: Number = None, prior_dist: str = None, prior_pars: str | Sequence = None, **kwargs)[source]

Add a parameter to the problem.

If there are more than one parameter tables, the parameter is added to the last one.

Parameters:
  • id – The parameter id

  • estimate – Whether the parameter is estimated

  • nominal_value – The nominal value of the parameter

  • lb – The lower bound of the parameter

  • ub – The upper bound of the parameter

  • prior_dist – The type of the prior distribution

  • prior_pars – The parameters of the prior distribution

  • kwargs – additional columns/values to add to the parameter table

assert_valid(**kwargs) None[source]

Assert that the PEtab problem is valid.

Parameters:

kwargs – Additional arguments passed to Problem.validate().

Raises:

AssertionError – If the PEtab problem is not valid.

property condition_df: DataFrame | None

Combined condition tables as DataFrame.

property conditions: list[Condition]

List of conditions in the condition table(s).

property experiment_df: DataFrame | None

Experiment table as DataFrame.

property experiments: list[Experiment]

List of experiments in the experiment table(s).

static from_combine(filename: Path | str) Problem[source]

Read PEtab COMBINE archive (http://co.mbine.org/documents/archive).

See also petab.v2.create_combine_archive().

Parameters:

filename – Path to the PEtab-COMBINE archive

Returns:

A petab.v2.Problem instance.

static from_yaml(yaml_config: dict | Path | str, base_path: str | Path = None) Problem[source]

Factory method to load model and tables as specified by YAML file.

Parameters:
  • yaml_config – PEtab configuration as dictionary or YAML file name

  • base_path – Base directory or URL to resolve relative paths

get_changes_for_period(period: ExperimentPeriod) list[Change][source]

Get the changes for a given experiment period.

Parameters:

period – The experiment period to get the changes for.

Returns:

A list of changes for the given period.

get_lb(free: bool = True, fixed: bool = True)[source]

Generic function to get lower parameter bounds.

Parameters:
  • free – Whether to return free parameters, i.e. parameters to estimate.

  • fixed – Whether to return fixed parameters, i.e. parameters not to estimate.

Return type:

The lower parameter bounds.

get_measurements_for_experiment(experiment: Experiment) list[Measurement][source]

Get the measurements for a given experiment.

Parameters:

experiment – The experiment to get the measurements for.

Returns:

A list of measurements for the given experiment.

get_observable_ids() list[str][source]

Returns dictionary of observable ids.

get_optimization_parameters() list[str][source]

Get the list of optimization parameter IDs from parameter table.

Returns:

A list of IDs of parameters selected for optimization (i.e., those with estimate = True).

get_output_parameters(observable: bool = True, noise: bool = True) list[str][source]

Get output parameters.

Returns IDs of symbols used in observable and noise formulas that are not observables and that are not defined in the model.

Parameters:
  • observable – Include parameters from observableFormulas

  • noise – Include parameters from noiseFormulas

Returns:

List of output parameter IDs, including any placeholder parameters.

get_priors() dict[str, Distribution][source]

Get prior distributions.

Note that this will default to uniform distributions over the parameter bounds for parameters without an explicit prior.

Returns:

The prior distributions for the estimated parameters in case the problem has a MAP objective, an empty dictionary otherwise.

static get_problem(problem: str | Path | Problem) Problem[source]

Get a PEtab problem from a file or a problem object.

Parameters:

problem – Path to a PEtab problem file or a PEtab problem object.

Returns:

A PEtab problem object.

get_startpoint_distributions() dict[str, Distribution][source]

Get distributions for sampling startpoints.

The distributions are the prior distributions for estimated parameters that have a prior distribution defined, and uniform distributions over the parameter bounds for estimated parameters without an explicit prior.

Returns:

Mapping of parameter IDs to distributions for sampling startpoints.

get_ub(free: bool = True, fixed: bool = True)[source]

Generic function to get upper parameter bounds.

Parameters:
  • free – Whether to return free parameters, i.e. parameters to estimate.

  • fixed – Whether to return fixed parameters, i.e. parameters not to estimate.

Return type:

The upper parameter bounds.

get_x_ids(free: bool = True, fixed: bool = True)[source]

Generic function to get parameter ids.

Parameters:
  • free – Whether to return free parameters, i.e. parameters to estimate.

  • fixed – Whether to return fixed parameters, i.e. parameters not to estimate.

Return type:

The parameter IDs.

get_x_nominal(free: bool = True, fixed: bool = True) list[source]

Generic function to get parameter nominal values.

Parameters:
  • free – Whether to return free parameters, i.e. parameters to estimate.

  • fixed – Whether to return fixed parameters, i.e. parameters not to estimate.

Return type:

The parameter nominal values.

get_x_nominal_dict(free: bool = True, fixed: bool = True) dict[str, float][source]

Get parameter nominal values as dict.

Parameters:
  • free – Whether to return free parameters, i.e. parameters to estimate.

  • fixed – Whether to return fixed parameters, i.e. parameters not to estimate.

Returns:

A dictionary mapping parameter IDs to their nominal values.

property has_map_objective: bool

Whether this problem encodes a maximum a posteriori (MAP) objective.

A PEtab problem is considered to have a MAP objective if there is a prior distribution specified for at least one estimated parameter.

Returns:

True if MAP objective, False otherwise.

property has_ml_objective: bool

Whether this problem encodes a maximum likelihood (ML) objective.

A PEtab problem is considered to have an ML objective if there are no prior distributions specified for any estimated parameters.

Returns:

True if ML objective, False otherwise.

property id: str | None

The ID of the PEtab problem if set, None otherwise.

property lb: list

Parameter table lower bounds.

property mapping_df: DataFrame | None

Combined mapping tables as DataFrame.

property mappings: list[Mapping]

List of mappings in the mapping table(s).

property measurement_df: DataFrame | None

Combined measurement tables as DataFrame.

property measurements: list[Measurement]

List of measurements in the measurement table(s).

property model: Model | None

The model of the problem.

This is a convenience property for `Problem`s with only one single model.

Returns:

The model of the problem, or None if no model is defined.

Raises:

ValueError: If the problem has more than one model defined.

model_dump(**kwargs) dict[str, Any][source]

Convert this Problem to a dictionary.

This function is intended for debugging purposes and should not be used for serialization. The output of this function may change without notice.

The output includes all PEtab tables, but not the models.

See pydantic.BaseModel.model_dump for details.

Example:

>>> from pprint import pprint
>>> p = Problem()
>>> p += Parameter(id="par", lb=0, ub=1)
>>> pprint(p.model_dump())
{'conditions': [],
 'config': {'condition_files': [],
            'experiment_files': [],
            'extensions': {},
            'format_version': '2.0.0',
            'id': None,
            'mapping_files': [],
            'measurement_files': [],
            'model_files': {},
            'observable_files': [],
            'parameter_files': []},
 'experiments': [],
 'mappings': [],
 'measurements': [],
 'observables': [],
 'parameters': [{'estimate': 'true',
                 'id': 'par',
                 'lb': 0.0,
                 'nominal_value': None,
                 'prior_distribution': '',
                 'prior_parameters': '',
                 'ub': 1.0}]}
models: list[Model]
property n_estimated: int

The number of estimated parameters.

property n_measurements: int

Number of measurements.

property n_priors: int

Number of priors.

property observable_df: DataFrame | None

Combined observable tables as DataFrame.

property observables: list[Observable]

List of observables in the observable table(s).

property parameter_df: DataFrame | None

Combined parameter tables as DataFrame.

property parameters: list[Parameter]

List of parameters in the parameter table(s).

sample_parameter_startpoints(n_starts: int = 100, **kwargs)[source]

Create 2D array with starting points for optimization

sample_parameter_startpoints_dict(n_starts: int = 100) list[dict[str, float]][source]

Create dictionaries with starting points for optimization

Returns:

A list of dictionaries with parameter IDs mapping to sampled parameter values.

to_files(base_path: str | Path | None) None[source]

Write the PEtab problem to files.

Writes the model, condition, experiment, measurement, parameter, observable, and mapping tables to their respective files as specified by the rel_path and base_path of their respective objects.

This expects that all objects have their rel_path and base_path set correctly, which is usually done by Problem.from_yaml().

Parameters:

base_path – The base path the yaml file and tables will be written to. If None, the base_path of the individual tables and Problem.config.base_path will be used.

property ub: list

Parameter table upper bounds

validate(validation_tasks: list[ValidationTask] = None) ValidationResultList[source]

Validate the PEtab problem.

Parameters:

validation_tasks – List of validation tasks to run. If None or empty, Problem.validation_tasks are used.

Returns:

A list of validation results.

validation_tasks: list[ValidationTask]
property x_fixed_ids: list[str]

Parameter table parameter IDs, for fixed parameters.

property x_fixed_indices: list[int]

Parameter table non-estimated parameter indices.

property x_free_ids: list[str]

Parameter table parameter IDs, for free parameters.

property x_free_indices: list[int]

Parameter table estimated parameter indices.

property x_ids: list[str]

Parameter table parameter IDs

property x_nominal: list

Parameter table nominal values

property x_nominal_fixed: list

Parameter table nominal values, for fixed parameters.

property x_nominal_free: list

Parameter table nominal values, for free parameters.

class petab.v2.ProblemConfig(*, filepath: AnyUrl | Path | None = None, base_path: AnyUrl | Path | None = None, format_version: str = '2.0.0', id: str | None = None, parameter_files: list[AnyUrl | Path] = [], model_files: dict[str, ModelFile] | None = {}, measurement_files: list[AnyUrl | Path] = [], condition_files: list[AnyUrl | Path] = [], experiment_files: list[AnyUrl | Path] = [], observable_files: list[AnyUrl | Path] = [], mapping_files: list[AnyUrl | Path] = [], extensions: list[ExtensionConfig] | dict = {})[source]

Bases: BaseModel

The PEtab problem configuration.

base_path: AnyUrl | Path | None

The base path to resolve relative paths.

condition_files: list[AnyUrl | Path]
experiment_files: list[AnyUrl | Path]
extensions: list[ExtensionConfig] | dict

Extensions used by the problem.

filepath: AnyUrl | Path | None

The path to the PEtab problem configuration.

format_version: str

The PEtab format version.

property format_version_tuple: tuple[int, int, int, str]

The format version as a tuple of major/minor/patch `int`s and a suffix.

id: str | None

The problem ID.

mapping_files: list[AnyUrl | Path]
measurement_files: list[AnyUrl | Path]
model_config = {'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_files: dict[str, ModelFile] | None

The model IDs and files used by the problem (id->ModelFile).

observable_files: list[AnyUrl | Path]
parameter_files: list[AnyUrl | Path]
to_yaml(filename: str | Path)[source]

Write the configuration to a YAML file.

Parameters:

filename – Destination file name. The parent directory will be created if necessary.

class petab.v2.Rayleigh(scale: float, trunc: tuple[float, float] | None = None, log: bool | float = False)[source]

Bases: Distribution

Rayleigh distribution.

A (possibly truncated) Rayleigh distribution.

Parameters:
  • scale – The scale parameter of the distribution.

  • trunc – The truncation limits of the distribution. None if the distribution is not truncated.

  • log – If True, the distribution is transformed to a log-Rayleigh distribution. If a float, the distribution is transformed to a log-Rayleigh distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the scale parameter is the scale of the underlying Rayleigh distribution.

property scale: float

The scale parameter of the underlying distribution.

class petab.v2.Uniform(low: float, high: float, *, log: bool | float = False)[source]

Bases: Distribution

A (log-)uniform distribution.

Parameters:
  • low – The lower bound of the distribution.

  • high – The upper bound of the distribution.

  • log – If True, the distribution is transformed to a log-uniform distribution. If a float, the distribution is transformed to a log-uniform distribution with the given log-base. If False, no transformation is applied. If a transformation is applied, the lower and upper bounds are the lower and upper bounds of the underlying uniform distribution. Note that this differs from the usual definition of a log-uniform distribution, where the logarithm of the variable is uniformly distributed between the logarithms of the bounds (see also LogUniform).

petab.v2.get_condition_df(condition_file: str | DataFrame | Path | None) DataFrame | None[source]

Read the provided condition file into a pandas.Dataframe.

Parameters:

condition_file – File name of PEtab condition file or pandas.Dataframe

petab.v2.get_experiment_df(experiments_file: str | DataFrame | Path | None) DataFrame | None[source]

Read the provided experiments file into a pandas.Dataframe.

Parameters:

experiments_file – Name of the file to read from or pandas.Dataframe.

Returns:

Experiments DataFrame

petab.v2.get_mapping_df(mapping_file: None | str | Path | DataFrame) DataFrame[source]

Read the provided mapping file into a pandas.Dataframe.

Parameters:

mapping_file – Name of file to read from or pandas.Dataframe

Returns:

Mapping DataFrame

petab.v2.get_measurement_df(measurement_file: None | str | Path | DataFrame) DataFrame[source]

Read the provided measurement file into a pandas.Dataframe.

Parameters:

measurement_file – Name of file to read from or pandas.Dataframe

Returns:

Measurement DataFrame

petab.v2.get_observable_df(observable_file: str | DataFrame | Path | None) DataFrame | None[source]

Read the provided observable file into a pandas.Dataframe.

Parameters:

observable_file – Name of the file to read from or pandas.Dataframe.

Returns:

Observable DataFrame

petab.v2.get_parameter_df(parameter_file: str | Path | DataFrame | Iterable[str | Path | DataFrame] | None) DataFrame | None[source]

Read the provided parameter file into a pandas.Dataframe.

Parameters:
  • parameter_file – Name of the file to read from or pandas.Dataframe,

  • Iterable. (or an)

Returns:

Parameter DataFrame, or None if None was passed.

petab.v2.lint_problem(problem: Problem | str | Path) ValidationResultList[source]

Validate a PEtab problem.

Parameters:

problem – PEtab problem to check. Instance of Problem or path to a PEtab problem YAML file.

Returns:

A list of validation results. Empty if no issues were found.

petab.v2.load_yaml(yaml_config: dict | Path | str) dict[source]

Load YAML

Convenience function to allow for providing YAML inputs as filename, URL or as dictionary.

Parameters:

yaml_config – PEtab YAML config as filename or dict or URL.

Returns:

The unmodified dictionary if yaml_config was dictionary. Otherwise the parsed the YAML file.

petab.v2.write_condition_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab condition table

Parameters:
  • df – PEtab condition table

  • filename – Destination file name

petab.v2.write_experiment_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab experiments table

Parameters:
  • df – PEtab experiments table

  • filename – Destination file name. The parent directory will be created if necessary.

petab.v2.write_mapping_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab mapping table

Parameters:
  • df – PEtab mapping table

  • filename – Destination file name. The parent directory will be created if necessary.

petab.v2.write_measurement_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab measurement table

Parameters:
  • df – PEtab measurement table

  • filename – Destination file name. The parent directory will be created if necessary.

petab.v2.write_observable_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab observable table

Parameters:
  • df – PEtab observable table

  • filename – Destination file name. The parent directory will be created if necessary.

petab.v2.write_parameter_df(df: DataFrame, filename: str | Path) None[source]

Write PEtab parameter table

Parameters:
  • df – PEtab parameter table

  • filename – Destination file name. The parent directory will be created if necessary.

Modules

C

This file contains constant definitions.

calculate

Functions performing various calculations.

conditions

Functions operating on the PEtab condition table

converters

Conversion of PEtab problems.

core

Types around the PEtab object model.

experiments

Functions operating on the PEtab experiments table.

lint

Validation of PEtab problems

math

Functions for parsing and evaluating mathematical expressions.

models

Handling of different model types supported by PEtab.

petab1to2

Convert PEtab version 1 problems to version 2.