pymob.sim.config package#
Submodules#
pymob.sim.config.base module#
- class pymob.sim.config.base.Config(config: str | ConfigParser | None = None)#
Bases:
BaseModelConfiguration manager for pymob.
This class loads a
settings.cfgfile, validates it against the pydantic models defined above and provides convenient accessors.- Parameters:
config (str or configparser.ConfigParser, optional) – Path to a configuration file or an already parsed
ConfigParser.
- create_directory(directory: Literal['results', 'scenario'], force: bool = False) None#
Create a results or scenario directory if it does not exist.
- Parameters:
directory (Literal["results", "scenario"]) – Which directory to create.
force (bool, optional) – If
Truecreate without prompting.
- data_structure: Datastructure#
- error_model: Errormodel#
- import_casestudy_modules(reset_path: bool = False) None#
Import all modules of the current case study.
this script handles the import of a case study without the typical __init__.py file. It iterates over all .py files in the root directory of the case study (typically: sim, mod, stats, plot, data, prior) and imports them with import_module(…)
- Parameters:
reset_path (bool, optional) – Reset
sys.pathbefore importing. Default isFalse.
- import_simulation_from_case_study() Any#
Retrieve the
Simulationclass defined in the case-study.- Returns:
The
Simulationclass object.- Return type:
Any
- Raises:
ImportError – If the class cannot be found.
- property input_file_paths: List[str]#
List of all input files required for the simulation.
- Return type:
List[str]
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'case_study': FieldInfo(annotation=Casestudy, required=False, default=Casestudy(init_root='/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', root='.', name='unnamed_case_study', version=None, pymob_version=None, scenario='unnamed_scenario', package='case_studies', modules=['sim', 'mod', 'prob', 'data', 'plot'], simulation='Simulation', output=None, data=None, scenario_path_override=None, observations=None, logging='DEBUG', logfile=None, output_path='case_studies/unnamed_case_study/results/unnamed_scenario', data_path='case_studies/unnamed_case_study/data', default_settings_path='case_studies/unnamed_case_study/scenarios/unnamed_scenario/settings.cfg'), alias='case-study', alias_priority=2), 'data_structure': FieldInfo(annotation=Datastructure, required=False, default=Datastructure(indices=[]), alias='data-structure', alias_priority=2), 'error_model': FieldInfo(annotation=Errormodel, required=False, default=Errormodel(), alias='error-model', alias_priority=2), 'inference': FieldInfo(annotation=Inference, required=False, default=Inference(eps=1e-08, objective_function='total_average', n_objectives=1, objective_names=[], backend=None, extra_vars=[], plot=None, n_predictions=100)), 'inference_numpyro': FieldInfo(annotation=Numpyro, required=False, default=Numpyro(user_defined_probability_model=None, user_defined_error_model=None, user_defined_preprocessing=None, gaussian_base_distribution=False, kernel='nuts', init_strategy='init_to_uniform', chains=1, draws=2000, warmup=1000, thinning=1, nuts_draws=2000, nuts_step_size=0.8, nuts_max_tree_depth=10, nuts_target_accept_prob=0.8, nuts_dense_mass=True, nuts_adapt_step_size=True, nuts_adapt_mass_matrix=True, sa_adapt_state_size=None, svi_iterations=10000, svi_learning_rate=0.0001), alias='inference.numpyro', alias_priority=2), 'inference_pyabc': FieldInfo(annotation=Pyabc, required=False, default=Pyabc(sampler='SingleCoreSampler', population_size=100, minimum_epsilon=0.0, min_eps_diff=0.0, max_nr_populations=1000, database_path='/tmp/pyabc.db'), alias='inference.pyabc', alias_priority=2), 'inference_pyabc_redis': FieldInfo(annotation=Redis, required=False, default=Redis(password='nopassword', port=1111, n_predictions=50, history_id=-1, model_id=0), alias='inference.pyabc.redis', alias_priority=2), 'inference_pymoo': FieldInfo(annotation=Pymoo, required=False, default=Pymoo(algortihm='UNSGA3', population_size=100, max_nr_populations=1000, ftol=1e-05, xtol=1e-07, cvtol=1e-07, verbose=True), alias='inference.pymoo', alias_priority=2), 'jaxsolver': FieldInfo(annotation=Jaxsolver, required=False, default=Jaxsolver(diffrax_solver='Dopri5', rtol=1e-06, atol=1e-07, pcoeff=0.0, icoeff=1.0, dcoeff=0.0, max_steps=100000, throw_exception=True), alias='jax-solver', alias_priority=2), 'model_parameters': FieldInfo(annotation=Modelparameters, required=False, default=Modelparameters(), alias='model-parameters', alias_priority=2), 'multiprocessing': FieldInfo(annotation=Multiprocessing, required=False, default=Multiprocessing(cores=1)), 'report': FieldInfo(annotation=Report, required=False, default=Report(debug_report=False, pandoc_output_format='html', model=True, parameters=True, parameters_format='pandas', diagnostics=True, diagnostics_with_batch_dim_vars=False, diagnostics_exclude_vars=[], goodness_of_fit=True, goodness_of_fit_use_predictions=True, goodness_of_fit_nrmse_mode='range', table_parameter_estimates=True, table_parameter_estimates_format='csv', table_parameter_estimates_significant_figures=3, table_parameter_estimates_error_metric='sd', table_parameter_estimates_parameters_as_rows=True, table_parameter_estimates_with_batch_dim_vars=False, table_parameter_estimates_exclude_vars=[], table_parameter_estimates_override_names={}, plot_trace=True, plot_parameter_pairs=True), alias='report', alias_priority=2), 'simulation': FieldInfo(annotation=Simulation, required=False, default=Simulation(model=None, model_class=None, solver=None, y0=[], x_in=[], input_files=[], n_ode_states=-1, batch_dimension='batch_id', x_dimension='time', modeltype='deterministic', solver_post_processing=None, seed=1)), 'solverbase': FieldInfo(annotation=Solverbase, required=False, default=Solverbase(x_dim='time', exclude_kwargs_model=('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), exclude_kwargs_postprocessing=('t', 'time', 'interpolation', 'results')))}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_parameters: Modelparameters#
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- multiprocessing: Multiprocessing#
- print() None#
Print a summary of the configuration.
- save(fp: str | None = None, force: bool = False) None#
Save the configuration to a
settings.cfgfile.Uses serializers defined at the top, which parse the options to str so they can be processed by configfile.
In case the model configuration should be stored to a json file use something like json.dumps(self.model_dump()), because the build in function, is somewhat disabled by the listparsers which are needed for configfile lists.
- Parameters:
fp (Optional[str]) – File path to write the settings file to. If
Nonethe default location derived from the case study is used.force (bool, optional) – Overwrite without prompting. Default is
False.
- set_option(section: str, option: str, value: str) None#
Set a configuration option.
- Parameters:
section (str) – Name of the configuration section (e.g.
simulation).option (str) – Option name within the section.
value (str) – New value as a string; will be parsed according to the section’s type definitions.
- simulation: Simulation#
- solverbase: Solverbase#
pymob.sim.config.casestudy_registry module#
- pymob.sim.config.casestudy_registry.get_case_study_model(name: str)#
Return the registered model class for name, or
Noneif not registered.
- pymob.sim.config.casestudy_registry.register_case_study_config(name: str, model_cls: Type[BaseModel]) None#
Register a Pydantic model for a case-study-specific configuration section.
- Parameters:
name (str) – Identifier matching
case_study.name(e.g.lotka_volterra_case_study).model_cls (Type[BaseModel]) – The Pydantic model that defines the expected options for the section.
pymob.sim.config.parameters module#
- class pymob.sim.config.parameters.Expression(expression: str | Expression)#
Bases:
objectRandom variables are context dependent. They may be dependent on other Variables, or datasets. In the config they represent an abstract structure, so they remain unevaluated expressions that must follow python syntax. Once, the context is available, the expressions can be evaluated by Expression.evaluate(context={…}).
- evaluate(context: Dict = {}) Any#
- class pymob.sim.config.parameters.Param(*, name: str | None = None, value: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] = 0.0, dims: ~typing.Tuple[str, ...] = (), unit: str | ~typing.List[str] | None = None, prior: ~pymob.sim.config.parameters.RandomVariable | None = None, min: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, max: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, step: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, hyper: bool = False, free: bool = True)#
Bases:
BaseModelThis class serves as a Basic model for declaring parameters Including a distribution with optional depdendencies
- Parameters:
value (float|NumericArray) – The parameter value. If it is not a 0-d array, float or 1-d array of length one, it should be accompanied by a dimension for each axis in the array. The array coordinates must be specified in the observation coordinates or in index coordinates
dims (Tuple[str, ...]) – Dimensions of the parameter. If the batch dimension is not specified here, it will be automatically added in the Evaluator (dispatch_constructor). If dims are specified here, they should be present in: 1) dimension in sim.config.data_structure and sim.coordinates 2) dimension in sim.config.parameters (so here) and sim.coordinates 3) dimension in sim.indices
prior (Optional[RandomVariable]) – This is a string or pymob.sim.parameters.RandomVariable that specifies the prior. Strings are automatically parsed to RandomVariables if the syntax is correct. The prior should follow the specification of scipy.stats
unit (Optional[str|List[str]]) – The unit of the parameter. The parameter can be either given explicit units or placeholders can be used, e.g. ‘{X}’ or ‘{T}’, where T is the time dimension and and X is the input dimension. These placeholders can then be replaced, if units are specified in the sim.observations.attrs section of the dataset. Here it is important, that the name of the attr matches the
- dims: Tuple[str, ...]#
- free: bool#
- hyper: bool#
- max: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- min: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'dims': FieldInfo(annotation=Tuple[str, ...], required=False, default=()), 'free': FieldInfo(annotation=bool, required=False, default=True), 'hyper': FieldInfo(annotation=bool, required=False, default=False), 'max': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'min': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'name': FieldInfo(annotation=Union[str, NoneType], required=False), 'prior': FieldInfo(annotation=Union[Annotated[RandomVariable, BeforeValidator], NoneType], required=False), 'step': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'unit': FieldInfo(annotation=Union[str, List[str], NoneType], required=False), 'value': FieldInfo(annotation=Union[float, NDArray], required=False, default=0.0)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- name: str | None#
- post_update()#
- prior: RandomVariable | None#
- step: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- to_xarray(coordinates)#
Converts the parameter to an xarray based on the dimensional structure and adds additional info (prior, starting values, …) as metadata.
- unit: str | List[str] | None#
- value: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)]#
- class pymob.sim.config.parameters.RandomVariable(*, distribution: str, parameters: Dict[str, Expression], obs: Expression | None = None, obs_inv: Expression | None = None)#
Bases:
BaseModelBasic infrastructure to parse priors into their components so that they can be more easily parsed to other backends. Parsing to distributions needs more context: - other parameters (for hierarchical parameter structures) - data structure and coordinates to identify dimension sizes
- classmethod check_distribution(new_value, info, **kwargs)#
- classmethod check_parameters(new_value, info, **kwargs)#
- distribution: str#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'distribution': FieldInfo(annotation=str, required=True), 'obs': FieldInfo(annotation=Union[Expression, NoneType], required=False), 'obs_inv': FieldInfo(annotation=Union[Expression, NoneType], required=False), 'parameters': FieldInfo(annotation=Dict[str, Expression], required=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_ser() str#
- obs: Expression | None#
- obs_inv: Expression | None#
- parameters: Dict[str, Expression]#
- class pymob.sim.config.parameters.UndefinedNameFinder#
Bases:
NodeVisitor- find_undefined_names(expr)#
- visit_FunctionDef(node)#
- visit_Name(node)#
- pymob.sim.config.parameters.string_to_prior_dict(prior_str: str)#
- pymob.sim.config.parameters.to_rv(option: str | RandomVariable | Dict) RandomVariable#
pymob.sim.config.sections module#
- class pymob.sim.config.sections.Casestudy(*, init_root: str = '/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', root: str = '.', name: str = 'unnamed_case_study', version: str | None = None, pymob_version: str | None = None, scenario: str = 'unnamed_scenario', package: str = 'case_studies', modules: List[str] = ['sim', 'mod', 'prob', 'data', 'plot'], simulation: str = 'Simulation', output: str | None = None, data: str | None = None, scenario_path_override: str | None = None, observations: str | None = None, logging: str = 'DEBUG', logfile: str | None = None)#
Bases:
PymobModelConfiguration model for a case study.
- init_root#
Working directory at the time of creation (excluded from serialization).
- Type:
str
- root#
Root directory of the repository.
- Type:
str
- name#
Name of the case study.
- Type:
str
- version#
Optional version string.
- Type:
Optional[str]
- pymob_version#
Version of pymob used.
- Type:
Optional[str]
- scenario#
Scenario name.
- Type:
str
- package#
Package containing the case study.
- Type:
str
- modules#
List of modules to import for the case study.
- Type:
List[str]
- simulation#
Name of the simulation class defined in
sim.py.- Type:
str
- output, data, scenario_path_override, observations
Paths data, scenario overrides and observation files.
- Type:
Optional[str]
- logging, logfile
Logging level and optional logfile.
- Type:
str
- data: str | None#
- property data_path: str#
Path where case-study data files are stored.
- Return type:
str
- property default_settings_path: str#
Default location of the
settings.cfgfile for the case study.- Return type:
str
- init_root: str#
- logfile: str | None#
- logging: str#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'data': FieldInfo(annotation=Union[str, NoneType], required=False), 'init_root': FieldInfo(annotation=str, required=False, default='/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', exclude=True), 'logfile': FieldInfo(annotation=Union[str, NoneType], required=False), 'logging': FieldInfo(annotation=str, required=False, default='DEBUG'), 'modules': FieldInfo(annotation=List[str], required=False, default=['sim', 'mod', 'prob', 'data', 'plot'], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'name': FieldInfo(annotation=str, required=False, default='unnamed_case_study'), 'observations': FieldInfo(annotation=Union[str, NoneType], required=False), 'output': FieldInfo(annotation=Union[str, NoneType], required=False), 'package': FieldInfo(annotation=str, required=False, default='case_studies'), 'pymob_version': FieldInfo(annotation=Union[str, NoneType], required=False), 'root': FieldInfo(annotation=str, required=False, default='.'), 'scenario': FieldInfo(annotation=str, required=False, default='unnamed_scenario'), 'scenario_path_override': FieldInfo(annotation=Union[str, NoneType], required=False), 'simulation': FieldInfo(annotation=str, required=False, default='Simulation', description='Simulation Class defined in sim.py module in the case study.'), 'version': FieldInfo(annotation=Union[str, NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- modules: List[str]#
- name: str#
- observations: str | None#
- output: str | None#
- property output_path: str#
Path where results are stored.
- Return type:
str
- package: str#
- pymob_version: str | None#
- root: str#
- scenario: str#
- property scenario_path: str#
Path to the scenario directory, taking overrides into account.
- Return type:
str
- scenario_path_override: str | None#
- classmethod set_root(new_value, info, **kwargs) str#
Validate and possibly change the working directory based on
root.- Returns:
The absolute path that becomes the new working directory.
- Return type:
str
Note
For conditionally updating values (e.g. when data variables change) see pydantic/pydantic#7127
- simulation: str#
- version: str | None#
- class pymob.sim.config.sections.DataVariable(*, dimensions: List[str], unit: str | List[str] | None = None, min: float = nan, max: float = nan, observed: bool = True, dimensions_evaluator: List[str] | None = None)#
Bases:
BaseModelDescribe a data variable used in a case study.
- Parameters:
dimensions (List[str]) – Dimensions that must be present in the observations and the dimensional order of the data variable.
min (float, optional) – Minimum value used for scaling.
np.nanmeans the minimum is taken from the observations. Default isnp.nan.max (float, optional) – Maximum value used for scaling.
np.nanmeans the maximum is taken from the observations. Default isnp.nan.observed (bool, optional) – Whether the variable was observed. Default is
True.dimensions_evaluator (List[str] or None, optional) – Order of dimensions returned by the evaluator. If
Nonethe order ofdimensionsis used.
Examples
>>> dv = DataVariable(dimensions=["time", "species"]) >>> dv.dimensions ['time', 'species'] >>> dv.min = 0.0 >>> dv.max = 1.0
- dimensions: List[str]#
- dimensions_evaluator: List[str] | None#
- max: float#
- min: float#
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'dimensions': FieldInfo(annotation=List[str], required=True), 'dimensions_evaluator': FieldInfo(annotation=Union[List[str], NoneType], required=False), 'max': FieldInfo(annotation=float, required=False, default=nan), 'min': FieldInfo(annotation=float, required=False, default=nan), 'observed': FieldInfo(annotation=bool, required=False, default=True), 'unit': FieldInfo(annotation=Union[str, List[str], NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- observed: bool#
- post_update() DataVariable#
Validate that
dimensions_evaluatormatchesdimensions.
- classmethod set_data_variable_bounds(v, info, **kwargs) List[str] | None#
Ensure that
dimensions_evaluatorhas the same length and names asdimensions.- Raises:
AssertionError – If the lengths differ or the sets of names differ.
- unit: str | List[str] | None#
- class pymob.sim.config.sections.Datastructure(*, indices: List[str] = [], **extra_data: Any)#
Bases:
PymobModelContainer for data-variable definitions.
The class stores
DataVariableobjects in__pydantic_extra__.- property all: Dict[str, DataVariable]#
Dictionary of all data variables.
- property data_variables: List[str]#
List of all data-variable names.
- property data_variables_max: List[float]#
List of
maxvalues for all data variables.
- property data_variables_min: List[float]#
List of
minvalues for all data variables.
- property dimdict: Dict[str, List[str]]#
Mapping of variable name to its dimensions.
- property dimensions: List[str]#
Legacy method returning the union of all dimensions.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- property evaluator_dim_order: List[str]#
Legacy method returning the order of dimensions used by the evaluator.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- indices: List[str]#
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'indices': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- property observed_data_variables: List[str]#
List of observed data-variable names.
- property observed_data_variables_max: List[float]#
List of
maxvalues for observed data variables.
- property observed_data_variables_min: List[float]#
List of
minvalues for observed data variables.
- property observed_dimdict: Dict[str, List[str]]#
Mapping of observed variable name to its dimensions.
- remove(key: str) None#
Removes a data variable from the data structure.
- property var_dim_mapper: Dict[str, List[str]]#
Mapping from variable name to evaluator dimension indices.
- Return type:
Dict[str, List[int]]
- class pymob.sim.config.sections.Errormodel(**extra_data: Any)#
Bases:
PymobModelContainer for error-model specifications.
Each entry is an
OptionRVdescribing a random variable.- property all: Dict[str, RandomVariable]#
All error-model random variables.
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class pymob.sim.config.sections.Inference(*, eps: float = 1e-08, objective_function: str = 'total_average', n_objectives: int = 1, objective_names: List[str] = [], backend: str | None = None, extra_vars: List[str] = [], plot: str | Callable | None = None, n_predictions: int = 100)#
Bases:
PymobModelConfiguration for inference settings.
- eps#
Numerical epsilon for convergence.
- Type:
float
- objective_function#
Name of the objective function.
- Type:
str
- n_objectives#
Number of objectives.
- Type:
int
- objective_names#
Names of the objectives.
- Type:
List[str]
- backend#
Inference backend to use.
- Type:
Optional[str]
- extra_vars#
Additional variables to monitor.
- Type:
List[str]
- plot#
Plotting function.
- Type:
Optional[Callable]
- n_predictions#
Number of posterior predictive draws.
- Type:
int
- backend: str | None#
- eps: float#
- extra_vars: List[str]#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'backend': FieldInfo(annotation=Union[str, NoneType], required=False), 'eps': FieldInfo(annotation=float, required=False, default=1e-08), 'extra_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'n_objectives': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'n_predictions': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'objective_function': FieldInfo(annotation=str, required=False, default='total_average'), 'objective_names': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'plot': FieldInfo(annotation=Union[str, Callable, NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- n_objectives: int#
- n_predictions: int#
- objective_function: str#
- objective_names: List[str]#
- plot: str | Callable | None#
- class pymob.sim.config.sections.Jaxsolver(*, diffrax_solver: str = 'Dopri5', rtol: float = 1e-06, atol: float = 1e-07, pcoeff: float = 0.0, icoeff: float = 1.0, dcoeff: float = 0.0, max_steps: int = 100000, throw_exception: bool = True)#
Bases:
PymobModelConfiguration for the JAX solver.
- diffrax_solver#
Name of the Diffrax solver to use.
- Type:
str
- rtol, atol
Relative and absolute tolerances.
- Type:
float
- pcoeff, icoeff, dcoeff, max_steps
Coefficients for the solver.
- Type:
float or int
- throw_exception#
Whether to raise an exception on solver failure.
- Type:
bool
- atol: float#
- dcoeff: float#
- diffrax_solver: str#
- icoeff: float#
- max_steps: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'atol': FieldInfo(annotation=float, required=False, default=1e-07), 'dcoeff': FieldInfo(annotation=float, required=False, default=0.0), 'diffrax_solver': FieldInfo(annotation=str, required=False, default='Dopri5'), 'icoeff': FieldInfo(annotation=float, required=False, default=1.0), 'max_steps': FieldInfo(annotation=int, required=False, default=100000), 'pcoeff': FieldInfo(annotation=float, required=False, default=0.0), 'rtol': FieldInfo(annotation=float, required=False, default=1e-06), 'throw_exception': FieldInfo(annotation=bool, required=False, default=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- pcoeff: float#
- rtol: float#
- throw_exception: bool#
- class pymob.sim.config.sections.ModelParameterDict#
Bases:
TypedDictTyped dictionary used for model parameters.
- parameters#
Mapping of parameter names to values (float, str or int).
- Type:
dict
- y0#
Initial conditions for the ODE system.
- Type:
xr.Dataset
- x_in#
Input exposure time series.
- Type:
xr.Dataset
- parameters: Dict[str, float | str | int]#
- x_in: Dataset#
- y0: Dataset#
- class pymob.sim.config.sections.Modelparameters(**extra_data: Any)#
Bases:
PymobModelContainer for model parameters.
Parameters are stored in
__pydantic_extra__asParamobjects.- property dimensions: List[str]#
Legacy method returning the union of all parameter dimensions.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- property fixed_value_dict: int32'>)]]#
Dictionary of fixed parameter values.
- property free_value_dict: int32'>)]]#
Dictionary of free parameter values.
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- property n_free: int#
Number of free parameters.
- remove(key: str) None#
Removes a Parameter.
- reorder(keys: List[str]) None#
Reorders model parameters. This may be necessary for hierarchical models, because priors take draws from hyperpriors to parameterize their distributions. Hence, they must be available earlier.
- Parameters:
keys (List[str]) – Desired order of parameter keys. Unlisted keys are appended.
- property value_dict: int32'>)]]#
Dictionary of all parameter values.
- class pymob.sim.config.sections.Multiprocessing(*, cores: int = 1)#
Bases:
PymobModelConfiguration for multiprocessing.
- cores#
Number of cores to use.
1means no parallelism.- Type:
int
- cores: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'cores': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- property n_cores: int#
Compute the effective number of cores.
- Return type:
int
- class pymob.sim.config.sections.Numpyro(*, user_defined_probability_model: str | None = None, user_defined_error_model: str | None = None, user_defined_preprocessing: str | None = None, gaussian_base_distribution: bool = False, kernel: str = 'nuts', init_strategy: str = 'init_to_uniform', chains: int = 1, draws: int = 2000, warmup: int = 1000, thinning: int = 1, nuts_draws: int = 2000, nuts_step_size: float = 0.8, nuts_max_tree_depth: int = 10, nuts_target_accept_prob: float = 0.8, nuts_dense_mass: bool = True, nuts_adapt_step_size: bool = True, nuts_adapt_mass_matrix: bool = True, sa_adapt_state_size: int | None = None, svi_iterations: int = 10000, svi_learning_rate: float = 0.0001)#
Bases:
PymobModelConfiguration for the NumPyro inference backend.
- user_defined_probability_model, user_defined_error_model,
- user_defined_preprocessing#
Paths to user-defined modules.
- Type:
Optional[str]
- gaussian_base_distribution#
Whether to use a Gaussian base distribution.
- Type:
bool
- kernel, init_strategy
MCMC kernel and initialisation strategy.
- Type:
str
- chains, draws, warmup, thinning
MCMC sampling parameters.
- Type:
int
- nuts_draws, nuts_step_size, nuts_max_tree_depth,
- nuts_target_accept_prob, nuts_dense_mass,
- nuts_adapt_step_size, nuts_adapt_mass_matrix
NUTS sampler settings.
- Type:
bool or float
- sa_adapt_state_size#
- Type:
Optional Simulated annealing state size.
- svi_iterations, svi_learning_rate
SVI settings.
- Type:
int, float
- chains: int#
- draws: int#
- gaussian_base_distribution: bool#
- init_strategy: str#
- kernel: str#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'chains': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'draws': FieldInfo(annotation=int, required=False, default=2000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'gaussian_base_distribution': FieldInfo(annotation=bool, required=False, default=False), 'init_strategy': FieldInfo(annotation=str, required=False, default='init_to_uniform'), 'kernel': FieldInfo(annotation=str, required=False, default='nuts'), 'nuts_adapt_mass_matrix': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_adapt_step_size': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_dense_mass': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_draws': FieldInfo(annotation=int, required=False, default=2000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_max_tree_depth': FieldInfo(annotation=int, required=False, default=10), 'nuts_step_size': FieldInfo(annotation=float, required=False, default=0.8, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_target_accept_prob': FieldInfo(annotation=float, required=False, default=0.8, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'sa_adapt_state_size': FieldInfo(annotation=Union[int, NoneType], required=False), 'svi_iterations': FieldInfo(annotation=int, required=False, default=10000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'svi_learning_rate': FieldInfo(annotation=float, required=False, default=0.0001, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'thinning': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'user_defined_error_model': FieldInfo(annotation=Union[str, NoneType], required=False), 'user_defined_preprocessing': FieldInfo(annotation=Union[str, NoneType], required=False), 'user_defined_probability_model': FieldInfo(annotation=Union[str, NoneType], required=False), 'warmup': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- nuts_adapt_mass_matrix: bool#
- nuts_adapt_step_size: bool#
- nuts_dense_mass: bool#
- nuts_draws: int#
- nuts_max_tree_depth: int#
- nuts_step_size: float#
- nuts_target_accept_prob: float#
- sa_adapt_state_size: int | None#
- svi_iterations: int#
- svi_learning_rate: float#
- thinning: int#
- user_defined_error_model: str | None#
- user_defined_preprocessing: str | None#
- user_defined_probability_model: str | None#
- warmup: int#
- class pymob.sim.config.sections.ParameterDict(*args, **kwargs)#
Bases:
dictDictionary that triggers a callback on mutation.
This is used to keep the configuration in sync with the underlying simulation objects.
- Parameters:
callback (Callable, optional) – Function called with the dictionary after each mutation.
**kwargs (dict) – Initial key/value pairs.
- update(*args, **kwargs) None#
Update the dictionary and invoke the callback.
- class pymob.sim.config.sections.Pyabc(*, sampler: str = 'SingleCoreSampler', population_size: int = 100, minimum_epsilon: float = 0.0, min_eps_diff: float = 0.0, max_nr_populations: int = 1000, database_path: str = '/tmp/pyabc.db')#
Bases:
PymobModelConfiguration for the pyABC inference backend.
- sampler#
Sampler class name.
- Type:
str
- population_size#
Number of particles per population.
- Type:
int
- minimum_epsilon, min_eps_diff
Epsilon settings.
- Type:
float
- max_nr_populations#
Maximum number of populations.
- Type:
int
- database_path#
Path to the SQLite database used by pyABC.
- Type:
str
- database_path: str#
- max_nr_populations: int#
- min_eps_diff: float#
- minimum_epsilon: float#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'database_path': FieldInfo(annotation=str, required=False, default='/tmp/pyabc.db'), 'max_nr_populations': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'min_eps_diff': FieldInfo(annotation=float, required=False, default=0.0, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'minimum_epsilon': FieldInfo(annotation=float, required=False, default=0.0, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'population_size': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'sampler': FieldInfo(annotation=str, required=False, default='SingleCoreSampler')}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- population_size: int#
- sampler: str#
- class pymob.sim.config.sections.PymobModel#
Bases:
BaseModelBase class for all configuration models used in pymob.
This class inherits from
pydantic.BaseModeland provides dictionary-style access to its fields.- Parameters:
**kwargs (dict) – Field values passed to the underlying
BaseModel.
Examples
>>> class MyModel(PymobModel): ... a: int = 1 ... b: str = "x" >>> m = MyModel() >>> m["a"] 1 >>> m["b"] = "y" >>> m.b 'y'
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class pymob.sim.config.sections.Pymoo(*, algortihm: str = 'UNSGA3', population_size: int = 100, max_nr_populations: int = 1000, ftol: float = 1e-05, xtol: float = 1e-07, cvtol: float = 1e-07, verbose: bool = True)#
Bases:
PymobModelConfiguration for the pymoo multi-objective optimisation backend.
- algortihm#
Optimisation algorithm.
- Type:
str
- population_size, max_nr_populations
Population settings.
- Type:
int
- ftol, xtol, cvtol
Tolerances.
- Type:
float
- verbose#
Verbosity flag.
- Type:
bool
- algortihm: str#
- cvtol: float#
- ftol: float#
- max_nr_populations: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'algortihm': FieldInfo(annotation=str, required=False, default='UNSGA3'), 'cvtol': FieldInfo(annotation=float, required=False, default=1e-07, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'ftol': FieldInfo(annotation=float, required=False, default=1e-05, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'max_nr_populations': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'population_size': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'verbose': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'xtol': FieldInfo(annotation=float, required=False, default=1e-07, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- population_size: int#
- verbose: bool#
- xtol: float#
- class pymob.sim.config.sections.Redis(*, password: str = 'nopassword', port: int = 1111, **extra_data: Any)#
Bases:
PymobModelConfiguration for the Redis backend used by pyABC.
- password#
Redis password.
- Type:
str
- port#
Port number.
- Type:
int
- n_predictions, history_id, model_id
Evaluation settings.
- Type:
int
- history_id: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'history_id': FieldInfo(annotation=int, required=False, default=-1, alias='eval.history_id', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'model_id': FieldInfo(annotation=int, required=False, default=0, alias='eval.model_id', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'n_predictions': FieldInfo(annotation=int, required=False, default=50, alias='eval.n_predictions', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'password': FieldInfo(annotation=str, required=False, default='nopassword'), 'port': FieldInfo(annotation=int, required=False, default=1111, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_id: int#
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- n_predictions: int#
- password: str#
- port: int#
- class pymob.sim.config.sections.Report(*, debug_report: bool = False, pandoc_output_format: Literal['html', 'latex-si', 'latex', 'pdf'] = 'html', model: bool = True, parameters: bool = True, parameters_format: Literal['xarray', 'pandas'] = 'pandas', diagnostics: bool = True, diagnostics_with_batch_dim_vars: bool = False, diagnostics_exclude_vars: List[str] = [], goodness_of_fit: bool = True, goodness_of_fit_use_predictions: bool = True, goodness_of_fit_nrmse_mode: Literal['mean', 'range', 'iqr'] = 'range', table_parameter_estimates: bool = True, table_parameter_estimates_format: Literal['latex', 'csv', 'tsv'] = 'csv', table_parameter_estimates_significant_figures: int = 3, table_parameter_estimates_error_metric: Literal['hdi', 'sd'] = 'sd', table_parameter_estimates_parameters_as_rows: bool = True, table_parameter_estimates_with_batch_dim_vars: bool = False, table_parameter_estimates_exclude_vars: List[str] = [], table_parameter_estimates_override_names: Mapping[str, str | float | int | List[float | int]] = {}, plot_trace: bool = True, plot_parameter_pairs: bool = True)#
Bases:
PymobModelConfiguration for report generation.
- debug_report#
Include debug information.
- Type:
bool
- pandoc_output_format#
Output format for the generated report.
- Type:
Literal[“html”, “latex-si”, “latex”, “pdf”]
- model, parameters, diagnostics, goodness_of_fit,
- table_parameter_estimates, plot_trace, plot_parameter_pairs
Flags controlling which sections are included.
- Type:
bool
- debug_report: bool#
- diagnostics: bool#
- diagnostics_exclude_vars: List[str]#
- diagnostics_with_batch_dim_vars: bool#
- goodness_of_fit: bool#
- goodness_of_fit_nrmse_mode: Literal['mean', 'range', 'iqr']#
- goodness_of_fit_use_predictions: bool#
- model: bool#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'debug_report': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'diagnostics': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'diagnostics_exclude_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'diagnostics_with_batch_dim_vars': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'goodness_of_fit': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'goodness_of_fit_nrmse_mode': FieldInfo(annotation=Literal['mean', 'range', 'iqr'], required=False, default='range'), 'goodness_of_fit_use_predictions': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'model': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'pandoc_output_format': FieldInfo(annotation=Literal['html', 'latex-si', 'latex', 'pdf'], required=False, default='html'), 'parameters': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'parameters_format': FieldInfo(annotation=Literal['xarray', 'pandas'], required=False, default='pandas'), 'plot_parameter_pairs': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'plot_trace': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_error_metric': FieldInfo(annotation=Literal['hdi', 'sd'], required=False, default='sd'), 'table_parameter_estimates_exclude_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_format': FieldInfo(annotation=Literal['latex', 'csv', 'tsv'], required=False, default='csv'), 'table_parameter_estimates_override_names': FieldInfo(annotation=Mapping[str, Union[str, float, int, List[Union[float, int]]]], required=False, default={}, metadata=[BeforeValidator(func=functools.partial(<function string_to_dict>, split_str=' ', sep_str='=')), PlainSerializer(func=functools.partial(<function dict_to_string>, replace_whitespace=''), return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_parameters_as_rows': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_significant_figures': FieldInfo(annotation=int, required=False, default=3), 'table_parameter_estimates_with_batch_dim_vars': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- pandoc_output_format: Literal['html', 'latex-si', 'latex', 'pdf']#
- parameters: bool#
- parameters_format: Literal['xarray', 'pandas']#
- plot_parameter_pairs: bool#
- plot_trace: bool#
- table_parameter_estimates: bool#
- table_parameter_estimates_error_metric: Literal['hdi', 'sd']#
- table_parameter_estimates_exclude_vars: List[str]#
- table_parameter_estimates_format: Literal['latex', 'csv', 'tsv']#
- table_parameter_estimates_override_names: Mapping[str, str | float | int | List[float | int]]#
- table_parameter_estimates_parameters_as_rows: bool#
- table_parameter_estimates_significant_figures: int#
- table_parameter_estimates_with_batch_dim_vars: bool#
- class pymob.sim.config.sections.Simulation(*, model: str | None = None, model_class: str | None = None, solver: str | None = None, y0: List[str] = [], x_in: List[str] = [], input_files: List[str] = [], n_ode_states: int = -1, batch_dimension: str = 'batch_id', x_dimension: str = 'time', modeltype: Literal['stochastic', 'deterministic'] = 'deterministic', solver_post_processing: str | None = None, seed: int = 1, **extra_data: Any)#
Bases:
PymobModelConfiguration model for a simulation.
- model, solver
Names of the deterministic model and solver to use.
- Type:
Optional[str]
- y0, x_in, input_files
Lists of initial condition files, exposure files and other input files.
- Type:
List[str]
- n_ode_states#
Number of ODE states;
-1means autodetect.- Type:
int
- batch_dimension, x_dimension
Names of the batch and time dimensions.
- Type:
str
- modeltype#
Type of model.
- Type:
Literal[“stochastic”, “deterministic”]
- seed#
Random seed.
- Type:
int
- batch_dimension: str#
- input_files: List[str]#
- model: str | None#
- model_class: str | None#
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'batch_dimension': FieldInfo(annotation=str, required=False, default='batch_id'), 'input_files': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'model': FieldInfo(annotation=Union[str, NoneType], required=False, description='The deterministic model', validate_default=True), 'model_class': FieldInfo(annotation=Union[str, NoneType], required=False, description='A class that holds the mechanistic model. This is the path to the module class, e.g. `lotka_volterra_case_study.mod.Model`.', validate_default=True), 'modeltype': FieldInfo(annotation=Literal['stochastic', 'deterministic'], required=False, default='deterministic'), 'n_ode_states': FieldInfo(annotation=int, required=False, default=-1), 'seed': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'solver': FieldInfo(annotation=Union[str, NoneType], required=False, validate_default=True), 'solver_post_processing': FieldInfo(annotation=Union[str, NoneType], required=False, validate_default=True), 'x_dimension': FieldInfo(annotation=str, required=False, default='time'), 'x_in': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'y0': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- modeltype: Literal['stochastic', 'deterministic']#
- n_ode_states: int#
- seed: int#
- solver: str | None#
- solver_post_processing: str | None#
- x_dimension: str#
- x_in: List[str]#
- y0: List[str]#
- class pymob.sim.config.sections.Solverbase(*, x_dim: str = 'time', exclude_kwargs_model: Tuple[str, ...] = ('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), exclude_kwargs_postprocessing: Tuple[str, ...] = ('t', 'time', 'interpolation', 'results'))#
Bases:
PymobModelBase configuration for solvers.
- x_dim#
Name of the time dimension.
- Type:
str
- exclude_kwargs_model, exclude_kwargs_postprocessing
Keyword arguments to exclude when passing to the model or post-processing.
- Type:
Tuple[str, …]
- exclude_kwargs_model: Tuple[str, ...]#
- exclude_kwargs_postprocessing: Tuple[str, ...]#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'exclude_kwargs_model': FieldInfo(annotation=Tuple[str, ...], required=False, default=('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), metadata=[BeforeValidator(func=<function string_to_tuple>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'exclude_kwargs_postprocessing': FieldInfo(annotation=Tuple[str, ...], required=False, default=('t', 'time', 'interpolation', 'results'), metadata=[BeforeValidator(func=<function string_to_tuple>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'x_dim': FieldInfo(annotation=str, required=False, default='time')}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- x_dim: str#
- pymob.sim.config.sections.datavar_to_string(prm: DataVariable) str#
Serialize a
DataVariableto akey=valuestring.- Parameters:
prm (DataVariable) –
- Return type:
str
- pymob.sim.config.sections.dict_to_string(dct: Dict, replace_whitespace='', join_str=' ', sep_str='=') str#
Serialize a dictionary to a space-separated
key=valuestring.- Parameters:
dct (dict) – Dictionary to serialize.
replace_whitespace (str, optional) – Replacement for whitespace inside values.
- Return type:
str
- pymob.sim.config.sections.list_to_string(lst: List) str#
Serialize a list to a space-separated string.
- Parameters:
lst (List) –
- Return type:
str
- pymob.sim.config.sections.nested_dict_to_string(nested_dict: Dict[str, Dict[str, float | None]], dict_model: Type[PymobModel]) str#
- pymob.sim.config.sections.param_to_string(prm: Param) str#
Serialize a
Paramto akey=valuestring.- Parameters:
prm (Param) –
- Return type:
str
- pymob.sim.config.sections.string_to_datavar(option: str | DataVariable) DataVariable#
Convert a string or
DataVariableinstance to aDataVariable.- Parameters:
option (str | DataVariable) –
- Return type:
- pymob.sim.config.sections.string_to_dict(option: Dict[str, float | str | int] | str, split_str=' ', sep_str='=') Dict[str, float | str | int]#
Parse a configuration string into a dictionary.
The string must consist of space-separated
key=valuepairs. Values are interpreted asfloat,NumericArrayor Python literals when possible.- Parameters:
option (Union[dict, str]) – Either an existing dictionary or a string to be parsed.
- Returns:
Mapping of keys to parsed values.
- Return type:
dict
Examples
>>> string_to_dict("a=1 b=2") {'a': 1.0, 'b': 2.0}
- pymob.sim.config.sections.string_to_list(option: List | str) List#
Convert a string or list/tuple to a list of strings.
- Parameters:
option (Union[List, str]) – Input that may already be a list/tuple or a space-separated string.
- Returns:
List of strings.
- Return type:
List[str]
Examples
>>> string_to_list("a b c") ['a', 'b', 'c'] >>> string_to_list(["x", "y"]) ['x', 'y']
- pymob.sim.config.sections.string_to_param(option: str | Param) Param#
Convert a string or
Paraminstance to aParam.
- pymob.sim.config.sections.string_to_tuple(option: List | str) Tuple#
Convert a string or list/tuple to a tuple of strings.
- Parameters:
option (Union[List, str]) –
- Return type:
Tuple[str, …]
- pymob.sim.config.sections.to_nested_dict(option: str | Dict[str, str | Dict[str, float | None]], dict_model: Type[PymobModel]) Dict[str, Dict[str, float | None]]#
Module contents#
- class pymob.sim.config.Casestudy(*, init_root: str = '/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', root: str = '.', name: str = 'unnamed_case_study', version: str | None = None, pymob_version: str | None = None, scenario: str = 'unnamed_scenario', package: str = 'case_studies', modules: List[str] = ['sim', 'mod', 'prob', 'data', 'plot'], simulation: str = 'Simulation', output: str | None = None, data: str | None = None, scenario_path_override: str | None = None, observations: str | None = None, logging: str = 'DEBUG', logfile: str | None = None)#
Bases:
PymobModelConfiguration model for a case study.
- init_root#
Working directory at the time of creation (excluded from serialization).
- Type:
str
- root#
Root directory of the repository.
- Type:
str
- name#
Name of the case study.
- Type:
str
- version#
Optional version string.
- Type:
Optional[str]
- pymob_version#
Version of pymob used.
- Type:
Optional[str]
- scenario#
Scenario name.
- Type:
str
- package#
Package containing the case study.
- Type:
str
- modules#
List of modules to import for the case study.
- Type:
List[str]
- simulation#
Name of the simulation class defined in
sim.py.- Type:
str
- output, data, scenario_path_override, observations
Paths data, scenario overrides and observation files.
- Type:
Optional[str]
- logging, logfile
Logging level and optional logfile.
- Type:
str
- data: str | None#
- property data_path: str#
Path where case-study data files are stored.
- Return type:
str
- property default_settings_path: str#
Default location of the
settings.cfgfile for the case study.- Return type:
str
- init_root: str#
- logfile: str | None#
- logging: str#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'data': FieldInfo(annotation=Union[str, NoneType], required=False), 'init_root': FieldInfo(annotation=str, required=False, default='/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', exclude=True), 'logfile': FieldInfo(annotation=Union[str, NoneType], required=False), 'logging': FieldInfo(annotation=str, required=False, default='DEBUG'), 'modules': FieldInfo(annotation=List[str], required=False, default=['sim', 'mod', 'prob', 'data', 'plot'], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'name': FieldInfo(annotation=str, required=False, default='unnamed_case_study'), 'observations': FieldInfo(annotation=Union[str, NoneType], required=False), 'output': FieldInfo(annotation=Union[str, NoneType], required=False), 'package': FieldInfo(annotation=str, required=False, default='case_studies'), 'pymob_version': FieldInfo(annotation=Union[str, NoneType], required=False), 'root': FieldInfo(annotation=str, required=False, default='.'), 'scenario': FieldInfo(annotation=str, required=False, default='unnamed_scenario'), 'scenario_path_override': FieldInfo(annotation=Union[str, NoneType], required=False), 'simulation': FieldInfo(annotation=str, required=False, default='Simulation', description='Simulation Class defined in sim.py module in the case study.'), 'version': FieldInfo(annotation=Union[str, NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- modules: List[str]#
- name: str#
- observations: str | None#
- output: str | None#
- property output_path: str#
Path where results are stored.
- Return type:
str
- package: str#
- pymob_version: str | None#
- root: str#
- scenario: str#
- property scenario_path: str#
Path to the scenario directory, taking overrides into account.
- Return type:
str
- scenario_path_override: str | None#
- classmethod set_root(new_value, info, **kwargs) str#
Validate and possibly change the working directory based on
root.- Returns:
The absolute path that becomes the new working directory.
- Return type:
str
Note
For conditionally updating values (e.g. when data variables change) see pydantic/pydantic#7127
- simulation: str#
- version: str | None#
- class pymob.sim.config.Config(config: str | ConfigParser | None = None)#
Bases:
BaseModelConfiguration manager for pymob.
This class loads a
settings.cfgfile, validates it against the pydantic models defined above and provides convenient accessors.- Parameters:
config (str or configparser.ConfigParser, optional) – Path to a configuration file or an already parsed
ConfigParser.
- create_directory(directory: Literal['results', 'scenario'], force: bool = False) None#
Create a results or scenario directory if it does not exist.
- Parameters:
directory (Literal["results", "scenario"]) – Which directory to create.
force (bool, optional) – If
Truecreate without prompting.
- data_structure: Datastructure#
- error_model: Errormodel#
- import_casestudy_modules(reset_path: bool = False) None#
Import all modules of the current case study.
this script handles the import of a case study without the typical __init__.py file. It iterates over all .py files in the root directory of the case study (typically: sim, mod, stats, plot, data, prior) and imports them with import_module(…)
- Parameters:
reset_path (bool, optional) – Reset
sys.pathbefore importing. Default isFalse.
- import_simulation_from_case_study() Any#
Retrieve the
Simulationclass defined in the case-study.- Returns:
The
Simulationclass object.- Return type:
Any
- Raises:
ImportError – If the class cannot be found.
- property input_file_paths: List[str]#
List of all input files required for the simulation.
- Return type:
List[str]
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'case_study': FieldInfo(annotation=Casestudy, required=False, default=Casestudy(init_root='/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/latest/docs/source', root='.', name='unnamed_case_study', version=None, pymob_version=None, scenario='unnamed_scenario', package='case_studies', modules=['sim', 'mod', 'prob', 'data', 'plot'], simulation='Simulation', output=None, data=None, scenario_path_override=None, observations=None, logging='DEBUG', logfile=None, output_path='case_studies/unnamed_case_study/results/unnamed_scenario', data_path='case_studies/unnamed_case_study/data', default_settings_path='case_studies/unnamed_case_study/scenarios/unnamed_scenario/settings.cfg'), alias='case-study', alias_priority=2), 'data_structure': FieldInfo(annotation=Datastructure, required=False, default=Datastructure(indices=[]), alias='data-structure', alias_priority=2), 'error_model': FieldInfo(annotation=Errormodel, required=False, default=Errormodel(), alias='error-model', alias_priority=2), 'inference': FieldInfo(annotation=Inference, required=False, default=Inference(eps=1e-08, objective_function='total_average', n_objectives=1, objective_names=[], backend=None, extra_vars=[], plot=None, n_predictions=100)), 'inference_numpyro': FieldInfo(annotation=Numpyro, required=False, default=Numpyro(user_defined_probability_model=None, user_defined_error_model=None, user_defined_preprocessing=None, gaussian_base_distribution=False, kernel='nuts', init_strategy='init_to_uniform', chains=1, draws=2000, warmup=1000, thinning=1, nuts_draws=2000, nuts_step_size=0.8, nuts_max_tree_depth=10, nuts_target_accept_prob=0.8, nuts_dense_mass=True, nuts_adapt_step_size=True, nuts_adapt_mass_matrix=True, sa_adapt_state_size=None, svi_iterations=10000, svi_learning_rate=0.0001), alias='inference.numpyro', alias_priority=2), 'inference_pyabc': FieldInfo(annotation=Pyabc, required=False, default=Pyabc(sampler='SingleCoreSampler', population_size=100, minimum_epsilon=0.0, min_eps_diff=0.0, max_nr_populations=1000, database_path='/tmp/pyabc.db'), alias='inference.pyabc', alias_priority=2), 'inference_pyabc_redis': FieldInfo(annotation=Redis, required=False, default=Redis(password='nopassword', port=1111, n_predictions=50, history_id=-1, model_id=0), alias='inference.pyabc.redis', alias_priority=2), 'inference_pymoo': FieldInfo(annotation=Pymoo, required=False, default=Pymoo(algortihm='UNSGA3', population_size=100, max_nr_populations=1000, ftol=1e-05, xtol=1e-07, cvtol=1e-07, verbose=True), alias='inference.pymoo', alias_priority=2), 'jaxsolver': FieldInfo(annotation=Jaxsolver, required=False, default=Jaxsolver(diffrax_solver='Dopri5', rtol=1e-06, atol=1e-07, pcoeff=0.0, icoeff=1.0, dcoeff=0.0, max_steps=100000, throw_exception=True), alias='jax-solver', alias_priority=2), 'model_parameters': FieldInfo(annotation=Modelparameters, required=False, default=Modelparameters(), alias='model-parameters', alias_priority=2), 'multiprocessing': FieldInfo(annotation=Multiprocessing, required=False, default=Multiprocessing(cores=1)), 'report': FieldInfo(annotation=Report, required=False, default=Report(debug_report=False, pandoc_output_format='html', model=True, parameters=True, parameters_format='pandas', diagnostics=True, diagnostics_with_batch_dim_vars=False, diagnostics_exclude_vars=[], goodness_of_fit=True, goodness_of_fit_use_predictions=True, goodness_of_fit_nrmse_mode='range', table_parameter_estimates=True, table_parameter_estimates_format='csv', table_parameter_estimates_significant_figures=3, table_parameter_estimates_error_metric='sd', table_parameter_estimates_parameters_as_rows=True, table_parameter_estimates_with_batch_dim_vars=False, table_parameter_estimates_exclude_vars=[], table_parameter_estimates_override_names={}, plot_trace=True, plot_parameter_pairs=True), alias='report', alias_priority=2), 'simulation': FieldInfo(annotation=Simulation, required=False, default=Simulation(model=None, model_class=None, solver=None, y0=[], x_in=[], input_files=[], n_ode_states=-1, batch_dimension='batch_id', x_dimension='time', modeltype='deterministic', solver_post_processing=None, seed=1)), 'solverbase': FieldInfo(annotation=Solverbase, required=False, default=Solverbase(x_dim='time', exclude_kwargs_model=('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), exclude_kwargs_postprocessing=('t', 'time', 'interpolation', 'results')))}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_parameters: Modelparameters#
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- multiprocessing: Multiprocessing#
- print() None#
Print a summary of the configuration.
- save(fp: str | None = None, force: bool = False) None#
Save the configuration to a
settings.cfgfile.Uses serializers defined at the top, which parse the options to str so they can be processed by configfile.
In case the model configuration should be stored to a json file use something like json.dumps(self.model_dump()), because the build in function, is somewhat disabled by the listparsers which are needed for configfile lists.
- Parameters:
fp (Optional[str]) – File path to write the settings file to. If
Nonethe default location derived from the case study is used.force (bool, optional) – Overwrite without prompting. Default is
False.
- set_option(section: str, option: str, value: str) None#
Set a configuration option.
- Parameters:
section (str) – Name of the configuration section (e.g.
simulation).option (str) – Option name within the section.
value (str) – New value as a string; will be parsed according to the section’s type definitions.
- simulation: Simulation#
- solverbase: Solverbase#
- class pymob.sim.config.DataVariable(*, dimensions: List[str], unit: str | List[str] | None = None, min: float = nan, max: float = nan, observed: bool = True, dimensions_evaluator: List[str] | None = None)#
Bases:
BaseModelDescribe a data variable used in a case study.
- Parameters:
dimensions (List[str]) – Dimensions that must be present in the observations and the dimensional order of the data variable.
min (float, optional) – Minimum value used for scaling.
np.nanmeans the minimum is taken from the observations. Default isnp.nan.max (float, optional) – Maximum value used for scaling.
np.nanmeans the maximum is taken from the observations. Default isnp.nan.observed (bool, optional) – Whether the variable was observed. Default is
True.dimensions_evaluator (List[str] or None, optional) – Order of dimensions returned by the evaluator. If
Nonethe order ofdimensionsis used.
Examples
>>> dv = DataVariable(dimensions=["time", "species"]) >>> dv.dimensions ['time', 'species'] >>> dv.min = 0.0 >>> dv.max = 1.0
- dimensions: List[str]#
- dimensions_evaluator: List[str] | None#
- max: float#
- min: float#
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'dimensions': FieldInfo(annotation=List[str], required=True), 'dimensions_evaluator': FieldInfo(annotation=Union[List[str], NoneType], required=False), 'max': FieldInfo(annotation=float, required=False, default=nan), 'min': FieldInfo(annotation=float, required=False, default=nan), 'observed': FieldInfo(annotation=bool, required=False, default=True), 'unit': FieldInfo(annotation=Union[str, List[str], NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- observed: bool#
- post_update() DataVariable#
Validate that
dimensions_evaluatormatchesdimensions.
- classmethod set_data_variable_bounds(v, info, **kwargs) List[str] | None#
Ensure that
dimensions_evaluatorhas the same length and names asdimensions.- Raises:
AssertionError – If the lengths differ or the sets of names differ.
- unit: str | List[str] | None#
- class pymob.sim.config.Datastructure(*, indices: List[str] = [], **extra_data: Any)#
Bases:
PymobModelContainer for data-variable definitions.
The class stores
DataVariableobjects in__pydantic_extra__.- property all: Dict[str, DataVariable]#
Dictionary of all data variables.
- property data_variables: List[str]#
List of all data-variable names.
- property data_variables_max: List[float]#
List of
maxvalues for all data variables.
- property data_variables_min: List[float]#
List of
minvalues for all data variables.
- property dimdict: Dict[str, List[str]]#
Mapping of variable name to its dimensions.
- property dimensions: List[str]#
Legacy method returning the union of all dimensions.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- property evaluator_dim_order: List[str]#
Legacy method returning the order of dimensions used by the evaluator.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- indices: List[str]#
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'indices': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- property observed_data_variables: List[str]#
List of observed data-variable names.
- property observed_data_variables_max: List[float]#
List of
maxvalues for observed data variables.
- property observed_data_variables_min: List[float]#
List of
minvalues for observed data variables.
- property observed_dimdict: Dict[str, List[str]]#
Mapping of observed variable name to its dimensions.
- remove(key: str) None#
Removes a data variable from the data structure.
- property var_dim_mapper: Dict[str, List[str]]#
Mapping from variable name to evaluator dimension indices.
- Return type:
Dict[str, List[int]]
- class pymob.sim.config.Errormodel(**extra_data: Any)#
Bases:
PymobModelContainer for error-model specifications.
Each entry is an
OptionRVdescribing a random variable.- property all: Dict[str, RandomVariable]#
All error-model random variables.
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class pymob.sim.config.Expression(expression: str | Expression)#
Bases:
objectRandom variables are context dependent. They may be dependent on other Variables, or datasets. In the config they represent an abstract structure, so they remain unevaluated expressions that must follow python syntax. Once, the context is available, the expressions can be evaluated by Expression.evaluate(context={…}).
- evaluate(context: Dict = {}) Any#
- class pymob.sim.config.Inference(*, eps: float = 1e-08, objective_function: str = 'total_average', n_objectives: int = 1, objective_names: List[str] = [], backend: str | None = None, extra_vars: List[str] = [], plot: str | Callable | None = None, n_predictions: int = 100)#
Bases:
PymobModelConfiguration for inference settings.
- eps#
Numerical epsilon for convergence.
- Type:
float
- objective_function#
Name of the objective function.
- Type:
str
- n_objectives#
Number of objectives.
- Type:
int
- objective_names#
Names of the objectives.
- Type:
List[str]
- backend#
Inference backend to use.
- Type:
Optional[str]
- extra_vars#
Additional variables to monitor.
- Type:
List[str]
- plot#
Plotting function.
- Type:
Optional[Callable]
- n_predictions#
Number of posterior predictive draws.
- Type:
int
- backend: str | None#
- eps: float#
- extra_vars: List[str]#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'backend': FieldInfo(annotation=Union[str, NoneType], required=False), 'eps': FieldInfo(annotation=float, required=False, default=1e-08), 'extra_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'n_objectives': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'n_predictions': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'objective_function': FieldInfo(annotation=str, required=False, default='total_average'), 'objective_names': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'plot': FieldInfo(annotation=Union[str, Callable, NoneType], required=False)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- n_objectives: int#
- n_predictions: int#
- objective_function: str#
- objective_names: List[str]#
- plot: str | Callable | None#
- class pymob.sim.config.Jaxsolver(*, diffrax_solver: str = 'Dopri5', rtol: float = 1e-06, atol: float = 1e-07, pcoeff: float = 0.0, icoeff: float = 1.0, dcoeff: float = 0.0, max_steps: int = 100000, throw_exception: bool = True)#
Bases:
PymobModelConfiguration for the JAX solver.
- diffrax_solver#
Name of the Diffrax solver to use.
- Type:
str
- rtol, atol
Relative and absolute tolerances.
- Type:
float
- pcoeff, icoeff, dcoeff, max_steps
Coefficients for the solver.
- Type:
float or int
- throw_exception#
Whether to raise an exception on solver failure.
- Type:
bool
- atol: float#
- dcoeff: float#
- diffrax_solver: str#
- icoeff: float#
- max_steps: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'atol': FieldInfo(annotation=float, required=False, default=1e-07), 'dcoeff': FieldInfo(annotation=float, required=False, default=0.0), 'diffrax_solver': FieldInfo(annotation=str, required=False, default='Dopri5'), 'icoeff': FieldInfo(annotation=float, required=False, default=1.0), 'max_steps': FieldInfo(annotation=int, required=False, default=100000), 'pcoeff': FieldInfo(annotation=float, required=False, default=0.0), 'rtol': FieldInfo(annotation=float, required=False, default=1e-06), 'throw_exception': FieldInfo(annotation=bool, required=False, default=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- pcoeff: float#
- rtol: float#
- throw_exception: bool#
- class pymob.sim.config.Modelparameters(**extra_data: Any)#
Bases:
PymobModelContainer for model parameters.
Parameters are stored in
__pydantic_extra__asParamobjects.- property dimensions: List[str]#
Legacy method returning the union of all parameter dimensions.
- Return type:
List[str]
Note
TODO: Remove when dimensions is not accessed any longer
- property fixed_value_dict: int32'>)]]#
Dictionary of fixed parameter values.
- property free_value_dict: int32'>)]]#
Dictionary of free parameter values.
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- property n_free: int#
Number of free parameters.
- remove(key: str) None#
Removes a Parameter.
- reorder(keys: List[str]) None#
Reorders model parameters. This may be necessary for hierarchical models, because priors take draws from hyperpriors to parameterize their distributions. Hence, they must be available earlier.
- Parameters:
keys (List[str]) – Desired order of parameter keys. Unlisted keys are appended.
- property value_dict: int32'>)]]#
Dictionary of all parameter values.
- class pymob.sim.config.Multiprocessing(*, cores: int = 1)#
Bases:
PymobModelConfiguration for multiprocessing.
- cores#
Number of cores to use.
1means no parallelism.- Type:
int
- cores: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'cores': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- property n_cores: int#
Compute the effective number of cores.
- Return type:
int
- class pymob.sim.config.Numpyro(*, user_defined_probability_model: str | None = None, user_defined_error_model: str | None = None, user_defined_preprocessing: str | None = None, gaussian_base_distribution: bool = False, kernel: str = 'nuts', init_strategy: str = 'init_to_uniform', chains: int = 1, draws: int = 2000, warmup: int = 1000, thinning: int = 1, nuts_draws: int = 2000, nuts_step_size: float = 0.8, nuts_max_tree_depth: int = 10, nuts_target_accept_prob: float = 0.8, nuts_dense_mass: bool = True, nuts_adapt_step_size: bool = True, nuts_adapt_mass_matrix: bool = True, sa_adapt_state_size: int | None = None, svi_iterations: int = 10000, svi_learning_rate: float = 0.0001)#
Bases:
PymobModelConfiguration for the NumPyro inference backend.
- user_defined_probability_model, user_defined_error_model,
- user_defined_preprocessing#
Paths to user-defined modules.
- Type:
Optional[str]
- gaussian_base_distribution#
Whether to use a Gaussian base distribution.
- Type:
bool
- kernel, init_strategy
MCMC kernel and initialisation strategy.
- Type:
str
- chains, draws, warmup, thinning
MCMC sampling parameters.
- Type:
int
- nuts_draws, nuts_step_size, nuts_max_tree_depth,
- nuts_target_accept_prob, nuts_dense_mass,
- nuts_adapt_step_size, nuts_adapt_mass_matrix
NUTS sampler settings.
- Type:
bool or float
- sa_adapt_state_size#
- Type:
Optional Simulated annealing state size.
- svi_iterations, svi_learning_rate
SVI settings.
- Type:
int, float
- chains: int#
- draws: int#
- gaussian_base_distribution: bool#
- init_strategy: str#
- kernel: str#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'chains': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'draws': FieldInfo(annotation=int, required=False, default=2000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'gaussian_base_distribution': FieldInfo(annotation=bool, required=False, default=False), 'init_strategy': FieldInfo(annotation=str, required=False, default='init_to_uniform'), 'kernel': FieldInfo(annotation=str, required=False, default='nuts'), 'nuts_adapt_mass_matrix': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_adapt_step_size': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_dense_mass': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_draws': FieldInfo(annotation=int, required=False, default=2000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_max_tree_depth': FieldInfo(annotation=int, required=False, default=10), 'nuts_step_size': FieldInfo(annotation=float, required=False, default=0.8, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'nuts_target_accept_prob': FieldInfo(annotation=float, required=False, default=0.8, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'sa_adapt_state_size': FieldInfo(annotation=Union[int, NoneType], required=False), 'svi_iterations': FieldInfo(annotation=int, required=False, default=10000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'svi_learning_rate': FieldInfo(annotation=float, required=False, default=0.0001, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'thinning': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'user_defined_error_model': FieldInfo(annotation=Union[str, NoneType], required=False), 'user_defined_preprocessing': FieldInfo(annotation=Union[str, NoneType], required=False), 'user_defined_probability_model': FieldInfo(annotation=Union[str, NoneType], required=False), 'warmup': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- nuts_adapt_mass_matrix: bool#
- nuts_adapt_step_size: bool#
- nuts_dense_mass: bool#
- nuts_draws: int#
- nuts_max_tree_depth: int#
- nuts_step_size: float#
- nuts_target_accept_prob: float#
- sa_adapt_state_size: int | None#
- svi_iterations: int#
- svi_learning_rate: float#
- thinning: int#
- user_defined_error_model: str | None#
- user_defined_preprocessing: str | None#
- user_defined_probability_model: str | None#
- warmup: int#
- class pymob.sim.config.Param(*, name: str | None = None, value: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] = 0.0, dims: ~typing.Tuple[str, ...] = (), unit: str | ~typing.List[str] | None = None, prior: ~pymob.sim.config.parameters.RandomVariable | None = None, min: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, max: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, step: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None = None, hyper: bool = False, free: bool = True)#
Bases:
BaseModelThis class serves as a Basic model for declaring parameters Including a distribution with optional depdendencies
- Parameters:
value (float|NumericArray) – The parameter value. If it is not a 0-d array, float or 1-d array of length one, it should be accompanied by a dimension for each axis in the array. The array coordinates must be specified in the observation coordinates or in index coordinates
dims (Tuple[str, ...]) – Dimensions of the parameter. If the batch dimension is not specified here, it will be automatically added in the Evaluator (dispatch_constructor). If dims are specified here, they should be present in: 1) dimension in sim.config.data_structure and sim.coordinates 2) dimension in sim.config.parameters (so here) and sim.coordinates 3) dimension in sim.indices
prior (Optional[RandomVariable]) – This is a string or pymob.sim.parameters.RandomVariable that specifies the prior. Strings are automatically parsed to RandomVariables if the syntax is correct. The prior should follow the specification of scipy.stats
unit (Optional[str|List[str]]) – The unit of the parameter. The parameter can be either given explicit units or placeholders can be used, e.g. ‘{X}’ or ‘{T}’, where T is the time dimension and and X is the input dimension. These placeholders can then be replaced, if units are specified in the sim.observations.attrs section of the dataset. Here it is important, that the name of the attr matches the
- dims: Tuple[str, ...]#
- free: bool#
- hyper: bool#
- max: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- min: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'dims': FieldInfo(annotation=Tuple[str, ...], required=False, default=()), 'free': FieldInfo(annotation=bool, required=False, default=True), 'hyper': FieldInfo(annotation=bool, required=False, default=False), 'max': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'min': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'name': FieldInfo(annotation=Union[str, NoneType], required=False), 'prior': FieldInfo(annotation=Union[Annotated[RandomVariable, BeforeValidator], NoneType], required=False), 'step': FieldInfo(annotation=Union[float, NDArray, NoneType], required=False), 'unit': FieldInfo(annotation=Union[str, List[str], NoneType], required=False), 'value': FieldInfo(annotation=Union[float, NDArray], required=False, default=0.0)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- name: str | None#
- post_update()#
- prior: RandomVariable | None#
- step: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)] | None#
- to_xarray(coordinates)#
Converts the parameter to an xarray based on the dimensional structure and adds additional info (prior, starting values, …) as metadata.
- unit: str | List[str] | None#
- value: float | ~numpydantic.vendor.nptyping.base_meta_classes.NDArray[~typing.Any, (<class 'numpy.float64'>, <class 'numpy.int64'>, <class 'numpy.float32'>, <class 'numpy.int32'>)]#
- class pymob.sim.config.Pyabc(*, sampler: str = 'SingleCoreSampler', population_size: int = 100, minimum_epsilon: float = 0.0, min_eps_diff: float = 0.0, max_nr_populations: int = 1000, database_path: str = '/tmp/pyabc.db')#
Bases:
PymobModelConfiguration for the pyABC inference backend.
- sampler#
Sampler class name.
- Type:
str
- population_size#
Number of particles per population.
- Type:
int
- minimum_epsilon, min_eps_diff
Epsilon settings.
- Type:
float
- max_nr_populations#
Maximum number of populations.
- Type:
int
- database_path#
Path to the SQLite database used by pyABC.
- Type:
str
- database_path: str#
- max_nr_populations: int#
- min_eps_diff: float#
- minimum_epsilon: float#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'database_path': FieldInfo(annotation=str, required=False, default='/tmp/pyabc.db'), 'max_nr_populations': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'min_eps_diff': FieldInfo(annotation=float, required=False, default=0.0, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'minimum_epsilon': FieldInfo(annotation=float, required=False, default=0.0, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'population_size': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'sampler': FieldInfo(annotation=str, required=False, default='SingleCoreSampler')}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- population_size: int#
- sampler: str#
- class pymob.sim.config.PymobModel#
Bases:
BaseModelBase class for all configuration models used in pymob.
This class inherits from
pydantic.BaseModeland provides dictionary-style access to its fields.- Parameters:
**kwargs (dict) – Field values passed to the underlying
BaseModel.
Examples
>>> class MyModel(PymobModel): ... a: int = 1 ... b: str = "x" >>> m = MyModel() >>> m["a"] 1 >>> m["b"] = "y" >>> m.b 'y'
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class pymob.sim.config.Pymoo(*, algortihm: str = 'UNSGA3', population_size: int = 100, max_nr_populations: int = 1000, ftol: float = 1e-05, xtol: float = 1e-07, cvtol: float = 1e-07, verbose: bool = True)#
Bases:
PymobModelConfiguration for the pymoo multi-objective optimisation backend.
- algortihm#
Optimisation algorithm.
- Type:
str
- population_size, max_nr_populations
Population settings.
- Type:
int
- ftol, xtol, cvtol
Tolerances.
- Type:
float
- verbose#
Verbosity flag.
- Type:
bool
- algortihm: str#
- cvtol: float#
- ftol: float#
- max_nr_populations: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'algortihm': FieldInfo(annotation=str, required=False, default='UNSGA3'), 'cvtol': FieldInfo(annotation=float, required=False, default=1e-07, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'ftol': FieldInfo(annotation=float, required=False, default=1e-05, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'max_nr_populations': FieldInfo(annotation=int, required=False, default=1000, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'population_size': FieldInfo(annotation=int, required=False, default=100, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'verbose': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'xtol': FieldInfo(annotation=float, required=False, default=1e-07, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- population_size: int#
- verbose: bool#
- xtol: float#
- class pymob.sim.config.RandomVariable(*, distribution: str, parameters: Dict[str, Expression], obs: Expression | None = None, obs_inv: Expression | None = None)#
Bases:
BaseModelBasic infrastructure to parse priors into their components so that they can be more easily parsed to other backends. Parsing to distributions needs more context: - other parameters (for hierarchical parameter structures) - data structure and coordinates to identify dimension sizes
- classmethod check_distribution(new_value, info, **kwargs)#
- classmethod check_parameters(new_value, info, **kwargs)#
- distribution: str#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'distribution': FieldInfo(annotation=str, required=True), 'obs': FieldInfo(annotation=Union[Expression, NoneType], required=False), 'obs_inv': FieldInfo(annotation=Union[Expression, NoneType], required=False), 'parameters': FieldInfo(annotation=Dict[str, Expression], required=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_ser() str#
- obs: Expression | None#
- obs_inv: Expression | None#
- parameters: Dict[str, Expression]#
- class pymob.sim.config.Redis(*, password: str = 'nopassword', port: int = 1111, **extra_data: Any)#
Bases:
PymobModelConfiguration for the Redis backend used by pyABC.
- password#
Redis password.
- Type:
str
- port#
Port number.
- Type:
int
- n_predictions, history_id, model_id
Evaluation settings.
- Type:
int
- history_id: int#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'history_id': FieldInfo(annotation=int, required=False, default=-1, alias='eval.history_id', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'model_id': FieldInfo(annotation=int, required=False, default=0, alias='eval.model_id', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'n_predictions': FieldInfo(annotation=int, required=False, default=50, alias='eval.n_predictions', alias_priority=2, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'password': FieldInfo(annotation=str, required=False, default='nopassword'), 'port': FieldInfo(annotation=int, required=False, default=1111, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_id: int#
- model_post_init(__context: Any) None#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
__context – The context.
- n_predictions: int#
- password: str#
- port: int#
- class pymob.sim.config.Report(*, debug_report: bool = False, pandoc_output_format: Literal['html', 'latex-si', 'latex', 'pdf'] = 'html', model: bool = True, parameters: bool = True, parameters_format: Literal['xarray', 'pandas'] = 'pandas', diagnostics: bool = True, diagnostics_with_batch_dim_vars: bool = False, diagnostics_exclude_vars: List[str] = [], goodness_of_fit: bool = True, goodness_of_fit_use_predictions: bool = True, goodness_of_fit_nrmse_mode: Literal['mean', 'range', 'iqr'] = 'range', table_parameter_estimates: bool = True, table_parameter_estimates_format: Literal['latex', 'csv', 'tsv'] = 'csv', table_parameter_estimates_significant_figures: int = 3, table_parameter_estimates_error_metric: Literal['hdi', 'sd'] = 'sd', table_parameter_estimates_parameters_as_rows: bool = True, table_parameter_estimates_with_batch_dim_vars: bool = False, table_parameter_estimates_exclude_vars: List[str] = [], table_parameter_estimates_override_names: Mapping[str, str | float | int | List[float | int]] = {}, plot_trace: bool = True, plot_parameter_pairs: bool = True)#
Bases:
PymobModelConfiguration for report generation.
- debug_report#
Include debug information.
- Type:
bool
- pandoc_output_format#
Output format for the generated report.
- Type:
Literal[“html”, “latex-si”, “latex”, “pdf”]
- model, parameters, diagnostics, goodness_of_fit,
- table_parameter_estimates, plot_trace, plot_parameter_pairs
Flags controlling which sections are included.
- Type:
bool
- debug_report: bool#
- diagnostics: bool#
- diagnostics_exclude_vars: List[str]#
- diagnostics_with_batch_dim_vars: bool#
- goodness_of_fit: bool#
- goodness_of_fit_nrmse_mode: Literal['mean', 'range', 'iqr']#
- goodness_of_fit_use_predictions: bool#
- model: bool#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'debug_report': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'diagnostics': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'diagnostics_exclude_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'diagnostics_with_batch_dim_vars': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'goodness_of_fit': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'goodness_of_fit_nrmse_mode': FieldInfo(annotation=Literal['mean', 'range', 'iqr'], required=False, default='range'), 'goodness_of_fit_use_predictions': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'model': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'pandoc_output_format': FieldInfo(annotation=Literal['html', 'latex-si', 'latex', 'pdf'], required=False, default='html'), 'parameters': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'parameters_format': FieldInfo(annotation=Literal['xarray', 'pandas'], required=False, default='pandas'), 'plot_parameter_pairs': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'plot_trace': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_error_metric': FieldInfo(annotation=Literal['hdi', 'sd'], required=False, default='sd'), 'table_parameter_estimates_exclude_vars': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_format': FieldInfo(annotation=Literal['latex', 'csv', 'tsv'], required=False, default='csv'), 'table_parameter_estimates_override_names': FieldInfo(annotation=Mapping[str, Union[str, float, int, List[Union[float, int]]]], required=False, default={}, metadata=[BeforeValidator(func=functools.partial(<function string_to_dict>, split_str=' ', sep_str='=')), PlainSerializer(func=functools.partial(<function dict_to_string>, replace_whitespace=''), return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_parameters_as_rows': FieldInfo(annotation=bool, required=False, default=True, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'table_parameter_estimates_significant_figures': FieldInfo(annotation=int, required=False, default=3), 'table_parameter_estimates_with_batch_dim_vars': FieldInfo(annotation=bool, required=False, default=False, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- pandoc_output_format: Literal['html', 'latex-si', 'latex', 'pdf']#
- parameters: bool#
- parameters_format: Literal['xarray', 'pandas']#
- plot_parameter_pairs: bool#
- plot_trace: bool#
- table_parameter_estimates: bool#
- table_parameter_estimates_error_metric: Literal['hdi', 'sd']#
- table_parameter_estimates_exclude_vars: List[str]#
- table_parameter_estimates_format: Literal['latex', 'csv', 'tsv']#
- table_parameter_estimates_override_names: Mapping[str, str | float | int | List[float | int]]#
- table_parameter_estimates_parameters_as_rows: bool#
- table_parameter_estimates_significant_figures: int#
- table_parameter_estimates_with_batch_dim_vars: bool#
- class pymob.sim.config.Simulation(*, model: str | None = None, model_class: str | None = None, solver: str | None = None, y0: List[str] = [], x_in: List[str] = [], input_files: List[str] = [], n_ode_states: int = -1, batch_dimension: str = 'batch_id', x_dimension: str = 'time', modeltype: Literal['stochastic', 'deterministic'] = 'deterministic', solver_post_processing: str | None = None, seed: int = 1, **extra_data: Any)#
Bases:
PymobModelConfiguration model for a simulation.
- model, solver
Names of the deterministic model and solver to use.
- Type:
Optional[str]
- y0, x_in, input_files
Lists of initial condition files, exposure files and other input files.
- Type:
List[str]
- n_ode_states#
Number of ODE states;
-1means autodetect.- Type:
int
- batch_dimension, x_dimension
Names of the batch and time dimensions.
- Type:
str
- modeltype#
Type of model.
- Type:
Literal[“stochastic”, “deterministic”]
- seed#
Random seed.
- Type:
int
- batch_dimension: str#
- input_files: List[str]#
- model: str | None#
- model_class: str | None#
- model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'protected_namespaces': (), 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'batch_dimension': FieldInfo(annotation=str, required=False, default='batch_id'), 'input_files': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'model': FieldInfo(annotation=Union[str, NoneType], required=False, description='The deterministic model', validate_default=True), 'model_class': FieldInfo(annotation=Union[str, NoneType], required=False, description='A class that holds the mechanistic model. This is the path to the module class, e.g. `lotka_volterra_case_study.mod.Model`.', validate_default=True), 'modeltype': FieldInfo(annotation=Literal['stochastic', 'deterministic'], required=False, default='deterministic'), 'n_ode_states': FieldInfo(annotation=int, required=False, default=-1), 'seed': FieldInfo(annotation=int, required=False, default=1, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), 'solver': FieldInfo(annotation=Union[str, NoneType], required=False, validate_default=True), 'solver_post_processing': FieldInfo(annotation=Union[str, NoneType], required=False, validate_default=True), 'x_dimension': FieldInfo(annotation=str, required=False, default='time'), 'x_in': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'y0': FieldInfo(annotation=List[str], required=False, default=[], metadata=[BeforeValidator(func=<function string_to_list>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- modeltype: Literal['stochastic', 'deterministic']#
- n_ode_states: int#
- seed: int#
- solver: str | None#
- solver_post_processing: str | None#
- x_dimension: str#
- x_in: List[str]#
- y0: List[str]#
- class pymob.sim.config.Solverbase(*, x_dim: str = 'time', exclude_kwargs_model: Tuple[str, ...] = ('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), exclude_kwargs_postprocessing: Tuple[str, ...] = ('t', 'time', 'interpolation', 'results'))#
Bases:
PymobModelBase configuration for solvers.
- x_dim#
Name of the time dimension.
- Type:
str
- exclude_kwargs_model, exclude_kwargs_postprocessing
Keyword arguments to exclude when passing to the model or post-processing.
- Type:
Tuple[str, …]
- exclude_kwargs_model: Tuple[str, ...]#
- exclude_kwargs_postprocessing: Tuple[str, ...]#
- model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'exclude_kwargs_model': FieldInfo(annotation=Tuple[str, ...], required=False, default=('t', 'time', 'x_in', 'y', 'x', 'Y', 'X'), metadata=[BeforeValidator(func=<function string_to_tuple>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'exclude_kwargs_postprocessing': FieldInfo(annotation=Tuple[str, ...], required=False, default=('t', 'time', 'interpolation', 'results'), metadata=[BeforeValidator(func=<function string_to_tuple>), PlainSerializer(func=<function list_to_string>, return_type=<class 'str'>, when_used='json')]), 'x_dim': FieldInfo(annotation=str, required=False, default='time')}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- x_dim: str#
- pymob.sim.config.register_case_study_config(name: str, model_cls: Type[BaseModel]) None#
Register a Pydantic model for a case-study-specific configuration section.
- Parameters:
name (str) – Identifier matching
case_study.name(e.g.lotka_volterra_case_study).model_cls (Type[BaseModel]) – The Pydantic model that defines the expected options for the section.