petab

PEtab global

petab.ENV_NUM_THREADS

Name of environment variable to set number of threads or processes PEtab should use for operations that can be performed in parallel. By default, all operations are performed sequentially.

class petab.CompositeProblem(parameter_df: Optional[pandas.core.frame.DataFrame] = None, problems: Optional[List[petab.problem.Problem]] = None)

Bases: object

Representation of a PEtab problem consisting of multiple models

problems

List petab.Problems

parameter_df

PEtab parameter DataFrame

static from_yaml(yaml_config: Union[Dict, str])petab.composite_problem.CompositeProblem

Create from YAML file

Factory method to create a CompositeProblem instance from a PEtab YAML config file

Parameters

yaml_config – PEtab configuration as dictionary or YAML file name

class petab.Counter(**kwds)

Bases: dict

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string
>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15
>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0
>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9
>>> c.clear()                       # empty the counter
>>> c
Counter()

Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
_keep_positive()

Internal method to strip elements with a negative or zero count

clear()None.  Remove all items from D.
copy()

Return a shallow copy.

elements()

Iterator over elements repeating each as many times as its count.

>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors … product *= factor # and multiply them >>> product 1836

Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.

classmethod fromkeys(iterable, v=None)

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

items()a set-like object providing a view on D’s items
keys()a set-like object providing a view on D’s keys
most_common(n=None)

List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
pop(k[, d])v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem()(k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

subtract(**kwds)

Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.subtract('witch')             # subtract elements from another iterable
>>> c.subtract(Counter('watch'))    # subtract elements from another counter
>>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
-1
update(**kwds)

Like dict.update() but add counts instead of replacing them.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.update('witch')           # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d)                 # add elements from another counter
>>> c['h']                      # four 'h' in which, witch, and watch
4
values()an object providing a view on D’s values
class petab.OrderedDict

Bases: dict

Dictionary that remembers insertion order

clear()None.  Remove all items from od.
copy()a shallow copy of od
fromkeys(value=None)

Create a new ordered dictionary with keys from iterable and values set to value.

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

items()a set-like object providing a view on D’s items
keys()a set-like object providing a view on D’s keys
move_to_end(key, last=True)

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

pop(k[, d])v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem(last=True)

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F)None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()an object providing a view on D’s values
class petab.Problem(sbml_model: Optional[libsbml.Model] = None, sbml_reader: Optional[libsbml.SBMLReader] = None, sbml_document: Optional[libsbml.SBMLDocument] = None, condition_df: Optional[pandas.core.frame.DataFrame] = None, measurement_df: Optional[pandas.core.frame.DataFrame] = None, parameter_df: Optional[pandas.core.frame.DataFrame] = None, visualization_df: Optional[pandas.core.frame.DataFrame] = None, observable_df: Optional[pandas.core.frame.DataFrame] = None)

Bases: object

PEtab parameter estimation problem as defined by

  • SBML model

  • condition table

  • measurement table

  • parameter table

  • observables table

Optionally it may contain visualization tables.

condition_df

PEtab condition table

measurement_df

PEtab measurement table

parameter_df

PEtab parameter table

observable_df

PEtab observable table

visualization_df

PEtab visualization table

sbml_reader

Stored to keep object alive.

sbml_document

Stored to keep object alive.

sbml_model

PEtab SBML model

_apply_mask(v: List, free: bool = True, fixed: bool = True)

Apply mask of only free or only fixed values.

Parameters
  • v – The full vector the mask is to be applied to.

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

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

Returns

The reduced vector with applied mask.

Return type

v

create_parameter_df(*args, **kwargs)

Create a new PEtab parameter table

See create_parameter_df

static from_combine(filename: str)petab.problem.Problem

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

See also create_combine_archive.

Parameters

filename – Path to the PEtab-COMBINE archive

Returns

A petab.Problem instance.

static from_files(sbml_file: Optional[str] = None, condition_file: Optional[str] = None, measurement_file: Optional[Union[str, Iterable[str]]] = None, parameter_file: Optional[Union[str, List[str]]] = None, visualization_files: Optional[Union[str, Iterable[str]]] = None, observable_files: Optional[Union[str, Iterable[str]]] = None)petab.problem.Problem

Factory method to load model and tables from files.

Parameters
  • sbml_file – PEtab SBML model

  • condition_file – PEtab condition table

  • measurement_file – PEtab measurement table

  • parameter_file – PEtab parameter table

  • visualization_files – PEtab visualization tables

  • observable_files – PEtab observables tables

static from_folder(folder: str, model_name: Optional[str] = None)petab.problem.Problem

Factory method to use the standard folder structure and file names, i.e.

${model_name}/
  +-- experimentalCondition_${model_name}.tsv
  +-- measurementData_${model_name}.tsv
  +-- model_${model_name}.xml
  +-- parameters_${model_name}.tsv
Parameters
  • folder – Path to the directory in which the files are located.

  • model_name – If specified, overrides the model component in the file names. Defaults to the last component of folder.

static from_yaml(yaml_config: Union[Dict, str])petab.problem.Problem

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

Parameters

yaml_config – PEtab configuration as dictionary or YAML file name

get_lb(free: bool = True, fixed: bool = True, scaled: bool = False)

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.

  • scaled – Whether to scale the values according to the parameter scale, or return them on linear scale.

Returns

The lower parameter bounds.

Return type

v

get_model_parameters()

See petab.sbml.get_model_parameters

get_noise_distributions()

See get_noise_distributions.

get_observable_ids()

Returns dictionary of observable ids.

get_observables(remove: bool = False)

Returns dictionary of observables definitions. See assignment_rules_to_dict for details.

get_optimization_parameter_scales()

Return list of optimization parameter scaling strings.

See petab.parameters.get_optimization_parameters.

get_optimization_parameters()

Return list of optimization parameter IDs.

See petab.parameters.get_optimization_parameters.

get_optimization_to_simulation_parameter_mapping(warn_unmapped: bool = True, scaled_parameters: bool = False)

See get_simulation_to_optimization_parameter_mapping.

get_sigmas(remove: bool = False)

Return dictionary of observableId => sigma as defined in the SBML model. This does not include parameter mappings defined in the measurement table.

get_simulation_conditions_from_measurement_df()

See petab.get_simulation_conditions

get_ub(free: bool = True, fixed: bool = True, scaled: bool = False)

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.

  • scaled – Whether to scale the values according to the parameter scale, or return them on linear scale.

Returns

The upper parameter bounds.

Return type

v

get_x_ids(free: bool = True, fixed: bool = True)

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.

Returns

The parameter ids.

Return type

v

get_x_nominal(free: bool = True, fixed: bool = True, scaled: bool = False)

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.

  • scaled – Whether to scale the values according to the parameter scale, or return them on linear scale.

Returns

The parameter nominal values.

Return type

v

property lb

Parameter table lower bounds.

property lb_scaled

Parameter table lower bounds with applied parameter scaling

sample_parameter_startpoints(n_starts: int = 100)

Create starting points for optimization

See sample_parameter_startpoints

to_files(sbml_file: Optional[str] = None, condition_file: Optional[str] = None, measurement_file: Optional[str] = None, parameter_file: Optional[str] = None, visualization_file: Optional[str] = None, observable_file: Optional[str] = None, yaml_file: Optional[str] = None)None

Write PEtab tables to files for this problem

Writes PEtab files for those entities for which a destination was passed.

NOTE: If this instance was created from multiple measurement or visualization tables, they will be merged and written to a single file.

Parameters
  • sbml_file – SBML model destination

  • condition_file – Condition table destination

  • measurement_file – Measurement table destination

  • parameter_file – Parameter table destination

  • visualization_file – Visualization table destination

  • observable_file – Observables table destination

  • yaml_file – YAML file destination

Raises
  • ValueError – If a destination was provided for a non-existing

  • entity.

property ub

Parameter table upper bounds

property ub_scaled

Parameter table upper bounds with applied parameter scaling

property x_fixed_ids

Parameter table parameter IDs, for fixed parameters.

property x_fixed_indices

Parameter table non-estimated parameter indices.

property x_free_ids

Parameter table parameter IDs, for free parameters.

property x_free_indices

Parameter table estimated parameter indices.

property x_ids

Parameter table parameter IDs

property x_nominal

Parameter table nominal values

property x_nominal_fixed

Parameter table nominal values, for fixed parameters.

property x_nominal_fixed_scaled

Parameter table nominal values with applied parameter scaling, for fixed parameters.

property x_nominal_free

Parameter table nominal values, for free parameters.

property x_nominal_free_scaled

Parameter table nominal values with applied parameter scaling, for free parameters.

property x_nominal_scaled

Parameter table nominal values with applied parameter scaling

class petab.Simulator(petab_problem: petab.problem.Problem, working_dir: Optional[Union[pathlib.Path, str]] = None)

Bases: abc.ABC

Base class that specific simulators should inherit.

Specific simulators should minimally implement the simulate_without_noise method. Example (AMICI): https://bit.ly/33SUSG4

noise_formulas

The formulae that will be used to calculate the scale of noise distributions.

petab_problem

A PEtab problem, which will be simulated.

rng

A NumPy random generator, used to sample from noise distributions.

temporary_working_dir

Whether working_dir is a temporary directory, which can be deleted without significant consequence.

working_dir

All simulator-specific output files will be saved here. This directory and its contents may be modified and deleted, and should be considered ephemeral.

add_noise(simulation_df: pandas.core.frame.DataFrame, noise_scaling_factor: float = 1, **kwargs)pandas.core.frame.DataFrame

Add noise to simulated data.

Parameters
  • simulation_df – A PEtab measurements table that contains simulated data.

  • noise_scaling_factor – A multiplier of the scale of the noise distribution.

  • **kwargs – Additional keyword arguments are passed to sample_noise.

Returns

Simulated data with noise, as a PEtab measurements table.

remove_working_dir(force: bool = False, **kwargs)None

Remove the simulator working directory, and all files within.

See the __init__ method arguments.

Parameters
  • force – If True, the working directory is removed regardless of whether it is a temporary directory.

  • **kwargs – Additional keyword arguments are passed to shutil.rmtree.

simulate(noise: bool = False, noise_scaling_factor: float = 1, **kwargs)pandas.core.frame.DataFrame

Simulate a PEtab problem, optionally with noise.

Parameters
  • noise – If True, noise is added to simulated data.

  • noise_scaling_factor – A multiplier of the scale of the noise distribution.

  • **kwargs – Additional keyword arguments are passed to simulate_without_noise.

Returns

Simulated data, as a PEtab measurements table.

abstract simulate_without_noise()pandas.core.frame.DataFrame

Simulate the PEtab problem.

This is an abstract method that should be implemented with a simulation package. Examples of this are referenced in the class docstring.

Returns

Simulated data, as a PEtab measurements table, which should be equivalent to replacing all values in the petab.C.MEASUREMENT column of the measurements table (of the PEtab problem supplied to the __init__ method), with simulated values.

petab.add_global_parameter(sbml_model: libsbml.Model, parameter_id: str, parameter_name: Optional[str] = None, constant: bool = False, units: str = 'dimensionless', value: float = 0.0)libsbml.Parameter

Add new global parameter to SBML model

Parameters
  • sbml_model – SBML model

  • parameter_id – ID of the new parameter

  • parameter_name – Name of the new parameter

  • constant – Is parameter constant?

  • units – SBML unit ID

  • value – parameter value

Returns

The created parameter

petab.add_model_output(sbml_model: libsbml.Model, observable_id: str, formula: str, observable_name: Optional[str] = None)None

Add PEtab-style output to model

We expect that all formula parameters are added to the model elsewhere.

Parameters
  • sbml_model – Model to add output to

  • formula – Formula string for model output

  • observable_id – ID without “observable_” prefix

  • observable_name – Any observable name

petab.add_model_output_sigma(sbml_model: libsbml.Model, observable_id: str, formula: str)None

Add PEtab-style sigma for the given observable id

We expect that all formula parameters are added to the model elsewhere.

Parameters
  • sbml_model – Model to add to

  • observable_id – Observable id for which to add sigma

  • formula – Formula for sigma

petab.add_model_output_with_sigma(sbml_model: libsbml.Model, observable_id: str, observable_formula: str, observable_name: Optional[str] = None)None

Add PEtab-style output and corresponding sigma with single (newly created) parameter

We expect that all formula parameters are added to the model elsewhere.

Parameters
  • sbml_model – Model to add output to

  • observable_formula – Formula string for model output

  • observable_id – ID without “observable_” prefix

  • observable_name – Any name

petab.assert_all_parameters_present_in_parameter_df(parameter_df: pandas.core.frame.DataFrame, sbml_model: libsbml.Model, observable_df: pandas.core.frame.DataFrame, measurement_df: pandas.core.frame.DataFrame, condition_df: pandas.core.frame.DataFrame)None

Ensure all required parameters are contained in the parameter table with no additional ones

Parameters
  • parameter_df – PEtab parameter DataFrame

  • sbml_model – PEtab SBML Model

  • observable_df – PEtab observable table

  • measurement_df – PEtab measurement table

  • condition_df – PEtab condition table

Raises

AssertionError – in case of problems

petab.assert_measured_observables_defined(measurement_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame)None

Check if all observables in the measurement table have been defined in the observable table

Parameters
  • measurement_df – PEtab measurement table

  • observable_df – PEtab observable table

Raises

AssertionError – in case of problems

petab.assert_measurement_conditions_present_in_condition_table(measurement_df: pandas.core.frame.DataFrame, condition_df: pandas.core.frame.DataFrame)None

Ensure that all entries from measurement_df.simulationConditionId and measurement_df.preequilibrationConditionId are present in condition_df.index.

Parameters
  • measurement_df – PEtab measurement table

  • condition_df – PEtab condition table

Raises

AssertionError – in case of problems

petab.assert_model_parameters_in_condition_or_parameter_table(sbml_model: libsbml.Model, condition_df: pandas.core.frame.DataFrame, parameter_df: pandas.core.frame.DataFrame)None

Model parameters that are targets of AssignmentRule must not be present in parameter table or in condition table columns. Other parameters must only be present in either in parameter table or condition table columns. Check that.

Parameters
  • parameter_df – PEtab parameter DataFrame

  • sbml_model – PEtab SBML Model

  • condition_df – PEtab condition table

Raises

AssertionError – in case of problems

petab.assert_no_leading_trailing_whitespace(names_list: Iterable[str], name: str)None

Check that there is no trailing whitespace in elements of Iterable

Parameters
  • names_list – strings to check for whitespace

  • name – name of names_list for error messages

Raises

AssertionError – if there is trailing whitespace

petab.assert_noise_distributions_valid(observable_df: pandas.core.frame.DataFrame)None

Ensure that noise distributions and transformations for observables are valid.

Parameters

observable_df – PEtab observable table

Raises

AssertionError – in case of problems

petab.assert_overrides_match_parameter_count(measurement_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame)None

Ensure that number of parameters in the observable definition matches the number of overrides in measurement_df

Parameters
  • measurement_df – PEtab measurement table

  • observable_df – PEtab observable table

petab.assert_parameter_bounds_are_numeric(parameter_df: pandas.core.frame.DataFrame)None

Check if all entries in the lowerBound and upperBound columns of the parameter table are numeric.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.assert_parameter_estimate_is_boolean(parameter_df: pandas.core.frame.DataFrame)None

Check if all entries in the estimate column of the parameter table are 0 or 1.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.assert_parameter_id_is_string(parameter_df: pandas.core.frame.DataFrame)None

Check if all entries in the parameterId column of the parameter table are string and not empty.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.assert_parameter_prior_parameters_are_valid(parameter_df: pandas.core.frame.DataFrame)None

Check that the prior parameters are valid.

Parameters

parameter_df – PEtab parameter table

Raises

AssertionError in case of invalide prior parameters

petab.assert_parameter_prior_type_is_valid(parameter_df: pandas.core.frame.DataFrame)None

Check that valid prior types have been selected

Parameters

parameter_df – PEtab parameter table

Raises

AssertionError in case of invalid prior

petab.assert_parameter_scale_is_valid(parameter_df: pandas.core.frame.DataFrame)None

Check if all entries in the parameterScale column of the parameter table are ‘lin’ for linear, ‘log’ for natural logarithm or ‘log10’ for base 10 logarithm.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.assert_single_condition_and_sbml_file(problem_config: Dict)None

Check that there is only a single condition file and a single SBML file specified.

Parameters

problem_config – Dictionary as defined in the YAML schema inside the problems list.

Raises

NotImplementedError – If multiple condition or SBML files specified.

petab.assert_unique_observable_ids(observable_df: pandas.core.frame.DataFrame)None

Check if the observableId column of the observable table is unique.

Parameters

observable_df – PEtab observable DataFrame

Raises

AssertionError – in case of problems

petab.assert_unique_parameter_ids(parameter_df: pandas.core.frame.DataFrame)None

Check if the parameterId column of the parameter table is unique.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.assignment_rules_to_dict(sbml_model: libsbml.Model, filter_function=<function <lambda>>, remove: bool = False)Dict[str, Dict[str, Any]]

Turn assignment rules into dictionary.

Parameters
  • sbml_model – a sbml model instance.

  • filter_function – callback function taking assignment variable as input and returning True/False to indicate if the respective rule should be turned into an observable.

  • remove – Remove the all matching assignment rules from the model

Returns

{
    assigneeId:
    {
        'name': assigneeName,
        'formula': formulaString
    }
}

petab.calculate_chi2(measurement_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], simulation_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], observable_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], parameter_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], normalize: bool = True, scale: bool = True)float

Calculate the chi2 value.

Parameters
  • measurement_dfs – The problem measurement tables.

  • simulation_dfs – Simulation tables corresponding to the measurement tables.

  • observable_dfs – The problem observable tables.

  • parameter_dfs – The problem parameter tables.

  • normalize – Whether to normalize residuals by the noise standard deviation terms.

  • scale – Whether to calculate residuals of scaled values.

Returns

The aggregated chi2 value.

Return type

chi2

petab.calculate_chi2_for_table_from_residuals(residual_df: pandas.core.frame.DataFrame)float

Compute chi2 value for a single residual table.

petab.calculate_llh(measurement_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], simulation_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], observable_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], parameter_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame])float

Calculate total log likelihood.

Parameters
  • measurement_dfs – The problem measurement tables.

  • simulation_dfs – Simulation tables corresponding to the measurement tables.

  • observable_dfs – The problem observable tables.

  • parameter_dfs – The problem parameter tables.

Returns

The log-likelihood.

Return type

llh

petab.calculate_llh_for_table(measurement_df: pandas.core.frame.DataFrame, simulation_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame, parameter_df: pandas.core.frame.DataFrame)float

Calculate log-likelihood for one set of tables. For the arguments, see calculate_llh.

petab.calculate_residuals(measurement_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], simulation_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], observable_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], parameter_dfs: Union[List[pandas.core.frame.DataFrame], pandas.core.frame.DataFrame], normalize: bool = True, scale: bool = True)List[pandas.core.frame.DataFrame]

Calculate residuals.

Parameters
  • measurement_dfs – The problem measurement tables.

  • simulation_dfs – Simulation tables corresponding to the measurement tables.

  • observable_dfs – The problem observable tables.

  • parameter_dfs – The problem parameter tables.

  • normalize – Whether to normalize residuals by the noise standard deviation terms.

  • scale – Whether to calculate residuals of scaled values.

Returns

Data frames in the same structure as measurement_dfs with a field residual instead of measurement.

Return type

residual_dfs

petab.calculate_residuals_for_table(measurement_df: pandas.core.frame.DataFrame, simulation_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame, parameter_df: pandas.core.frame.DataFrame, normalize: bool = True, scale: bool = True)pandas.core.frame.DataFrame

Calculate residuals for a single measurement table. For the argumenets, see calculate_residuals.

petab.calculate_single_llh(measurement: float, simulation: float, scale: str, noise_distribution: str, noise_value: float)float

Calculate a single log likelihood.

Parameters
  • measurement – The measurement value.

  • simulation – The simulated value.

  • scale – The scale on which the noise model is to be applied.

  • noise_distribution – The noise distribution.

  • noise_value – The considered noise models possess a single noise parameter, e.g. the normal standard deviation.

Returns

The computed likelihood for the given values.

Return type

llh

petab.check_condition_df(df: pandas.core.frame.DataFrame, sbml_model: Optional[libsbml.Model] = None)None

Run sanity checks on PEtab condition table

Parameters
  • df – PEtab condition DataFrame

  • sbml_model – SBML Model for additional checking of parameter IDs

Raises

AssertionError – in case of problems

petab.check_ids(ids: Iterable[str], kind: str = '')None

Check IDs are valid

Parameters
  • ids – Iterable of IDs to check

  • kind – Kind of IDs, for more informative error message

Raises

ValueError - in case of invalid IDs

petab.check_measurement_df(df: pandas.core.frame.DataFrame, observable_df: Optional[pandas.core.frame.DataFrame] = None)None

Run sanity checks on PEtab measurement table

Parameters
  • df – PEtab measurement DataFrame

  • observable_df – PEtab observable DataFrame for checking if measurements are compatible with observable transformations.

Raises

AssertionError, ValueError – in case of problems

petab.check_observable_df(observable_df: pandas.core.frame.DataFrame)None

Check validity of observable table

Parameters

observable_df – PEtab observable DataFrame

Raises

AssertionError – in case of problems

petab.check_parameter_bounds(parameter_df: pandas.core.frame.DataFrame)None

Check if all entries in the lowerBound are smaller than upperBound column in the parameter table and that bounds are positive for parameterScale log|log10.

Parameters

parameter_df – PEtab parameter DataFrame

Raises

AssertionError – in case of problems

petab.check_parameter_df(df: pandas.core.frame.DataFrame, sbml_model: Optional[libsbml.Model] = None, observable_df: Optional[pandas.core.frame.DataFrame] = None, measurement_df: Optional[pandas.core.frame.DataFrame] = None, condition_df: Optional[pandas.core.frame.DataFrame] = None)None

Run sanity checks on PEtab parameter table

Parameters
  • df – PEtab condition DataFrame

  • sbml_model – SBML Model for additional checking of parameter IDs

  • observable_df – PEtab observable table for additional checks

  • measurement_df – PEtab measurement table for additional checks

  • condition_df – PEtab condition table for additional checks

Raises

AssertionError – in case of problems

petab.concat_tables(tables: Union[str, pandas.core.frame.DataFrame, Iterable[Union[pandas.core.frame.DataFrame, str]]], file_parser: Optional[Callable] = None)pandas.core.frame.DataFrame

Concatenate DataFrames provided as DataFrames or filenames, and a parser

Parameters
  • tables – Iterable of tables to join, as DataFrame or filename.

  • file_parser – Function used to read the table in case filenames are provided, accepting a filename as only argument.

Returns

The concatenated DataFrames

petab.condition_table_is_parameter_free(condition_df: pandas.core.frame.DataFrame)bool

Check if all entries in the condition table are numeric (no parameter IDs)

Parameters

condition_df – PEtab condition table

Returns

True if there are no parameter overrides in the condition table, False otherwise.

petab.create_assigment_rule(sbml_model: libsbml.Model, assignee_id: str, formula: str, rule_id: Optional[str] = None, rule_name: Optional[str] = None)libsbml.AssignmentRule

Create SBML AssignmentRule

Parameters
  • sbml_model – Model to add output to

  • assignee_id – Target of assignment

  • formula – Formula string for model output

  • rule_id – SBML id for created rule

  • rule_name – SBML name for created rule

Returns

The created AssignmentRule

petab.create_combine_archive(yaml_file: str, filename: str, family_name: Optional[str] = None, given_name: Optional[str] = None, email: Optional[str] = None, organization: Optional[str] = None)None

Create COMBINE archive (http://co.mbine.org/documents/archive) based on PEtab YAML file.

Parameters
  • yaml_file – Path to PEtab YAML file

  • family_name – Family name of archive creator

  • given_name – Given name of archive creator

  • email – E-mail address of archive creator

  • organization – Organization of archive creator

petab.create_condition_df(parameter_ids: Iterable[str], condition_ids: Optional[Iterable[str]] = None)pandas.core.frame.DataFrame

Create empty condition DataFrame

Parameters
  • parameter_ids – the columns

  • condition_ids – the rows

Returns

A pandas.DataFrame with empty given rows and columns and all nan values

petab.create_measurement_df()pandas.core.frame.DataFrame

Create empty measurement dataframe

Returns

Created DataFrame

petab.create_observable_df()pandas.core.frame.DataFrame

Create empty observable dataframe

Returns

Created DataFrame

petab.create_parameter_df(sbml_model: libsbml.Model, condition_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame, measurement_df: pandas.core.frame.DataFrame, include_optional: bool = False, parameter_scale: str = 'log10', lower_bound: Optional[Iterable] = None, upper_bound: Optional[Iterable] = None)pandas.core.frame.DataFrame

Create a new PEtab parameter table

All table entries can be provided as string or list-like with length matching the number of parameters

Parameters
  • sbml_model – SBML Model

  • condition_df – PEtab condition DataFrame

  • measurement_df – PEtab measurement DataFrame

  • include_optional – By default this only returns parameters that are required to be present in the parameter table. If set to True, this returns all parameters that are allowed to be present in the parameter table (i.e. also including parameters specified in the SBML model).

  • parameter_scale – parameter scaling

  • lower_bound – lower bound for parameter value

  • upper_bound – upper bound for parameter value

Returns

The created parameter DataFrame

petab.create_problem_yaml(sbml_files: Union[str, List[str]], condition_files: Union[str, List[str]], measurement_files: Union[str, List[str]], parameter_file: str, observable_files: Union[str, List[str]], yaml_file: str, visualization_files: Optional[Union[str, List[str]]] = None)None

Create and write default YAML file for a single PEtab problem

Parameters
  • sbml_files – Path of SBML model file or list of such

  • condition_files – Path of condition file or list of such

  • measurement_files – Path of measurement file or list of such

  • parameter_file – Path of parameter file

  • observable_files – Path of observable file or lsit of such

  • yaml_file – Path to which YAML file should be written

  • visualization_files – Optional Path to visualization file or list of

  • such

petab.evaluate_noise_formula(measurement: pandas.core.series.Series, noise_formulas: dict, parameter_df: pandas.core.frame.DataFrame, simulation: float)float

Fill in parameters for measurement and evaluate noise_formula.

Parameters
  • measurement – A measurement table row.

  • noise_formulas – The noise formulas as computed by get_symbolic_noise_formulas.

  • parameter_df – The parameter table.

  • simulation – The simulation corresponding to the measurement, scaled.

Returns

The noise value.

Return type

noise_value

petab.flatten_timepoint_specific_output_overrides(petab_problem: petab.problem.Problem)None

Flatten timepoint-specific output parameter overrides.

If the PEtab problem definition has timepoint-specific observableParameters or noiseParameters for the same observable, replace those by replicating the respective observable.

This is a helper function for some tools which may not support such timepoint-specific mappings. The observable table and measurement table are modified in place.

Parameters

petab_problem – PEtab problem to work on

petab.get_condition_df(condition_file: Optional[Union[str, pandas.core.frame.DataFrame]])pandas.core.frame.DataFrame

Read the provided condition file into a pandas.Dataframe

Conditions are rows, parameters are columns, conditionId is index.

Parameters

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

petab.get_default_condition_file_name(model_name: str, folder: str = '')

Get file name according to proposed convention

petab.get_default_measurement_file_name(model_name: str, folder: str = '')

Get file name according to proposed convention

petab.get_default_parameter_file_name(model_name: str, folder: str = '')

Get file name according to proposed convention

petab.get_default_sbml_file_name(model_name: str, folder: str = '')

Get file name according to proposed convention

petab.get_formula_placeholders(formula_string: str, observable_id: str, override_type: str)List[str]

Get placeholder variables in noise or observable definition for the given observable ID.

Parameters
  • formula_string – observable formula

  • observable_id – ID of current observable

  • override_type – ‘observable’ or ‘noise’, depending on whether formula is for observable or for noise model

Returns

List of placeholder parameter IDs in the order expected in the observableParameter column of the measurement table.

petab.get_handle(path_or_buf: Union[PathLike[str], str, IO[T], io.RawIOBase, io.BufferedIOBase, io.TextIOBase, _io.TextIOWrapper, mmap.mmap], mode: str, encoding: Optional[str] = None, compression: Optional[Union[str, Dict[str, Any]]] = None, memory_map: bool = False, is_text: bool = True, errors: Optional[str] = None, storage_options: Optional[Dict[str, Any]] = None)pandas.io.common.IOHandles

Get file handle for given path/buffer and mode.

Parameters
  • path_or_buf (str or file handle) – File path or object.

  • mode (str) – Mode to open path_or_buf with.

  • encoding (str or None) – Encoding to use.

  • compression (str or dict, default None) –

    If string, specifies compression mode. If dict, value at key ‘method’ specifies compression mode. Compression mode must be one of {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. If compression mode is ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no compression). If dict and compression mode is one of {‘zip’, ‘gzip’, ‘bz2’}, or inferred as one of the above, other entries passed as additional compression options.

    Changed in version 1.0.0: May now be a dict with key ‘method’ as compression mode and other keys as compression options if compression mode is ‘zip’.

    Changed in version 1.1.0: Passing compression options as keys in dict is now supported for compression modes ‘gzip’ and ‘bz2’ as well as ‘zip’.

  • memory_map (boolean, default False) – See parsers._parser_params for more information.

  • is_text (boolean, default True) – Whether the type of the content passed to the file/buffer is string or bytes. This is not the same as “b” not in mode. If a string content is passed to a binary file/buffer, a wrapper is inserted.

  • errors (str, default 'strict') – Specifies how encoding and decoding errors are to be handled. See the errors argument for open() for a full list of options.

  • storage_options (StorageOptions = None) – Passed to _get_filepath_or_buffer

  • versionchanged: (.) – 1.2.0:

  • the dataclass IOHandles (Returns) –

petab.get_measurement_df(measurement_file: Union[None, str, pandas.core.frame.DataFrame])pandas.core.frame.DataFrame

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.get_measurement_parameter_ids(measurement_df: pandas.core.frame.DataFrame)List[str]

Return list of ID of parameters which occur in measurement table as observable or noise parameter overrides.

Parameters

measurement_df – PEtab measurement DataFrame

Returns

List of parameter IDs

petab.get_model_parameters(sbml_model: libsbml.Model, with_values=False)Union[List[str], Dict[str, float]]

Return SBML model parameters which are not AssignmentRule targets for observables or sigmas

Parameters
  • sbml_model – SBML model

  • with_values – If false, returns list of SBML model parameter IDs which

  • not AssignmentRule targets for observables or sigmas. If true (are) –

:param : :param returns a dictionary with those parameter IDs as keys and parameter: :param values from the SBML model as values.:

petab.get_noise_distributions(measurement_df: pandas.core.frame.DataFrame)dict

Returns dictionary of cost definitions per observable, if specified.

Looks through all parameters satisfying sbml_parameter_is_cost and return as dictionary.

Parameters

measurement_df – PEtab measurement table

Returns

Dictionary with observableId => cost definition

petab.get_notnull_columns(df: pandas.core.frame.DataFrame, candidates: Iterable)

Return list of df-columns in candidates which are not all null/nan.

The output can e.g. be used as input for pandas.DataFrame.groupby.

Parameters
  • df – Dataframe

  • candidates – Columns of df to consider

petab.get_observable_df(observable_file: Optional[Union[str, pandas.core.frame.DataFrame]])pandas.core.frame.DataFrame

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.get_observable_id(parameter_id: str)str

Get PEtab observable ID from PEtab-style sigma or observable AssignmentRule-target parameter_id.

e.g. for ‘observable_obs1’ -> ‘obs1’, for ‘sigma_obs1’ -> ‘obs1’

Parameters

parameter_id – Some parameter ID

Returns

Observable ID

petab.get_observables(sbml_model: libsbml.Model, remove: bool = False)dict

Get observables defined in SBML model according to PEtab format.

Returns

Dictionary of observable definitions. See assignment_rules_to_dict for details.

petab.get_optimization_parameter_scaling(parameter_df: pandas.core.frame.DataFrame)Dict[str, str]

Get Dictionary with optimization parameter IDs mapped to parameter scaling strings.

Parameters

parameter_df – PEtab parameter DataFrame

Returns

Dictionary with optimization parameter IDs mapped to parameter scaling strings.

petab.get_optimization_parameters(parameter_df: pandas.core.frame.DataFrame)List[str]

Get list of optimization parameter IDs from parameter table.

Parameters

parameter_df – PEtab parameter DataFrame

Returns

List of IDs of parameters selected for optimization.

petab.get_optimization_to_simulation_parameter_mapping(condition_df: pandas.core.frame.DataFrame, measurement_df: pandas.core.frame.DataFrame, parameter_df: Optional[pandas.core.frame.DataFrame] = None, observable_df: Optional[pandas.core.frame.DataFrame] = None, sbml_model: Optional[libsbml.Model] = None, simulation_conditions: Optional[pandas.core.frame.DataFrame] = None, warn_unmapped: Optional[bool] = True, scaled_parameters: bool = False, fill_fixed_parameters: bool = True)List[Tuple[Dict[str, Union[str, numbers.Number]], Dict[str, Union[str, numbers.Number]], Dict[str, str], Dict[str, str]]]

Create list of mapping dicts from PEtab-problem to SBML parameters.

Mapping can be performed in parallel. The number of threads is controlled by the environment variable with the name of petab.ENV_NUM_THREADS.

Parameters
  • condition_df – The dataframes in the PEtab format.

  • measurement_df – The dataframes in the PEtab format.

  • parameter_df – The dataframes in the PEtab format.

  • observable_df – The dataframes in the PEtab format.

  • sbml_model – The sbml model with observables and noise specified according to the PEtab format.

  • simulation_conditions – Table of simulation conditions as created by petab.get_simulation_conditions.

  • warn_unmapped – If True, log warning regarding unmapped parameters

  • scaled_parameters – Whether parameter values should be scaled.

  • fill_fixed_parameters – Whether to fill in nominal values for fixed parameters (estimate=0 in parameters table).

Returns

Parameter value and parameter scale mapping for all conditions.

The length of the returned array is the number of unique combinations of simulationConditionId``s and ``preequilibrationConditionId``s from the measurement table. Each entry is a tuple of four dicts of length equal to the number of model parameters. The first two dicts map simulation parameter IDs to optimization parameter IDs or values (where values are fixed) for preequilibration and simulation condition, respectively. The last two dicts map simulation parameter IDs to the parameter scale of the respective parameter, again for preequilibration and simulation condition. If no preequilibration condition is defined, the respective dicts will be empty. ``NaN is used where no mapping exists.

petab.get_output_parameters(observable_df: pandas.core.frame.DataFrame, sbml_model: libsbml.Model)List[str]

Get output parameters

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

Parameters
  • observable_df – PEtab observable table

  • sbml_model – SBML model

Returns

List of output parameter IDs

petab.get_parameter_df(parameter_file: Optional[Union[str, List[str], pandas.core.frame.DataFrame]])pandas.core.frame.DataFrame

Read the provided parameter file into a pandas.Dataframe.

Parameters

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

Returns

Parameter DataFrame

petab.get_parameter_mapping_for_condition(condition_id: str, is_preeq: bool, cur_measurement_df: pandas.core.frame.DataFrame, sbml_model: libsbml.Model, condition_df: pandas.core.frame.DataFrame, parameter_df: Optional[pandas.core.frame.DataFrame] = None, simulation_parameters: Optional[Dict[str, str]] = None, warn_unmapped: bool = True, scaled_parameters: bool = False, fill_fixed_parameters: bool = True)Tuple[Dict[str, Union[str, numbers.Number]], Dict[str, str]]

Create dictionary of parameter value and parameter scale mappings from PEtab-problem to SBML parameters for the given condition.

Parameters
  • condition_id – Condition ID for which to perform mapping

  • is_preeq – If True, output parameters will not be mapped

  • cur_measurement_df – Measurement sub-table for current condition

  • condition_df – PEtab condition DataFrame

  • parameter_df – PEtab parameter DataFrame

  • sbml_model – The sbml model with observables and noise specified according to the PEtab format used to retrieve simulation parameter IDs.

  • simulation_parameters – Model simulation parameter IDs mapped to parameter values (output of petab.sbml.get_model_parameters(.., with_values=True)). Optional, saves time if precomputed.

  • warn_unmapped – If True, log warning regarding unmapped parameters

  • fill_fixed_parameters – Whether to fill in nominal values for fixed parameters (estimate=0 in parameters table).

Returns

Tuple of two dictionaries. First dictionary mapping model parameter IDs to mapped parameters IDs to be estimated or to filled-in values in case of non-estimated parameters. Second dictionary mapping model parameter IDs to their scale. NaN is used where no mapping exists.

petab.get_parametric_overrides(condition_df: pandas.core.frame.DataFrame)List[str]

Get parametric overrides from condition table

Parameters

condition_df – PEtab condition table

Returns

List of parameter IDs that are mapped in a condition-specific way

petab.get_placeholders(observable_df: pandas.core.frame.DataFrame)List[str]

Get all placeholder parameters from observable table observableFormulas and noiseFormulas

Parameters

observable_df – PEtab observable table

Returns

List of placeholder parameters from observable table observableFormulas and noiseFormulas.

petab.get_priors_from_df(parameter_df: pandas.core.frame.DataFrame, mode: str)List[Tuple]

Create list with information about the parameter priors

Parameters
  • parameter_df – PEtab parameter table

  • mode – ‘initialization’ or ‘objective’

Returns

List with prior information.

petab.get_required_parameters_for_parameter_table(sbml_model: libsbml.Model, condition_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame, measurement_df: pandas.core.frame.DataFrame)Set[str]

Get set of parameters which need to go into the parameter table

Parameters
  • sbml_model – PEtab SBML model

  • condition_df – PEtab condition table

  • observable_df – PEtab observable table

  • measurement_df – PEtab measurement table

Returns

Set of parameter IDs which PEtab requires to be present in the parameter table. That is all {observable,noise}Parameters from the measurement table as well as all parametric condition table overrides that are not defined in the SBML model.

petab.get_rows_for_condition(measurement_df: pandas.core.frame.DataFrame, condition: Union[pandas.core.series.Series, pandas.core.frame.DataFrame, Dict])pandas.core.frame.DataFrame

Extract rows in measurement_df for condition according to ‘preequilibrationConditionId’ and ‘simulationConditionId’ in condition.

Parameters
  • measurement_df – PEtab measurement DataFrame

  • condition – DataFrame with single row (or Series) and columns ‘preequilibrationConditionId’ and ‘simulationConditionId’. Or dictionary with those keys.

Returns

The subselection of rows in measurement_df for the condition

condition.

petab.get_sbml_model(filepath_or_buffer)Tuple[libsbml.SBMLReader, libsbml.SBMLDocument, libsbml.Model]

Get an SBML model from file or URL or file handle

Parameters

filepath_or_buffer – File or URL or file handle to read the model from

Returns

The SBML document, model and reader

petab.get_sigmas(sbml_model: libsbml.Model, remove: bool = False)dict

Get sigmas defined in SBML model according to PEtab format.

Returns

Dictionary of sigma definitions.

Keys are observable IDs, for values see assignment_rules_to_dict for details.

petab.get_simulation_conditions(measurement_df: pandas.core.frame.DataFrame)pandas.core.frame.DataFrame

Create a table of separate simulation conditions. A simulation condition is a specific combination of simulationConditionId and preequilibrationConditionId.

Parameters

measurement_df – PEtab measurement table

Returns

Dataframe with columns ‘simulationConditionId’ and ‘preequilibrationConditionId’. All-null columns will be omitted. Missing ‘preequilibrationConditionId’s will be set to ‘’ (empty string).

petab.get_simulation_df(simulation_file: str)pandas.core.frame.DataFrame

Read PEtab simulation table

Parameters

simulation_file – URL or filename of PEtab simulation table

Returns

Simulation DataFrame

petab.get_symbolic_noise_formulas(observable_df)dict

Sympify noise formulas.

Parameters

obervable_df – The observable table.

Returns

Dictionary of {observable_id}: {noise_formula}.

Return type

noise_formulas

petab.get_valid_parameters_for_parameter_table(sbml_model: libsbml.Model, condition_df: pandas.core.frame.DataFrame, observable_df: pandas.core.frame.DataFrame, measurement_df: pandas.core.frame.DataFrame)Set[str]

Get set of parameters which may be present inside the parameter table

Parameters
  • sbml_model – PEtab SBML model

  • condition_df – PEtab condition table

  • observable_df – PEtab observable table

  • measurement_df – PEtab measurement table

Returns

Set of parameter IDs which PEtab allows to be present in the parameter table.

petab.get_visualization_df(visualization_file: str)pandas.core.frame.DataFrame

Read PEtab visualization table

Parameters

visualization_file – URL or filename of PEtab visualization table

Returns

Visualization DataFrame

petab.globalize_parameters(sbml_model: libsbml.Model, prepend_reaction_id: bool = False)None

Turn all local parameters into global parameters with the same properties

Local parameters are currently ignored by other PEtab functions. Use this function to convert them to global parameters. There may exist local parameters with identical IDs within different kinetic laws. This is not checked here. If in doubt that local parameter IDs are unique, enable prepend_reaction_id to create global parameters named ${reaction_id}_${local_parameter_id}.

Parameters
  • sbml_model – The SBML model to operate on

  • prepend_reaction_id – Prepend reaction id of local parameter when creating global parameters

petab.handle_missing_overrides(mapping_par_opt_to_par_sim: Dict[str, Union[str, numbers.Number]], warn: bool = True, condition_id: Optional[str] = None)None

Find all observable parameters and noise parameters that were not mapped and set their mapping to np.nan.

Assumes that parameters matching “(noise|observable)Parameter[0-9]+_” were all supposed to be overwritten.

Parameters
  • mapping_par_opt_to_par_sim – Output of get_parameter_mapping_for_condition

  • warn – If True, log warning regarding unmapped parameters

  • condition_id – Optional condition ID for more informative output

petab.is_composite_problem(yaml_config: Union[Dict, str])bool

Does this YAML file comprise multiple models?

Parameters

yaml_config – PEtab configuration as dictionary or YAML file name

petab.is_empty(val)bool

Check if the value val, e.g. a table entry, is empty.

Parameters

val – The value to check.

Returns

Whether the field is to be considered empty.

Return type

empty

petab.is_file_like(obj)bool

Check if the object is a file-like object.

For objects to be considered file-like, they must be an iterator AND have either a read and/or write method as an attribute.

Note: file-like objects must be iterable, but iterable objects need not be file-like.

Parameters

obj (The object to check) –

Returns

is_file_like – Whether obj has file-like properties.

Return type

bool

Examples

>>> import io
>>> buffer = io.StringIO("data")
>>> is_file_like(buffer)
True
>>> is_file_like([1, 2, 3])
False
petab.is_sbml_consistent(sbml_document: libsbml.SBMLDocument, check_units: bool = False)bool

Check for SBML validity / consistency

Parameters
  • sbml_document – SBML document to check

  • check_units – Also check for unit-related issues

Returns

False if problems were detected, otherwise True

petab.is_url(url)bool

Check to see if a URL has a valid protocol.

Parameters

url (str or unicode) –

Returns

isurl – If url has a valid protocol return True otherwise False.

Return type

bool

petab.is_valid_identifier(x: str)bool

Check whether x is a valid identifier

Check whether x is a valid identifier for conditions, parameters, observables… . Identifiers may contain upper and lower case letters, digits and underscores, but must not start with a digit.

Parameters

x – string to check

Returns

True if valid, False otherwise

petab.lint_problem(problem: petab.problem.Problem)bool

Run PEtab validation on problem

Parameters

problem – PEtab problem to check

Returns

True is errors occurred, False otherwise

petab.load_sbml_from_file(sbml_file: str)Tuple[libsbml.SBMLReader, libsbml.SBMLDocument, libsbml.Model]

Load SBML model from file

Parameters

sbml_file – Filename of the SBML file

Returns

The SBML document, model and reader

petab.load_sbml_from_string(sbml_string: str)Tuple[libsbml.SBMLReader, libsbml.SBMLDocument, libsbml.Model]

Load SBML model from string

Parameters

sbml_string – Model as XML string

Returns

The SBML document, model and reader

petab.load_yaml(yaml_config: Union[Dict, str])Dict

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.log_sbml_errors(sbml_document: libsbml.SBMLDocument, minimum_severity=1)None

Log libsbml errors

Parameters
  • sbml_document – SBML document to check

  • minimum_severity – Minimum severity level to report (see libsbml)

petab.map_scale(parameters: Iterable[numbers.Number], scale_strs: Iterable[str])Iterable[numbers.Number]

As scale(), but for Iterables

petab.measurement_table_has_observable_parameter_numeric_overrides(measurement_df: pandas.core.frame.DataFrame)bool

Are there any numbers to override observable parameters?

Parameters

measurement_df – PEtab measurement table

Returns

True if there any numbers to override observable parameters, False otherwise.

petab.measurement_table_has_timepoint_specific_mappings(measurement_df: pandas.core.frame.DataFrame)bool

Are there time-point or replicate specific parameter assignments in the measurement table.

Parameters

measurement_df – PEtab measurement table

Returns

True if there are time-point or replicate specific parameter assignments in the measurement table, False otherwise.

petab.measurements_have_replicates(measurement_df: pandas.core.frame.DataFrame)bool

Tests whether the measurements come with replicates

Parameters

measurement_df – Measurement table

Returns

True if there are replicates, False otherwise

petab.merge_preeq_and_sim_pars(parameter_mappings: Iterable[Tuple[Dict[str, Union[str, numbers.Number]], Dict[str, Union[str, numbers.Number]]]], scale_mappings: Iterable[Tuple[Dict[str, str], Dict[str, str]]])Tuple[List[Tuple[Dict[str, Union[str, numbers.Number]], Dict[str, Union[str, numbers.Number]]]], List[Tuple[Dict[str, str], Dict[str, str]]]]

Merge preequilibration and simulation parameters and scales for a list of conditions while checking for compatibility.

Parameters
  • parameter_mappings – As returned by petab.get_optimization_to_simulation_parameter_mapping

  • scale_mappings – As returned by petab.get_optimization_to_simulation_scale_mapping.

Returns

The parameter and scale simulation mappings, modified and checked.

petab.merge_preeq_and_sim_pars_condition(condition_map_preeq: Dict[str, Union[str, numbers.Number]], condition_map_sim: Dict[str, Union[str, numbers.Number]], condition_scale_map_preeq: Dict[str, str], condition_scale_map_sim: Dict[str, str], condition: Any)None

Merge preequilibration and simulation parameters and scales for a single condition while checking for compatibility.

This function is meant for the case where we cannot have different parameters (and scales) for preequilibration and simulation. Therefore, merge both and ensure matching scales and parameters. condition_map_sim and condition_scale_map_sim will ne modified in place.

Parameters
  • condition_map_preeq – Parameter mapping as obtained from get_parameter_mapping_for_condition

  • condition_map_sim – Parameter mapping as obtained from get_parameter_mapping_for_condition

  • condition_scale_map_preeq – Parameter scale mapping as obtained from get_get_scale_mapping_for_condition

  • condition_scale_map_sim – Parameter scale mapping as obtained from get_get_scale_mapping_for_condition

  • condition – Condition identifier for more informative error messages

petab.normalize_parameter_df(parameter_df: pandas.core.frame.DataFrame)pandas.core.frame.DataFrame

Add missing columns and fill in default values.

petab.reduce(function, sequence[, initial])value

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

petab.sample_from_prior(prior: Tuple[str, list, str, list], n_starts: int)numpy.array

Creates samples for one parameter based on prior

Parameters
  • prior – A tuple as obtained from petab.parameter.get_priors_from_df

  • n_starts – Number of samples

Returns

Array with sampled values

petab.sample_noise(petab_problem: petab.problem.Problem, measurement_row: pandas.core.series.Series, simulated_value: float, noise_formulas: Optional[Dict[str, sympy.core.expr.Expr]] = None, rng: Optional[numpy.random._generator.Generator] = None, noise_scaling_factor: float = 1, zero_bounded: bool = False)float

Generate a sample from a PEtab noise distribution.

Parameters
  • petab_problem – The PEtab problem used to generate the simulated value. Instance of petab.Problem.

  • measurement_row – The row in the PEtab problem measurement table that corresponds to the simulated value.

  • simulated_value – A simulated value without noise.

  • noise_formulas – Processed noise formulas from the PEtab observables table, in the form output by the petab.calculate.get_symbolic_noise_formulas method.

  • rng – A NumPy random generator.

  • noise_scaling_factor – A multiplier of the scale of the noise distribution.

  • zero_bounded – Return zero if the sign of the return value and simulated_value differ. Can be used to ensure non-negative and non-positive values, if the sign of simulated_value should not change.

Returns

The sample from the PEtab noise distribution.

petab.sample_parameter_startpoints(parameter_df: pandas.core.frame.DataFrame, n_starts: int = 100, seed: Optional[int] = None)numpy.array

Create numpy.array with starting points for an optimization

Parameters
  • parameter_df – PEtab parameter DataFrame

  • n_starts – Number of points to be sampled

  • seed – Random number generator seed (see numpy.random.seed)

Returns

Array of sampled starting points with dimensions n_startpoints x n_optimization_parameters

petab.sbml_parameter_is_observable(sbml_parameter: libsbml.Parameter)bool

Returns whether the libsbml.Parameter sbml_parameter matches the defined observable format.

petab.sbml_parameter_is_sigma(sbml_parameter: libsbml.Parameter)bool

Returns whether the libsbml.Parameter sbml_parameter matches the defined sigma format.

petab.scale(parameter: numbers.Number, scale_str: str)numbers.Number

Scale parameter according to scale_str

Parameters
  • parameter – Parameter to be scaled.

  • scale_str – One of ‘lin’ (synonymous with ‘’), ‘log’, ‘log10’.

Returns

The scaled parameter.

Return type

parameter

petab.split_parameter_replacement_list(list_string: Union[str, numbers.Number], delim: str = ';')List[Union[str, float]]

Split values in observableParameters and noiseParameters in measurement table.

Parameters
  • list_string – delim-separated stringified list

  • delim – delimiter

Returns

List of split values. Numeric values converted to float.

petab.to_float_if_float(x: Any)Any

Return input as float if possible, otherwise return as is

Parameters

x – Anything

Returns

x as float if possible, otherwise x

petab.unique_preserve_order(seq: Sequence)List

Return a list of unique elements in Sequence, keeping only the first occurrence of each element

seq: Sequence to prune

Returns

List of unique elements in seq

petab.unscale(parameter: numbers.Number, scale_str: str)numbers.Number

Unscale parameter according to scale_str

Parameters
  • parameter – Parameter to be unscaled.

  • scale_str – One of ‘lin’ (synonymous with ‘’), ‘log’, ‘log10’.

Returns

The unscaled parameter.

Return type

parameter

petab.validate(yaml_config: Union[Dict, str], path_prefix: Optional[str] = None)

Validate syntax and semantics of PEtab config YAML

Parameters
  • yaml_config – PEtab YAML config as filename or dict.

  • path_prefix – Base location for relative paths. Defaults to location of YAML file if a filename was provided for yaml_config or the current working directory.

petab.validate_yaml_semantics(yaml_config: Union[Dict, str], path_prefix: Optional[str] = None)

Validate PEtab YAML file semantics

Check for existence of files. Assumes valid syntax.

Version number and contents of referenced files are not yet checked.

Parameters
  • yaml_config – PEtab YAML config as filename or dict.

  • path_prefix – Base location for relative paths. Defaults to location of YAML file if a filename was provided for yaml_config or the current working directory.

Raises

AssertionError – in case of problems

petab.validate_yaml_syntax(yaml_config: Union[Dict, str], schema: Union[None, Dict, str] = None)

Validate PEtab YAML file syntax

Parameters
  • yaml_config – PEtab YAML file to validate, as file name or dictionary

  • schema – Custom schema for validation

Raises

see jsonschema.validate

petab.warn(message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

petab.write_condition_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab condition table

Parameters
  • df – PEtab condition table

  • filename – Destination file name

petab.write_measurement_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab measurement table

Parameters
  • df – PEtab measurement table

  • filename – Destination file name

petab.write_observable_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab observable table

Parameters
  • df – PEtab observable table

  • filename – Destination file name

petab.write_parameter_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab parameter table

Parameters
  • df – PEtab parameter table

  • filename – Destination file name

petab.write_sbml(sbml_doc: libsbml.SBMLDocument, filename: str)None

Write PEtab visualization table

Parameters
  • sbml_doc – SBML document containing the SBML model

  • filename – Destination file name

petab.write_simulation_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab simulation table

Parameters
  • df – PEtab simulation table

  • filename – Destination file name

petab.write_visualization_df(df: pandas.core.frame.DataFrame, filename: str)None

Write PEtab visualization table

Parameters
  • df – PEtab visualization table

  • filename – Destination file name

petab.write_yaml(yaml_config: Dict[str, Any], filename: str)None

Write PEtab YAML file

Parameters
  • yaml_config – Data to write

  • filename – File to create