pymob.sim package#
Submodules#
pymob.sim.config module#
- class pymob.sim.config.ArrayParam(*, name: str | None = None, value: List[float] = [0.0], min: List[float] | None = None, max: List[float] | None = None, step: List[float] | None = None, prior: str | None = None, free: bool = True)#
Bases:
BaseModel- free: bool#
- max: List[float] | None#
- min: List[float] | None#
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'free': FieldInfo(annotation=bool, required=False, default=True), 'max': FieldInfo(annotation=Union[List[float], NoneType], required=False), 'min': FieldInfo(annotation=Union[List[float], NoneType], required=False), 'name': FieldInfo(annotation=Union[str, NoneType], required=False), 'prior': FieldInfo(annotation=Union[str, NoneType], required=False), 'step': FieldInfo(annotation=Union[List[float], NoneType], required=False), 'value': FieldInfo(annotation=List[float], required=False, default=[0.0])}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- name: str | None#
- prior: str | None#
- step: List[float] | None#
- value: List[float]#
- class pymob.sim.config.Casestudy(*, init_root: str = '/home/docs/checkouts/readthedocs.org/user_builds/pymob/checkouts/0.4.0/docs/source', root: str = '.', name: str = 'unnamed_case_study', 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: List[str] = [], logging: str = 'DEBUG', logfile: str | None = None)#
Bases:
BaseModel- 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.4.0/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=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')]), 'output': FieldInfo(annotation=Union[str, NoneType], required=False), 'package': FieldInfo(annotation=str, required=False, default='case_studies'), '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.')}#
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: List[str]#
- output: str | None#
- property output_path: str#
- package: str#
- root: str#
- scenario: str#
- property scenario_path#
- classmethod set_root(new_value, info, **kwargs)#
- simulation: str#
- class pymob.sim.config.Config(config: str | ConfigParser | None = None)#
Bases:
BaseModelConfiguration manager for pymob.
- create_directory(directory: Literal['results', 'scenario'], force=False)#
- data_structure: Datastructure#
- error_model: Errormodel#
- import_casestudy_modules()#
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() Callable#
- property input_file_paths: list#
- 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.4.0/docs/source', root='.', name='unnamed_case_study', scenario='unnamed_scenario', package='case_studies', modules=['sim', 'mod', 'prob', 'data', 'plot'], simulation='Simulation', output=None, data=None, observations=[], 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(objective_function='total_average', n_objectives=1, objective_names=[], backend=None, extra_vars=[], plot=None, n_predictions=1)), 'inference_numpyro': FieldInfo(annotation=Numpyro, required=False, default=Numpyro(user_defined_probability_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, svi_iterations=10000, svi_learning_rate=0.0001, sa_adapt_state_size=None), 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), '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)), 'simulation': FieldInfo(annotation=Simulation, required=False, default=Simulation(model=None, solver=None, y0=[], x_in=[], input_files=[], n_ode_states=-1, replicated=False, modeltype='stochastic', solver_post_processing=None, seed=1))}#
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()#
- 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)
- simulation: Simulation#
- class pymob.sim.config.DataVariable(*, dimensions: List[str], min: float = nan, max: float = nan, dimensions_evaluator: List[str] | None = None)#
Bases:
BaseModelDescribe 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
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] = {}#
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)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- post_update()#
- classmethod set_data_variable_bounds(v, info, **kwargs)#
- class pymob.sim.config.Datastructure(**extra_data: Any)#
Bases:
BaseModel- 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 var_dim_mapper: Dict[str, List[str]]#
- class pymob.sim.config.Errormodel(**extra_data: Any)#
Bases:
BaseModel- property all: Dict[str, 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.
- class pymob.sim.config.FloatParam(*, name: str | None = None, value: float = 0.0, min: float | None = None, max: float | None = None, step: float | None = None, prior: str | None = None, free: bool = True)#
Bases:
BaseModel- free: bool#
- max: float | None#
- min: float | None#
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'free': FieldInfo(annotation=bool, required=False, default=True), 'max': FieldInfo(annotation=Union[float, NoneType], required=False), 'min': FieldInfo(annotation=Union[float, NoneType], required=False), 'name': FieldInfo(annotation=Union[str, NoneType], required=False), 'prior': FieldInfo(annotation=Union[str, NoneType], required=False), 'step': FieldInfo(annotation=Union[float, NoneType], required=False), 'value': FieldInfo(annotation=float, required=False, default=0.0)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- name: str | None#
- prior: str | None#
- step: float | None#
- value: float#
- class pymob.sim.config.Inference(*, 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 = 1)#
Bases:
BaseModel- backend: str | None#
- 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), '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=1, 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.Modelparameters(**extra_data: Any)#
Bases:
BaseModel- property all: Dict[str, FloatParam | ArrayParam]#
- property fixed: Dict[str, FloatParam | ArrayParam]#
- property free: Dict[str, FloatParam | ArrayParam]#
- property free_value_dict: Dict[str, float | List[float]]#
- 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#
- property value_dict: Dict[str, float | List[float]]#
- class pymob.sim.config.Multiprocessing(*, cores: int = 1)#
Bases:
BaseModel- 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_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, svi_iterations: int = 10000, svi_learning_rate: float = 0.0001, sa_adapt_state_size: int | None = None)#
Bases:
BaseModel- 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'), '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_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.
- sa_adapt_state_size: int | None#
- svi_iterations: int#
- svi_learning_rate: float#
- thinning: int#
- 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:
BaseModel- 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.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:
BaseModel- 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:
BaseModel- 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.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, replicated: bool = False, modeltype: Literal['stochastic', 'deterministic'] = 'stochastic', solver_post_processing: str | None = None, seed: int = 1, **extra_data: Any)#
Bases:
BaseModel- 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]] = {'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='stochastic'), 'n_ode_states': FieldInfo(annotation=int, required=False, default=-1), 'replicated': FieldInfo(annotation=bool, required=False, default=False), '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_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#
- replicated: bool#
- seed: int#
- solver: str | None#
- solver_post_processing: str | None#
- x_in: List[str]#
- y0: List[str]#
- pymob.sim.config.datavar_to_string(prm: DataVariable)#
- pymob.sim.config.dict_to_string(dct: Dict)#
- pymob.sim.config.list_to_string(lst: List)#
- pymob.sim.config.param_to_string(prm: ArrayParam | FloatParam)#
- 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 | FloatParam | ArrayParam) FloatParam | ArrayParam#
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.evaluators 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", ... ) >>> >>> print(result_dataset) <xarray.Dataset> Dimensions: (letters: 3) Coordinates: * letters (letters) <U1 'A' 'B' 'C' Data variables: my_other_var_1 (float64) float64 4.0 my_other_var_2 (float64) 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: Callable, parameters: Dict, dimensions: Sequence[str], n_ode_states: int, var_dim_mapper: Dict, data_structure: Dict, coordinates: Dict, data_variables: Sequence[str], stochastic: bool, indices: Dict | None = {}, post_processing: Callable | None = None, **kwargs)#
Bases:
objectThe 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()#
- result: Dataset#
- property results#
- pymob.sim.evaluator.create_dataset_from_dict(Y: dict, data_structure, coordinates)#
- pymob.sim.evaluator.create_dataset_from_numpy(Y, Y_names, coordinates)#
pymob.sim.solvetools module#
- class pymob.sim.solvetools.SolverBase#
Bases:
objectThe idea of creating a solver as a class is that it is easier to pass on important arguments of the simulation relevant to the Solver. Therefore a solver can access all attributes of an Evaluator
- static solve()#
- pymob.sim.solvetools.create_interpolation(x_in: Dataset, y: str, x: str = 'time', factor: float = 0.0001, interpolation: Literal['fill-forward', 'linear'] = 'fill-forward') Dataset#
Make the interpolation safe by adding a coordinate just before each x-value (except the first vaue). The distance between the new and the next point are calculated as a fraction of the previous distance between neighboring points. The corresponding y-values are first set to NaN and then interpolated based on the interpolation method.
- Parameters:
x_in (xr.Dataset) – The input dataset which contains a coordinate (x) and a data variable (y)
x (str, optional) – The name of the x coordinate, by default “time”
factor (float, optional) – The distance between the newly added points and the following existing points on the x-scale, by default 1e-4
interpolation (Literal["fill-forward", "linear"], optional) – The interpolation method. In addition to ‘fill-forward’ and ‘linear’, any method give in xr.interpolate_na can be chosen, by default “fill-forward”
- Returns:
The interpolated dataset
- Return type:
xr.Dataset
- pymob.sim.solvetools.mappar(func, parameters, exclude=[], to: Literal['tuple', 'dict'] = 'tuple')#
- pymob.sim.solvetools.solve_analytic_1d(model, parameters, dimensions, coordinates, data_variables, seed=None)#
Solves an anlytic function for all coordinates in the first data dimension of the model
parameters: define the model
y0: set the initial values of the ODE states
coordinates: are needed to know over which values to integrate
seed: In case stochastic processes take place inside the model this is necessary
In order to make things explicit, all information which is needed by the model needs to be specified in the function signature. This also makes the solvers functionally oriented, a feature that helps the usability of models accross inference frameworks. Where functions should not have side effects.
Additionally, passing arguments via the signature makes it easier to write up models in a casual way and only later embed them into more regulated structures such as pymob
- pymob.sim.solvetools.solve_ivp_1d(model, parameters, coordinates, data_variables)#
Initial value problems always need the same number of recurrent arguments
parameters: define the model
y0: set the initial values of the ODE states
coordinates: are needed to know over which values to integrate
seed: In case stochastic processes take place inside the model this is necessary
In order to make things explicit, all information which is needed by the model needs to be specified in the function signature. This also makes the solvers functionally oriented, a feature that helps the usability of models accross inference frameworks. Where functions should not have side effects.
Additionally, passing arguments via the signature makes it easier to write up models in a casual way and only later embed them into more regulated structures such as pymob