|
| 1 | +import pandas as pd |
| 2 | +from SALib.analyze.morris import analyze as morris_analyze |
| 3 | +from SALib.analyze.sobol import analyze as sobol_analyze |
| 4 | +from SALib.sample.morris import sample as morris_sample |
| 5 | +from SALib.sample.sobol import sample as sobol_sample |
| 6 | + |
| 7 | +from autoemulate.experimental.data.utils import ConversionMixin |
| 8 | +from autoemulate.experimental.emulators.base import Emulator |
| 9 | +from autoemulate.experimental.types import DistributionLike, NumpyLike, TensorLike |
| 10 | + |
| 11 | +# NOTE: we still use these functions from main |
| 12 | +# should we just move them to experimental as well? |
| 13 | +from autoemulate.sensitivity_analysis import ( |
| 14 | + _morris_results_to_df, |
| 15 | + _plot_morris_analysis, |
| 16 | + _plot_sobol_analysis, |
| 17 | + _sobol_results_to_df, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class SensitivityAnalysis(ConversionMixin): |
| 22 | + """ |
| 23 | + Global sensitivity analysis. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + emulator: Emulator, |
| 29 | + x: TensorLike | None = None, |
| 30 | + problem: dict | None = None, |
| 31 | + ): |
| 32 | + """ |
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + emulator : Emulator |
| 36 | + Fitted emulator. |
| 37 | + x : InputLike | None |
| 38 | + Simulator input parameter values. |
| 39 | + problem : dict | None |
| 40 | + The problem definition dictionary. If None, the problem is generated |
| 41 | + from x using minimum and maximum values of the features as bounds. |
| 42 | + The dictionary should contain: |
| 43 | + - 'num_vars': Number of input variables (int) |
| 44 | + - 'names': List of variable names (list of str) |
| 45 | + - 'bounds': List of [min, max] bounds for each variable (list of lists) |
| 46 | + - 'output_names': Optional list of output names (list of str) |
| 47 | +
|
| 48 | + Example:: |
| 49 | + problem = { |
| 50 | + "num_vars": 2, |
| 51 | + "names": ["x1", "x2"], |
| 52 | + "bounds": [[0, 1], [0, 1]], |
| 53 | + "output_names": ["y1", "y2"], # optional |
| 54 | + } |
| 55 | + """ |
| 56 | + if problem is not None: |
| 57 | + problem = self._check_problem(problem) |
| 58 | + elif x is not None: |
| 59 | + problem = self._generate_problem(x) |
| 60 | + else: |
| 61 | + msg = "Either problem or x must be provided." |
| 62 | + raise ValueError(msg) |
| 63 | + |
| 64 | + self.emulator = emulator |
| 65 | + self.problem = problem |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def _check_problem(problem: dict) -> dict: |
| 69 | + """ |
| 70 | + Check that the problem definition is valid. |
| 71 | + """ |
| 72 | + if not isinstance(problem, dict): |
| 73 | + msg = "problem must be a dictionary." |
| 74 | + raise ValueError(msg) |
| 75 | + |
| 76 | + if "num_vars" not in problem: |
| 77 | + msg = "problem must contain 'num_vars'." |
| 78 | + raise ValueError(msg) |
| 79 | + if "names" not in problem: |
| 80 | + msg = "problem must contain 'names'." |
| 81 | + raise ValueError(msg) |
| 82 | + if "bounds" not in problem: |
| 83 | + msg = "problem must contain 'bounds'." |
| 84 | + raise ValueError(msg) |
| 85 | + |
| 86 | + if len(problem["names"]) != problem["num_vars"]: |
| 87 | + msg = "Length of 'names' must match 'num_vars'." |
| 88 | + raise ValueError(msg) |
| 89 | + if len(problem["bounds"]) != problem["num_vars"]: |
| 90 | + msg = "Length of 'bounds' must match 'num_vars'." |
| 91 | + raise ValueError(msg) |
| 92 | + |
| 93 | + return problem |
| 94 | + |
| 95 | + @staticmethod |
| 96 | + def _generate_problem(x: TensorLike) -> dict: |
| 97 | + """ |
| 98 | + Generate a problem definition from a design matrix. |
| 99 | +
|
| 100 | + Parameters |
| 101 | + ---------- |
| 102 | + x : TensorLike |
| 103 | + Simulator input parameter values [n_samples, n_parameters]. |
| 104 | + """ |
| 105 | + if x.ndim == 1: |
| 106 | + msg = "x must be a 2D array." |
| 107 | + raise ValueError(msg) |
| 108 | + |
| 109 | + return { |
| 110 | + "num_vars": x.shape[1], |
| 111 | + "names": [f"X{i + 1}" for i in range(x.shape[1])], |
| 112 | + "bounds": [ |
| 113 | + [x[:, i].min().item(), x[:, i].max().item()] for i in range(x.shape[1]) |
| 114 | + ], |
| 115 | + } |
| 116 | + |
| 117 | + def _sample(self, method: str, N: int) -> NumpyLike: |
| 118 | + if method == "sobol": |
| 119 | + # Saltelli sampling |
| 120 | + return sobol_sample(self.problem, N) |
| 121 | + if method == "morris": |
| 122 | + # vanilla Morris (1991) sampling |
| 123 | + return morris_sample(self.problem, N) |
| 124 | + msg = f"Unknown method: {method}. Must be 'sobol' or 'morris'." |
| 125 | + raise ValueError(msg) |
| 126 | + |
| 127 | + def _predict(self, param_samples: NumpyLike) -> NumpyLike: |
| 128 | + """ |
| 129 | + Make predictions with emulator for N input samples. |
| 130 | + """ |
| 131 | + |
| 132 | + param_tensor = self._convert_to_tensors(param_samples) |
| 133 | + assert isinstance(param_tensor, TensorLike) |
| 134 | + y_pred = self.emulator.predict(param_tensor) |
| 135 | + |
| 136 | + # handle types, convert to numpy |
| 137 | + if isinstance(y_pred, TensorLike): |
| 138 | + y_pred_np, _ = self._convert_to_numpy(y_pred) |
| 139 | + elif isinstance(y_pred, DistributionLike): |
| 140 | + y_pred_np, _ = self._convert_to_numpy(y_pred.mean) |
| 141 | + else: |
| 142 | + msg = "Emulator has to return Tensor or Distribution" |
| 143 | + raise ValueError(msg) |
| 144 | + |
| 145 | + return y_pred_np |
| 146 | + |
| 147 | + def _get_output_names(self, num_outputs: int) -> list[str]: |
| 148 | + """ |
| 149 | + Get the output names from the problem definition or generate default names. |
| 150 | + """ |
| 151 | + # check if output_names is given |
| 152 | + if "output_names" not in self.problem: |
| 153 | + output_names = [f"y{i + 1}" for i in range(num_outputs)] |
| 154 | + elif isinstance(self.problem["output_names"], list): |
| 155 | + output_names = self.problem["output_names"] |
| 156 | + else: |
| 157 | + msg = "'output_names' must be a list of strings." |
| 158 | + raise ValueError(msg) |
| 159 | + |
| 160 | + return output_names |
| 161 | + |
| 162 | + def run( |
| 163 | + self, |
| 164 | + method: str = "sobol", |
| 165 | + n_samples: int = 1024, |
| 166 | + conf_level: float = 0.95, |
| 167 | + ) -> pd.DataFrame: |
| 168 | + """ |
| 169 | + Perform global sensitivity analysis on a fitted emulator. |
| 170 | +
|
| 171 | + Parameters |
| 172 | + ---------- |
| 173 | + method: str |
| 174 | + The sensitivity analysis method to perform, one of ["sobol", "morris"]. |
| 175 | + n_samples : int |
| 176 | + Number of samples to generate for the analysis. Higher values give more |
| 177 | + accurate results but increase computation time. Default is 1024. |
| 178 | + conf_level : float |
| 179 | + Confidence level (between 0 and 1) for calculating confidence intervals |
| 180 | + of the Sobol sensitivity indices. Default is 0.95 (95% confidence). This |
| 181 | + is not used in Morris sensitivity analysis. |
| 182 | +
|
| 183 | + Returns |
| 184 | + ------- |
| 185 | + pandas.DataFrame |
| 186 | + DataFrame with columns: |
| 187 | + - 'parameter': Input parameter name |
| 188 | + - 'output': Output variable name |
| 189 | + - 'S1', 'S2', 'ST': First, second, and total order sensitivity indices |
| 190 | + - 'S1_conf', 'S2_conf', 'ST_conf': Confidence intervals for each index |
| 191 | +
|
| 192 | + Notes |
| 193 | + ----- |
| 194 | + The Sobol method requires N * (2D + 2) model evaluations, where D is the number |
| 195 | + of input parameters. For example, with N=1024 and 5 parameters, this requires |
| 196 | + 12,288 evaluations. The Morris method requires far fewer computations. |
| 197 | + """ |
| 198 | + if method not in ["sobol", "morris"]: |
| 199 | + msg = f"Unknown method: {method}. Must be 'sobol' or 'morris'." |
| 200 | + raise ValueError(msg) |
| 201 | + |
| 202 | + param_samples = self._sample(method, n_samples) |
| 203 | + y = self._predict(param_samples) |
| 204 | + output_names = self._get_output_names(y.shape[1]) |
| 205 | + |
| 206 | + results = {} |
| 207 | + for i, name in enumerate(output_names): |
| 208 | + if method == "sobol": |
| 209 | + Si = sobol_analyze(self.problem, y[:, i], conf_level=conf_level) |
| 210 | + elif method == "morris": |
| 211 | + Si = morris_analyze(self.problem, param_samples, y[:, i]) |
| 212 | + results[name] = Si # type: ignore PGH003 |
| 213 | + |
| 214 | + if method == "sobol": |
| 215 | + return _sobol_results_to_df(results) |
| 216 | + return _morris_results_to_df(results, self.problem) |
| 217 | + |
| 218 | + @staticmethod |
| 219 | + def plot_sobol(results, index="S1", n_cols=None, figsize=None): |
| 220 | + """ |
| 221 | + Plot Sobol sensitivity analysis results. |
| 222 | +
|
| 223 | + Parameters: |
| 224 | + ----------- |
| 225 | + results : pd.DataFrame |
| 226 | + The results from sobol_results_to_df. |
| 227 | + index : str, default "S1" |
| 228 | + The type of sensitivity index to plot. |
| 229 | + - "S1": first-order indices |
| 230 | + - "S2": second-order/interaction indices |
| 231 | + - "ST": total-order indices |
| 232 | + n_cols : int, optional |
| 233 | + The number of columns in the plot. Defaults to 3 if there are 3 or |
| 234 | + more outputs, otherwise the number of outputs. |
| 235 | + figsize : tuple, optional |
| 236 | + Figure size as (width, height) in inches. If None, set automatically. |
| 237 | + """ |
| 238 | + return _plot_sobol_analysis(results, index, n_cols, figsize) |
| 239 | + |
| 240 | + @staticmethod |
| 241 | + def plot_morris(results, param_groups=None, n_cols=None, figsize=None): |
| 242 | + """ |
| 243 | + Plot Morris analysis results. |
| 244 | +
|
| 245 | + Parameters: |
| 246 | + ----------- |
| 247 | + results : pd.DataFrame |
| 248 | + The results from sobol_results_to_df. |
| 249 | + param_groups : dic[str, list[str]] | None |
| 250 | + Optional parameter groupings used to give all the same plot color |
| 251 | + of the form ({<group name> : [param1, ...], }). |
| 252 | + n_cols : int, optional |
| 253 | + The number of columns in the plot. Defaults to 3 if there are 3 or |
| 254 | + more outputs, otherwise the number of outputs. |
| 255 | + figsize : tuple, optional |
| 256 | + Figure size as (width, height) in inches.If None, set calculated. |
| 257 | + """ |
| 258 | + return _plot_morris_analysis(results, param_groups, n_cols, figsize) |
0 commit comments