petab_select

Model selection extension for PEtab.

class petab_select.BackwardCandidateSpace(*args, predecessor_model=None, max_steps=None, **kwargs)[source]

The backward method class.

__init__(*args, predecessor_model=None, max_steps=None, **kwargs)

See class attributes for arguments.

accept(model, distance)

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

consider(model)

Add a candidate model, if it should be added.

Parameters:

model (Model | None) – The candidate model. This value may be None if the ModelSubspace decided to exclude the model that would have been sent.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if the limit of the number of accepted models has been reached, then no further models should be sent.

distance(model)

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()

Get the limit on the number of accepted models.

Return type:

float | int

get_predecessor_model()

Get the predecessor model.

Return type:

str | Model

is_plausible(model)

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

n_accepted()

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)

Parse settings that were stored in YAML.

Parameters:

yaml_dict (dict[str, str]) – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict[str, str | Model]

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)

Set the predecessor model.

See class attributes for arguments.

update_after_calibration(*args, iteration_calibrated_models, **kwargs)

Do work in the candidate space after calibration.

For example, this is used by the FamosCandidateSpace to switch methods.

Different candidate spaces require different arguments. All arguments are here, to ensure candidate spaces can be switched easily and still receive sufficient arguments.

wrap_search_subspaces(search_subspaces)

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces (Callable[[], None]) – The method that searches the subspaces of a model space.

Return type:

Callable

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.BruteForceCandidateSpace(*args, **kwargs)[source]

The brute-force method class.

__init__(*args, **kwargs)[source]

See class attributes for arguments.

accept(model, distance)

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

consider(model)

Add a candidate model, if it should be added.

Parameters:

model (Model | None) – The candidate model. This value may be None if the ModelSubspace decided to exclude the model that would have been sent.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if the limit of the number of accepted models has been reached, then no further models should be sent.

distance(model)

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

None | float | int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()

Get the limit on the number of accepted models.

Return type:

float | int

get_predecessor_model()

Get the predecessor model.

Return type:

str | Model

is_plausible(model)

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

n_accepted()

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)

Parse settings that were stored in YAML.

Parameters:

yaml_dict (dict[str, str]) – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict[str, str | Model]

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)

Set the predecessor model.

See class attributes for arguments.

update_after_calibration(*args, iteration_calibrated_models, **kwargs)

Do work in the candidate space after calibration.

For example, this is used by the FamosCandidateSpace to switch methods.

Different candidate spaces require different arguments. All arguments are here, to ensure candidate spaces can be switched easily and still receive sufficient arguments.

wrap_search_subspaces(search_subspaces)

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces (Callable[[], None]) – The method that searches the subspaces of a model space.

Return type:

Callable

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.CandidateSpace(method, criterion, predecessor_model=None, excluded_hashes=None, limit=inf, summary_tsv=None, previous_predecessor_model=None, calibrated_models=None, iteration=0)[source]

A base class for collecting candidate models.

The intended use of subclasses is to identify suitable models in a model space, that will be provided to a model selection method for selection.

criterion

The criterion by which models are compared.

distances

The distances of all candidate models from the initial model.

predecessor_model

The model used for comparison, e.g. for stepwise methods.

previous_predecessor_model

The previous predecessor model.

excluded_hashes

A list of model hashes that will not be accepted into the candidate space. The hashes of accepted models are added to :attr:excluded_hashes.

governing_method

Used to store the search method that governs the choice of method during a search. In some cases, this is always the same as the method attribute. An example of a difference is in the bidirectional method, where governing_method stores the bidirectional method, whereas method may also store the forward or backward methods.

iteration

The iteration of model selection.

limit

A handler to limit the number of accepted models.

models

The current set of candidate models.

method

The model selection method of the candidate space.

predecessor_model

The model used for comparison, e.g. for stepwise methods.

previous_predecessor_model

The previous predecessor model.

retry_model_space_search_if_no_models

Whether a search with a candidate space should be repeated upon failure. Useful for the BidirectionalCandidateSpace, which switches directions upon failure.

summary_tsv

A string or pathlib.Path. A summary of the model selection progress will be written to this file.

calibrated_models

All models that have been calibrated across all iterations of model selection.

latest_iteration_calibrated_models

The calibrated models from the most recent iteration.

__init__(method, criterion, predecessor_model=None, excluded_hashes=None, limit=inf, summary_tsv=None, previous_predecessor_model=None, calibrated_models=None, iteration=0)[source]

See class attributes for arguments.

accept(model, distance)[source]

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

consider(model)[source]

Add a candidate model, if it should be added.

Parameters:

model (Model | None) – The candidate model. This value may be None if the ModelSubspace decided to exclude the model that would have been sent.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if the limit of the number of accepted models has been reached, then no further models should be sent.

distance(model)[source]

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

None | float | int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)[source]

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)[source]

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()[source]

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)[source]

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()[source]

Get the limit on the number of accepted models.

Return type:

float | int

get_predecessor_model()[source]

Get the predecessor model.

Return type:

str | Model

is_plausible(model)[source]

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

n_accepted()[source]

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)[source]

Parse settings that were stored in YAML.

Parameters:

yaml_dict (dict[str, str]) – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict[str, str | Model]

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)[source]

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()[source]

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)[source]

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)[source]

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)[source]

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)[source]

Set the predecessor model.

See class attributes for arguments.

update_after_calibration(*args, iteration_calibrated_models, **kwargs)[source]

Do work in the candidate space after calibration.

For example, this is used by the FamosCandidateSpace to switch methods.

Different candidate spaces require different arguments. All arguments are here, to ensure candidate spaces can be switched easily and still receive sufficient arguments.

wrap_search_subspaces(search_subspaces)[source]

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces (Callable[[], None]) – The method that searches the subspaces of a model space.

Return type:

Callable

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)[source]

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.Criterion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

String literals for model selection criteria.

AIC = 'AIC'

The Akaike information criterion.

AICC = 'AICc'

The corrected Akaike information criterion.

BIC = 'BIC'

The Bayesian information criterion.

LH = 'LH'

The likelihood.

LLH = 'LLH'

The log-likelihood.

NLLH = 'NLLH'

The negative log-likelihood.

SSR = 'SSR'

The sum of squared residuals.

__init__(*args, **kwds)
class petab_select.CriterionComputer(model)[source]

Compute various criteria.

__init__(model)[source]
get_aic()[source]

Get the Akaike information criterion.

Return type:

float

get_aicc()[source]

Get the corrected Akaike information criterion.

Return type:

float

get_bic()[source]

Get the Bayesian information criterion.

Return type:

float

get_lh()[source]

Get the likelihood.

Return type:

float

get_llh()[source]

Get the log-likelihood.

Return type:

float

get_n_estimated()[source]

Get the number of estimated parameters.

Return type:

int

get_n_measurements()[source]

Get the number of measurements.

Return type:

int

get_n_priors()[source]

Get the number of priors.

Return type:

int

get_nllh()[source]

Get the negative log-likelihood.

Return type:

float

property petab_problem: Problem

The PEtab problem that corresponds to the model.

Implemented as a property such that the petab.Problem object is only constructed if explicitly requested.

Improves speed of operations on models by a lot. For example, analysis of models that already have criteria computed can skip loading their PEtab problem again.

class petab_select.FamosCandidateSpace(*args, predecessor_model=None, critical_parameter_sets=[], swap_parameter_sets=[], method_scheme=None, n_reattempts=0, consecutive_laterals=False, **kwargs)[source]

The FAMoS method class.

This candidate space implements and extends the original FAMoS algorithm (doi: 10.1371/journal.pcbi.1007230).

critical_parameter_sets

A list of lists, where each inner list contains parameter IDs. All models must estimate at least 1 parameter from each critical parameter set.

swap_parameter_sets

A list of lists, where each inner list contains parameter IDs. The lateral moves in FAMoS are constrained to be between parameters that exist in the same swap parameter set.

method_scheme

A dictionary that specifies how to switch between methods when the current method doesn’t produce a better model. Keys are n-tuples that described a pattern of length n methods. Values are methods. If the previous methods match the pattern in the key, then the method in the value will be used next. The order of the dictionary is important: only the first matched pattern will be used. Defaults to the method scheme described in the original FAMoS publication.

n_reattempts

Integer. The total number of times that a jump-to-most-distance action will be performed, triggered whenever the model selection would normally terminate. Defaults to no reattempts (0).

consecutive_laterals

Boolean. If True, the method will continue performing lateral moves while they produce better models. Otherwise, the method scheme will be applied after one lateral move.

__init__(*args, predecessor_model=None, critical_parameter_sets=[], swap_parameter_sets=[], method_scheme=None, n_reattempts=0, consecutive_laterals=False, **kwargs)[source]

See class attributes for arguments.

accept(model, distance)

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

check_critical(model)[source]

Check if the model contains all necessary critical parameters

Return type:

bool

check_swap(model)[source]

Check if parameters that are swapped are contained in the same swap parameter set.

Return type:

bool

consider(model)[source]

Re-define consider of FAMoS to be the consider method of the inner_candidate_space. Update all the attributes changed in the consider method.

Return type:

bool

distance(model)

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

None | float | int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()

Get the limit on the number of accepted models.

Return type:

float | int

get_most_distant()[source]

Get most distant model to all the checked models. We take models from the sorted list of best models (self.best_models) and construct complements of these models. For all these complements we compute the distance in number of different estimated parameters to all models from history. For each complement we take the minimum of these distances as it’s distance to history. Then we choose the complement model with the maximal distance to history.

TODO: Next we check if this model is contained in any subspace. If so we choose it. If not we choose the model in a subspace that has least distance to this complement model.

Return type:

Model

get_predecessor_model()

Get the predecessor model.

Return type:

str | Model

insert_model_into_best_models(model_to_insert)[source]

Inserts a model into the list of best_models which are sorted w.r.t. the criterion specified.

Return type:

None

is_plausible(model)[source]

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

jump_to_most_distant()[source]

Jump to most distant model with respect to the history of all calibrated models.

n_accepted()

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)[source]

Parse settings that were stored in YAML.

Parameters:

yaml_dict – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)

Set the predecessor model.

See class attributes for arguments.

switch_inner_candidate_space(excluded_hashes)[source]

Switch the inner candidate space to match the current method.

Parameters:

excluded_hashes (list[ModelHash]) – Hashes of excluded models.

switch_method()[source]

Switch to the next method with respect to the history of methods used and the switching scheme in self.method_scheme.

Return type:

None

update_after_calibration(*args, iteration_calibrated_models, **kwargs)[source]

See CandidateSpace.update_after_calibration.

Return type:

None

update_from_iteration_calibrated_models(iteration_calibrated_models)[source]

Update self.best_models with the latest iteration_calibrated_models and determine if there was a new best model. If so, return False. True otherwise.

Return type:

bool

update_method(method)[source]

Update self.method to method.

wrap_search_subspaces(search_subspaces)[source]

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces – The method that searches the subspaces of a model space.

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.ForwardCandidateSpace(*args, predecessor_model=None, max_steps=None, **kwargs)[source]

The forward method class.

direction

1 for the forward method, -1 for the backward method.

max_steps

Maximum number of steps forward in a single iteration of forward selection. Defaults to no maximum (None).

__init__(*args, predecessor_model=None, max_steps=None, **kwargs)[source]

See class attributes for arguments.

accept(model, distance)

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

consider(model)

Add a candidate model, if it should be added.

Parameters:

model (Model | None) – The candidate model. This value may be None if the ModelSubspace decided to exclude the model that would have been sent.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if the limit of the number of accepted models has been reached, then no further models should be sent.

distance(model)[source]

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()

Get the limit on the number of accepted models.

Return type:

float | int

get_predecessor_model()

Get the predecessor model.

Return type:

str | Model

is_plausible(model)[source]

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

n_accepted()

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)

Parse settings that were stored in YAML.

Parameters:

yaml_dict (dict[str, str]) – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict[str, str | Model]

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)

Set the predecessor model.

See class attributes for arguments.

update_after_calibration(*args, iteration_calibrated_models, **kwargs)

Do work in the candidate space after calibration.

For example, this is used by the FamosCandidateSpace to switch methods.

Different candidate spaces require different arguments. All arguments are here, to ensure candidate spaces can be switched easily and still receive sufficient arguments.

wrap_search_subspaces(search_subspaces)

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces (Callable[[], None]) – The method that searches the subspaces of a model space.

Return type:

Callable

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.LateralCandidateSpace(*args, max_steps=None, **kwargs)[source]

Find models with the same number of estimated parameters.

__init__(*args, max_steps=None, **kwargs)[source]
Additional args:
max_number_of_steps:

Maximal allowed number of swap moves. If 0 then there is no maximum.

accept(model, distance)

Add a candidate model to the candidate space.

Parameters:
  • model (Model) – The model that will be added.

  • distance (None | float | int) – The distance of the model from the predecessor model.

Return type:

None

consider(model)

Add a candidate model, if it should be added.

Parameters:

model (Model | None) – The candidate model. This value may be None if the ModelSubspace decided to exclude the model that would have been sent.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if the limit of the number of accepted models has been reached, then no further models should be sent.

distance(model)

Compute the distance between two models that are neighbors.

Parameters:

model (Model) – The candidate model.

Return type:

None | float | int

Returns:

The distance from self.predecessor_model to model, or None if the distance should not be computed.

distances_in_estimated_parameters(model, predecessor_model=None)

Distance between two models in model space, using different metrics.

All metrics are in terms of estimated parameters.

Metrics:
l1:

The L_1 distance between two models.

size:

The difference in the number of estimated parameters between two models.

Parameters:
  • model (Model) – The candidate model.

  • predecessor_model (Model | None) – See class attributes.

Return type:

dict[str, float | int]

Returns:

The distances between the models, as a dictionary, where a key is the name of the metric, and the value is the corresponding distance.

excluded(model_hash)

Check whether a model is excluded.

Parameters:

model – The model.

Return type:

bool

Returns:

True if the model is excluded, otherwise False.

get_excluded_hashes()

Get the excluded hashes.

Return type:

set[ModelHash]

Returns:

The hashes of excluded models.

get_iteration_calibrated_models(calibrated_models, reset=False)

Get all calibrated models for the current iteration.

The full list of models identified for calibration in an iteration of model selection may include models for which calibration results are already available. This combines the calibration results of the uncalibrated models, with the models that were already calibrated, to produce the full list of models that were identified for calibration in the current iteration.

Parameters:
  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration. Keys are model hashes, values are models.

  • reset (bool) – Whether to remove the previously calibrated models from the candidate space, after they are used to produce the full list of calibrated models.

  • iteration – If provided, the iteration attribute of each model will be set to this.

Return type:

Models

Returns:

All calibrated models for the current iteration.

get_limit()

Get the limit on the number of accepted models.

Return type:

float | int

get_predecessor_model()

Get the predecessor model.

Return type:

str | Model

is_plausible(model)[source]

Determine whether a candidate model is plausible.

A plausible model is one that could possibly be chosen by model selection method, in the absence of information about other models in the model space.

For example, given a forward selection method that starts with an initial model self.predecessor_model that has no estimated parameters, then only models with one or more estimated parameters are plausible.

Parameters:

model (Model) – The candidate model.

Return type:

bool

Returns:

True if model is plausible, else False.

n_accepted()

Get the current number of accepted models.

Return type:

int

Returns:

The number of models.

classmethod read_arguments_from_yaml_dict(yaml_dict)

Parse settings that were stored in YAML.

Parameters:

yaml_dict (dict[str, str]) – The information that was read from the YAML file. Keys are class attributes, values are the corresponding values.

Return type:

dict[str, str | Model]

Returns:

The settings, parsed into PEtab Select objects where possible.

reset(predecessor_model=None, excluded_hashes=None, limit=None)

Reset the candidate models, optionally reinitialize with a model.

Parameters:
  • predecessor_model (Model | None) – The initial model.

  • excluded_hashes (list[ModelHash] | None) – These hashes will extend the current excluded hashes.

  • limit (float | int) – The new upper limit of the number of models in this candidate space. Defaults to the previous limit.

Return type:

None

reset_accepted()

Reset the accepted models.

Return type:

None

set_excluded_hashes(hashes, extend=False)

Set the excluded hashes.

Parameters:
Return type:

None

set_iteration_user_calibrated_models(user_calibrated_models)

Hide previously-calibrated models from the calibration tool.

This allows previously-calibrated model results, e.g. from a previous model selection job, to be re-used in this job. Calibrated models are stored here between model selection iterations, while the calibration tool calibrates the uncalibrated models of the iteration. The models are then combined as the full model calibration results for the iteration, with get_iteration_calibrated_models().

Parameters:

user_calibrated_models (Models | None) – The previously-calibrated models.

Return type:

None

set_limit(limit=None)

Set the limit on the number of accepted models.

Parameters:

limit (float | int) – The limit.

Return type:

None

set_predecessor_model(predecessor_model)

Set the predecessor model.

See class attributes for arguments.

update_after_calibration(*args, iteration_calibrated_models, **kwargs)

Do work in the candidate space after calibration.

For example, this is used by the FamosCandidateSpace to switch methods.

Different candidate spaces require different arguments. All arguments are here, to ensure candidate spaces can be switched easily and still receive sufficient arguments.

wrap_search_subspaces(search_subspaces)

Decorate the subspace searches of a model space.

Used by candidate spaces to perform changes that alter the search. See BidirectionalCandidateSpace for an example, where it’s used to switch directions.

Parameters:

search_subspaces (Callable[[], None]) – The method that searches the subspaces of a model space.

Return type:

Callable

Returns:

The wrapped search_subspaces.

write_summary_tsv(row)

Write the summary of the last iteration to a TSV file.

The destination is defined in self.summary_tsv.

Parameters:

row (list[Any]) – The row that will be written to disk.

class petab_select.Method(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

String literals for model selection methods.

BACKWARD = 'backward'

The backward stepwise method.

BRUTE_FORCE = 'brute_force'

The brute-force method.

FAMOS = 'famos'

The FAMoS method.

FORWARD = 'forward'

The forward stepwise method.

LATERAL = 'lateral'

The lateral, or swap, method.

MOST_DISTANT = 'most_distant'

The jump-to-most-distant-model method.

__init__(*args, **kwds)
class petab_select.Model(**data)[source]

A model.

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

compute_criterion(criterion, raise_on_failure=True)[source]

Compute a criterion value for the model.

The value will also be stored, which will overwrite any previously stored value for the criterion.

Parameters:
  • criterion (Criterion) – The criterion.

  • raise_on_failure (bool) – Whether to raise a ValueError if the criterion could not be computed. If False, None is returned.

Return type:

float

Returns:

The criterion value.

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to include in the copied model.

  • exclude (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to exclude in the copied model.

  • update (Optional[Dict[str, Any]]) – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.

Return type:

Self

Returns:

A copy of the model with included, excluded and updated fields as specified.

criteria: dict[Criterion, float]

The criterion values of the calibrated model (e.g. AIC).

estimated_parameters: dict[str, float] | None

The parameter estimates of the calibrated model (always unscaled).

static from_yaml(filename, model_subspace_petab_problem=None)[source]

Load a model from a YAML file.

Parameters:
  • filename (Union[str, Path]) – The filename.

  • model_subspace_petab_problem (Problem | None) – A preloaded copy of the PEtab problem of the model subspace that this model belongs to.

Return type:

Model

get_criterion(criterion, compute=True, raise_on_failure=True)[source]

Get a criterion value for the model.

Parameters:
  • criterion (Criterion) – The criterion.

  • compute (bool) – Whether to attempt computing the criterion value. For example, the AIC can be computed if the likelihood is available.

  • raise_on_failure (bool) – Whether to raise a ValueError if the criterion could not be computed. If False, None is returned.

Return type:

float | None

Returns:

The criterion value, or None if it is not available.

get_estimated_parameter_ids(full=True)[source]

Get estimated parameter IDs.

Parameters:

full (bool) – Whether to provide all IDs, including additional parameters that are not part of the model selection problem but estimated.

Return type:

list[str]

get_hash()[source]

Deprecated. Use Model.hash instead.

Return type:

ModelHash

get_parameter_values(parameter_ids=None)[source]

Get parameter values.

Includes ESTIMATE for parameters that should be estimated.

Parameters:

parameter_ids (list[str] | None) – The IDs of parameters that values will be returned for. Order is maintained. Defaults to the model subspace PEtab problem parameters (including those not part of the model selection problem).

Return type:

list[Union[float, int, Literal['estimate']]]

Returns:

The values of parameters.

has_criterion(criterion)[source]

Check whether a value for a criterion has been set.

Return type:

bool

property hash: ModelHash

Get the model hash.

iteration: int | None

The iteration of model selection that calibrated this model.

model_config: ClassVar[ConfigDict] = {}

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

classmethod model_construct(_fields_set=None, **values)

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set (set[str] | None) – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values (Any) – Trusted or pre-validated data dictionary.

Return type:

Self

Returns:

A new instance of the Model class with validated data.

model_copy(*, update=None, deep=False)
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Return type:

Self

Returns:

New model instance.

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode (Union[Literal['json', 'python'], str]) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to include in the output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to exclude from the output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model.

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to include in the JSON output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to exclude from the JSON output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to serialize using field aliases.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

str

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

model_hash: ModelHash

The model hash (treat as read-only after initialization).

model_id: str

The model ID.

classmethod model_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=<class 'pydantic.json_schema.GenerateJsonSchema'>, mode='validation', *, union_format='any_of')

Generates a JSON schema for a model class.

Parameters:
  • by_alias (bool) – Whether to use attribute aliases or not.

  • ref_template (str) – The reference template.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.

Return type:

dict[str, Any]

Returns:

The JSON schema for the given model class.

model_label: str | None

The model label (e.g. for plotting).

classmethod model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Return type:

str

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(_Model__context)[source]

Add additional instance attributes.

Return type:

None

classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force (bool) – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors (bool) – Whether to raise errors, defaults to True.

  • _parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.

  • _types_namespace (Mapping[str, Any] | None) – The types namespace, defaults to None.

Return type:

bool | None

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

model_subspace_id: str

The ID of the subspace that this model belongs to.

model_subspace_indices: list[int]

The location of this model in its subspace.

model_subspace_petab_yaml: Path | None

The location of the base PEtab problem for the model subspace.

N.B.: Not the PEtab problem for this model specifically! Use Model.to_petab() to get the model-specific PEtab problem.

classmethod model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None)

Validate a pydantic model instance.

Parameters:
  • obj (Any) – The object to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes (bool | None) – Whether to extract data from object attributes.

  • context (Any | None) – Additional context to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Return type:

Self

Returns:

The validated model instance.

classmethod model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data (str | bytes | bytearray) – The JSON data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj (Any) – The object containing string data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

parameters: dict[str, float | int | Literal[ESTIMATE]]

PEtab problem parameters overrides for this model.

For example, fixes parameters to certain values, or sets them to be estimated.

predecessor_model_hash: ModelHash

The predecessor model hash.

resolve_paths(root_path)

Resolve all paths to be relative to root_path.

Return type:

None

set_criterion(criterion, value)[source]

Set a criterion value.

Return type:

None

set_estimated_parameters(estimated_parameters, scaled=False)[source]

Set parameter estimates.

Parameters:
  • estimated_parameters (dict[str, float]) – The estimated parameters.

  • scaled (bool) – Whether the parameter estimates are on the scale defined in the PEtab problem (True), or unscaled (False).

Return type:

None

set_relative_paths(root_path)

Change all paths to be relative to root_path.

Return type:

None

to_petab(output_path=None, set_estimated_parameters=None)[source]

Generate the PEtab problem for this model.

Parameters:
  • output_path (Union[str, Path]) – If specified, the PEtab tables will be written to disk, inside this directory.

  • set_estimated_parameters (bool | None) – Whether to implement Model.estimated_parameters as the nominal values of the PEtab problem parameter table. Defaults to True if Model.estimated_parameters is set.

Return type:

dict[str, Union[Problem, str, Path]]

Returns:

The PEtab problem. Also returns the path of the PEtab problem YAML file, if output_path is specified.

to_yaml(filename)

Save a model to a YAML file.

All paths will be made relative to the filename directory.

Parameters:

filename (Union[str, Path]) – Location of the YAML file.

Return type:

None

class petab_select.ModelHash(**data)[source]

The model hash.

The model hash is designed to be human-readable and able to be converted back into the corresponding model. Currently, if two models from two different model subspaces are actually the same PEtab problem, they will still have different model hashes.

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to include in the copied model.

  • exclude (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to exclude in the copied model.

  • update (Optional[Dict[str, Any]]) – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.

Return type:

Self

Returns:

A copy of the model with included, excluded and updated fields as specified.

get_model(problem)[source]

Get the model that a hash corresponds to.

Parameters:

problem (Problem) – The Problem that will be used to look up the model.

Return type:

Model

Returns:

The model.

static hash_model_subspace_indices(model_subspace_indices)[source]

Hash the location of a model in its subspace.

Parameters:

model_subspace_indices (list[int]) – The location (indices) of the model in its subspace.

Return type:

str

Returns:

The hash.

static kwargs_from_str(hash_str)[source]

Convert a model hash string into constructor kwargs.

Return type:

dict[str, str]

model_config: ClassVar[ConfigDict] = {}

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

classmethod model_construct(_fields_set=None, **values)

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set (set[str] | None) – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values (Any) – Trusted or pre-validated data dictionary.

Return type:

Self

Returns:

A new instance of the Model class with validated data.

model_copy(*, update=None, deep=False)
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Return type:

Self

Returns:

New model instance.

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode (Union[Literal['json', 'python'], str]) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to include in the output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to exclude from the output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model.

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to include in the JSON output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to exclude from the JSON output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to serialize using field aliases.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

str

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=<class 'pydantic.json_schema.GenerateJsonSchema'>, mode='validation', *, union_format='any_of')

Generates a JSON schema for a model class.

Parameters:
  • by_alias (bool) – Whether to use attribute aliases or not.

  • ref_template (str) – The reference template.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.

Return type:

dict[str, Any]

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Return type:

str

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context, /)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Return type:

None

classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force (bool) – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors (bool) – Whether to raise errors, defaults to True.

  • _parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.

  • _types_namespace (Mapping[str, Any] | None) – The types namespace, defaults to None.

Return type:

bool | None

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

model_subspace_id: str

The ID of the model subspace of the model.

Unique up to a single model space.

model_subspace_indices_hash: str

A hash of the location of the model in its model subspace.

Unique up to a single model subspace.

classmethod model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None)

Validate a pydantic model instance.

Parameters:
  • obj (Any) – The object to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes (bool | None) – Whether to extract data from object attributes.

  • context (Any | None) – Additional context to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Return type:

Self

Returns:

The validated model instance.

classmethod model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data (str | bytes | bytearray) – The JSON data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj (Any) – The object containing string data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

unhash_model_subspace_indices()[source]

Get the location of a model in its subspace.

Return type:

list[int]

Returns:

The location, as indices of the subspace.

class petab_select.ModelSpace(model_subspaces)[source]

A model space, as a collection of model subspaces.

model_subspaces

List of model subspaces.

exclusions

Hashes of models that are excluded from the model space.

__init__(model_subspaces)[source]
static load(data, root_path=None)[source]

Load a model space from dataframe(s) or file(s).

Parameters:
  • data (str | Path | DataFrame | list[str | Path | DataFrame]) – The data. TSV file(s) or pandas dataframe(s).

  • root_path (str | Path) – Any paths in dataframe will be resolved relative to this path. Paths in TSV files will be resolved relative to the directory of the TSV file.

Return type:

ModelSpace

Returns:

The model space.

reset_exclusions(exclusions=None)[source]

Reset the exclusions in the model subspaces.

Return type:

None

save(filename=None)[source]

Export the model space to a dataframe (and TSV).

Parameters:

filename (str | Path | None) – If provided, the dataframe will be saved here as a TSV. Paths will be made relative to the parent directory of this filename.

Return type:

DataFrame

Returns:

The dataframe.

search(candidate_space, limit=inf, exclude=True)[source]

Search all model subspaces according to a candidate space method.

Parameters:
  • candidate_space (CandidateSpace) – The candidate space.

  • limit (int) – The maximum number of models to send to the candidate space (i.e. this limit is on the number of models considered, not necessarily approved as candidates). Note that using a limit may produce unexpected results. For example, it may bias candidate models to be chosen only from a subset of model subspaces.

  • exclude (bool) – Whether to exclude the new candidates from the model subspaces.

class petab_select.ModelSubspace(model_subspace_id, petab_yaml, parameters, exclusions=None)[source]

Efficient representation of exponentially large model subspaces.

model_subspace_id

The ID of the model subspace.

petab_yaml

The location of the PEtab problem YAML file.

parameters

The key is the ID of the parameter. The value is a list of values that the parameter can take (including ESTIMATE).

exclusions

Hashes of models that have been previously submitted to a candidate space for consideration (CandidateSpace.consider()).

__init__(model_subspace_id, petab_yaml, parameters, exclusions=None)[source]
property can_estimate: list[str]

Parameters that can be estimated, according to the subspace.

Parameters that are estimated as part of the PEtab problem are not considered.

property can_estimate_all: list[str]

All parameters than can be estimated in this subspace.

property can_fix: list[str]

Parameters that can be fixed, according to the subspace.

Parameters that are fixed as part of the PEtab problem are not considered.

property can_fix_all: list[str]

All arameters that can be fixed, according to the subspace.

check_compatibility_stepwise_method(candidate_space)[source]

Check whether a candidate space is compatible with this subspace.

Directional methods (e.g. forward, backward) are not supported among different PEtab problems.

Parameters:

candidate_space (CandidateSpace) – The candidate space with a stepwise method.

Return type:

bool

Returns:

Whether the candidate space is compatible.

exclude_model(model)[source]

Exclude a model from the model subspace.

Models are excluded in ModelSubspace.indices_to_model, which contains the only call to Model.__init__ in the ModelSubspace class.

Parameters:

model (Model) – The model that will be excluded.

Return type:

None

exclude_model_hash(model_hash)[source]

Exclude a model hash from the model subspace.

Parameters:

model_hash (str) – The model hash.

Return type:

None

exclude_model_hashes(model_hashes)[source]

Exclude model hashes from the model subspace.

Parameters:

model_hashes (Iterable[str]) – The model hashes.

Return type:

None

exclude_models(models)[source]

Exclude models from the model subspace.

Models are excluded in ModelSubspace.indices_to_model(), which contains the only call to Model.__init__() in the ModelSubspace class.

Parameters:

models (Iterable[Model]) – The models that will be excluded.

Return type:

None

excluded(model)[source]

Whether a model is excluded.

Return type:

bool

static from_definition(definition, root_path=None)[source]

Create a ModelSubspace from a definition.

Parameters:
  • definition (dict[str, str] | Series) – A description of the model subspace. Keys are properties of the model subspace, including parameters that can take different values.

  • root_path (str | Path) – Any paths will be resolved relative to this path.

Return type:

ModelSubspace

Returns:

The model subspace.

get_estimated(additional_parameters=None)[source]

Get the IDs of parameters that are estimated.

Parameters:

additional_parameters (dict[str, Union[float, int, Literal['estimate']]] | None) – A specific parameterization that will take priority when determining estimated parameters.

Return type:

list[str]

Returns:

The parameter IDs.

get_models(estimated_parameters)[source]

Get models in the subspace by estimated parameters.

All models that have the provided estimated_parameters are returned.

Parameters:

estimated_parameters (list[str]) –

The IDs of parameters that are estimated in the model. All other parameters will be fixed. Note that these parameters are in the subset of PEtab parameters that exist in the model subspace definition. Parameters in the PEtab problem but not the model subspace definition should not be included here.

FIXME(dilpath) TODO support the full set of PEtab parameters? Then would need to turn off estimation for parameters that are not provided in estimated_parameters – maybe unexpected for users.

Return type:

Iterator[Model]

Returns:

A list of models.

indices_to_model(indices)[source]

Get a model from the subspace, by indices of possible parameter values.

Model exclusions are handled here.

Parameters:

indices (list[int]) – The indices of the lists in the values of the ModelSubspace.parameters dictionary, ordered by the keys of this dictionary.

Return type:

Model | None

Returns:

A model with the PEtab problem of this subspace and the parameterization that corresponds to the indices. None, if the model is excluded from the subspace.

indices_to_parameters(indices)[source]

Convert parameter indices to values.

Parameters:

indices (list[int]) – See ModelSubspace.indices_to_model().

Return type:

dict[str, Union[float, int, Literal['estimate']]]

Returns:

The parameterization that corresponds to the indices.

property must_estimate: list[str]

Subspace parameters that must be estimated.

Does not include parameters that are estimated in the PEtab parameters table.

property must_estimate_all: list[str]

All parameters that must be estimated in this subspace.

property must_fix: list[str]

Subspace parameters that must be fixed.

Parameters that are fixed as part of the PEtab problem are not considered.

property must_fix_all: list[str]

All parameters that must be fixed in this subspace.

property parameters_all: dict[str, float | int | Literal['estimate']]

Get all parameters, including those only in the PEtab problem.

Parameter values in the PEtab problem are overwritten by the model subspace values.

parameters_to_indices(parameters)[source]

Convert parameter values to indices.

Parameters:

parameters (dict[str, Union[float, int, Literal['estimate']]]) – Keys are parameter IDs, values are parameter values.

Returns:

The indices of the subspace that correspond to the parameterization.

parameters_to_model(parameters)[source]

Convert parameter values to a model.

Parameters:

parameters (dict[str, Union[float, int, Literal['estimate']]]) – Keys are parameter IDs, values are parameter values.

Return type:

Model | None

Returns:

A model with the PEtab problem of this subspace and the parameterization. None, if the model is excluded from the subspace.

search(candidate_space, limit=inf)[source]

Search for candidate models in this model subspace.

Nothing is returned, as the result is managed by the candidate_space.

Parameters:
  • candidate_space (CandidateSpace) – The candidate space.

  • limit (int) – Limit the number of models.

send_model_to_candidate_space(model, candidate_space, exclude=False)[source]

Send a model to a candidate space for consideration.

Parameters:
  • model (Model) – The model.

  • candidate_space (CandidateSpace) – The candidate space.

  • exclude (bool | None) – Whether to add the model to the exclusions.

Return type:

bool

Returns:

Whether it is OK to send additional models to the candidate space. For example, if len(candidate_space.models) == candidate_space.limit, then no further models should be sent.

to_definition(root_path=None)[source]

Get the definition of the model subspace.

Parameters:

root_path (str | Path | None) – If provided, the model_subspace_petab_yaml will be made relative to this path.

Return type:

Series

Returns:

The definition.

class petab_select.Models(root=PydanticUndefined, **data)[source]

A collection of models.

__init__(root=PydanticUndefined, **data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

append(item)

S.append(value) – append value to the end of the sequence

Return type:

None

clear() None -- remove all items from S
copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to include in the copied model.

  • exclude (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to exclude in the copied model.

  • update (Optional[Dict[str, Any]]) – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.

Return type:

Self

Returns:

A copy of the model with included, excluded and updated fields as specified.

count(value) integer -- return number of occurrences of value
property df: DataFrame

Get a dataframe of model attributes.

extend(other)

S.extend(iterable) – extend sequence by appending elements from the iterable

Return type:

None

static from_yaml(filename, model_subspace_petab_problem=None, problem=None)[source]

Load models from a YAML file.

Parameters:
  • filename (str | Path) – Location of the YAML file.

  • model_subspace_petab_problem (Problem) – A preloaded copy of the PEtab problem. N.B.: all models should share the same PEtab problem if this is provided (e.g. all models belong to the same model subspace, or all model subspaces have the same model_subspace_petab_yaml in the model space file(s)).

  • problem (Problem) – The PEtab Select problem. N.B.: all models should belong to the same PEtab Select problem if this is provided.

Return type:

Models

Returns:

The models.

get_criterion(criterion, as_dict=False, relative=False)[source]

Get the criterion value for all models.

Parameters:
  • criterion (Criterion) – The criterion.

  • as_dict (bool) – Whether to return a dictionary, with model hashes for keys.

  • relative (bool) – Whether to compute criterion values relative to the smallest criterion value.

Return type:

list[float] | dict[ModelHash, float]

Returns:

The criterion values.

index(item, *args)

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

Return type:

int

insert(index, item)

S.insert(index, value) – insert value before index

lint()[source]

Lint the models, e.g. check all hashes are unique.

Currently raises an exception when invalid.

model_config: ClassVar[ConfigDict] = {}

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

classmethod model_construct(root, _fields_set=None)

Create a new model using the provided root object and update fields set.

Parameters:
  • root (TypeVar(RootModelRootType)) – The root object of the model.

  • _fields_set (set[str] | None) – The set of fields to be updated.

Return type:

Self

Returns:

The new model.

Raises:

NotImplemented – If the model is not a subclass of RootModel.

model_copy(*, update=None, deep=False)
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Return type:

Self

Returns:

New model instance.

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode (Union[Literal['json', 'python'], str]) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to include in the output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to exclude from the output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model.

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to include in the JSON output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to exclude from the JSON output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to serialize using field aliases.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

str

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=<class 'pydantic.json_schema.GenerateJsonSchema'>, mode='validation', *, union_format='any_of')

Generates a JSON schema for a model class.

Parameters:
  • by_alias (bool) – Whether to use attribute aliases or not.

  • ref_template (str) – The reference template.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.

Return type:

dict[str, Any]

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Return type:

str

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force (bool) – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors (bool) – Whether to raise errors, defaults to True.

  • _parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.

  • _types_namespace (Mapping[str, Any] | None) – The types namespace, defaults to None.

Return type:

bool | None

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

classmethod model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None)

Validate a pydantic model instance.

Parameters:
  • obj (Any) – The object to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes (bool | None) – Whether to extract data from object attributes.

  • context (Any | None) – Additional context to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Return type:

Self

Returns:

The validated model instance.

classmethod model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data (str | bytes | bytearray) – The JSON data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj (Any) – The object containing string data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

pop([index]) item -- remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

remove(value)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE

root: list[Model]

The list of models.

set_problem(problem)[source]

Set the PEtab Select problem for this set of models.

Return type:

None

to_yaml(filename, relative_paths=True)[source]

Save models to a YAML file.

Parameters:
  • filename (str | Path) – Location of the YAML file.

  • relative_paths (bool) – Whether to rewrite the paths in each model (e.g. the path to the model’s PEtab problem) relative to the filename location.

Return type:

None

values()

Get the models. DEPRECATED.

Return type:

Models

class petab_select.Problem(**data)[source]

The model selection problem.

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

candidate_space_arguments: dict[str, Any]

Method-specific arguments.

These are forwarded to the candidate space constructor.

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to include in the copied model.

  • exclude (Set[int] | Set[str] | Mapping[int, Any] | Mapping[str, Any] | None) – Optional set or mapping specifying which fields to exclude in the copied model.

  • update (Optional[Dict[str, Any]]) – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.

Return type:

Self

Returns:

A copy of the model with included, excluded and updated fields as specified.

criterion: Annotated[Criterion, PlainSerializer(lambda x: x.value, return_type=str)]

The criterion used to compare models.

exclude_model_hashes(model_hashes)[source]

Exclude models from the model space, by model hashes.

Parameters:

model_hashes (Iterable[str]) – The model hashes.

Return type:

None

exclude_models(models)[source]

Exclude models from the model space.

Parameters:

models (Models) – The models.

Return type:

None

format_version: str

The file format version.

static from_yaml(filename)[source]

Load a problem from a YAML file.

Return type:

Problem

get_best(models, criterion=None, compute_criterion=False)[source]

Get the best model from a collection of models.

The best model is selected based on the selection problem’s criterion.

Parameters:
  • models (Models) – The models.

  • criterion (str | None) – The criterion. Defaults to the problem criterion.

  • compute_criterion (bool) – Whether to try computing criterion values, if sufficient information is available (e.g., likelihood and number of parameters, to compute AIC).

Return type:

Model

Returns:

The best model.

method: Annotated[Method, PlainSerializer(lambda x: x.value, return_type=str)]

The method used to search the model space.

model_config: ClassVar[ConfigDict] = {}

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

classmethod model_construct(_fields_set=None, **values)

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set (set[str] | None) – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values (Any) – Trusted or pre-validated data dictionary.

Return type:

Self

Returns:

A new instance of the Model class with validated data.

model_copy(*, update=None, deep=False)
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Return type:

Self

Returns:

New model instance.

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode (Union[Literal['json', 'python'], str]) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to include in the output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – A set of fields to exclude from the output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model.

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to include in the JSON output.

  • exclude (Union[set[int], set[str], Mapping[int, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], Mapping[str, Union[set[int], set[str], Mapping[int, Union[IncEx, bool]], Mapping[str, Union[IncEx, bool]], bool]], None]) – Field(s) to exclude from the JSON output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to serialize using field aliases.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (Union[bool, Literal['none', 'warn', 'error']]) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Optional[Callable[[Any], Any]]) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Return type:

str

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

model_hash_to_model(model_hash)[source]

Get the model that matches a model hash.

Parameters:

model_hash (str | ModelHash) – The model hash.

Return type:

Model

Returns:

The model.

classmethod model_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=<class 'pydantic.json_schema.GenerateJsonSchema'>, mode='validation', *, union_format='any_of')

Generates a JSON schema for a model class.

Parameters:
  • by_alias (bool) – Whether to use attribute aliases or not.

  • ref_template (str) – The reference template.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.

Return type:

dict[str, Any]

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Return type:

str

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force (bool) – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors (bool) – Whether to raise errors, defaults to True.

  • _parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.

  • _types_namespace (Mapping[str, Any] | None) – The types namespace, defaults to None.

Return type:

bool | None

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

model_space_files: list[Path]

The files that define the model space.

classmethod model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None)

Validate a pydantic model instance.

Parameters:
  • obj (Any) – The object to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes (bool | None) – Whether to extract data from object attributes.

  • context (Any | None) – Additional context to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Return type:

Self

Returns:

The validated model instance.

classmethod model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data (str | bytes | bytearray) – The JSON data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj (Any) – The object containing string data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Optional[Literal['allow', 'ignore', 'forbid']]) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Return type:

Self

Returns:

The validated Pydantic model.

new_candidate_space(*args, method=None, **kwargs)[source]

Construct a new candidate space.

Parameters:
  • args – Arguments are passed to the candidate space constructor.

  • kwargs – Arguments are passed to the candidate space constructor.

  • method (Method) – The model selection method.

Return type:

CandidateSpace

save(directory)[source]

Save all data (problem and model space) to a directory.

Inside the directory, two files will be created: (1) petab_select_problem.yaml, and (2) model_space.tsv.

All paths will be made relative to the directory.

Return type:

None

to_yaml(filename)[source]

Save a problem to a YAML file.

All paths will be made relative to the filename directory.

Parameters:

filename (str | Path) – Location of the YAML file.

Return type:

None

petab_select.calculate_aic(nllh, n_estimated)[source]

Calculate the Akaike information criterion (AIC) for a model.

Parameters:
  • nllh (float) – The negative log likelihood.

  • n_estimated (int) – The number of estimated parameters in the model.

Return type:

float

Returns:

The AIC value.

petab_select.calculate_aicc(nllh, n_estimated, n_measurements, n_priors)[source]

Calculate the corrected Akaike information criterion (AICc) for a model.

Parameters:
  • nllh (float) – The negative log likelihood.

  • n_estimated (int) – The number of estimated parameters in the model.

  • n_measurements (int) – The number of measurements used in the likelihood.

  • n_priors (int) – The number of priors used in the objective function.

Return type:

float

Returns:

The AICc value.

petab_select.calculate_bic(nllh, n_estimated, n_measurements, n_priors)[source]

Calculate the Bayesian information criterion (BIC) for a model.

Args
nllh:

The negative log likelihood.

n_estimated:

The number of estimated parameters in the model.

n_measurements:

The number of measurements used in the likelihood.

n_priors:

The number of priors used in the objective function.

Returns:

The BIC value.

petab_select.compute_weights(models, criterion, as_dict=False)[source]

Compute criterion weights.

N.B.: regardless of the criterion, the formula used is the Akaike weights formula, but with criterion values instead of the AIC.

Parameters:
  • models (Models) – The models.

  • criterion (Criterion) – The criterion.

  • as_dict (bool) – Whether to return a dictionary, with model hashes for keys.

Return type:

list[float] | dict[ModelHash, float]

Returns:

The criterion weights.

petab_select.default_compare(model0, model1, criterion, criterion_threshold=0)[source]

Compare two calibrated models by their criterion values.

It is assumed that the model model0 provides a value for the criterion criterion, or is the VIRTUAL_INITIAL_MODEL.

Parameters:
  • model0 (Model) – The original model.

  • model1 (Model) – The new model.

  • criterion (Criterion) – The criterion.

  • criterion_threshold (float) – The non-negative value by which the new model must improve on the original model.

Return type:

bool

Returns:

True` if ``model1 has a better criterion value than model0, else False.

petab_select.end_iteration(problem, candidate_space, calibrated_models)[source]

Finalize model selection iteration.

All models from the current iteration are provided to the calibration tool. This includes user-calibrated models that the tool did not see until now.

A termination signal is also provided, if the model selection algorithm ends.

Parameters:
  • problem (Problem) – The PEtab Select problem.

  • candidate_space (CandidateSpace) – The candidate space.

  • calibrated_models (Models) – The calibration results for the uncalibrated models of this iteration.

Returns:

petab_select.constants.MODELS:

All calibrated models for the current iteration.

petab_select.constants.TERMINATE:

Whether PEtab Select has decided to end the model selection, as a boolean.

Return type:

A dictionary, with the following items

petab_select.get_best(problem, models, criterion=None)[source]

Get the best model from a list of models.

Parameters:
  • problem (Problem) – The PEtab Select problem.

  • models (list[Model]) – The list of models.

  • criterion (str | Criterion | None) – The criterion by which models will be compared. Defaults to problem.criterion.

Return type:

Model

Returns:

The best model.

petab_select.get_best_by_iteration(models, *args, **kwargs)[source]

Get the best model of each iteration.

See :func:get_best for additional required arguments.

Parameters:
  • models (Models) – The models.

  • *args – Forwarded to :func:get_best.

  • **kwargs

    Forwarded to :func:get_best.

Return type:

dict[int, Models]

Returns:

The strictly improving models. Keys are iteration, values are models.

petab_select.get_graph(models, labels=None)[source]

Get a graph representation of the models in terms of their ancestry.

Edges connect models with their predecessor models.

Parameters:
  • models (Models) – The models.

  • labels (dict[ModelHash, str]) – Alternative labels for the models. Keys are model hashes, values are the labels.

Return type:

DiGraph

Returns:

The graph.

petab_select.get_parameter_changes(models, as_dict=False)[source]

Get the differences in parameters betweem models and their predecessors.

Parameters:
  • models (Models) – The models.

  • as_dict (bool) – Whether to return a dictionary, with model hashes for keys.

Return type:

dict[ModelHash, list[tuple[set[str], set[str]]]] | list[tuple[set[str], set[str]]]

Returns:

The parameter changes. Each model has a 2-tuple of sets of parameters. The first and second sets are the added and removed parameters, respectively. If the predecessor model is undefined (e.g. the VIRTUAL_INITIAL_MODEL), then both sets will be empty.

petab_select.group_by_iteration(models, sort=True)[source]

Group models by their iteration.

Parameters:
  • models (Models) – The models.

  • sort (bool) – Whether to sort the iterations.

Return type:

dict[int | None, Models]

Returns:

Key is iteration, value is models.

petab_select.group_by_predecessor_model(models)[source]

Group models by their predecessor model.

Parameters:

models (Models) – The models.

Return type:

dict[ModelHash, Models]

Returns:

Key is predecessor model hash, value is models.

petab_select.model_to_petab(model, output_path=None)[source]

Generate the PEtab problem for a model.

Parameters:
  • model (Model) – The model.

  • output_path (str | Path | None) – If specified, the PEtab problem will be output to files in this directory.

Return type:

dict[str, Problem | str | Path]

Returns:

The PEtab problem, and the path to the PEtab problem YAML file, if an output path is provided.

petab_select.models_from_yaml_list(model_list_yaml, petab_problem=None, allow_single_model=True, problem=None)[source]

Deprecated. Use petab_select.Models.from_yaml instead.

Return type:

Models

petab_select.models_to_petab(models, output_path_prefix=None)[source]

Generate the PEtab problems for a list of models.

Parameters:
  • models (Models) – The list of model.

  • output_path_prefix (list[str | Path] | None) – If specified, the PEtab problem will be output to files in subdirectories of this path, where each subdirectory corresponds to a model.

Return type:

list[dict[str, Problem | str | Path]]

Returns:

The PEtab problems, and the paths to the PEtab problem YAML files, if an output path prefix is provided.

petab_select.models_to_yaml_list(models, output_yaml, relative_paths=True)[source]

Deprecated. Use petab_select.Models.to_yaml instead.

Return type:

None

petab_select.parameter_string_to_value(parameter_string, passthrough_estimate=False)[source]

Cast a parameter value from string to numeric.

Parameters:
  • parameter_string (str) – The parameter value, as a string.

  • passthrough_estimate (bool) – Whether to return ESTIMATE as ESTIMATE. If False, raises an exception if parameter_string == ESTIMATE.

Return type:

float | int | str

Returns:

The parameter value, as a numeric type.

petab_select.start_iteration(problem, candidate_space=None, limit=inf, limit_sent=inf, excluded_hashes=None, criterion=None, user_calibrated_models=None)[source]

Search the model space for candidate models.

The predecessor model can be specified in the candidate_space (CandidateSpace.set_predecessor_model). If `candidate_space() is not provided, then the predecessor model can be specified in problem (Problem.candidate_space_arguments).

Parameters:
  • problem (Problem) – A PEtab Select problem.

  • candidate_space (CandidateSpace | None) – The candidate space. Defaults to a new candidate space based on the method defined in the problem.

  • limit (float | int) – The maximum number of models to add to the candidate space.

  • limit_sent (float | int) – The maximum number of models sent to the candidate space (which are possibly rejected and excluded).

  • excluded_hashes (list[ModelHash] | None) – Hashes of models that will be excluded from the candidate space.

  • criterion (Criterion | None) – The criterion by which models will be compared. Defaults to the criterion defined in the PEtab Select problem.

  • user_calibrated_models (Models | None) – Models that were already calibrated by the user. If a model in the candidates has the same hash as a model in user_calibrated_models, then the candidate will be replaced with the calibrated version. Calibration tools will only receive uncalibrated models from this method.

Returns:

petab_select.constants.CANDIDATE_SPACE:

The candidate space.

petab_select.constants.MODELS:

The uncalibrated models of the current iteration.

Return type:

A dictionary, with the following items