pymob.sim package#

Submodules#

pymob.sim.config module#

class pymob.sim.config.Casestudy(*, init_root: str = '/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/0.5.23/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: PymobModel

Configuration 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.cfg file for the case study.

Return type:

str

init_root: str#
logfile: str | None#
logging: str#
model_config: ClassVar[ConfigDict] = {'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/0.5.23/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: BaseModel

Configuration manager for pymob.

This class loads a settings.cfg file, 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.

case_study: Casestudy#
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 True create 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.path before importing. Default is False.

import_simulation_from_case_study() Any#

Retrieve the Simulation class defined in the case-study.

Returns:

The Simulation class object.

Return type:

Any

Raises:

ImportError – If the class cannot be found.

inference: Inference#
inference_numpyro: Numpyro#
inference_pyabc: Pyabc#
inference_pyabc_redis: Redis#
inference_pymoo: Pymoo#
property input_file_paths: List[str]#

List of all input files required for the simulation.

Return type:

List[str]

jaxsolver: Jaxsolver#
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/0.5.23/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(), 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, 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.

report: Report#
save(fp: str | None = None, force: bool = False) None#

Save the configuration to a settings.cfg file.

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 None the 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], min: float = nan, max: float = nan, observed: bool = True, dimensions_evaluator: List[str] | None = None)#

Bases: BaseModel

Describe 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.nan means the minimum is taken from the observations. Default is np.nan.

  • max (float, optional) – Maximum value used for scaling. np.nan means the maximum is taken from the observations. Default is np.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 None the order of dimensions is 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)}#

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_evaluator matches dimensions.

classmethod set_data_variable_bounds(v, info, **kwargs) List[str] | None#

Ensure that dimensions_evaluator has the same length and names as dimensions.

Raises:

AssertionError – If the lengths differ or the sets of names differ.

class pymob.sim.config.Datastructure(**extra_data: Any)#

Bases: PymobModel

Container for data-variable definitions.

The class stores DataVariable objects 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 max values for all data variables.

property data_variables_min: List[float]#

List of min values 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

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 observed_data_variables: List[str]#

List of observed data-variable names.

property observed_data_variables_max: List[float]#

List of max values for observed data variables.

property observed_data_variables_min: List[float]#

List of min values 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: PymobModel

Container for error-model specifications.

Each entry is an OptionRV describing 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.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: PymobModel

Configuration 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] = {'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: PymobModel

Configuration 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] = {}#

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.ModelParameterDict#

Bases: TypedDict

Typed 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.Modelparameters(**extra_data: Any)#

Bases: PymobModel

Container for model parameters.

Parameters are stored in __pydantic_extra__ as Param objects.

property all: Dict[str, Param]#

All parameters.

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: Dict[str, Param]#

Parameters marked as fixed.

property fixed_value_dict: int32'>)]]#

Dictionary of fixed parameter values.

property free: Dict[str, Param]#

Parameters marked as free.

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: PymobModel

Configuration for multiprocessing.

cores#

Number of cores to use. 1 means 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: PymobModel

Configuration 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.ParameterDict(*args, **kwargs)#

Bases: dict

Dictionary 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.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: PymobModel

Configuration 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] = {'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: BaseModel

Base class for all configuration models used in pymob.

This class inherits from pydantic.BaseModel and 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] = {}#

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: PymobModel

Configuration 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.Redis(*, password: str = 'nopassword', port: int = 1111, **extra_data: Any)#

Bases: PymobModel

Configuration 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] = {'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: Dict[str, str | float | int | List[float | int]] = {}, plot_trace: bool = True, plot_parameter_pairs: bool = True)#

Bases: PymobModel

Configuration 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=Dict[str, Union[str, float, int, List[Union[float, int]]]], required=False, default={}, metadata=[BeforeValidator(func=<function string_to_dict>), PlainSerializer(func=<function dict_to_string>, 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: Dict[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, 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: PymobModel

Configuration 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; -1 means 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_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]] = {'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), '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: PymobModel

Base 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': 'forbid', '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.datavar_to_string(prm: DataVariable) str#

Serialize a DataVariable to a key=value string.

Parameters:

prm (DataVariable) –

Return type:

str

pymob.sim.config.dict_to_string(dct: Dict, replace_whitespace='') str#

Serialize a dictionary to a space-separated key=value string.

Parameters:
  • dct (dict) – Dictionary to serialize.

  • replace_whitespace (str, optional) – Replacement for whitespace inside values.

Return type:

str

pymob.sim.config.list_to_string(lst: List) str#

Serialize a list to a space-separated string.

Parameters:

lst (List) –

Return type:

str

pymob.sim.config.param_to_string(prm: Param) str#

Serialize a Param to a key=value string.

Parameters:

prm (Param) –

Return type:

str

pymob.sim.config.string_to_datavar(option: str | DataVariable) DataVariable#

Convert a string or DataVariable instance to a DataVariable.

Parameters:

option (str | DataVariable) –

Return type:

DataVariable

pymob.sim.config.string_to_dict(option: Dict[str, str | float | int | List[float | int | str]] | str) Dict[str, str | float | int | List[float | int | str]]#

Parse a configuration string into a dictionary.

The string must consist of space-separated key=value pairs. Values are interpreted as float, NumericArray or 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.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.string_to_param(option: str | Param) Param#

Convert a string or Param instance to a Param.

Parameters:

option (str | Param) –

Return type:

Param

pymob.sim.config.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.base module#

pymob.sim.base.enlist_attr(ds: Dataset | DataArray, attr: str)#

Transforms a string representation of a metadata attribute of an xarray dataset or datarray to a list

pymob.sim.base.stack_variables(ds: ~xarray.core.dataset.Dataset, variables: ~typing.List[str], new_coordinates: ~typing.List[str], new_dim: str, pattern: ~typing.Callable = <function <lambda>>)#

Combine data variables and coordinates into a new variable of a higher dimension.

Parameters:
  • ds (xr.Dataset) – The input xarray Dataset.

  • variables (List[str]) – List of variable bases to stack.

  • new_coordinates (List[str]) – List of new coordinates for the higher dimension. Note that this must be the same for all variables you want to stack.

  • new_dim (str) – The name of the new dimension.

  • pattern (Callable, optional) – A function to generate names for new variables based on the variable and coordinate names.

Returns:

The modified xarray Dataset with stacked variables.

Return type:

xr.Dataset

Examples

A use case is the following. Consider a dataset that has the variables

cext_A cext_B cext_C my_other_var_1 my_other_var_2

And you want to combine the variables with the same base cext_ into a new variable that has the base as a dimension.

>>> import xarray as xr
>>> from typing import List, Callable
>>> from pymob.sim.base import stack_variables
>>>
>>> # Example usage:
>>> an_xarray_dataset = xr.Dataset({
...     'cext_A': ([], 1.0),
...     'cext_B': ([], 2.0),
...     'cext_C': ([], 3.0),
...     'my_other_var_1': ([], 4.0),
...     'my_other_var_2': ([], 5.0),
... })
>>>
>>> result_dataset = stack_variables(
...     ds=an_xarray_dataset,
...     variables=["cext"],
...     new_coordinates=["A", "B", "C"],
...     new_dim="letters",
... )
>>>
>>> result_dataset
<xarray.Dataset>
Dimensions:         (letters: 3)
Coordinates:
  * letters         (letters) <U1 'A' 'B' 'C'
Data variables:
    my_other_var_1  float64 4.0
    my_other_var_2  float64 5.0
    cext            (letters) float64 1.0 2.0 3.0
pymob.sim.base.unlist_attrs(ds: Dataset | DataArray)#

Transforms lists of variables to a comma separated string to work around errors when storing the dataset or dataarray to disk

pymob.sim.evaluator module#

class pymob.sim.evaluator.Evaluator(model: Callable, solver: type | Callable, dimensions: Sequence[str], dimension_sizes: Dict[str, int], parameter_dims: Dict[str, Tuple[str, ...]], n_ode_states: int, var_dim_mapper: Dict, data_structure: Dict, data_structure_and_dimensionality: Dict, coordinates: Dict[str, ndarray[Any, dtype[ScalarType]]], coordinates_input_vars: Dict[str, Dict[str, Dict[str, ndarray[Any, dtype[ScalarType]]]]], dims_input_vars: Dict[str, Dict[str, Tuple[str, ...]]], coordinates_indices: Dict, data_variables: Sequence[str], stochastic: bool, batch_dimension: str, indices: Dict = {}, post_processing: Callable | None = None, solver_options: Dict = {}, **kwargs)#

Bases: object

The Evaluator is an instance to evaluate a model. It’s purpose is primarily to create objects that can be spawned and evaluated in parallel and can individually track the results of a simulation or a parameter inference process. If needed the evaluations can be tracked and results can later be collected.

Seed may not be set as a property, because this should be something passed through

property allowed_model_signature_arguments#
property dimensionality#
get_call_signature()#
property parameters: frozendict#
result: Dataset#
property results#
spawn()#
pymob.sim.evaluator.create_dataset_from_dict(Y: dict, data_structure, coordinates, var_dim_mapper)#
pymob.sim.evaluator.create_dataset_from_numpy(Y, Y_names, coordinates)#

pymob.sim.solvetools module#

Module contents#