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.
- consider(model)
Add a candidate model, if it should be added.
- Parameters:
model (
Model|None) – The candidate model. This value may beNoneif theModelSubspacedecided to exclude the model that would have been sent.- Return type:
- 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.
- 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.
- excluded(model_hash)
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- get_excluded_hashes()
Get the excluded hashes.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- n_accepted()
Get the current number of accepted models.
- Return type:
- Returns:
The number of models.
- classmethod read_arguments_from_yaml_dict(yaml_dict)
Parse settings that were stored in YAML.
- reset(predecessor_model=None, excluded_hashes=None, limit=None)
Reset the candidate models, optionally reinitialize with a model.
- Parameters:
- Return type:
- set_excluded_hashes(hashes, extend=False)
Set the excluded hashes.
- 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().
- set_limit(limit=None)
Set the limit on the number of accepted models.
- 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
FamosCandidateSpaceto 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
BidirectionalCandidateSpacefor an example, where it’s used to switch directions.
- class petab_select.BruteForceCandidateSpace(*args, **kwargs)[source]
The brute-force method class.
- accept(model, distance)
Add a candidate model to the candidate space.
- consider(model)
Add a candidate model, if it should be added.
- Parameters:
model (
Model|None) – The candidate model. This value may beNoneif theModelSubspacedecided to exclude the model that would have been sent.- Return type:
- 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.
- 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.
- excluded(model_hash)
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- get_excluded_hashes()
Get the excluded hashes.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- n_accepted()
Get the current number of accepted models.
- Return type:
- Returns:
The number of models.
- classmethod read_arguments_from_yaml_dict(yaml_dict)
Parse settings that were stored in YAML.
- reset(predecessor_model=None, excluded_hashes=None, limit=None)
Reset the candidate models, optionally reinitialize with a model.
- Parameters:
- Return type:
- set_excluded_hashes(hashes, extend=False)
Set the excluded hashes.
- 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().
- set_limit(limit=None)
Set the limit on the number of accepted models.
- 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
FamosCandidateSpaceto 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
BidirectionalCandidateSpacefor an example, where it’s used to switch directions.
- 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_methodstores 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.
- consider(model)[source]
Add a candidate model, if it should be added.
- Parameters:
model (
Model|None) – The candidate model. This value may beNoneif theModelSubspacedecided to exclude the model that would have been sent.- Return type:
- 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.
- 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.
- excluded(model_hash)[source]
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- n_accepted()[source]
Get the current number of accepted models.
- Return type:
- Returns:
The number of models.
- classmethod read_arguments_from_yaml_dict(yaml_dict)[source]
Parse settings that were stored in YAML.
- reset(predecessor_model=None, excluded_hashes=None, limit=None)[source]
Reset the candidate models, optionally reinitialize with a model.
- Parameters:
- Return type:
- 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().
- 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
FamosCandidateSpaceto 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.
- 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.
- property petab_problem: Problem
The PEtab problem that corresponds to the model.
Implemented as a property such that the
petab.Problemobject 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.
- check_critical(model)[source]
Check if the model contains all necessary critical parameters
- Return type:
- check_swap(model)[source]
Check if parameters that are swapped are contained in the same swap parameter set.
- Return type:
- consider(model)[source]
Re-define
considerof FAMoS to be theconsidermethod of theinner_candidate_space. Update all the attributes changed in theconsidermethod.- Return type:
- distance(model)
Compute the distance between two models that are neighbors.
- 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.
- excluded(model_hash)
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- get_excluded_hashes()
Get the excluded hashes.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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:
- 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:
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- 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:
- 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:
- 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:
- Return type:
- set_excluded_hashes(hashes, extend=False)
Set the excluded hashes.
- 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().
- set_limit(limit=None)
Set the limit on the number of accepted models.
- 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.
- 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:
- update_after_calibration(*args, iteration_calibrated_models, **kwargs)[source]
See CandidateSpace.update_after_calibration.
- Return type:
- update_from_iteration_calibrated_models(iteration_calibrated_models)[source]
Update
self.best_modelswith the latestiteration_calibrated_modelsand determine if there was a new best model. If so, returnFalse.Trueotherwise.- Return type:
- 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
BidirectionalCandidateSpacefor 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.
- class petab_select.ForwardCandidateSpace(*args, predecessor_model=None, max_steps=None, **kwargs)[source]
The forward method class.
- direction
1for the forward method,-1for 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.
- consider(model)
Add a candidate model, if it should be added.
- Parameters:
model (
Model|None) – The candidate model. This value may beNoneif theModelSubspacedecided to exclude the model that would have been sent.- Return type:
- 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.
- 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.
- excluded(model_hash)
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- get_excluded_hashes()
Get the excluded hashes.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- n_accepted()
Get the current number of accepted models.
- Return type:
- Returns:
The number of models.
- classmethod read_arguments_from_yaml_dict(yaml_dict)
Parse settings that were stored in YAML.
- reset(predecessor_model=None, excluded_hashes=None, limit=None)
Reset the candidate models, optionally reinitialize with a model.
- Parameters:
- Return type:
- set_excluded_hashes(hashes, extend=False)
Set the excluded hashes.
- 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().
- set_limit(limit=None)
Set the limit on the number of accepted models.
- 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
FamosCandidateSpaceto 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
BidirectionalCandidateSpacefor an example, where it’s used to switch directions.
- 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.
- consider(model)
Add a candidate model, if it should be added.
- Parameters:
model (
Model|None) – The candidate model. This value may beNoneif theModelSubspacedecided to exclude the model that would have been sent.- Return type:
- 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.
- 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.
- excluded(model_hash)
Check whether a model is excluded.
- Parameters:
model – The model.
- Return type:
- Returns:
Trueif themodelis excluded, otherwiseFalse.
- get_excluded_hashes()
Get the excluded hashes.
- 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:
- Returns:
All calibrated models for the current iteration.
- 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_modelthat has no estimated parameters, then only models with one or more estimated parameters are plausible.
- n_accepted()
Get the current number of accepted models.
- Return type:
- Returns:
The number of models.
- classmethod read_arguments_from_yaml_dict(yaml_dict)
Parse settings that were stored in YAML.
- reset(predecessor_model=None, excluded_hashes=None, limit=None)
Reset the candidate models, optionally reinitialize with a model.
- Parameters:
- Return type:
- set_excluded_hashes(hashes, extend=False)
Set the excluded hashes.
- 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().
- set_limit(limit=None)
Set the limit on the number of accepted models.
- 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
FamosCandidateSpaceto 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
BidirectionalCandidateSpacefor an example, where it’s used to switch directions.
- 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.
- 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.
- get_criterion(criterion, compute=True, raise_on_failure=True)[source]
Get a criterion value for the model.
- Parameters:
- Return type:
- Returns:
The criterion value, or
Noneif it is not available.
- get_parameter_values(parameter_ids=None)[source]
Get parameter values.
Includes
ESTIMATEfor parameters that should be estimated.
- 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]).
- 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:
- 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:
- 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:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
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 modificationsmode (
Literal['validation','serialization']) – The mode in which to generate the schema.
- Return type:
- 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:
- 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.
- 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:
- 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.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.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.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.
- 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 implementModel.estimated_parametersas the nominal values of the PEtab problem parameter table. Defaults toTrueifModel.estimated_parametersis set.
- Return type:
- Returns:
The PEtab problem. Also returns the path of the PEtab problem YAML file, if
output_pathis specified.
- 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.
- static hash_model_subspace_indices(model_subspace_indices)[source]
Hash the location of a model in its subspace.
- 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]).
- 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:
- 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:
- 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:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
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 modificationsmode (
Literal['validation','serialization']) – The mode in which to generate the schema.
- Return type:
- 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:
- 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:
- 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:
- 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.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.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.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.
- 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.
- static load(data, root_path=None)[source]
Load a model space from dataframe(s) or file(s).
- Parameters:
- Return type:
- Returns:
The model space.
- reset_exclusions(exclusions=None)[source]
Reset the exclusions in the model subspaces.
- Return type:
- 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()).
- 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_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.
- 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:
- 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.
- exclude_models(models)[source]
Exclude models from the model subspace.
Models are excluded in
ModelSubspace.indices_to_model(), which contains the only call toModel.__init__()in theModelSubspaceclass.
- static from_definition(definition, root_path=None)[source]
Create a
ModelSubspacefrom a definition.- Parameters:
- Return type:
- Returns:
The model subspace.
- get_models(estimated_parameters)[source]
Get models in the subspace by estimated parameters.
All models that have the provided
estimated_parametersare 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:
- 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 theModelSubspace.parametersdictionary, ordered by the keys of this dictionary.- Return type:
- 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.
- 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_fix: list[str]
Subspace parameters that must be fixed.
Parameters that are fixed as part of the PEtab problem are not considered.
- 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.
- 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:
- 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.
- 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.
- 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
- extend(other)
S.extend(iterable) – extend sequence by appending elements from the iterable
- Return type:
- static from_yaml(filename, model_subspace_petab_problem=None, problem=None)[source]
Load models from a YAML file.
- Parameters:
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 samemodel_subspace_petab_yamlin 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:
- Returns:
The models.
- get_criterion(criterion, as_dict=False, relative=False)[source]
Get the criterion value for all models.
- Parameters:
- Return type:
- 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:
- 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.
- 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]).
- 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:
- 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:
- 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:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
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 modificationsmode (
Literal['validation','serialization']) – The mode in which to generate the schema.
- Return type:
- 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:
- 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.
- 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:
- 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.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.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.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.
- 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.
- format_version: str
The file format version.
- 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:
- Return type:
- 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]).
- 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:
- 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:
- 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:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
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 modificationsmode (
Literal['validation','serialization']) – The mode in which to generate the schema.
- Return type:
- 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:
- 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.
- 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:
- 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.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.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.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:
- petab_select.calculate_aic(nllh, n_estimated)[source]
Calculate the Akaike information criterion (AIC) for a model.
- petab_select.calculate_aicc(nllh, n_estimated, n_measurements, n_priors)[source]
Calculate the corrected Akaike information criterion (AICc) for a model.
- Parameters:
- Return type:
- 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
criterionvalues instead of the AIC.
- 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
model0provides a value for the criterioncriterion, or is theVIRTUAL_INITIAL_MODEL.- Parameters:
- Return type:
- Returns:
True` if ``model1has a better criterion value thanmodel0, elseFalse.
- 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.
- petab_select.get_best_by_iteration(models, *args, **kwargs)[source]
Get the best model of each iteration.
See :func:
get_bestfor additional required arguments.
- 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.
- petab_select.get_parameter_changes(models, as_dict=False)[source]
Get the differences in parameters betweem models and their predecessors.
- Parameters:
- 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.model_to_petab(model, output_path=None)[source]
Generate the PEtab problem for a model.
- 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:
- petab_select.models_to_petab(models, output_path_prefix=None)[source]
Generate the PEtab problems for a list of models.
- Parameters:
- Return type:
- 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:
- petab_select.parameter_string_to_value(parameter_string, passthrough_estimate=False)[source]
Cast a parameter value from string to numeric.
- 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