saconfidence 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ """Estimate how many model runs Sobol sensitivity indices need."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from .core import Result, estimate, sample
6
+
7
+ __all__ = ["Result", "estimate", "sample"]
8
+ __version__ = version("saconfidence")
saconfidence/core.py ADDED
@@ -0,0 +1,271 @@
1
+ """How many model runs do Sobol indices need? Estimated from a small pilot.
2
+
3
+ The half-width of the confidence interval on a Sobol index falls as
4
+ ``1 / sqrt(n)`` with the number of base samples ``n``. A pilot measures the
5
+ constant ``c`` in ``half-width = c / sqrt(n)``, and ``n = (c / target)**2``
6
+ base samples then give intervals as narrow as the target.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ from SALib.analyze import sobol as _analyze
14
+ from SALib.sample import sobol as _sample
15
+ from scipy import stats
16
+
17
+ ORDER_NAMES = {"ST": "Total order", "S1": "First order", "S2": "Second order"}
18
+ MIN_BLOCK = 8 # the smallest block of base samples that is analysed
19
+ GROUPS = 8 # the pilot is analysed with each eighth left out, so it needs this many base samples
20
+
21
+
22
+ def sample(problem, n=16, calc_second_order=True, seed=0):
23
+ """Draw the pilot sample: SALib's scrambled Sobol sample.
24
+
25
+ With one seed, a larger sample starts with the rows of a smaller one, so
26
+ the pilot runs are the first runs of the full sample.
27
+
28
+ Parameters
29
+ ----------
30
+ problem : dict
31
+ A SALib problem.
32
+ n : int
33
+ Number of base samples, a power of two.
34
+ calc_second_order : bool
35
+ Include the runs that second-order indices need.
36
+ seed : int
37
+ Seed of the sample.
38
+
39
+ Returns
40
+ -------
41
+ numpy.ndarray
42
+ One row for each model run: ``n * (2D + 2)`` rows for ``D`` parameters,
43
+ or ``n * (D + 2)`` without second order.
44
+ """
45
+ return _sample.sample(problem, n, calc_second_order=calc_second_order, scramble=True, seed=seed)
46
+
47
+
48
+ def estimate(problem, Y, target=0.05, calc_second_order=True, conf_level=0.95, num_resamples=200, seed=0):
49
+ """Estimate the sample size Sobol indices need, from pilot model output.
50
+
51
+ The whole pilot gives the constant ``c`` of ``half-width = c / sqrt(n)``.
52
+ Analysing it again with each eighth left out in turn (a jackknife) shows
53
+ how much ``c`` could move, pooled over the indices of an order: its range.
54
+ To check the rule, the pilot is also analysed in disjoint blocks of half,
55
+ a quarter and an eighth of its size, no smaller than 8 base samples.
56
+
57
+ Parameters
58
+ ----------
59
+ problem : dict
60
+ A SALib problem.
61
+ Y : array_like
62
+ Model output for a SALib Sobol sample of the problem, in sample order,
63
+ with at least 8 base samples.
64
+ target : float
65
+ The half-width the confidence intervals should reach.
66
+ calc_second_order : bool
67
+ Whether the sample was drawn with second order.
68
+ conf_level : float
69
+ Confidence level of the intervals.
70
+ num_resamples : int
71
+ Bootstrap resamples in each SALib analysis.
72
+ seed : int
73
+ Seed of the bootstrap.
74
+
75
+ Returns
76
+ -------
77
+ Result
78
+ Print it for the sample size needed, or call its ``plot``.
79
+
80
+ Examples
81
+ --------
82
+ >>> X = sample(problem, 16)
83
+ >>> Y = Ishigami.evaluate(X)
84
+ >>> result = estimate(problem, Y, target=0.05)
85
+ >>> print(result)
86
+ """
87
+ Y = np.asarray(Y, dtype=float).ravel()
88
+ names = list(dict.fromkeys(problem.get("groups") or problem["names"]))
89
+ per = (2 if calc_second_order else 1) * len(names) + 2
90
+ n = Y.size // per
91
+ if Y.size % per or n < GROUPS or not np.isfinite(Y).all():
92
+ raise ValueError(
93
+ f"Y must be finite and hold at least {GROUPS} base samples of {per} runs each. It has {Y.size} values."
94
+ )
95
+ Y = Y.reshape(n, per)
96
+
97
+ def analyse(keep, seed):
98
+ """Analyse some of the base samples: order, label, value and half-width of each index."""
99
+ s = _analyze.analyze(
100
+ problem,
101
+ Y[keep].ravel(),
102
+ calc_second_order=calc_second_order,
103
+ num_resamples=num_resamples,
104
+ conf_level=conf_level,
105
+ seed=seed,
106
+ )
107
+ return [
108
+ (df.columns[0], name if isinstance(name, str) else " × ".join(name), value, half)
109
+ for df in s.to_df()
110
+ for name, (value, half) in zip(df.index, df.to_numpy())
111
+ ]
112
+
113
+ with np.errstate(all="ignore"):
114
+ rows = []
115
+ sizes = [n] + [n // d for d in (2, 4, 8) if n // d >= MIN_BLOCK]
116
+ for k, m in enumerate(sizes):
117
+ for j in range(n // m):
118
+ block = slice(j * m, (j + 1) * m)
119
+ for order, label, value, half in analyse(block, seed + 1000 * k + j + 1): # SALib ignores a seed of 0
120
+ rows.append((order, label, m, j, value, half, half * m**0.5))
121
+ tested = pd.DataFrame(rows, columns=["order", "label", "size", "block", "value", "halfwidth", "c"])
122
+ whole = tested[tested["size"] == n].set_index(["order", "label"])
123
+
124
+ # The jackknife: how far the log half-width moves when an eighth of the pilot
125
+ # is left out. One seed, so that the eight analyses share their resamples.
126
+ kept = [np.delete(np.arange(n), g) for g in np.array_split(np.arange(n), GROUPS)]
127
+ log = np.log([[half for *_, half in analyse(rest, seed + 1)] for rest in kept])
128
+ var = pd.Series((GROUPS - 1) * log.var(axis=0), index=whole.index).groupby("order")
129
+ sd = np.sqrt(var.mean() + 0.5 / num_resamples) # the second term is the noise of the resampling
130
+ spread = np.exp(stats.t.ppf(0.5 + conf_level / 2, (GROUPS - 1) * var.count()) * sd)
131
+
132
+ rows = []
133
+ for (order, label), g in tested.groupby(["order", "label"], sort=False):
134
+ g = g[g["c"] > 0]
135
+ slope = np.polyfit(np.log(g["size"]), np.log(g["halfwidth"]), 1)[0] if len(g) > 2 else np.nan
136
+ w, s = whole.loc[(order, label)], spread[order]
137
+ rows.append((order, label, w["value"], w["halfwidth"], w["c"], w["c"] / s, w["c"] * s, slope))
138
+ columns = ["order", "label", "value", "halfwidth", "c", "c_lo", "c_hi", "slope"]
139
+ return Result(names, n, calc_second_order, target, tested, pd.DataFrame(rows, columns=columns))
140
+
141
+
142
+ @dataclass
143
+ class Result:
144
+ """What the pilot shows. Print it for the sample size needed.
145
+
146
+ Attributes
147
+ ----------
148
+ names : list
149
+ Parameter names, or group names if the problem has groups.
150
+ n : int
151
+ Base samples in the pilot.
152
+ calc_second_order : bool
153
+ Whether the pilot has second order.
154
+ target : float
155
+ The half-width to reach. Set it to ask for another.
156
+ tested : pandas.DataFrame
157
+ Every index in every block analysed.
158
+ indices : pandas.DataFrame
159
+ A row for each index: its value and half-width in the pilot, the
160
+ constant ``c`` with its range, and the fitted slope of log half-width
161
+ on log ``n``, where -0.5 is assumed. A pilot of 8 base samples has no
162
+ slope.
163
+ """
164
+
165
+ names: list
166
+ n: int
167
+ calc_second_order: bool
168
+ target: float
169
+ tested: pd.DataFrame
170
+ indices: pd.DataFrame
171
+
172
+ def widest(self, keep=None):
173
+ """Find the widest interval of each order and the base samples it needs.
174
+
175
+ Parameters
176
+ ----------
177
+ keep : list, optional
178
+ Only look at the indices of these parameters.
179
+
180
+ Returns
181
+ -------
182
+ pandas.DataFrame
183
+ A row for each order: the index, its half-width, ``c`` with its
184
+ range, and the base samples ``n`` that reach the target, with
185
+ their range ``n_lo`` to ``n_hi``.
186
+ """
187
+ d = self.indices
188
+ if keep is not None:
189
+ d = d[[set(label.split(" × ")) <= set(keep) for label in d["label"]]]
190
+ g = d.groupby("order", sort=False)
191
+ out = d.loc[g["c"].idxmax()].set_index("order")
192
+ out[["c_lo", "c_hi"]] = g[["c_lo", "c_hi"]].max()
193
+ for end in ("", "_lo", "_hi"):
194
+ out["n" + end] = (out["c" + end] / self.target) ** 2
195
+ return out
196
+
197
+ def runs(self, drop=None):
198
+ """Count the model runs needed, with all parameters and with fewer.
199
+
200
+ Leaving a parameter out assumes that the other indices and their
201
+ intervals stay as they are. That holds while ``dropped_ST``, the sum of
202
+ the total-order indices left out, is small.
203
+
204
+ Parameters
205
+ ----------
206
+ drop : list, optional
207
+ Parameters to leave out, in order. By default the least
208
+ influential goes first, by total-order index in the pilot.
209
+
210
+ Returns
211
+ -------
212
+ pandas.DataFrame
213
+ A row for each number of parameters and design: the base samples
214
+ ``n`` with their range, ``n_pow2`` (``n`` rounded up to a power of
215
+ two) and the model ``runs`` that takes.
216
+ """
217
+ st = self.indices[self.indices["order"] == "ST"].set_index("label")["value"]
218
+ drop = list(st.sort_values().index if drop is None else drop)
219
+ designs = [("first and total order", ["ST", "S1"], 1), ("with second order", ["ST", "S1", "S2"], 2)]
220
+ rows = []
221
+ for k in range(len(drop) + 1):
222
+ keep = [name for name in self.names if name not in drop[:k]]
223
+ if len(keep) < 1 + self.calc_second_order:
224
+ break
225
+ w = self.widest(keep)
226
+ row = {"parameters": len(keep), "dropped": drop[k - 1] if k else "", "dropped_ST": st[drop[:k]].sum()}
227
+ for design, orders, mult in designs[: 1 + self.calc_second_order]:
228
+ need = w.loc[orders, ["n", "n_lo", "n_hi"]].max()
229
+ rows.append({**row, "design": design, "per": mult * len(keep) + 2, **need})
230
+ out = pd.DataFrame(rows)
231
+ out["n_pow2"] = 2.0 ** np.ceil(np.log2(out["n"].clip(lower=1)))
232
+ out["runs"] = out["n_pow2"] * out.pop("per")
233
+ return out
234
+
235
+ def __str__(self):
236
+ """Return both tables as text."""
237
+ per = (2 if self.calc_second_order else 1) * len(self.names) + 2
238
+ whole = dict.fromkeys(("n", "n_lo", "n_hi", "n_pow2", "runs"), "{:,.0f}".format)
239
+ widest = self.widest()[["label", "halfwidth", "slope", "n", "n_lo", "n_hi"]]
240
+ return (
241
+ f"Pilot of {self.n:,} base samples, {self.n * per:,} model runs. Target half-width {self.target:g}.\n\n"
242
+ "Widest interval of each order, and the base samples n it needs:\n"
243
+ f"{widest.to_string(formatters=whole, float_format='{:.3f}'.format)}\n\n"
244
+ "Model runs needed, as the least influential parameters are left out:\n"
245
+ f"{self.runs().to_string(formatters=whole, float_format='{:.3f}'.format, index=False)}"
246
+ )
247
+
248
+ def plot(self, ax=None):
249
+ """Plot the scaling of each order and the effect of fewer parameters.
250
+
251
+ Parameters
252
+ ----------
253
+ ax : sequence of matplotlib.axes.Axes, optional
254
+ One axes for each order and one more. Made if not given.
255
+
256
+ Returns
257
+ -------
258
+ sequence of matplotlib.axes.Axes
259
+ """
260
+ import matplotlib.pyplot as plt
261
+
262
+ from .plotting import parameters, scaling
263
+
264
+ orders = list(self.widest().index)
265
+ if ax is None:
266
+ k = len(orders) + 1
267
+ _, ax = plt.subplots(1, k, figsize=(4 * k, 3.6), layout="constrained")
268
+ for order, a in zip(orders, ax):
269
+ scaling(self, order, a)
270
+ parameters(self, ax[-1])
271
+ return ax
@@ -0,0 +1,90 @@
1
+ """Plots of a pilot result. As in SALib, each takes an axes and returns it."""
2
+
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ from matplotlib.cbook import boxplot_stats
6
+ from matplotlib.ticker import LogLocator
7
+
8
+ from .core import ORDER_NAMES
9
+
10
+
11
+ def _axes(ax, target, **labels):
12
+ """Add a line at the target, a grid, and a log y axis with plain numbers."""
13
+ ax.axhline(target, color="k", lw=0.8)
14
+ ax.grid(True)
15
+ ax.set_axisbelow(True)
16
+ ax.set(yscale="log", ylabel="Widest interval half-width", **labels)
17
+ ax.yaxis.set_major_locator(LogLocator(subs=(1, 2, 5)))
18
+ ax.yaxis.set_major_formatter("{x:g}")
19
+ ax.yaxis.set_minor_formatter("")
20
+ return ax
21
+
22
+
23
+ def scaling(result, order="ST", ax=None):
24
+ """Plot the widest interval of an order against base samples.
25
+
26
+ The boxes are its half-width inside the pilot: in the blocks the pilot is
27
+ cut into, and in the whole pilot, where the whiskers are the range of
28
+ ``c``. The points are ``c / sqrt(n)`` beyond the pilot, with the same range
29
+ as error bars. The horizontal line is the target.
30
+
31
+ Parameters
32
+ ----------
33
+ result : Result
34
+ From :func:`saconfidence.estimate`.
35
+ order : {"ST", "S1", "S2"}
36
+ Total, first or second order.
37
+ ax : matplotlib.axes.Axes, optional
38
+ Axes to draw on. The current axes if not given.
39
+
40
+ Returns
41
+ -------
42
+ matplotlib.axes.Axes
43
+ """
44
+ ax = ax or plt.gca()
45
+ w = result.widest().loc[order]
46
+ t = result.tested[(result.tested["order"] == order) & (result.tested["label"] == w["label"])]
47
+ sizes = sorted(t["size"].unique())
48
+ doublings = np.clip(np.nan_to_num(np.ceil(np.log2(w["n"] / result.n)), nan=1, posinf=12), 1, 12)
49
+ n = result.n * 2.0 ** np.arange(doublings + 1)
50
+ lo, y, hi = (w[c] / np.sqrt(n) for c in ("c_lo", "c", "c_hi"))
51
+
52
+ boxes = [boxplot_stats(t.loc[t["size"] == m, "halfwidth"].dropna(), whis=(0, 100))[0] for m in sizes[:-1]]
53
+ half = (hi[0] / y[0]) ** 0.34 # the middle half of a 95% range
54
+ boxes.append({"med": y[0], "q1": y[0] / half, "q3": y[0] * half, "whislo": lo[0], "whishi": hi[0]})
55
+ ax.bxp(boxes, positions=sizes, widths=[0.4 * m for m in sizes], showfliers=False, manage_ticks=False)
56
+ ax.errorbar(n[1:], y[1:], yerr=[(y - lo)[1:], (hi - y)[1:]], marker="o", capsize=3, label="Predicted")
57
+ ax.set_xscale("log", base=2)
58
+ ax.set_xticks(np.concatenate([sizes, n[1:]])[(len(sizes) - 1) % 2 :: 2]) # every other size, with the pilot
59
+ ax.xaxis.set_major_formatter("{x:.0f}")
60
+ return _axes(ax, result.target, xlabel="Base samples", title=ORDER_NAMES[order])
61
+
62
+
63
+ def parameters(result, ax=None, lines=6):
64
+ """Plot the widest interval against model runs, as parameters are left out.
65
+
66
+ Parameters
67
+ ----------
68
+ result : Result
69
+ From :func:`saconfidence.estimate`.
70
+ ax : matplotlib.axes.Axes, optional
71
+ Axes to draw on. The current axes if not given.
72
+ lines : int
73
+ The most numbers of parameters to draw.
74
+
75
+ Returns
76
+ -------
77
+ matplotlib.axes.Axes
78
+ """
79
+ ax = ax or plt.gca()
80
+ r = result.runs()
81
+ r = r[r["design"] == r["design"].iloc[-1]]
82
+ r = r.iloc[np.unique(np.linspace(0, len(r) - 1, lines).round().astype(int))]
83
+ per = r["runs"] / r["n_pow2"]
84
+ runs = np.geomspace(result.n * per.max(), 2 * r["runs"].max())
85
+ ax.set_prop_cycle(color=plt.cm.viridis(np.linspace(0, 0.9, len(r))))
86
+ for k, n, p in zip(r["parameters"], r["n"], per):
87
+ ax.plot(runs, result.target * np.sqrt(n * p / runs), label=k)
88
+ ax.legend(title="Parameters kept", loc="upper right", ncols=2)
89
+ ax.set_xscale("log")
90
+ return _axes(ax, result.target, xlabel=f"Model runs, {r['design'].iloc[0]}", title="Fewer parameters")
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.5
2
+ Name: saconfidence
3
+ Version: 0.0.1
4
+ Summary: How many model runs do Sobol sensitivity indices need? Estimated from a small pilot sample with SALib.
5
+ Project-URL: Documentation, https://barneydobson.github.io/SAconfidence
6
+ Project-URL: Repository, https://github.com/barneydobson/SAconfidence
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: matplotlib>=3.6
9
+ Requires-Dist: numpy
10
+ Requires-Dist: pandas
11
+ Requires-Dist: salib>=1.5
12
+ Requires-Dist: scipy
13
+ Provides-Extra: dev
14
+ Requires-Dist: pre-commit; extra == 'dev'
15
+ Requires-Dist: pytest; extra == 'dev'
16
+ Requires-Dist: pytest-cov; extra == 'dev'
17
+ Requires-Dist: ruff; extra == 'dev'
18
+ Provides-Extra: doc
19
+ Requires-Dist: mkdocs-include-markdown-plugin; extra == 'doc'
20
+ Requires-Dist: mkdocs-material; extra == 'doc'
21
+ Requires-Dist: mkdocstrings[python]; extra == 'doc'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # SAconfidence
25
+
26
+ _Don't be the person who doesn't check their error bars..._
27
+
28
+ How many model runs does your model need to get converged Sobol sensitivity
29
+ indices? SAconfidence estimates that from a small pilot, using
30
+ [SALib](https://salib.readthedocs.io).
31
+
32
+ A Sobol index is the share of the variation in a model output that is due to a
33
+ parameter: on its own (first order, `S1`), with all its interactions (total
34
+ order, `ST`), or through its interaction with one other parameter (second
35
+ order, `S2`).
36
+
37
+ SALib estimates the indices from a sample of model runs, so each has a 95%
38
+ confidence interval, such as 0.56 ± 0.08. The number after the ± is the
39
+ half-width: the true value is probably within that distance of the estimate.
40
+ The indices are converged when every half-width is below a target you choose.
41
+
42
+ ![One index and its confidence interval at four sample sizes](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/half_width.png)
43
+
44
+ The sample is built from `n` base samples. Each costs `D + 2` model runs for `D`
45
+ parameters, or `2D + 2` if you want second-order indices. The half-width falls
46
+ in proportion to `1 / sqrt(n)`, so four times the runs halve it, as in the
47
+ figure.
48
+
49
+ That rule is why a tiny pilot is enough. A pilot of 16 base samples measures
50
+ every half-width, and the rule gives the `n` at which the widest one reaches
51
+ the target.
52
+
53
+ This is a draft. Install it with `pip install saconfidence`. The functions are
54
+ described in the [documentation](https://barneydobson.github.io/SAconfidence).
55
+
56
+ ## Use
57
+
58
+ ```python
59
+ import saconfidence as sac
60
+
61
+ problem = {"num_vars": 3, "names": ["x1", "x2", "x3"], "bounds": [[0, 1]] * 3}
62
+
63
+ X = sac.sample(problem, 16) # SALib's Sobol sample, 16 base samples
64
+ Y = my_model(X) # one output for each row
65
+ result = sac.estimate(problem, Y, target=0.05)
66
+
67
+ print(result)
68
+ result.plot()
69
+ ```
70
+
71
+ `problem` is a SALib problem. `target` is the half-width the 95% confidence
72
+ intervals should reach.
73
+
74
+ ## Output
75
+
76
+ `python examples/sobol_g.py` takes a pilot of 16 base samples of the Sobol G
77
+ function with eight parameters. It prints:
78
+
79
+ ```text
80
+ Pilot of 16 base samples, 288 model runs. Target half-width 0.05.
81
+
82
+ Widest interval of each order, and the base samples n it needs:
83
+ label halfwidth slope n n_lo n_hi
84
+ order
85
+ ST x1 0.625 -0.449 2,497 452 13,808
86
+ S1 x1 0.555 -0.568 1,970 354 10,973
87
+ S2 x1 × x2 1.154 -0.773 8,527 1,744 41,698
88
+
89
+ Model runs needed, as the least influential parameters are left out:
90
+ parameters dropped dropped_ST design n n_lo n_hi n_pow2 runs
91
+ 8 0.000 first and total order 2,497 452 13,808 4,096 40,960
92
+ 8 0.000 with second order 8,527 1,744 41,698 16,384 294,912
93
+ 7 x8 0.000 first and total order 2,497 452 13,808 4,096 36,864
94
+ 7 x8 0.000 with second order 8,527 1,744 41,698 16,384 262,144
95
+ 6 x7 0.000 first and total order 2,497 452 13,808 4,096 32,768
96
+ 6 x7 0.000 with second order 8,527 1,744 41,698 16,384 229,376
97
+ 5 x6 0.000 first and total order 2,497 452 13,808 4,096 28,672
98
+ 5 x6 0.000 with second order 8,527 1,744 41,698 16,384 196,608
99
+ 4 x5 0.000 first and total order 2,497 452 13,808 4,096 24,576
100
+ 4 x5 0.000 with second order 8,527 1,744 41,698 16,384 163,840
101
+ 3 x4 0.012 first and total order 2,497 452 13,808 4,096 20,480
102
+ 3 x4 0.012 with second order 8,527 1,744 41,698 16,384 131,072
103
+ 2 x3 0.042 first and total order 2,497 452 13,808 4,096 16,384
104
+ 2 x3 0.042 with second order 8,527 1,744 41,698 16,384 98,304
105
+ ```
106
+
107
+ The first table has a row for each order. `label` is the index with the widest
108
+ interval, `halfwidth` is its half-width in the pilot, and `n` is the base
109
+ samples that would bring it down to the target, somewhere between `n_lo` and
110
+ `n_hi`. That range comes from analysing the pilot eight more times, each with a
111
+ different eighth of it left out. `slope` checks the rule: it is measured inside
112
+ the pilot and should be near -0.5, though a small pilot measures it roughly.
113
+
114
+ The second table is the cost. Sobol samples should be a power of two, so
115
+ `n_pow2` is `n` rounded up to one, and `runs` is the model runs that takes. The
116
+ later rows show what leaving parameters out would save, least influential
117
+ first. That assumes the other indices do not change, which holds while
118
+ `dropped_ST`, the sum of the total-order indices left out, is small.
119
+
120
+ It draws:
121
+
122
+ ![Figure for the Sobol G function](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/sobol_g.png)
123
+
124
+ Each of the first three panels follows the widest interval of one order. The
125
+ boxes are its half-width inside the pilot: in the two halves (8 base samples)
126
+ and in the whole pilot (16), where the whiskers show how uncertain it is. The
127
+ points are the rule's prediction beyond the pilot, with the same uncertainty as
128
+ error bars. The horizontal line is the target. The last panel shows the same
129
+ prediction against model runs when fewer parameters are kept.
130
+
131
+ ### Disappointed?
132
+
133
+ Global sensitivity analysis is expensive. However, just because a half-width
134
+ is not below 5%, it doesn't mean you can't say with confidence that something is
135
+ sensitive. `x1` [above](#saconfidence) is still greater than 0 even with the a
136
+ large half-width: _no more runs needed!_
137
+
138
+ ## How well it works
139
+
140
+ `python examples/sobol_g_measured.py` draws the first three panels again and
141
+ adds, as crosses, the widest half-width that SALib measures as the sample grows
142
+ to 4,096 base samples:
143
+
144
+ ![The same panels with the measured half-widths](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/sobol_g_measured.png)
145
+
146
+ The crosses follow the prediction and stay inside the error bars.
147
+
148
+ A larger pilot gives the same answer with narrower error bars. From 16 base
149
+ samples the total order needs 2,497, somewhere between 452 and 13,808. From 256
150
+ it needs 2,868, somewhere between 1,398 and 5,880.
151
+
152
+ `examples/check_scaling.py` compares the prediction with the half-width
153
+ measured at 4,096 base samples, over 20 seeds of the Ishigami and Sobol G
154
+ functions.
155
+
156
+ | Pilot, base samples | Predicted over measured half-width, 5% to 95% |
157
+ | --- | --- |
158
+ | 8 | 0.36 to 2.12 |
159
+ | 16 | 0.41 to 1.86 |
160
+ | 64 | 0.68 to 1.37 |
161
+ | 256 | 0.73 to 1.28 |
162
+
163
+ The sample size goes with the square of the ratio, so a pilot of 16 gives it
164
+ within about 0.2 to 3.5 times, and a pilot of 256 within about 0.5 to 1.6
165
+ times.
166
+
167
+ ## Limits
168
+
169
+ - It predicts the confidence intervals that SALib reports, which SALib gets by
170
+ resampling the model runs (a bootstrap).
171
+ - The error bars should hold the measured value 95% of the time. For the
172
+ Ishigami function, whose output has heavy tails, they did so in 90% of seeds
173
+ at some pilot sizes.
174
+ - A pilot needs at least 8 base samples. With 8 or 16, the total-order
175
+ half-width of the Ishigami function was predicted too small: by a third with
176
+ 8 and a fifth with 16.
177
+ - It takes one output at a time. For several, use the largest sample size.
178
+ - Leaving parameters out has only been tested where they matter little. There,
179
+ `examples/check_fewer_parameters.py` gives a predicted over measured
180
+ half-width of 0.84 to 1.19, from a pilot of 256.
181
+
182
+ ## Development
183
+
184
+ ```bash
185
+ pip install -e ".[dev,doc]"
186
+ pre-commit install
187
+ pytest
188
+ mkdocs serve
189
+ ```
@@ -0,0 +1,6 @@
1
+ saconfidence/__init__.py,sha256=YOSUD5RPksGBn1d8uACu-GOIgIJnCm8krciApm1Mbtc,233
2
+ saconfidence/core.py,sha256=O3XEOBcxFmSrSYdmL3jgEjcMaIdWLQEENXWIznJUt3o,11112
3
+ saconfidence/plotting.py,sha256=zgLjyrbUV898-Y2hjwVMydFKdLvY73qS2WOGI9yp61k,3685
4
+ saconfidence-0.0.1.dist-info/METADATA,sha256=jOebuQaV4hM3_ni2Pxn1YFzrvREBUXny-W4g0bsYzrw,8364
5
+ saconfidence-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ saconfidence-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any