### Run calisim example with Docker Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Execute an example script within a calisim Docker container. ```bash docker compose run --rm calisim python examples/optimisation/optuna_example.py ``` -------------------------------- ### Install calisim with Optional Extras Source: https://calisim.readthedocs.io/en/latest/tutorials/basics/installation.html Install calisim with specific optional dependencies like PyTorch, Hydra, or TorchX. You can install multiple extras by separating them with commas. ```bash # Install PyTorch extras pip install calisim[torch] ``` ```bash # Install Hydra extras pip install calisim[hydra] ``` ```bash # Install TorchX extras pip install calisim[torchx] ``` ```bash # Install multiple extras pip install calisim[torch,hydra,torchx] ``` -------------------------------- ### Install calisim with TorchX extras Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Install calisim with TorchX optional dependencies. ```bash pip install calisim[torchx] ``` -------------------------------- ### Install calisim with multiple extras Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Install calisim with PyTorch, Hydra, and TorchX optional dependencies. ```bash pip install calisim[torch,hydra,torchx] ``` -------------------------------- ### get_examples_outdir() Source: https://calisim.readthedocs.io/en/latest/api_reference/utils.html Provides the designated output directory for calibration examples. ```APIDOC ## get_examples_outdir() ### Description Get the output directory for calibration examples. ### Returns - **str** - The output directory. ``` -------------------------------- ### Install calisim with PyTorch extras Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Install calisim with PyTorch optional dependencies. ```bash pip install calisim[torch] ``` -------------------------------- ### Install calisim with pip Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Use this command to install the base calisim package. ```bash pip install calisim ``` -------------------------------- ### Install calisim with Hydra extras Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Install calisim with Hydra optional dependencies. ```bash pip install calisim[hydra] ``` -------------------------------- ### SPOTSetup Class Source: https://calisim.readthedocs.io/en/latest/api_reference/evolutionary.html The SPOTSetup class handles the configuration and execution of SPOTPY calibration setups. ```APIDOC ## Class SPOTSetup ### Description The SPOTPY calibration setup. ### Methods #### evaluation() ##### Description Get the observed data. ##### Returns The observed data. ##### Return Type np.ndarray | pd.DataFrame ##### Signature evaluation() -> ndarray | DataFrame #### objectivefunction(simulation, evaluation) ##### Description Call the objective function on simulated and observed data. ##### Parameters - **simulation** (np.ndarray | pd.DataFrame) - The simulated data. - **evaluation** (np.ndarray | pd.DataFrame) - The observed data. ##### Returns The objective function results. ##### Return Type float ##### Signature objectivefunction(_simulation : ndarray | DataFrame_, _evaluation : ndarray | DataFrame_) -> float #### parameters() ##### Description Generate parameters from the prior specification. ##### Returns The generated parameters. ##### Return Type np.ndarray ##### Signature parameters() -> ndarray #### setup_from_workflow(workflow) ##### Description Configure the calibration procedure from the workflow object. ##### Parameters - **workflow** (CalibrationWorkflowBase) - The calibration workflow object. ##### Signature setup_from_workflow(_workflow : CalibrationWorkflowBase_) -> None #### simulation(X) ##### Description Run the simulation. ##### Parameters - **X** (np.ndarray) - The simulation parameter vector. ##### Returns The simulation results. ##### Return Type np.ndarray ##### Signature simulation(_X : ndarray_) -> ndarray ``` -------------------------------- ### Initialize LotkaVolterraModel and get observed data Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Instantiate the LotkaVolterraModel and retrieve its observed data. This is a prerequisite for setting up calibration. ```python model = LotkaVolterraModel() observed_data = model.get_observed_data() observed_data.head(5) ``` -------------------------------- ### ExampleModelContainer Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Container for example models. ```APIDOC ## Class: ExampleModelContainer ### Description Container for example models. ### Parameters * `_model` (ExampleModelBase): The model to contain. ``` -------------------------------- ### Run calisim with Docker Source: https://calisim.readthedocs.io/en/latest/tutorials/basics/installation.html Instructions for setting up and running calisim within a Docker container. This involves setting the version, downloading the docker-compose.yaml file, pulling the image, and running an example. ```bash # Change the image version as needed export CALISIM_VERSION=latest # Get docker-compose.yaml file wget https://raw.githubusercontent.com/Plant-Food-Research-Open/calisim/refs/heads/main/docker-compose.yaml # Pull the image docker compose pull calisim # Run an example docker compose run --rm calisim python examples/optimisation/optuna_example.py ``` -------------------------------- ### get_def Source: https://calisim.readthedocs.io/en/latest/api_reference/orchestration.html Get the application definition for TorchX. ```APIDOC ## get_def ### Description Get the application definition. ### Parameters * **orchestration** (_OrchestrationModel_) – The orchestration data model. * **args** (_list_ _[__str_ _]_) – The script arguments. ### Returns The application definition. ### Return Type specs.AppDef ### Request Example ```json { "orchestration": { ... }, "args": ["arg1", "arg2"] } ``` ### Response Example ```json { "app_name": "my_app", "image": "my_image:latest" } ``` ``` -------------------------------- ### Get Sensitivity Analysis Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/sensitivity.html Retrieves a dictionary of available calibration implementations for sensitivity analysis. ```python calisim.sensitivity.implementation.get_implementations() -> dict[str, str] ``` -------------------------------- ### Get Surrogate Model Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/surrogate.html Retrieves a dictionary of available calibration implementations for surrogate modeling. ```python calisim.surrogate.implementation.get_implementations() → dict[str, str] ``` -------------------------------- ### ExampleModelBase Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Abstract base class for example simulation models. It defines methods for retrieving observed data and running simulations. ```APIDOC ## Class: ExampleModelBase ### Description The example simulation model abstract class. ### Methods #### `_get_observed_data()` * **Description**: Retrieve observed data. * **Returns**: The observed data. * **Return Type**: `np.ndarray` | `pd.DataFrame` * **Raises**: `NotImplementedError` #### `_simulate(_parameters : dict_)` * **Description**: Run the simulation. * **Parameters**: * `_parameters` (dict): The simulation parameters. * **Returns**: The simulated data. * **Return Type**: `np.ndarray` | `pd.DataFrame` * **Raises**: `NotImplementedError` ``` -------------------------------- ### Get Experimental Design Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/experimental_design.html Retrieves a dictionary of available calibration implementations for experimental design. Use this to see which methods are supported. ```python calisim.experimental_design.implementation.get_implementations() ``` -------------------------------- ### Get Quadrature Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/quadrature.html Retrieves a dictionary of available calibration implementations for quadrature methods. This function is useful for understanding which quadrature methods are supported by the library. ```python calisim.quadrature.implementation.get_implementations() → dict[str, str] ``` -------------------------------- ### Get Bayesian Calibration Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/bayesian.html Retrieves a dictionary of available calibration implementations for Bayesian calibration. ```python calisim.bayesian.implementation.get_implementations() ``` -------------------------------- ### Get Optimisation Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/optimisation.html Retrieves a dictionary of available calibration implementations for optimisation. This function is useful for discovering which optimisation strategies are supported. ```python calisim.optimisation.implementation.get_implementations() → dict[str, str][source] Get the calibration implementations for optimisation. Returns: The dictionary of calibration implementations for optimisation. Return type: Dict[str, type[CalibrationWorkflowBase]] ``` -------------------------------- ### Get History Matching Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/history_matching.html Retrieves a dictionary of available calibration implementations for history matching. Use this to see which methods are supported. ```python calisim.history_matching.implementation.get_implementations() ``` -------------------------------- ### Download docker-compose.yaml Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/installation.rst.txt Fetch the docker-compose.yaml file to manage calisim with Docker. ```bash wget https://raw.githubusercontent.com/Plant-Food-Research-Open/calisim/refs/heads/main/docker-compose.yaml ``` -------------------------------- ### get_sampler Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the parameter sampler. Returns the sampler. ```APIDOC ## get_sampler() ### Description Get the parameter sampler. ### Returns The sampler. ### Return Type Any ``` -------------------------------- ### Instantiate and Run Calibrator Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/custom_calibrators.html Create an OptimisationMethod calibrator instance with the defined objective function, specification, and implementation, then execute the calibration workflow. ```python calibrator = OptimisationMethod( calibration_func=objective, specification=specification, implementation=SciPyDEOptimisation ) calibrator.specify().execute().analyze() ``` -------------------------------- ### get_simulation_ids Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the simulation IDs. Returns the simulation IDs. ```APIDOC ## get_simulation_ids() ### Description Get the simulation IDs. ### Returns The simulation IDs. ### Return Type list[str] | None ``` -------------------------------- ### View config.yaml Defaults Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Displays the 'config.yaml' file, showing the default configuration for calibration, model, and metric. ```yaml defaults: - _self_ - calibration: lotka_optimisation - model: lotka_volterra - metric: mse ``` -------------------------------- ### Import necessary libraries Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/custom_calibrators.html Import all required libraries for creating custom calibrators and performing simulations. ```python from matplotlib import pyplot as plt import numpy as np import pandas as pd from scipy.optimize import differential_evolution from calisim.base import CalibrationWorkflowBase from calisim.data_model import ( DistributionModel, ParameterDataType, ParameterSpecification, ) from calisim.data_model import ParameterDataType, ParameterEstimateModel from calisim.example_models import LotkaVolterraModel from calisim.optimisation import OptimisationMethod, OptimisationMethodModel from calisim.statistics import MeanSquaredError import warnings warnings.filterwarnings("ignore") ``` -------------------------------- ### get_parameters Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the simulation parameters. Returns the simulation parameters. ```APIDOC ## get_parameters() ### Description Get the simulation parameters. ### Returns The simulation parameters. ### Return Type Any | None ``` -------------------------------- ### get_emulator Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the trained emulator model. Returns the emulator. ```APIDOC ## get_emulator() ### Description Get the trained emulator model. ### Returns The emulator. ### Return Type BaseEstimator ``` -------------------------------- ### get_constants Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the simulation constants. Returns the simulation constants. ```APIDOC ## get_constants() ### Description Get the simulation constants. ### Returns The simulation constants. ### Return Type dict[str, float | int | str | Any | None] | None ``` -------------------------------- ### Instantiate and Run OptimisationMethod Calibrator Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Create an OptimisationMethod calibrator instance, specifying the objective function, optimisation specification, and the 'optuna_extended' engine. This initiates the calibration workflow. ```python calibrator = OptimisationMethod( calibration_func=objective, specification=specification, engine="optuna_extended" ) ``` -------------------------------- ### get_observed_data Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the observed data for calibration. Returns the observed data for calibration. ```APIDOC ## get_observed_data() ### Description Get the observed data for calibration. ### Returns The observed data for calibration. ### Return Type np.ndarray | pd.DataFrame | None ``` -------------------------------- ### launch (standalone) Source: https://calisim.readthedocs.io/en/latest/api_reference/orchestration.html Dispatch a TorchX job using a scheduler. ```APIDOC ## launch ### Description Dispatch a TorchX job using a scheduler. ### Parameters * **orchestration** (_OrchestrationModel_) – The orchestration data model. * **definition** (_specs.AppDef_) – The application definition. ### Request Example ```json { "orchestration": { ... }, "definition": { ... } } ``` ### Response Example ```json { "job_id": "67890" } ``` ``` -------------------------------- ### get_default_rng Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get a numpy random number generator. Returns the random number generator. ```APIDOC ## get_default_rng(_random_seed : int | None = None_) ### Description Get a numpy random number generator. ### Parameters **random_seed** (_int_ _|__None_ _,__optional_) – The random seed. Defaults to None. ### Returns The random number generator. ### Return Type np.random.Generator ``` -------------------------------- ### View lotka_optimisation.yaml Configuration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Presents the 'lotka_optimisation.yaml' file, detailing the OptimisationMethod configuration with emukit engine, parameter specifications, and acquisition function. ```yaml _target_: calisim.optimisation.OptimisationMethod _partial_: true engine: emukit specification: _target_: calisim.optimisation.OptimisationMethodModel experiment_name: emukit_optimisation parameter_spec: parameters: - name: alpha distribution_name: uniform distribution_args: [0.45, 0.55] data_type: continuous - name: beta distribution_name: uniform distribution_args: [0.02, 0.03] data_type: continuous directions: [ minimize ] output_labels: [ Lynx ] acquisition_func: ei n_iterations: 25 n_init: 20 n_samples: 100 n_out: 1 verbose: false method_kwargs: noise_var: 0.001 ``` -------------------------------- ### get_parameter_estimates Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the estimated parameter values, and potentially their uncertainties. Returns the estimated parameter values. ```APIDOC ## get_parameter_estimates() ### Description Get the estimated parameter values, and potentially their uncertainties. ### Returns The estimated parameter values. ### Return Type ParameterEstimatesModel ``` -------------------------------- ### Configure Optimisation Method Specification Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Set up the specification for the optimisation procedure, including the experiment name, parameter specification, observed data, optimisation method, and directions. ```python specification = OptimisationMethodModel( experiment_name="optuna_extended_optimisation", parameter_spec=parameter_spec, observed_data=observed_data.lynx.values, method="nsgaiii", directions=["minimize"], n_iterations=100, calibration_func_kwargs=dict(t=observed_data.year), ) ``` -------------------------------- ### List Configuration Directory Contents Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Lists the contents of the 'conf' directory to show available configuration files and subdirectories. ```bash ! ls conf ``` -------------------------------- ### get_parameter_bounds Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the lower and upper bounds from a parameter specification. Returns the lower and upper bounds. ```APIDOC ## get_parameter_bounds(_spec : DistributionModel_) ### Description Get the lower and upper bounds from a parameter specification. ### Parameters **spec** (_DistributionModel_) – The parameter specification. ### Raises **ValueError** – Error raised when the bounds cannot be identified. ### Returns The lower and upper bounds. ### Return Type tuple[float, float] ``` -------------------------------- ### get_categorical_parameter Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get a categorical parameter value by its name and index. Returns the categorical parameter value. ```APIDOC ## get_categorical_parameter(_parameter_name : str_, _index : int_) ### Description Get a categorical parameter value by its name and index. ### Parameters * **parameter_name** (_str_) – The parameter name. * **index** (_int_) – The category index. ### Returns The categorical parameter value. ### Return Type str | None ``` -------------------------------- ### Import necessary libraries for TorchX job launching Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/torchx_jobs.html Imports required for setting up and using the TorchX job launcher with calisim. Includes data models, orchestration, and statistical utilities. ```python import numpy as np import pandas as pd import os import os.path as osp import torchx from calisim.data_model import OrchestrationModel from calisim.orchestration import TorchXJobLauncher from calisim.data_model import ( DistributionModel, ParameterDataType, ParameterSpecification, ) from calisim.abc import ( ApproximateBayesianComputationMethod, ApproximateBayesianComputationMethodModel, ) from calisim.statistics import L2Norm import warnings warnings.filterwarnings("ignore") ``` -------------------------------- ### LAMPESimulationBasedInference Source: https://calisim.readthedocs.io/en/latest/api_reference/sbi.html Implements LAPE-based simulation-based inference. ```APIDOC ## Class: LAMPESimulationBasedInference ### Description Implements LAPE-based simulation-based inference. ``` -------------------------------- ### get_calibration_func_kwargs Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Get the calibration function named arguments. Returns the calibration function named arguments. ```APIDOC ## get_calibration_func_kwargs() ### Description Get the calibration function named arguments. ### Returns The calibration function named arguments. ### Return Type dict ``` -------------------------------- ### Register ExtendedOptunaOptimisation as a plugin (Poetry) Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Configures the pyproject.toml file for Poetry users to register the ExtendedOptunaOptimisation class as a plugin named 'optuna_extended' under the 'calisim.external.optimisation' entry point group. ```toml [tool.poetry.plugins."calisim.external.optimisation"] optuna_extended = "calisim.optimisation.optuna_wrapper:ExtendedOptunaOptimisation" ``` -------------------------------- ### Launch TorchX Job with Parameters Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/torchx_jobs.html Launches a Python job using TorchXJobLauncher with the defined orchestration model and ground truth parameters. It then retrieves the job state. ```python runner = TorchXJobLauncher() file_name = "ground_truth" simulation_parameters = list(ground_truth.values()) job_results = runner.launch( orchestration, ["-c", cmd, file_name] + simulation_parameters ) job_results["state"] ``` -------------------------------- ### Register ExtendedOptunaOptimisation as a plugin (PEP 621) Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Configures the pyproject.toml file to register the ExtendedOptunaOptimisation class as a plugin named 'optuna_extended' under the 'calisim.external.optimisation' entry point group. ```toml [project.entry-points."calisim.external.optimisation"] optuna_extended = "calisim.optimisation.optuna_wrapper:ExtendedOptunaOptimisation" ``` -------------------------------- ### calisim.base.calibration_base.pre_post_hooks(_f) Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Execute prehooks and posthooks for calibration methods. It takes a callable function and returns a wrapper function. ```APIDOC ## calisim.base.calibration_base.pre_post_hooks(_f) ### Description Execute prehooks and posthooks for calibration methods. ### Method None (function call) ### Parameters #### Parameters - **f** (_Callable_) – The wrapped function. ### Returns The wrapper function. ### Return Type Callable ``` -------------------------------- ### Get Raw Hydra Configuration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Loads a raw configuration from YAML files. Use this to inspect the configuration structure before instantiation. ```python cfg = hydra_config.get_raw_config("config", "conf") print(hydra_config.pretty(cfg)) ``` -------------------------------- ### View mse.yaml Configuration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Shows the 'mse.yaml' file, defining the MeanSquaredError target for the metric configuration. ```yaml _target_: calisim.statistics.MeanSquaredError ``` -------------------------------- ### prepare_analyze() Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Perform preparations for the analyze step, returning metadata needed for analysis outputs. ```APIDOC ## prepare_analyze() ### Description Perform preparations for the analyze step. ### Method None (function call) ### Parameters None ### Returns A list of metadata needed for the analysis outputs. ### Return Type tuple[str, str, str, str | None] ``` -------------------------------- ### Instantiate and Run Calibrator Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Instantiate a calibrator object using a Hydra configuration, specifying the custom objective function and observed data. Then, execute and analyze the calibration workflow. ```python calibrator = cfg["calibration"](calibration_func=objective) calibrator.specification.calibration_func_kwargs=dict(t=observed_data.year) calibrator.specification.observed_data=observed_data.lynx.values calibrator.specify().execute().analyze() ``` -------------------------------- ### Verify plugin registration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Uses pandas and importlib.metadata to retrieve and display registered plugins for the 'calisim.external.optimisation' group, confirming the successful addition of 'optuna_extended'. ```python pd.DataFrame([ { "name": entrypoint.name, "module": entrypoint.value.split(":")[0], "target": entrypoint.value.split(":")[1], "group": entrypoint.group } for entrypoint in entry_points().select(group="calisim.external.optimisation") ]) ``` -------------------------------- ### Define Parameter Specification for Calibration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/calibrator_plugins.html Define the parameters for calibration, including their names, distributions, and bounds. This specification guides the optimisation process. ```python parameter_spec = ParameterSpecification( parameters=[ DistributionModel( name="alpha", distribution_name="uniform", distribution_args=[0.45, 0.55], data_type=ParameterDataType.CONTINUOUS, ), DistributionModel( name="beta", distribution_name="uniform", distribution_args=[0.02, 0.03], data_type=ParameterDataType.CONTINUOUS, ), ] ) ``` -------------------------------- ### Get Reliability Analysis Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/reliability.html Retrieves a dictionary of available calibration implementations for reliability analysis. This function helps discover supported methods. ```python calisim.reliability.implementation.get_implementations() ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/quadrature.html Retrieves the available calibration implementations for quadrature. ```APIDOC ## calisim.quadrature.implementation.get_implementations() -> dict[str, str] ### Description Get the calibration implementations for quadrature. ### Returns - **Dict[str, str]** - The dictionary of calibration implementations for quadrature. ``` -------------------------------- ### SirOdesModel Source: https://calisim.readthedocs.io/en/latest/api_reference/example_models.html Represents an SIR epidemiological model using ordinary differential equations. It provides methods to get observed data and run simulations. ```APIDOC ## SirOdesModel ### Description SIR ODE model. ### Methods #### get_observed_data() Retrieve observed data. Returns: The observed data. Return type: np.ndarray | pd.DataFrame #### simulate(_parameters : dict_) Run the simulation. Parameters: **parameters** (_dict_) – The simulation parameters. Returns: The simulated data. Return type: np.ndarray | pd.DataFrame ``` -------------------------------- ### Get ABC Implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/abc.html Retrieves a dictionary of available calibration implementations for Approximate Bayesian Computation. This is useful for understanding which ABC methods are supported by the library. ```python calisim.abc.implementation.get_implementations() ``` -------------------------------- ### AnharmonicOscillator Source: https://calisim.readthedocs.io/en/latest/api_reference/example_models.html Represents an anharmonic oscillator model. It provides methods to get the simulation dataframe, retrieve observed data, reset the trajectory, and run simulations or single steps. ```APIDOC ## AnharmonicOscillator ### Description Anharmonic oscillator simulation model. ### Methods #### get_df() Get the simulation dataframe. Returns: The simulation dataframe. Return type: pd.DataFrame #### get_observed_data() Retrieve observed data. Returns: The observed data. Return type: np.ndarray | pd.DataFrame #### reset_y() Reset the trajectory vector. Returns: None #### simulate(_parameters : dict_) Run the simulation. Parameters: **parameters** (_dict_) – The simulation parameters. Returns: The simulated data. Return type: np.ndarray | pd.DataFrame #### step(_parameters : dict_) Run the model for one time step. Parameters: **parameters** (_dict_) – The simulation parameters. ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/sensitivity.html Retrieves the available calibration implementations for sensitivity analysis. ```APIDOC ## calisim.sensitivity.implementation.get_implementations() -> dict[str, str] ### Description Get the calibration implementations for sensitivity analysis. ### Returns * A dictionary of calibration implementations for sensitivity analysis. ### Return type Dict[str, str] ``` -------------------------------- ### Instantiate Model from Configuration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Retrieves and checks the type of a model object instantiated from the configuration. This verifies the model's class. ```python model = cfg["model"] observed_data = model.get_observed_data() type(model) ``` -------------------------------- ### Define SciPy DE Optimisation Class Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/custom_calibrators.html This class extends `CalibrationWorkflowBase` to implement the SciPy differential evolution optimization method. It defines `specify` for parameter setup and `execute` for the calibration loop, including a nested `target_function`. ```python class SciPyDEOptimisation(CalibrationWorkflowBase): """The SciPy differential evolution optimisation method class.""" def specify(self) -> None: """Specify the parameters of the model calibration procedure.""" self.names = [] self.data_types = [] self.bounds = [] parameter_spec = self.specification.parameter_spec.parameters for spec in parameter_spec: parameter_name = spec.name data_type = spec.data_type if data_type == ParameterDataType.CONSTANT: parameter_value = spec.parameter_value self.constants[parameter_name] = parameter_value continue elif data_type == ParameterDataType.CATEGORICAL: bounds = self.set_categorical_parameter(spec) else: bounds = self.get_parameter_bounds(spec) self.names.append(parameter_name) self.data_types.append(data_type) self.bounds.append(bounds) def execute(self) -> None: """Execute the simulation calibration procedure.""" optimisation_kwargs = self.get_calibration_func_kwargs() self.history = [] self.eval_count = 0 output_labels = self.specification.output_labels if output_labels is None: output_labels = ["target"] def target_function(X: np.ndarray) -> np.ndarray: X_dict = { name: X[i] for i, name in enumerate(self.names) } X = [X] Y = self.calibration_func_wrapper( X, self, self.specification.observed_data, self.names, self.data_types, optimisation_kwargs, ) X_dict["eval_count"] = self.eval_count self.eval_count += 1 X_dict[output_labels[0]] = Y self.history.append(X_dict) return Y n_iterations = self.specification.n_iterations verbose = self.specification.verbose n_jobs = self.specification.n_jobs random_seed = self.specification.random_seed ``` -------------------------------- ### SBISimulationBasedInference Source: https://calisim.readthedocs.io/en/latest/api_reference/sbi.html Implements simulation-based inference methods using the SBI library. ```APIDOC ## Class: SBISimulationBasedInference ### Description The SBI simulation-based inference method class. ### Parameters * `_calibration_func` (Callable_): The function to be called for calibration. * `_specification` (CalibrationModel_): The data model specifying the method's configuration. * `_task` (str): The task identifier for the calibration. ### Methods * `analyze()`: Analyze the results of the simulation calibration procedure. * `execute()`: Execute the simulation calibration procedure. ``` -------------------------------- ### View lotka_volterra.yaml Configuration Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Displays the 'lotka_volterra.yaml' file, specifying the LotkaVolterraModel target for the model configuration. ```yaml _target_: calisim.example_models.LotkaVolterraModel ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/uncertainty.html Retrieves a dictionary of available calibration implementations for uncertainty analysis. ```APIDOC ## calisim.uncertainty.implementation.get_implementations() → dict[str, str] ### Description Get the calibration implementations for the uncertainty analysis. ### Returns * **dict[str, str]**: The dictionary of calibration implementations for the uncertainty analysis. ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/active_learning.html Retrieves available calibration implementations for active learning. ```APIDOC ## calisim.active_learning.implementation.get_implementations() -> dict[str, str] ### Description Get the calibration implementations for active learning. ### Returns - **dict[str, str]**: The dictionary of calibration implementations for active learning. ``` -------------------------------- ### prehook_specify() Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Prehook to run before the specify() function. It does not take any arguments and returns nothing. ```APIDOC ## prehook_specify() ### Description Prehook to run before specify(). ### Method None (function call) ### Parameters None ### Returns None ``` -------------------------------- ### LAMPESimulationBasedInference Class Source: https://calisim.readthedocs.io/en/latest/api_reference/sbi.html The LAMPE simulation-based inference method class provides functionalities to analyze, execute, postprocess, and preprocess simulation calibration procedures. ```APIDOC ## LAMPESimulationBasedInference Class ### Description The LAMPE simulation-based inference method class. ### Methods #### analyze() ##### Description Analyze the results of the simulation calibration procedure. ##### Method Signature `analyze() -> None` #### execute() ##### Description Execute the simulation calibration procedure. ##### Method Signature `execute() -> None` #### postprocess(_samples : Tensor_, _parameter_spec : list[DistributionModel] | Any | None_) ##### Description Reverse normalise the parameters of the simulation. ##### Parameters - **samples** (torch.Tensor) - The normalised parameters. - **parameter_spec** (list[DistributionModel] | Any | None) - The parameter specification. ##### Raises - **ValueError** – Error raised when an unsupported distribution is provided. ##### Returns The denormalised parameters. ##### Return Type torch.Tensor ##### Method Signature `postprocess(_samples : Tensor_, _parameter_spec : list[DistributionModel] | Any | None_) -> Tensor` #### preprocess(_theta : Tensor_, _parameter_spec : list[DistributionModel] | Any | None_) ##### Description Normalise the parameters of the simulation. ##### Parameters - **theta** (torch.Tensor) - The simulation parameters. - **parameter_spec** (list[DistributionModel] | Any | None) - The parameter specification. ##### Raises - **ValueError** – Error raised when an unsupported distribution is provided. ##### Returns The normalised parameters. ##### Return Type torch.Tensor ##### Method Signature `preprocess(_theta : Tensor_, _parameter_spec : list[DistributionModel] | Any | None_) -> Tensor` #### specify() ##### Description Specify the parameters of the model calibration procedure. ##### Method Signature `specify() -> None` ``` -------------------------------- ### GPyTorchSurrogateModel Methods Source: https://calisim.readthedocs.io/en/latest/api_reference/surrogate.html Provides methods to analyze and execute the simulation calibration procedure using GPyTorch. ```python analyze() → None execute() → None ``` -------------------------------- ### prehook_calibration_func(_parameters, _simulation_id, _observed_data, _**method_kwargs) Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Prehook to run before calling the calibration function. It accepts parameters, simulation IDs, and observed data, returning calibration function parameters. ```APIDOC ## prehook_calibration_func(_parameters, _simulation_id, _observed_data, _**method_kwargs) ### Description Prehook to run before calling the calibration function. ### Method None (function call) ### Parameters #### Parameters - **parameters** (_dict_ or _list_[_dict_]) – The simulation parameters. - **simulation_id** (_str_ or _list_[_str_]) – The simulation IDs. - **observed_data** (_np.ndarray_ or _None_) – The observed data. ### Returns The calibration function parameters. ### Return Type tuple ``` -------------------------------- ### prehook_analyze() Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Prehook to run before the analyze() function. It does not take any arguments and returns nothing. ```APIDOC ## prehook_analyze() ### Description Prehook to run before analyze(). ### Method None (function call) ### Parameters None ### Returns None ``` -------------------------------- ### SALib Sensitivity Analysis Sampling Source: https://calisim.readthedocs.io/en/latest/api_reference/sensitivity.html Samples from the parameter space for SALib-based sensitivity analysis. Requires specifying the number of samples. ```python SALibSensitivityAnalysis(_calibration_func : Callable_, _specification : CalibrationModel_, _task : str_).sample_parameters(_n_samples : int_) -> ndarray ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/surrogate.html Retrieves available calibration implementations for surrogate modeling. ```APIDOC ## calisim.surrogate.implementation.get_implementations() → dict[str, str] ### Description Get the calibration implementations for surrogate modelling. ### Returns * A dictionary of calibration implementations for surrogate modelling. ### Return type Dict[str, str] ``` -------------------------------- ### Optimize Lotka Volterra Model Parameters with Optuna Source: https://calisim.readthedocs.io/en/latest/tutorials/basics/quickstart.html This snippet sets up and runs an optimization workflow for the Lotka Volterra model using Optuna. It defines the model, observed data, parameter distributions, an objective function for calculating discrepancy, and the optimization method specification. Finally, it executes the optimization and retrieves the results. ```python # Load imports import numpy as np import pandas as pd from calisim.data_model import ( DistributionModel, ParameterDataType, ParameterSpecification, ) from calisim.example_models import LotkaVolterraModel from calisim.optimisation import OptimisationMethod, OptimisationMethodModel from calisim.statistics import MeanSquaredError from calisim.utils import get_examples_outdir # Get model model = LotkaVolterraModel() observed_data = model.get_observed_data() # Specify model parameter distributions parameter_spec = ParameterSpecification( parameters=[ DistributionModel( name="alpha", distribution_name="uniform", distribution_args=[0.45, 0.55], data_type=ParameterDataType.CONTINUOUS, ) ] ) # Define objective function def objective( parameters: dict, simulation_id: str, observed_data: np.ndarray | None, t: pd.Series ) -> float | list[float]: simulation_parameters = dict( alpha=parameters["alpha"], beta=0.024, h0=34.0, l0=5.9, t=t, gamma=0.84, delta=0.026, ) simulated_data = model.simulate(simulation_parameters).lynx.values metric = MeanSquaredError() discrepancy = metric.calculate(observed_data, simulated_data) return discrepancy # Specify calibration parameter values specification = OptimisationMethodModel( experiment_name="optuna_optimisation", parameter_spec=parameter_spec, observed_data=observed_data.lynx.values, outdir=get_examples_outdir(), method="tpes", directions=["minimize"], n_iterations=100, method_kwargs=dict(n_startup_trials=50), calibration_func_kwargs=dict(t=observed_data.year), ) # Choose calibration engine calibrator = OptimisationMethod( calibration_func=objective, specification=specification, engine="optuna" ) # Run the workflow calibrator.specify().execute().analyze() # View the results result_artifacts = "\n".join(calibrator.get_artifacts()) print(f"View results: \n{result_artifacts}") print(f"Parameter estimates: {calibrator.get_parameter_estimates()}") ``` -------------------------------- ### posthook_specify Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Posthook to run after specify(). ```APIDOC ## posthook_specify() ### Description Posthook to run after specify(). ### Return Type None ``` -------------------------------- ### Configure Optimisation Method Specification Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/custom_calibrators.html Define the parameters for the optimisation procedure, including the experiment name, parameter specification, observed data, number of iterations, and method-specific arguments. ```python specification = OptimisationMethodModel( experiment_name="scipy_optimisation", parameter_spec=parameter_spec, observed_data=observed_data.lynx.values, n_iterations=100, output_labels=["Lynx"], method_kwargs=dict( init='latinhypercube', popsize=15 ), calibration_func_kwargs=dict(t=observed_data.year), ) ``` -------------------------------- ### SPOTPYEvolutionary Class Source: https://calisim.readthedocs.io/en/latest/api_reference/evolutionary.html The SPOTPYEvolutionary class provides methods to manage and execute simulation calibration procedures using SPOTPY. ```APIDOC ## Class SPOTPYEvolutionary ### Description The SPOTPY evolutionary algorithm method class. ### Methods #### analyze() ##### Description Analyze the results of the simulation calibration procedure. ##### Signature analyze() -> None #### execute() ##### Description Execute the simulation calibration procedure. ##### Signature execute() -> None #### specify() ##### Description Specify the parameters of the model calibration procedure. ##### Signature specify() -> None ``` -------------------------------- ### Import Necessary Libraries Source: https://calisim.readthedocs.io/en/latest/tutorials/usage/advanced/hydra_config.html Imports required libraries for numerical operations, data manipulation, and calisim's Hydra configuration. ```python import numpy as np import pandas as pd from calisim.config import HydraConfiguration import warnings warnings.filterwarnings("ignore") ``` -------------------------------- ### Optimize Lotka Volterra Model Parameters with Optuna Source: https://calisim.readthedocs.io/en/latest/_sources/tutorials/basics/quickstart.rst.txt This code snippet sets up and runs an optimization workflow for the Lotka Volterra model using Optuna. It defines the model, observed data, parameter specifications, and the objective function for optimization. Ensure all necessary imports are available. ```python # Load imports import numpy as np import pandas as pd from calisim.data_model import ( DistributionModel, ParameterDataType, ParameterSpecification, ) from calisim.example_models import LotkaVolterraModel from calisim.optimisation import OptimisationMethod, OptimisationMethodModel from calisim.statistics import MeanSquaredError from calisim.utils import get_examples_outdir # Get model model = LotkaVolterraModel() observed_data = model.get_observed_data() # Specify model parameter distributions parameter_spec = ParameterSpecification( parameters=[ DistributionModel( name="alpha", distribution_name="uniform", distribution_args=[0.45, 0.55], data_type=ParameterDataType.CONTINUOUS, ) ] ) # Define objective function def objective( parameters: dict, simulation_id: str, observed_data: np.ndarray | None, t: pd.Series ) -> float | list[float]: simulation_parameters = dict( alpha=parameters["alpha"], beta=0.024, h0=34.0, l0=5.9, t=t, gamma=0.84, delta=0.026, ) simulated_data = model.simulate(simulation_parameters).lynx.values metric = MeanSquaredError() discrepancy = metric.calculate(observed_data, simulated_data) return discrepancy # Specify calibration parameter values specification = OptimisationMethodModel( experiment_name="optuna_optimisation", parameter_spec=parameter_spec, observed_data=observed_data.lynx.values, outdir=get_examples_outdir(), method="tpes", directions=["minimize"], n_iterations=100, method_kwargs=dict(n_startup_trials=50), calibration_func_kwargs=dict(t=observed_data.year), ) # Choose calibration engine calibrator = OptimisationMethod( calibration_func=objective, specification=specification, engine="optuna" ) # Run the workflow calibrator.specify().execute().analyze() # View the results result_artifacts = "\n".join(calibrator.get_artifacts()) print(f"View results: \n{result_artifacts}") print(f"Parameter estimates: {calibrator.get_parameter_estimates()}") ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/bayesian.html Retrieves a dictionary of available calibration implementations for Bayesian calibration. ```APIDOC ## calisim.bayesian.implementation.get_implementations() -> dict[str, str] ### Description Get the calibration implementations for Bayesian calibration. ### Returns - A dictionary of calibration implementations for Bayesian calibration. ### Return type Dict[str, str] ``` -------------------------------- ### prehook_execute() Source: https://calisim.readthedocs.io/en/latest/api_reference/base.html Prehook to run before the execute() function. It does not take any arguments and returns nothing. ```APIDOC ## prehook_execute() ### Description Prehook to run before execute(). ### Method None (function call) ### Parameters None ### Returns None ``` -------------------------------- ### OpenTurnsReliabilityAnalysis.execute Method Source: https://calisim.readthedocs.io/en/latest/api_reference/reliability.html Executes the simulation calibration procedure for reliability analysis using OpenTurns. This method initiates the analysis process. ```python def execute() -> None: """ Execute the simulation calibration procedure. """ pass ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/sbi.html Retrieves the available calibration implementations for simulation-based inference. ```APIDOC ## Function: get_implementations ### Description Get the calibration implementations for simulation-based inference. ### Returns * A dictionary mapping implementation names to their string representations. ``` -------------------------------- ### get_implementations Source: https://calisim.readthedocs.io/en/latest/api_reference/experimental_design.html Retrieves a dictionary of available calibration implementations for experimental design. ```APIDOC ## calisim.experimental_design.implementation.get_implementations() → dict[str, str] ### Description Get the calibration implementations for experimental design. ### Returns * **The dictionary** of calibration implementations for experimental design. ### Return type Dict[str, str] ```