|
| 1 | +from abc import ABC, abstractmethod |
| 2 | + |
| 3 | +import torch |
| 4 | +from tqdm import tqdm |
| 5 | + |
| 6 | +from autoemulate.experimental.data.utils import ValidationMixin |
| 7 | +from autoemulate.experimental.types import TensorLike |
| 8 | +from autoemulate.experimental_design import LatinHypercube |
| 9 | + |
| 10 | + |
| 11 | +class Simulator(ABC, ValidationMixin): |
| 12 | + """ |
| 13 | + Base class for simulations. All simulators should inherit from this class. |
| 14 | + This class provides the interface and common functionality for different |
| 15 | + simulation implementations. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, parameters_range: dict[str, tuple[float, float]], output_names: list[str] |
| 20 | + ): |
| 21 | + """ |
| 22 | + Parameters |
| 23 | + ---------- |
| 24 | + parameters_range : dict[str, tuple[float, float]] |
| 25 | + Dictionary mapping input parameter names to their (min, max) ranges. |
| 26 | + output_names: list[str] |
| 27 | + List of output parameters' names. |
| 28 | + """ |
| 29 | + self._parameters_range = parameters_range |
| 30 | + self._param_names = list(parameters_range.keys()) |
| 31 | + self._param_bounds = list(parameters_range.values()) |
| 32 | + self._output_names = output_names |
| 33 | + self._in_dim = len(self.param_names) |
| 34 | + self._out_dim = len(self.output_names) |
| 35 | + self._has_sample_forward = False |
| 36 | + |
| 37 | + @property |
| 38 | + def parameters_range(self) -> dict[str, tuple[float, float]]: |
| 39 | + """Dictionary mapping input parameter names to their (min, max) ranges.""" |
| 40 | + return self._parameters_range |
| 41 | + |
| 42 | + @property |
| 43 | + def param_names(self) -> list[str]: |
| 44 | + """List of parameter names.""" |
| 45 | + return self._param_names |
| 46 | + |
| 47 | + @property |
| 48 | + def param_bounds(self) -> list[tuple[float, float]]: |
| 49 | + """List of parameter bounds.""" |
| 50 | + return self._param_bounds |
| 51 | + |
| 52 | + @property |
| 53 | + def output_names(self) -> list[str]: |
| 54 | + """List of output parameter names.""" |
| 55 | + return self._output_names |
| 56 | + |
| 57 | + @property |
| 58 | + def in_dim(self) -> int: |
| 59 | + """Input dimensionality.""" |
| 60 | + return self._in_dim |
| 61 | + |
| 62 | + @property |
| 63 | + def out_dim(self) -> int: |
| 64 | + """Output dimensionality.""" |
| 65 | + return self._out_dim |
| 66 | + |
| 67 | + def sample_inputs(self, n_samples: int) -> TensorLike: |
| 68 | + """ |
| 69 | + Generate random samples using Latin Hypercube Sampling. |
| 70 | +
|
| 71 | + Parameters |
| 72 | + ---------- |
| 73 | + n_samples: int |
| 74 | + Number of samples to generate. |
| 75 | +
|
| 76 | + Returns |
| 77 | + ------- |
| 78 | + TensorLike |
| 79 | + Parameter samples (column order is given by self.param_names) |
| 80 | + """ |
| 81 | + |
| 82 | + lhd = LatinHypercube(self.param_bounds) |
| 83 | + sample_array = lhd.sample(n_samples) |
| 84 | + # TODO: have option to set dtype and ensure consistency throughout codebase? |
| 85 | + # added here as method was returning float64 and elsewhere had tensors of |
| 86 | + # float32 and this caused issues |
| 87 | + return torch.tensor(sample_array, dtype=torch.float32) |
| 88 | + |
| 89 | + @abstractmethod |
| 90 | + def _forward(self, x: TensorLike) -> TensorLike: |
| 91 | + """ |
| 92 | + Abstract method to perform the forward simulation. |
| 93 | +
|
| 94 | + Parameters |
| 95 | + ---------- |
| 96 | + x : TensorLike |
| 97 | + Input parameters into the simulation forward run. |
| 98 | +
|
| 99 | + Returns |
| 100 | + ------- |
| 101 | + TensorLike |
| 102 | + Simulated output tensor. Shape = (1, self.out_dim). |
| 103 | + For example, if the simulator outputs two simulated variables, |
| 104 | + then the shape would be (1, 2). |
| 105 | + """ |
| 106 | + |
| 107 | + def forward(self, x: TensorLike) -> TensorLike: |
| 108 | + """ |
| 109 | + Generate samples from input data using the simulator. Combines the |
| 110 | + abstract method `_forward` with some validation checks. |
| 111 | +
|
| 112 | + Parameters |
| 113 | + ---------- |
| 114 | + x : TensorLike |
| 115 | + Input tensor of shape (n_samples, self.in_dim). |
| 116 | +
|
| 117 | + Returns |
| 118 | + ------- |
| 119 | + TensorLike |
| 120 | + Simulated output tensor. |
| 121 | + """ |
| 122 | + y = self.check_matrix(self._forward(self.check_matrix(x))) |
| 123 | + x, y = self.check_pair(x, y) |
| 124 | + return y |
| 125 | + |
| 126 | + def forward_batch(self, samples: TensorLike) -> TensorLike: |
| 127 | + """ |
| 128 | + Run multiple simulations with different parameters. |
| 129 | +
|
| 130 | + Parameters |
| 131 | + ---------- |
| 132 | + samples: TensorLike |
| 133 | + Tensor of input parameters to make predictions for. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + ------- |
| 137 | + TensorLike |
| 138 | + Tensor of simulation results of shape (n_batch, self.out_dim). |
| 139 | + """ |
| 140 | + results = [] |
| 141 | + successful = 0 |
| 142 | + |
| 143 | + # Process each sample with progress tracking |
| 144 | + for i in tqdm(range(len(samples)), desc="Running simulations"): |
| 145 | + result = self.forward(samples[i : i + 1]) |
| 146 | + if result is not None: |
| 147 | + results.append(result) |
| 148 | + successful += 1 |
| 149 | + |
| 150 | + # Report results |
| 151 | + print( |
| 152 | + f"Successfully completed {successful}/{len(samples)}" |
| 153 | + f" simulations ({successful / len(samples) * 100:.1f}%)" |
| 154 | + ) |
| 155 | + |
| 156 | + # stack results into a 2D array on first dim using torch |
| 157 | + return torch.cat(results, dim=0) |
| 158 | + |
| 159 | + def get_parameter_idx(self, name: str) -> int: |
| 160 | + """ |
| 161 | + Get the index of a specific parameter. |
| 162 | +
|
| 163 | + Parameters |
| 164 | + ---------- |
| 165 | + name : str |
| 166 | + Name of the parameter to retrieve. |
| 167 | +
|
| 168 | + Returns |
| 169 | + ------- |
| 170 | + float |
| 171 | + Index of the specified parameter. |
| 172 | + """ |
| 173 | + if name not in self._param_names: |
| 174 | + raise ValueError(f"Parameter {name} not found.") |
| 175 | + return self._param_names.index(name) |
0 commit comments