### Install dependencies with pip install . Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/model_comparison/README.md Installs the required packages for the case study. It is recommended to run this within a virtual environment. ```bash pip install . ``` -------------------------------- ### Install dependencies Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/README.md Install the case study dependencies in editable mode. ```bash pip install -e . ``` -------------------------------- ### Set up environment with uv Source: https://github.com/alan-turing-institute/autoemulate/blob/main/AGENTS.md Install uv, create a virtual environment with all dependencies including dev extras, and activate the environment. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```bash uv sync --extra dev ``` ```bash source .venv/bin/activate ``` -------------------------------- ### Install AutoEmulate in development mode with UV Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Installs the package in editable mode with all development dependencies using UV. ```bash uv pip install -e '.[dev]' ``` -------------------------------- ### Install AutoEmulate from PyPI Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Installs the latest release of AutoEmulate from PyPI. Requires Python >=3.10 and <3.13. ```bash pip install autoemulate ``` -------------------------------- ### Install JupyterLab Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Installs JupyterLab into the active virtual environment. ```bash pip install jupyterlab ``` -------------------------------- ### NumPy-style docstring example Source: https://github.com/alan-turing-institute/autoemulate/blob/main/AGENTS.md NumPy-style docstring example for a fit method, showing parameter and return documentation. ```python def fit(self, X: np.ndarray, y: np.ndarray) -> "MyEmulator": """Fit the emulator to training data. Parameters ---------- X : np.ndarray of shape (n_samples, n_features) Input simulation parameters. y : np.ndarray of shape (n_samples,) or (n_samples, n_outputs) Simulation outputs. Returns ------- self : MyEmulator Fitted estimator. """ ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/alan-turing-institute/autoemulate/blob/main/CONTRIBUTING.md Register the pre-commit hooks in your clone so they run automatically on every git commit. This is part of the local pre-commit setup before pushing changes. ```bash pre-commit install ``` -------------------------------- ### Setup and PCA transform on input data Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/transforms.ipynb Sets up imports, a synthetic regression data generator, and demonstrates fitting a PCA transform on input data, transforming it, and inverting the transform. The output shapes are printed to verify the transform and inverse operations. ```python import torch from autoemulate.emulators import GaussianProcess from autoemulate.emulators.random_forest import RandomForest from autoemulate.emulators.transformed.base import TransformedEmulator from autoemulate.transforms import PCATransform, VAETransform, StandardizeTransform from sklearn.datasets import make_regression import torchmetrics from autoemulate.core.model_selection import evaluate from autoemulate.core.types import TensorLike # Uncomment to enable logging for GPs import logging # logging.basicConfig(level=logging.INFO) def make_data( random_state: int = 42, n_samples: int = 200, n_informative:int = 2, n_features: int = 5, noise: float = 0.2, n_targets: int = 500 ): x, y, _ = make_regression( n_samples=n_samples, n_features=n_features, noise=noise, random_state=random_state, n_informative=n_informative, n_targets=n_targets, coef=True, ) x = torch.tensor(x, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) return x, y # Train data x, y = make_data(random_state=42, n_targets=10) # Test data x2, y2 = make_data(random_state=43, n_targets=10) # Make transform pca = PCATransform(n_components=2) pca.fit(x) # Transform data print(pca(x).shape) # Invert PCA on tensor print(pca.inv(pca(x)).shape) ``` -------------------------------- ### Setup and imports for covariance structure benchmark Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/data/distributions.ipynb Imports necessary libraries and enables autoreload for interactive development. ```python import numpy as np, pandas as pd, time import matplotlib.pyplot as plt from autoemulate.experimental.data.gaussian import * from typing import List %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Clone AutoEmulate repository for UV installation Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Clones your forked AutoEmulate repository to your local machine. Replace YOUR-USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR-USERNAME/autoemulate.git ``` -------------------------------- ### Initialize NaghaviSimulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Initializes the NaghaviSimulator with output variable 'lv.P', 300 cycles, and a time step of 0.001. This setup is required before generating data for the emulator. ```python from cardiac_simulator import NaghaviSimulator simulator = NaghaviSimulator( output_variables=['lv.P'], # We simulate the left ventricle pressure n_cycles=300, dt=0.001, ) ``` -------------------------------- ### Instantiate Projectile simulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/01_custom_simulations.ipynb Creates an instance of the Projectile simulator with parameter ranges for angle and velocity, and output names for distance. This example shows how to set up the simulator for use with AutoEmulate. ```python param_ranges = {"angle": (5, 85), "velocity": (0.0, 1000)} output_names = ["distance"] projectile_simulator = Projectile(param_ranges=param_ranges, output_names=output_names) ``` -------------------------------- ### Simulate data with Epidemic simulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/03_history_matching.ipynb Creates an Epidemic simulator instance, samples 100 inputs, and runs the forward batch to get outputs. ```python simulator = Epidemic(show_progress_bar=False) x = simulator.sample_inputs(100, random_seed=random_seed) y, _ = simulator.forward_batch(x) ``` -------------------------------- ### Get outputs as dictionary with `get_outputs_as_dict` Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/01_custom_simulations.ipynb Retrieves the simulation outputs as a dictionary using the `get_outputs_as_dict()` method. Useful when the simulator has multiple outputs. ```python outputs_dict = projectile_simulator.get_outputs_as_dict() outputs_dict ``` -------------------------------- ### Refit best emulator on all training data Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/02_dim_reduction.ipynb Get the best performing emulator and refit it on all training data. The model class is reinitialized and refitted on the full training set. ```python em = ae.fit_from_reinitialized(x[train_idx], y[train_idx]) ``` -------------------------------- ### Run pre-commit on all files Source: https://github.com/alan-turing-institute/autoemulate/blob/main/CONTRIBUTING.md Run pre-commit on the entire tree, recommended right before opening a pull request. If a hook makes changes, re-stage the affected files and run again until you get a 'Passed' message. ```bash pre-commit run --all-files ``` -------------------------------- ### Setup and data generation for comparing transforms Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/compare_transforms.ipynb Imports required libraries and defines a make_data function that generates synthetic regression data using sklearn's make_regression, converting to torch tensors. Creates training (x, y) and test (x2, y2) datasets with different random states. ```python import torch from autoemulate.emulators import GaussianProcess from autoemulate.emulators.random_forest import RandomForest from autoemulate.emulators.transformed.base import TransformedEmulator from autoemulate.transforms import PCATransform, VAETransform, StandardizeTransform from sklearn.datasets import make_regression import torchmetrics from autoemulate.core.model_selection import evaluate from autoemulate.core.types import TensorLike from autoemulate.core.compare import AutoEmulate # Uncomment to enable logging for GPs import logging # logging.basicConfig(level=logging.INFO) def make_data( random_state: int = 42, n_samples: int = 200, n_informative:int = 2, n_features: int = 5, noise: float = 0.2, n_targets: int = 500 ): x, y, _ = make_regression( n_samples=n_samples, n_features=n_features, noise=noise, random_state=random_state, n_informative=n_informative, n_targets=n_targets, coef=True, ) x = torch.tensor(x, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) return x, y # Train data x, y = make_data(random_state=42, n_features=10, n_targets=2, noise=0.01) # Test data x2, y2 = make_data(random_state=43, n_features=10, n_targets=2, noise=0.01) ``` -------------------------------- ### Build documentation locally Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/community/contributing-docs.md Use this command to build the documentation locally. The --all flag builds all files; omit it to build only changed files. ```bash jupyter-book build docs --all ``` -------------------------------- ### Launch Jupyter notebook for case study Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/model_comparison/README.md Launches the Jupyter environment and runs the case study notebook. ```bash jupyter notebook sir_seir.ipynb ``` -------------------------------- ### Clone AutoEmulate repository for tutorials Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Clones the AutoEmulate repository to run interactive tutorials locally. ```bash git clone https://github.com/alan-turing-institute/autoemulate ``` -------------------------------- ### Get best result Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/03_history_matching.ipynb Retrieves the best result from the AutoEmulate comparison. ```python best_result = ae.best_result() ``` -------------------------------- ### Sample inputs and run simulation Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/01_emulation_sensitivity.ipynb Samples 100 input parameter sets and runs the simulator in batch to obtain outputs, then prints the shapes of the input and output arrays. ```python x = simulator.sample_inputs(100) y, _ = simulator.forward_batch(x) ``` ```python print(x.shape, y.shape) ``` -------------------------------- ### Sample simulator inputs and run forward batch Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Samples 500 inputs from the simulator and runs the forward model in a batch, returning outputs and inputs. The output shows the progress bar from the simulation run. ```python x = simulator.sample_inputs(500,random_seed=seed) y, x = simulator.forward_batch(x) ``` ```text Output: Running simulations: 100%|██████████| 500/500 [02:00<00:00, 4.15sample/s] ``` -------------------------------- ### Get NROY parameters Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/02_history_matching.ipynb Filters the query points to retain only those that have not been ruled out (NROY) based on the implausibility scores. ```python nroy_params = hm.get_nroy(implausability, x_new) ``` -------------------------------- ### Clone repository and navigate to case study Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/README.md Clone the AutoEmulate repository and navigate to the patient_calibration case study directory. ```bash git clone https://github.com/alan-turing-institute/autoemulate.git cd case_studies/patient_calibration ``` -------------------------------- ### Get best emulator model Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/03_bayes_calibration.ipynb Retrieves the best model from the AutoEmulate results and assigns it to `gp` for use in Bayesian calibration. ```python gp = ae.best_result().model ``` -------------------------------- ### Set up Sobol sensitivity analysis with AutoEmulate Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Imports SensitivityAnalysis and defines a problem dictionary with the simulator's dimensions, parameter names, and bounds. This is the first step to compute Sobol indices. ```python from autoemulate.core.sensitivity_analysis import SensitivityAnalysis # Define the problem dictionary for Sobol sensitivity analysis problem = { 'num_vars': simulator.in_dim, 'names': simulator.param_names, 'bounds': simulator.param_bounds } si = SensitivityAnalysis(model, problem=problem) ``` -------------------------------- ### Get best model result Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/compare_transforms.ipynb Retrieves the result dictionary for the best model, containing model class, transforms, and configuration. ```python outputs[best_model_idx] ``` -------------------------------- ### Set up AutoEmulate with GaussianProcessRBF Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/03_history_matching.ipynb Configures AutoEmulate with the simulated data and GaussianProcessRBF model with default parameters. ```python ae = AutoEmulate( x, y, models=[GaussianProcessRBF], model_params={}, show_progress_bar=False, random_seed=random_seed ) ``` -------------------------------- ### Create virtual environment for tutorials Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Creates a virtual environment named 'autoemulate' using Python's venv module. ```bash python -m venv autoemulate ``` -------------------------------- ### List available emulators with AutoEmulate.list_emulators() Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/01_quickstart.ipynb Imports AutoEmulate and lists the default emulator models, showing their backend, multioutput support, and uncertainty quantification capabilities. ```python from autoemulate import AutoEmulate AutoEmulate.list_emulators() ``` -------------------------------- ### Get Simulator Output Names Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Returns the list of output variable names from the simulator. The result is ['lv.P_min', 'lv.P_max', 'lv.P_mean', 'lv.P_range']. ```python simulator.output_names ``` -------------------------------- ### Create virtual environment with UV Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Creates a virtual environment in the current directory using UV. ```bash uv venv ``` -------------------------------- ### Use custom GP in AutoEmulate Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/advanced/01_add_emulators.ipynb Initializes an `AutoEmulate` object with the new GP class passed to the `models` argument. Example data is created using PyTorch tensors. ```python from autoemulate import AutoEmulate import torch # create some example data x = torch.linspace(0, 1, 100).unsqueeze(-1) y = torch.sin(2 * 3.14 * x) + 0.1 * torch.randn_like(x) ae = AutoEmulate(x, y, models=[GaussianProcessRBFandLinear], show_progress_bar=False) ``` -------------------------------- ### Run JupyterLab Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/README.md Launch JupyterLab to explore the case study notebook interactively. ```bash jupyter lab ``` -------------------------------- ### Initialize simulator and generate training data Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/double_pendulum_simulator.ipynb Creates a DoublePendulum simulator with 100 time points, samples 500 input parameter sets with a fixed random seed, and generates the corresponding output trajectories. ```python simulator = DoublePendulum(n_time_points=100) x = simulator.sample_inputs(500, random_seed=42) y = simulator.forward_batch(x) ``` -------------------------------- ### Run simulator and fit GP emulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/04_interval_excursion_set.ipynb Creates a Projectile simulator, generates 1000 training samples, visualizes the data, and fits a Gaussian process emulator using AutoEmulate. ```python simulator = Projectile( parameters_range={"c": (-5.0, 1.0), "v0": (0.0, 10.0)}, show_progress_bar=False, ) x = simulator.sample_inputs(1000) y, _ = simulator.forward_batch(x) c = x[:, 0] v0 = x[:, 1] plt.scatter(c, v0, c=y[:, 0], cmap='viridis') plt.xlabel('Drag coefficient') plt.ylabel('Initial velocity (m/s)') plt.colorbar(label="Distance (m)") plt.show() ae = AutoEmulate( x, y, models=[GaussianProcessRBF], model_params={}, show_progress_bar=False, ) gp = ae.best_result().model ``` -------------------------------- ### Sample inputs from the Sin simulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/02_active_learning.ipynb Instantiates the Sin simulator and samples 4 input points to inspect the sampled inputs. ```python simulator = Sin() x = simulator.sample_inputs(4) print(x) ``` -------------------------------- ### Extract NROY points and generate parameter bounds Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Extracts the NROY (non-implausible) points from the last history matching wave and generates parameter bounds for Bayesian calibration. The buffer_ratio is set to 0.0 to get exact min/max bounds from the NROY points. ```python # Get the last wave results test_parameters, impl_scores = hmw.wave_results[-1] nroy_points = hmw.get_nroy(impl_scores,test_parameters) # Implausibility < 3.0 # Get exact min/max bounds for the parameters from the NROY points params_post_hm = hmw.generate_param_bounds( nroy_x=nroy_points, param_names=simulator.param_names, buffer_ratio=0.0 ) ``` -------------------------------- ### Define Projectile simulator class Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/01_custom_simulations.ipynb Defines a custom simulator class that inherits from Simulator. It implements the required _forward method, which takes a tensor of shape (1, n) and returns a tensor of shape (1, m). The example calculates projectile distance using PyTorch operations. ```python class Projectile(Simulator): """ Simulator of projectile motion. """ def __init__(self, param_ranges, output_names): super().__init__(param_ranges, output_names, show_progress_bar=False) def _forward(self, x): """ Calculate the horizontal distance a projectile travels using PyTorch. Parameters: ---------- velocity: float or torch.Tensor Initial velocity in m/s. angle_degrees: float or torch.Tensor Launch angle in degrees. Returns: ------- torch.Tensor Distance traveled in meters. """ # Extract velocity and angle from input tensor angle_degrees = x[:, 0] velocity = x[:, 1] # Convert angle from degrees to radians and calculate distance angle_radians = torch.deg2rad(angle_degrees) # Calculate the distance using the projectile motion formula distance = (velocity ** 2) * torch.sin(2 * angle_radians) / 9.81 # Ensure the output is a 2D tensor if distance.ndim == 1: distance = distance.unsqueeze(1) return distance ``` -------------------------------- ### Import dependencies and core classes for stream-based active learning Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/02_active_learning.ipynb Imports necessary libraries (os, torch, numpy, matplotlib, pandas, tqdm, typing) and core AutoEmulate classes (stream, Simulator, GaussianProcessRBF, GaussianLike). Sets show_progress flag based on environment variable. ```python import os import torch, numpy as np, matplotlib.pyplot as plt, pandas as pd from tqdm import tqdm from typing import List, Dict, Tuple, Iterable # Import core classes from the source code. from autoemulate.learners import stream from autoemulate.simulations.base import Simulator from autoemulate.emulators import GaussianProcessRBF from autoemulate.core.types import GaussianLike show_progress = False # if os.environ.get("JUPYTER_BOOK") == "1" else True ``` -------------------------------- ### Configure AutoEmulate with transform lists Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/compare_transforms.ipynb Initializes AutoEmulate with two models (GaussianProcess, RandomForest) and two transform configurations: no transforms and a combination of StandardizeTransform and PCATransform for both x and y. ```python ae = AutoEmulate( x, y, models=[GaussianProcess, RandomForest], x_transforms_list=[[], [StandardizeTransform(), PCATransform(n_components=5)]], y_transforms_list=[[], [StandardizeTransform(), PCATransform(n_components=1)]] ) ``` -------------------------------- ### Run pre-commit hooks Source: https://github.com/alan-turing-institute/autoemulate/blob/main/AGENTS.md Run pre-commit hooks (ruff, pyright, nbstripout) locally. Enforced in CI on every PR. ```bash uv run pre-commit run --all-files ``` -------------------------------- ### Sample and simulate 10,000 inputs Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/01_custom_simulations.ipynb Samples 10,000 input parameter sets and runs a batch simulation to generate outputs for visualization. ```python inputs = projectile_simulator.sample_inputs(10_000) outputs, _ = projectile_simulator.forward_batch(inputs) ``` -------------------------------- ### Run Bayesian calibration with MCMC Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Sets up BayesianCalibration with the history matching emulator, parameter ranges from the NROY region, and observation data. Runs MCMC with 250 warmup steps and 1000 samples using the NUTS sampler, accounting for emulator uncertainty and observation noise. ```python from autoemulate.calibration.bayes import BayesianCalibration model_post_hm = hmw.emulator # Use the emulator from history matching parameter_range = {k:v for k,v in params_post_hm.items() if k in top_parameters_sa} bc = BayesianCalibration( emulator=model_post_hm, parameter_range=parameter_range, observations = {k: torch.tensor(v[0]) for k,v in observations.items()}, # take account of the emulator uncertainty model_uncertainty=True, # specify observation noise as variance observation_noise={k: v[1]**2 for k,v in observations.items()} ) mcmc = bc.run_mcmc(warmup_steps=250, num_samples=1000, sampler='nuts') ``` -------------------------------- ### Create TransformedEmulator with GP Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/transforms.ipynb Creates a TransformedEmulator with PCA and VAE transforms on inputs, Standardize and PCA on outputs, using a GaussianProcess model with 100 epochs. This is the core configuration for the transformed emulator. ```python emulator = TransformedEmulator( x=x, y=y, x_transforms=[PCATransform(n_components=4), VAETransform(latent_dim=2)], y_transforms=[StandardizeTransform(), PCATransform(n_components=1)], model=GaussianProcess, epochs=100, ) ``` -------------------------------- ### Import AutoEmulate and HistoryMatching modules Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/02_history_matching.ipynb Imports required for the tutorial: torch, matplotlib, and the AutoEmulate classes for Gaussian process emulation, model comparison, the Projectile simulator, and HistoryMatching. ```python import torch import matplotlib.pyplot as plt from autoemulate.emulators import GaussianProcessRBF from autoemulate.core.compare import AutoEmulate from autoemulate.simulations.projectile import Projectile from autoemulate.calibration.history_matching import HistoryMatching ``` -------------------------------- ### Navigate into AutoEmulate directory Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Changes the current directory to the cloned AutoEmulate repository. ```bash cd autoemulate ``` -------------------------------- ### Bayesian calibration of SEIR model with Pyro and GetDist Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/03_seir_bayes_calibration.ipynb Complete workflow for Bayesian calibration of an SEIR simulator using Pyro MCMC and a Gaussian process emulator, including plotting with GetDist. It covers generating training data, creating synthetic observations, running MCMC on the simulator, training an emulator with AutoEmulate, running MCMC on the emulator, and comparing posterior distributions. Note that the code references undefined names `pyro`, `az`, `plots`, and `arviz_to_mcsamples`; these are assumed to be imported earlier in the notebook. ```python import numpy as np import matplotlib.pyplot as plt import torch from scipy.integrate import solve_ivp from autoemulate.core.types import NumpyLike, TensorLike from autoemulate.simulations.base import Simulator from autoemulate.simulations.seir import SEIRSimulator simulator = SEIRSimulator(show_progress_bar=False) x = simulator.sample_inputs(1000) y, _ = simulator.forward_batch(x) # Plot transmission_rate = x[:, 0] recovery_rate = x[:, 1] exposure_rate = x[:, 2] plt.figure(figsize=(8, 6)) sc = plt.scatter(transmission_rate, recovery_rate, c=y, cmap='viridis') plt.xlabel('Transmission rate (beta)') plt.ylabel('Recovery rate (gamma)') plt.colorbar(sc, label="Peak infection rate") plt.title("SEIR Model Simulation") plt.show() # Step 2: Observed data true_beta = 0.3 true_gamma = 0.15 true_sigma = 0.2 params = torch.tensor([true_beta, true_gamma, true_sigma]).view(1, -1) true_infection_rate = simulator.forward(params) n_obs = 100 stdev = 0.05 noise = torch.normal(mean=0, std=stdev, size=(n_obs,)) observed_infection_rates = true_infection_rate[0] + noise observations = {"infection_rate": observed_infection_rates} # Step 3: Calibrate with simulator using Pyro import pyro.distributions as dist from pyro.infer import MCMC from pyro.infer.mcmc import RandomWalkKernel def model(): beta = pyro.sample("beta", dist.Uniform(0.1, 0.5)) gamma = pyro.sample("gamma", dist.Uniform(0.01, 0.2)) sigma = pyro.sample("sigma", dist.Uniform(0.05, 0.5)) mean = simulator.forward(torch.tensor([[beta, gamma, sigma]])) with pyro.plate("data", n_obs): pyro.sample( "infection_rate", dist.Normal(mean, stdev), obs=observations["infection_rate"], ) kernel = RandomWalkKernel(model, init_step_size=2.5) mcmc_sim = MCMC(kernel, warmup_steps=1500, num_samples=15000, num_chains=1) #might have to increase warmup syeps and num of samples for convergence mcmc_sim.run() sim_samples = mcmc_sim.get_samples() plt.scatter(sim_samples['beta'], sim_samples['gamma'], alpha=0.5) plt.xlabel('Beta') plt.ylabel('Gamma') plt.title('Simulator Posterior Samples') plt.show() # Step 4: Train Emulator and Calibrate from autoemulate.core.compare import AutoEmulate from autoemulate.emulators import GaussianProcessRBF from autoemulate.calibration.bayes import BayesianCalibration ae = AutoEmulate(x, y, models=[GaussianProcessRBF], model_params={}, show_progress_bar=False) ae.summarise() gp = ae.best_result().model bc = BayesianCalibration( gp, simulator.parameters_range, observations, observation_noise=stdev**2, ) mcmc_emu = bc.run_mcmc(warmup_steps=250, num_samples=1000, num_chains=2) mcmc_emu.summary() # Step 5: Plotting az_data = bc.to_arviz(mcmc_emu, posterior_predictive=True) _ = az.plot_pair(az_data, kind='kde') _ = az.plot_ppc(az_data) _ = az.plot_trace(az_data, figsize=(20, 8)) # Step 6: Compare Posterior Distributions sim_data = BayesianCalibration.to_getdist(mcmc_sim, label="Simulator") emu_data = arviz_to_mcsamples(az_data, dataset_label="Emulator") sim_data.smooth_scale_1D = 0.8 emu_data.smooth_scale_1D = 0.8 g = plots.get_subplot_plotter() g.triangle_plot( [sim_data, emu_data], filled=True, markers={"beta": true_beta, "gamma": true_gamma, "sigma": true_sigma}, ) plt.show() ``` -------------------------------- ### Train and evaluate a GaussianProcessRBF emulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/02_active_learning.ipynb Trains a GaussianProcessRBF emulator on 25 samples from the Sin simulator, then evaluates it on 1000 test points and plots the simulator, emulator mean, and confidence intervals. The uncertainty grows in regions far from the training data. ```python # Train emulator simulator = Sin() x_train = simulator.sample_inputs(25).sort(dim=0).values y_train, _ = simulator.forward_batch(x_train) def make_gp(x_train, y_train, lr=5e-2): return GaussianProcessRBF( x_train, y_train, lr=lr, standardize_y=False, ) emulator = make_gp(x_train, y_train) emulator.fit(x_train, y_train) # Test emulator x_test = simulator.sample_inputs(1000).sort(dim=0).values y_mean, var = emulator.predict_mean_and_variance(x_test) y_std = var.sqrt() y_true, _ = simulator.forward_batch(x_test) # Plot plt.plot(x_test.flatten(), y_true.flatten(), label='Simulator', alpha=0.5, c='k') plt.plot(x_test.flatten(), y_mean.flatten(), label='Emulator') plt.fill_between( x_test.flatten(), y_mean.flatten() - y_std.flatten(), y_mean.flatten() + y_std.flatten(), alpha=0.2, label='Confidence' ) plt.scatter(x_train, y_train, label='Training', marker='x') plt.legend() plt.show() ``` -------------------------------- ### Set up FlowProblem simulation parameters Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/01_emulation_sensitivity.ipynb Defines the parameter ranges for the flow problem simulation and creates a FlowProblem simulator instance with progress bar disabled. ```python parameters_range = { "T": (0.5, 2.0), # Cardiac cycle period (s) "td": (0.1, 0.5), # Pulse duration (s) "amp": (100.0, 1000.0), # Amplitude (e.g., pressure or flow rate) "dt": (0.0001, 0.01), # Time step (s) "C": (20.0, 60.0), # Compliance (unit varies based on context) "R": (0.01, 0.1), # Resistance (unit varies based on context) "L": (0.001, 0.005), # Inductance (unit varies based on context) "R_o": (0.01, 0.05), # Outflow resistance (unit varies based on context) "p_o": (5.0, 15.0) # Initial pressure (unit varies based on context) } output_names = ["pressure"] simulator = FlowProblem( parameters_range=parameters_range, output_names=output_names, show_progress_bar=False ) ``` -------------------------------- ### Create AutoEmulate with default GaussianProcess Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/double_pendulum_simulator.ipynb Creates a second AutoEmulate instance with default GaussianProcess settings and PCA transform, without custom kernel or model tuning. ```python ae_2 = AutoEmulate( x, y_new, models=[GaussianProcess], y_transforms_list=[[PCATransform(n_components=8)]], log_level="progress_bar") ``` -------------------------------- ### Run active learning experiment with Sinusoid simulation Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/02_active_learning.ipynb Runs the active learning experiment on the Sinusoid simulation, then summarizes and visualizes the results. The experiment uses 5 initial samples, 500 stream samples, adaptive-only learners, and a learning rate of 0.1. ```python metrics, summary = run_experiment( simulator=Sin(), seeds=[0, 1], n_initial_samples=5, n_stream_samples=500, adaptive_only=True, batch_size=None, lr=0.1 ) ``` ```python compute_statistics(summary) ``` ```python plot_metrics(metrics) ``` -------------------------------- ### Compare GP and RandomForest with transformed emulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/transforms.ipynb Loops over GaussianProcess and RandomForest models, creating a TransformedEmulator for each, fitting, predicting on training and test data, and printing R2 scores. Demonstrates how to handle Gaussian predictions by extracting the mean. ```python # Example using transformed emulator with GP and Random Forest from autoemulate.model_selection import r2_metric for model in [GaussianProcess, RandomForest]: # Create transformed emulator with GP emulator = TransformedEmulator( x=x, y=y, x_transforms=[PCATransform(n_components=4), VAETransform(latent_dim=2)], y_transforms=[StandardizeTransform(), PCATransform(n_components=1)], model=model, epochs=100, ) # Fit emulator.fit(x, y) # Predict on training data pred = emulator.predict(x[:30]) pred = pred if isinstance(pred, TensorLike) else pred.mean print(f"Train R2: {evaluate(pred, y[:30], r2_metric()):.3f}") # Predict on test data pred = emulator.predict(x2) pred = pred if isinstance(pred, TensorLike) else pred.mean print(f"Test R2: {evaluate(pred, y2, r2_metric()):.3f}") ``` -------------------------------- ### Run AutoEmulate with default settings Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/01_quickstart.ipynb Runs AutoEmulate with default settings to fit and compare emulator models on the given data. ```python # Run AutoEmulate with default settings ae = AutoEmulate(x, y, show_progress_bar=False) ``` -------------------------------- ### Initialize AutoEmulate with MLP Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Creates an AutoEmulate instance with the simulated inputs x and outputs y, using the MLP model with default hyperparameters. The training progress is shown as a progress bar. ```python from autoemulate.core.compare import AutoEmulate from autoemulate.emulators.nn.mlp import MLP ae = AutoEmulate( x, y, models=[MLP], # use default MLP params model_params={} ) ``` -------------------------------- ### Instantiate and train a stream.Random active learner Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/02_active_learning.ipynb Sets up a stream-based active learning learner using stream.Random with a query probability of 0.2, trains it on a stream of 500 samples, and fits the learner to the stream. ```python # Learner components simulator = Sin() x_train = simulator.sample_inputs(5) y_train, _ = simulator.forward_batch(x_train) emulator = make_gp(x_train, y_train, 0.1) # Learner itself! learner = stream.Random( simulator=simulator, emulator=emulator, x_train=x_train, y_train=y_train, p_query=0.2, show_progress=show_progress, ) # Stream of 500 samples X_stream = simulator.sample_inputs(500) learner.fit_samples(X_stream) ``` -------------------------------- ### Create directory for saving emulators Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/01_quickstart.ipynb Creates a directory to store saved emulator models. The path is 'my_emulators' and the directory is created only if it does not already exist. ```python import os path = "my_emulators" if not os.path.exists(path): os.makedirs(path) ``` -------------------------------- ### Instantiate HistoryMatchingWorkflow Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/03_history_matching.ipynb Instantiates the HistoryMatchingWorkflow with the simulator, fitted emulator (best_result), and observations. Optional parameters include the implausibility threshold, random seed, and original training data for refitting. ```python hmw = HistoryMatchingWorkflow( simulator=simulator, result=best_result, observations=observations, # optional parameters threshold=3.0, random_seed=random_seed, train_x=x, train_y=y ) ``` -------------------------------- ### Fit best TransformedEmulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/compare_transforms.ipynb Creates a TransformedEmulator using the best model's configuration and transforms, then fits it on the training data. ```python em = TransformedEmulator( x, y, model=outputs[best_model_idx]["model_cls"], x_transforms=outputs[best_model_idx]["x_transforms"], y_transforms=outputs[best_model_idx]["y_transforms"], **outputs[best_model_idx]["config"] ) em.fit(x, y) ``` -------------------------------- ### Initialize HistoryMatchingDashboard with wave results Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/simulator/03_history_matching.ipynb Retrieves the test parameters and implausibility scores for wave 0 using get_wave_results(0) and passes them along with parameter and output names to the HistoryMatchingDashboard constructor. ```python test_parameters, impl_scores = hmw.get_wave_results(0) dashboard = HistoryMatchingDashboard( samples=test_parameters, impl_scores=impl_scores, param_names=simulator.param_names, output_names=simulator.output_names, ) ``` -------------------------------- ### Simulate data with Epidemic simulator Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/03_bayes_calibration.ipynb Creates an Epidemic simulator instance and samples 1000 input parameter sets, then runs the simulator in batch to obtain outputs (peak infection rates). ```python simulator = Epidemic(show_progress_bar=False) x = simulator.sample_inputs(1000) y, _ = simulator.forward_batch(x) ``` -------------------------------- ### Fit AutoEmulate with PCA and ReshapeTransform Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/02_dim_reduction.ipynb Configure AutoEmulate with a GaussianProcessRBF model and a sequence of transforms: standardize inputs, then flatten outputs with ReshapeTransform, standardize, apply PCA with 16 components, and standardize again. The transforms are passed as lists of lists to allow testing different combinations. Setting n_bootstraps=None reduces computation time but increases uncertainty on the test score. ```python from autoemulate.core.compare import AutoEmulate from autoemulate.transforms import * from torch.distributions.transforms import ReshapeTransform import torch # Convert to tensors x, y = torch.Tensor(X).float(), torch.Tensor(Y).float().reshape(-1, n, n) # Split into train/test data test_idx = [np.array([13, 39, 30, 45, 17, 48, 26, 25, 32, 19])] train_idx = np.setdiff1d(np.arange(len(x)), test_idx) # Run AutoEmulate ae = AutoEmulate( x[train_idx], y[train_idx], models=["GaussianProcessRBF"], x_transforms_list=[[StandardizeTransform()]], y_transforms_list=[[ ReshapeTransform((n, n), (n * n,)), # include torch transform to flatten first StandardizeTransform(), PCATransform(n_components=16), StandardizeTransform() ]], # fewer bootstraps to reduce computation time, though more uncertainty on test score n_bootstraps=None, show_progress_bar=False, model_params={"posterior_predictive": True}, transformed_emulator_params={ "full_covariance": False, "output_from_samples": False } ) ``` -------------------------------- ### Make predictions with best.model.predict() Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/emulation/01_quickstart.ipynb Use the selected emulator's predict method to make predictions on the first ten simulator outputs. The exact input format is not shown; x is an existing variable from the tutorial. ```python best.model.predict(x[:10]) ``` -------------------------------- ### Run SMC and compare with MCMC Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/04_interval_excursion_set.ipynb Runs SMC with adaptive tempering, plots posterior and sample diagnostics, and compares MCMC vs SMC posterior densities using GetDist. ```python # Run SMC and plot diagnostics az_data_smc = ies.run_smc( n_particles=4000, ess_target_frac=0.6, move_steps=2, rw_step=0.25, seed=random_seed, uniform_prior=True, plot_diagnostics=True, return_az_data=True ) ``` ```python _ = az.plot_posterior(az_data_smc) ``` ```python assert isinstance(az_data_smc, az.InferenceData) ies.plot_samples(az_data_smc) ``` ```python assert isinstance(az_data_smc, az.InferenceData) g = plots.get_subplot_plotter() _ = g.triangle_plot( [ies.to_getdist(az_mcmc, "MCMC"), ies.to_getdist(az_data_smc, "SMC")], filled=True, ) ``` -------------------------------- ### Create observation from true parameters Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/02_history_matching.ipynb Creates an observation by running the simulator at true parameters, then sets the observation mean to the distance and variance to 5% of the distance squared. ```python true_drag = -2.0 true_velocity = 7.0 distance = simulator.forward(torch.tensor([[true_drag, true_velocity]])) stdev = distance.item() * 0.05 observation = {"distance": (distance.item(), stdev**2)} ``` -------------------------------- ### Import libraries and set random seeds for Bayesian model comparison Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/model_comparison/sir_seir.ipynb Sets up the Python environment for the case study by importing numpy, matplotlib, torch, pyro, and autoemulate modules. It also sets random seeds for reproducibility across numpy, torch, and pyro. ```python import numpy as np import matplotlib.pyplot as plt import torch import pyro import pyro.distributions as dist from pyro.infer import MCMC from pyro.infer.mcmc import RandomWalkKernel from autoemulate.simulations.epidemic import Epidemic from autoemulate.simulations.seir import SEIRSimulator from autoemulate.core.compare import AutoEmulate from autoemulate.emulators import GaussianProcessRBF from autoemulate.calibration.bayes import BayesianCalibration from autoemulate.calibration.evidence import EvidenceComputation # Set random seeds for reproducibility seed = 123 torch.manual_seed(seed) np.random.seed(seed) pyro.set_rng_seed(seed) ``` -------------------------------- ### Configure AutoEmulate with sklearn kernel and PCA transform Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/double_pendulum_simulator.ipynb Sets up an AutoEmulate with a GaussianProcess model using a custom sklearn kernel (RBF * ExpSineSquared + WhiteKernel) and PCA transform with 8 components, disabling model tuning. ```python from sklearn.gaussian_process.kernels import RBF, WhiteKernel from sklearn.gaussian_process.kernels import ExpSineSquared import numpy as np # Periodic kernel for oscillatory behavior + RBF for chaos kernel = RBF(length_scale=1.0) * ExpSineSquared(length_scale=1.0, periodicity=2*np.pi) + WhiteKernel() ae = AutoEmulate(x, y_new, models=[GaussianProcess], model_params={"kernel": kernel}, model_tuning=False, y_transforms_list=[[PCATransform(n_components=8)]], log_level="progress_bar" ) ``` -------------------------------- ### Run MCMC calibration with simulator using Pyro RandomWalkKernel Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/03_bayes_calibration.ipynb Defines a probabilistic model with uniform priors on beta and gamma, uses a simulator to compute the mean, and runs MCMC with a RandomWalkKernel. Requires a `simulator` object with a `forward` method, `n_obs`, `stdev`, and `observations` variables. The MCMC run uses 500 warmup steps, 5000 samples, and 1 chain. ```python import pyro.distributions as dist from pyro.infer import MCMC from pyro.infer.mcmc import RandomWalkKernel # define the probabilistic model def model(): # uniform priors on parameters range beta = pyro.sample("beta", dist.Uniform(0.1, 0.5)) gamma = pyro.sample("gamma", dist.Uniform(0.01, 0.2)) mean = simulator.forward(torch.tensor([[beta, gamma]])) with pyro.plate(f"data", n_obs): pyro.sample( "infection_rate", dist.Normal(mean, stdev), obs=observations["infection_rate"], ) # run Bayesian inference with MCMC kernel = RandomWalkKernel(model, init_step_size=2.5) mcmc_sim = MCMC( kernel, warmup_steps=500, num_samples=5000, num_chains=1 ) mcmc_sim.run() ``` -------------------------------- ### Fit emulator (repeated) Source: https://github.com/alan-turing-institute/autoemulate/blob/main/autoemulate/experimental/exploratory/transforms.ipynb Fits the emulator again, with a comment indicating the action. ```python # Fit emulator.fit(x, y) ``` -------------------------------- ### Activate virtual environment on Windows Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/installation.md Activates the virtual environment on Windows systems. ```bash autoemulate\Scripts\activate ``` -------------------------------- ### Run history matching waves Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Runs 5 waves of history matching, simulating 100 points per wave and sampling 1000 test points. The workflow stops early if the NROY region changes little between waves. Output shows simulation progress for each wave. ```python n_waves=5 history_matching_results = hmw.run_waves( n_waves=n_waves, # the number of simulations to run each wave n_simulations=100, # number of parameter samples to draw from which to select NROY samples to simulate n_test_samples=1000, max_retries=10 ) ``` ```text Output: Running simulations: 100%|██████████| 100/100 [00:32<00:00, 3.12sample/s] Running simulations: 100%|██████████| 100/100 [00:34<00:00, 2.88sample/s] Running simulations: 100%|██████████| 100/100 [00:35<00:00, 2.86sample/s] Running simulations: 100%|██████████| 100/100 [00:34<00:00, 2.91sample/s] Running simulations: 100%|██████████| 100/100 [00:36<00:00, 2.76sample/s] ``` -------------------------------- ### Run AutoEmulate with custom SimpleFNN model Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/advanced/01_add_emulators.ipynb Instantiate AutoEmulate with the custom SimpleFNN model. The show_progress_bar=False disables the progress bar during fitting. ```python ae = AutoEmulate(x, y, models=[SimpleFNN], show_progress_bar=False) ``` -------------------------------- ### Train Gaussian Process emulator with Matern kernel Source: https://github.com/alan-turing-institute/autoemulate/blob/main/case_studies/patient_calibration/patient_calibration_case_study.ipynb Trains a Gaussian Process emulator using only the most sensitive parameters as inputs, with a Matern 3/2 kernel and standardization. The output shows the model comparison progress. ```python from autoemulate.emulators.gaussian_process.kernel import matern_3_2_kernel sa_parameter_idx = [ simulator.get_parameter_idx(param) for param in top_parameters_sa ] ae_hm = AutoEmulate( # only use sensitive parameters as inputs to emulator x[:, sa_parameter_idx], y, models=["GaussianProcess"], model_params = { 'covar_module': matern_3_2_kernel, 'standardize_x': True, 'standardize_y': True } ) res = ae_hm.best_result() gp_matern = res.model ``` ```text Output: Comparing models: 100%|██████████| 1.00/1.00 [00:04<00:00, 4.72s/model] ``` -------------------------------- ### Summarise emulator MCMC results Source: https://github.com/alan-turing-institute/autoemulate/blob/main/docs/tutorials/tasks/03_bayes_calibration.ipynb Prints summary statistics of the posterior samples from the emulator-based MCMC run. Shows that posterior mean estimates are close to the true values. ```python mcmc_emu.summary() ```