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.4/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, observations: str | None = None, logging: str = 'DEBUG', logfile: str | None = None)#

Bases: PymobModel

data: str | None#
property data_path: str#
property default_settings_path: 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.4/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'), '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#
package: str#
pymob_version: str | None#
root: str#
scenario: str#
property scenario_path#
classmethod set_root(new_value, info, **kwargs)#
simulation: str#
version: str | None#
class pymob.sim.config.Config(config: str | ConfigParser | None = None)#

Bases: BaseModel

Configuration manager for pymob.

case_study: Casestudy#
create_directory(directory: Literal['results', 'scenario'], force=False)#
data_structure: Datastructure#
error_model: Errormodel#
import_casestudy_modules(reset_path=False)#

this script handles the import of a case study without the typical __init__.py file. It iterates through all .py files in the root directory of the case study (typically: sim, mod, stats, plot, data, prior) and imports them with import_module(…)

import_simulation_from_case_study()#
inference: Inference#
inference_numpyro: Numpyro#
inference_pyabc: Pyabc#
inference_pyabc_redis: Redis#
inference_pymoo: Pymoo#
property input_file_paths: list#
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.4/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, 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(table_parameter_estimates=True, table_parameter_estimates_format='csv', table_parameter_estimates_error_metric='sd', table_parameter_estimates_parameters_as_rows=True, table_parameter_estimates_with_batch_dim_vars=False, 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()#
report: Report#
save(fp: str | None = None, force=False)#

Saves 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 (Optiona[str] file path to write the settings file to) –

  • force ([bool] should the settings file be overwritten without asking) – for user confirmation (default: False)

set_option(section: str, option: str, value: str)#
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

Parameters:
  • dimensions (List[str]) – Specifies the dimensions, which have to be found in the observations and the dimensional order of the data variable

  • min (float) – The possible minimum of a data variable, is used to construct scalers. Defaults to ‘nan’, which sets the minimum to the minimum of the observations

  • min – The possible maxmimum of a data variable, is used to construct scalers Defaults to ‘nan’, which sets the maximum to the maximum of the observations

  • observed (bool) – If the data-variable was observed or not. Defaults to True

  • dimensions_evaluator (List[str]) – Specifies the dimensions and their order returned by the evaluator. This is necessary to bring observations and results together, if for some reason the returned simulation results from the evaluator have a different dimensional order than the observations

Return type:

None

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()#
classmethod set_data_variable_bounds(v, info, **kwargs)#
class pymob.sim.config.Datastructure(**extra_data: Any)#

Bases: PymobModel

property all: Dict[str, DataVariable]#
property data_variables: List[str]#
property data_variables_max#
property data_variables_min#
property dimdict: Dict[str, List[str]]#
property dimensions: List[str]#
property evaluator_dim_order: 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]] = {}#

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]#
property observed_data_variables_max#
property observed_data_variables_min#
property observed_dimdict: Dict[str, List[str]]#
remove(key) None#

Removes a data variable from the data structure

property var_dim_mapper: Dict[str, List[str]]#
class pymob.sim.config.Errormodel(**extra_data: Any)#

Bases: PymobModel

property all: Dict[str, RandomVariable]#
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

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

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

parameters: Dict[str, float | str | int]#
x_in: Dataset#
y0: Dataset#
class pymob.sim.config.Modelparameters(**extra_data: Any)#

Bases: PymobModel

property all: Dict[str, Param]#
property dimensions: List[str]#
property fixed: Dict[str, Param]#
property fixed_value_dict: int64'>)]]#
property free: Dict[str, Param]#
property free_value_dict: int64'>)]]#
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#
remove(key) None#

Removes a Parameter

reorder(keys: List[str])#

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]) – A list of model parameters to sort the model_parameter dictionary after. If the keys list is smaller than the list of model parameters, unlisted parameters will be appended to the keys list in order.

property value_dict: int64'>)]]#
class pymob.sim.config.Multiprocessing(*, cores: int = 1)#

Bases: PymobModel

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

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, metadata=[PlainSerializer(func=<function <lambda>>, return_type=<class 'str'>, when_used='json')]), '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

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

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

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

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

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

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

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(*, table_parameter_estimates: bool = True, table_parameter_estimates_format: Literal['latex', 'csv', 'tsv'] = 'csv', 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_override_names: Dict[str, str | float | int | List[float | int]] = {}, plot_trace: bool = True, plot_parameter_pairs: bool = True)#

Bases: PymobModel

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]] = {'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_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_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.

plot_parameter_pairs: bool#
plot_trace: bool#
table_parameter_estimates: bool#
table_parameter_estimates_error_metric: Literal['hdi', 'sd']#
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_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

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

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)#
pymob.sim.config.dict_to_string(dct: Dict, replace_whitespace='')#
pymob.sim.config.list_to_string(lst: List)#
pymob.sim.config.param_to_string(prm: Param)#
pymob.sim.config.string_to_datavar(option: str | DataVariable) 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]]#

Expects a string of this form e.g. ‘value=1 max=10 min=0 prior=Lognormal(loc=2,scale=1)’

pymob.sim.config.string_to_list(option: List | str) List#
pymob.sim.config.string_to_param(option: str | Param) Param#
pymob.sim.config.string_to_tuple(option: List | str) Tuple#

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#