saconfidence 0.0.1__tar.gz

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,30 @@
1
+ name: Test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ['3.10', '3.14']
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: astral-sh/setup-uv@v7
18
+ with:
19
+ activate-environment: true
20
+ python-version: ${{ matrix.python-version }}
21
+ - run: uv pip install -e ".[dev,doc]"
22
+ - run: pytest
23
+ - if: matrix.python-version == '3.14'
24
+ run: mkdocs build --strict
25
+
26
+ pre-commit:
27
+ runs-on: ubuntu-latest
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - uses: pre-commit/action@v3.0.1
@@ -0,0 +1,20 @@
1
+ name: Docs
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+
7
+ permissions:
8
+ contents: write
9
+
10
+ jobs:
11
+ deploy:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: astral-sh/setup-uv@v7
16
+ with:
17
+ activate-environment: true
18
+ python-version: '3.14'
19
+ - run: uv pip install -e ".[doc]"
20
+ - run: mkdocs gh-deploy --force
@@ -0,0 +1,19 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ pypi:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write # lets PyPI trust this workflow, so no token is stored
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ with:
16
+ fetch-depth: 0 # the version comes from the release tag
17
+ - uses: astral-sh/setup-uv@v7
18
+ - run: uv build
19
+ - run: uv publish
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ .ruff_cache/
9
+ site/
10
+ .coverage
@@ -0,0 +1,2 @@
1
+ # Line length is left to the writer.
2
+ MD013: false
@@ -0,0 +1,23 @@
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v6.0.0
4
+ hooks:
5
+ - id: check-merge-conflict
6
+ - id: debug-statements
7
+ - id: trailing-whitespace
8
+ - id: end-of-file-fixer
9
+ - repo: https://github.com/astral-sh/ruff-pre-commit
10
+ rev: v0.17.2
11
+ hooks:
12
+ - id: ruff-check
13
+ args: [--fix, --exit-non-zero-on-fix]
14
+ - id: ruff-format
15
+ - repo: https://github.com/igorshubovych/markdownlint-cli
16
+ rev: v0.50.0
17
+ hooks:
18
+ - id: markdownlint-fix
19
+ - repo: https://github.com/codespell-project/codespell
20
+ rev: v2.4.3
21
+ hooks:
22
+ - id: codespell
23
+ args: [--ignore-words-list, whis] # a matplotlib argument
@@ -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,166 @@
1
+ # SAconfidence
2
+
3
+ _Don't be the person who doesn't check their error bars..._
4
+
5
+ How many model runs does your model need to get converged Sobol sensitivity
6
+ indices? SAconfidence estimates that from a small pilot, using
7
+ [SALib](https://salib.readthedocs.io).
8
+
9
+ A Sobol index is the share of the variation in a model output that is due to a
10
+ parameter: on its own (first order, `S1`), with all its interactions (total
11
+ order, `ST`), or through its interaction with one other parameter (second
12
+ order, `S2`).
13
+
14
+ SALib estimates the indices from a sample of model runs, so each has a 95%
15
+ confidence interval, such as 0.56 ± 0.08. The number after the ± is the
16
+ half-width: the true value is probably within that distance of the estimate.
17
+ The indices are converged when every half-width is below a target you choose.
18
+
19
+ ![One index and its confidence interval at four sample sizes](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/half_width.png)
20
+
21
+ The sample is built from `n` base samples. Each costs `D + 2` model runs for `D`
22
+ parameters, or `2D + 2` if you want second-order indices. The half-width falls
23
+ in proportion to `1 / sqrt(n)`, so four times the runs halve it, as in the
24
+ figure.
25
+
26
+ That rule is why a tiny pilot is enough. A pilot of 16 base samples measures
27
+ every half-width, and the rule gives the `n` at which the widest one reaches
28
+ the target.
29
+
30
+ This is a draft. Install it with `pip install saconfidence`. The functions are
31
+ described in the [documentation](https://barneydobson.github.io/SAconfidence).
32
+
33
+ ## Use
34
+
35
+ ```python
36
+ import saconfidence as sac
37
+
38
+ problem = {"num_vars": 3, "names": ["x1", "x2", "x3"], "bounds": [[0, 1]] * 3}
39
+
40
+ X = sac.sample(problem, 16) # SALib's Sobol sample, 16 base samples
41
+ Y = my_model(X) # one output for each row
42
+ result = sac.estimate(problem, Y, target=0.05)
43
+
44
+ print(result)
45
+ result.plot()
46
+ ```
47
+
48
+ `problem` is a SALib problem. `target` is the half-width the 95% confidence
49
+ intervals should reach.
50
+
51
+ ## Output
52
+
53
+ `python examples/sobol_g.py` takes a pilot of 16 base samples of the Sobol G
54
+ function with eight parameters. It prints:
55
+
56
+ ```text
57
+ Pilot of 16 base samples, 288 model runs. Target half-width 0.05.
58
+
59
+ Widest interval of each order, and the base samples n it needs:
60
+ label halfwidth slope n n_lo n_hi
61
+ order
62
+ ST x1 0.625 -0.449 2,497 452 13,808
63
+ S1 x1 0.555 -0.568 1,970 354 10,973
64
+ S2 x1 × x2 1.154 -0.773 8,527 1,744 41,698
65
+
66
+ Model runs needed, as the least influential parameters are left out:
67
+ parameters dropped dropped_ST design n n_lo n_hi n_pow2 runs
68
+ 8 0.000 first and total order 2,497 452 13,808 4,096 40,960
69
+ 8 0.000 with second order 8,527 1,744 41,698 16,384 294,912
70
+ 7 x8 0.000 first and total order 2,497 452 13,808 4,096 36,864
71
+ 7 x8 0.000 with second order 8,527 1,744 41,698 16,384 262,144
72
+ 6 x7 0.000 first and total order 2,497 452 13,808 4,096 32,768
73
+ 6 x7 0.000 with second order 8,527 1,744 41,698 16,384 229,376
74
+ 5 x6 0.000 first and total order 2,497 452 13,808 4,096 28,672
75
+ 5 x6 0.000 with second order 8,527 1,744 41,698 16,384 196,608
76
+ 4 x5 0.000 first and total order 2,497 452 13,808 4,096 24,576
77
+ 4 x5 0.000 with second order 8,527 1,744 41,698 16,384 163,840
78
+ 3 x4 0.012 first and total order 2,497 452 13,808 4,096 20,480
79
+ 3 x4 0.012 with second order 8,527 1,744 41,698 16,384 131,072
80
+ 2 x3 0.042 first and total order 2,497 452 13,808 4,096 16,384
81
+ 2 x3 0.042 with second order 8,527 1,744 41,698 16,384 98,304
82
+ ```
83
+
84
+ The first table has a row for each order. `label` is the index with the widest
85
+ interval, `halfwidth` is its half-width in the pilot, and `n` is the base
86
+ samples that would bring it down to the target, somewhere between `n_lo` and
87
+ `n_hi`. That range comes from analysing the pilot eight more times, each with a
88
+ different eighth of it left out. `slope` checks the rule: it is measured inside
89
+ the pilot and should be near -0.5, though a small pilot measures it roughly.
90
+
91
+ The second table is the cost. Sobol samples should be a power of two, so
92
+ `n_pow2` is `n` rounded up to one, and `runs` is the model runs that takes. The
93
+ later rows show what leaving parameters out would save, least influential
94
+ first. That assumes the other indices do not change, which holds while
95
+ `dropped_ST`, the sum of the total-order indices left out, is small.
96
+
97
+ It draws:
98
+
99
+ ![Figure for the Sobol G function](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/sobol_g.png)
100
+
101
+ Each of the first three panels follows the widest interval of one order. The
102
+ boxes are its half-width inside the pilot: in the two halves (8 base samples)
103
+ and in the whole pilot (16), where the whiskers show how uncertain it is. The
104
+ points are the rule's prediction beyond the pilot, with the same uncertainty as
105
+ error bars. The horizontal line is the target. The last panel shows the same
106
+ prediction against model runs when fewer parameters are kept.
107
+
108
+ ### Disappointed?
109
+
110
+ Global sensitivity analysis is expensive. However, just because a half-width
111
+ is not below 5%, it doesn't mean you can't say with confidence that something is
112
+ sensitive. `x1` [above](#saconfidence) is still greater than 0 even with the a
113
+ large half-width: _no more runs needed!_
114
+
115
+ ## How well it works
116
+
117
+ `python examples/sobol_g_measured.py` draws the first three panels again and
118
+ adds, as crosses, the widest half-width that SALib measures as the sample grows
119
+ to 4,096 base samples:
120
+
121
+ ![The same panels with the measured half-widths](https://raw.githubusercontent.com/barneydobson/SAconfidence/main/docs/sobol_g_measured.png)
122
+
123
+ The crosses follow the prediction and stay inside the error bars.
124
+
125
+ A larger pilot gives the same answer with narrower error bars. From 16 base
126
+ samples the total order needs 2,497, somewhere between 452 and 13,808. From 256
127
+ it needs 2,868, somewhere between 1,398 and 5,880.
128
+
129
+ `examples/check_scaling.py` compares the prediction with the half-width
130
+ measured at 4,096 base samples, over 20 seeds of the Ishigami and Sobol G
131
+ functions.
132
+
133
+ | Pilot, base samples | Predicted over measured half-width, 5% to 95% |
134
+ | --- | --- |
135
+ | 8 | 0.36 to 2.12 |
136
+ | 16 | 0.41 to 1.86 |
137
+ | 64 | 0.68 to 1.37 |
138
+ | 256 | 0.73 to 1.28 |
139
+
140
+ The sample size goes with the square of the ratio, so a pilot of 16 gives it
141
+ within about 0.2 to 3.5 times, and a pilot of 256 within about 0.5 to 1.6
142
+ times.
143
+
144
+ ## Limits
145
+
146
+ - It predicts the confidence intervals that SALib reports, which SALib gets by
147
+ resampling the model runs (a bootstrap).
148
+ - The error bars should hold the measured value 95% of the time. For the
149
+ Ishigami function, whose output has heavy tails, they did so in 90% of seeds
150
+ at some pilot sizes.
151
+ - A pilot needs at least 8 base samples. With 8 or 16, the total-order
152
+ half-width of the Ishigami function was predicted too small: by a third with
153
+ 8 and a fifth with 16.
154
+ - It takes one output at a time. For several, use the largest sample size.
155
+ - Leaving parameters out has only been tested where they matter little. There,
156
+ `examples/check_fewer_parameters.py` gives a predicted over measured
157
+ half-width of 0.84 to 1.19, from a pilot of 256.
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ pip install -e ".[dev,doc]"
163
+ pre-commit install
164
+ pytest
165
+ mkdocs serve
166
+ ```
@@ -0,0 +1,13 @@
1
+ # API
2
+
3
+ ::: saconfidence.sample
4
+
5
+ ::: saconfidence.estimate
6
+
7
+ ::: saconfidence.Result
8
+
9
+ ## Plotting
10
+
11
+ ::: saconfidence.plotting.scaling
12
+
13
+ ::: saconfidence.plotting.parameters
Binary file
@@ -0,0 +1,2 @@
1
+ <!-- markdownlint-disable-next-line MD041 -->
2
+ {% include-markdown "../README.md" %}
Binary file
@@ -0,0 +1,38 @@
1
+ """Does the projection to fewer parameters match a run with those parameters held fixed?
2
+
3
+ A pilot of the Sobol G function with eight parameters is projected to six, four,
4
+ three and two parameters. Each projection is compared with the half-width
5
+ measured at 4,096 base samples with the other parameters fixed at 0.5.
6
+ Run from the repository root: python examples/check_fewer_parameters.py
7
+ """
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from SALib.analyze import sobol
12
+ from SALib.test_functions import Sobol_G
13
+
14
+ import saconfidence as sac
15
+
16
+ PILOT, LARGE, SEEDS = 256, 4096, 20
17
+ names = [f"x{i + 1}" for i in range(8)]
18
+ problem = {"num_vars": 8, "names": names, "bounds": [[0, 1]] * 8}
19
+
20
+ rows = []
21
+ for seed in range(SEEDS):
22
+ pilot = sac.estimate(problem, Sobol_G.evaluate(sac.sample(problem, PILOT, seed=seed)), seed=seed)
23
+ for kept in (6, 4, 3, 2):
24
+ projected = pilot.widest(keep=names[:kept])
25
+ small = {"num_vars": kept, "names": names[:kept], "bounds": [[0, 1]] * kept}
26
+ X = sac.sample(small, LARGE, seed=seed + 100)
27
+ Y = Sobol_G.evaluate(np.column_stack([X, np.full((len(X), 8 - kept), 0.5)]))
28
+ s = sobol.analyze(small, Y, num_resamples=500, seed=seed + 7)
29
+ measured = {"S1": s["S1_conf"].max(), "ST": s["ST_conf"].max(), "S2": np.nanmax(s["S2_conf"])}
30
+ for order, h in measured.items():
31
+ c = h * LARGE**0.5
32
+ inside = projected.loc[order, "c_lo"] <= c <= projected.loc[order, "c_hi"]
33
+ rows.append({"kept": kept, "order": order, "ratio": projected.loc[order, "c"] / c, "inside": inside})
34
+ table = pd.DataFrame(rows).groupby(["kept", "order"])
35
+ out = table["ratio"].quantile([0.05, 0.5, 0.95]).unstack().set_axis(["5%", "median", "95%"], axis=1)
36
+ out["inside range"] = table["inside"].mean()
37
+ print("Projected over measured half-width of the widest interval")
38
+ print(out.round(2).to_string())
@@ -0,0 +1,40 @@
1
+ """Does a small pilot predict the interval widths that SALib reports at 4,096 base samples?
2
+
3
+ For 20 seeds and two test functions, the half-width constant from a pilot is
4
+ compared with the one measured at 4,096. Takes about a minute.
5
+ Run from the repository root: python examples/check_scaling.py [pilot size]
6
+ """
7
+
8
+ import sys
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from SALib.analyze import sobol
13
+ from SALib.test_functions import Ishigami, Sobol_G
14
+
15
+ import saconfidence as sac
16
+
17
+ PILOT = int(sys.argv[1]) if len(sys.argv) > 1 else 256
18
+ LARGE, SEEDS = 4096, 20
19
+ CASES = {
20
+ "Ishigami": ({"num_vars": 3, "names": ["x1", "x2", "x3"], "bounds": [[-np.pi, np.pi]] * 3}, Ishigami.evaluate),
21
+ "Sobol G": ({"num_vars": 8, "names": [f"x{i + 1}" for i in range(8)], "bounds": [[0, 1]] * 8}, Sobol_G.evaluate),
22
+ }
23
+
24
+ rows = []
25
+ for case, (problem, model) in CASES.items():
26
+ per = 2 * problem["num_vars"] + 2
27
+ for seed in range(SEEDS):
28
+ Y = model(sac.sample(problem, LARGE, seed=seed))
29
+ pilot = sac.estimate(problem, Y[: PILOT * per], seed=seed).widest()
30
+ s = sobol.analyze(problem, Y, num_resamples=1000, seed=seed + 7)
31
+ measured = {"S1": s["S1_conf"].max(), "ST": s["ST_conf"].max(), "S2": np.nanmax(s["S2_conf"])}
32
+ for order, h in measured.items():
33
+ c = h * LARGE**0.5
34
+ inside = pilot.loc[order, "c_lo"] <= c <= pilot.loc[order, "c_hi"]
35
+ rows.append({"function": case, "order": order, "ratio": pilot.loc[order, "c"] / c, "inside": inside})
36
+ table = pd.DataFrame(rows).groupby(["function", "order"], sort=False)
37
+ out = table["ratio"].quantile([0.05, 0.5, 0.95]).unstack().set_axis(["5%", "median", "95%"], axis=1)
38
+ out["inside range"] = table["inside"].mean()
39
+ print(f"Predicted over measured half-width of the widest interval, pilot of {PILOT} base samples")
40
+ print(out.round(2).to_string())
@@ -0,0 +1,40 @@
1
+ """What a half-width is, and how it shrinks as the sample grows.
2
+
3
+ One Sobol index of the Ishigami function with its 95% confidence interval, at
4
+ four sample sizes. Run from the repository root: python examples/half_width.py
5
+ """
6
+
7
+ import matplotlib
8
+
9
+ matplotlib.use("Agg")
10
+
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ from SALib.analyze import sobol
14
+ from SALib.test_functions import Ishigami
15
+
16
+ import saconfidence as sac
17
+
18
+ problem = {"num_vars": 3, "names": ["x1", "x2", "x3"], "bounds": [[-np.pi, np.pi]] * 3}
19
+ Y = Ishigami.evaluate(sac.sample(problem, 4096, seed=1))
20
+
21
+ sizes = [64, 256, 1024, 4096]
22
+ results = [sobol.analyze(problem, Y[: n * 8], num_resamples=1000, seed=1) for n in sizes]
23
+ value = np.array([s["ST"][0] for s in results])
24
+ half = np.array([s["ST_conf"][0] for s in results])
25
+
26
+ fig, ax = plt.subplots(figsize=(6, 3.4), layout="constrained")
27
+ ax.axhline(0.558, color="k", lw=0.8, ls="--", label="True value")
28
+ ax.errorbar(sizes, value, yerr=half, fmt="o", capsize=4, label="Estimate and 95% confidence interval")
29
+ ax.annotate("", (80, value[0]), (80, value[0] + half[0]), arrowprops={"arrowstyle": "<->"})
30
+ ax.text(88, value[0] + half[0] / 2, f"half-width\n{half[0]:.2f}", va="center")
31
+ for n, v, h in zip(sizes[1:], value[1:], half[1:]):
32
+ ax.text(n * 1.12, v + h / 2, f"{h:.2f}", va="center")
33
+ ax.set_xscale("log", base=2)
34
+ ax.set_xticks(sizes, [f"{n:,}" for n in sizes])
35
+ ax.set(xlabel="Base samples", ylabel="Total-order index of x1", xlim=(45, 7000))
36
+ ax.grid(True)
37
+ ax.set_axisbelow(True)
38
+ ax.legend(loc="lower right")
39
+ fig.savefig("docs/half_width.png", dpi=150)
40
+ print(dict(zip(sizes, zip(value.round(2), half.round(2)))))
@@ -0,0 +1,21 @@
1
+ """Sobol G function with eight parameters, four of which hardly matter.
2
+
3
+ Run from the repository root: python examples/sobol_g.py
4
+ """
5
+
6
+ import matplotlib
7
+
8
+ matplotlib.use("Agg")
9
+
10
+ import matplotlib.pyplot as plt
11
+ from SALib.test_functions import Sobol_G
12
+
13
+ import saconfidence as sac
14
+
15
+ problem = {"num_vars": 8, "names": [f"x{i + 1}" for i in range(8)], "bounds": [[0, 1]] * 8}
16
+
17
+ X = sac.sample(problem, 16, seed=1) # 16 * (2 * 8 + 2) = 288 model runs
18
+ result = sac.estimate(problem, Sobol_G.evaluate(X), seed=1)
19
+ print(result)
20
+ result.plot()
21
+ plt.savefig("docs/sobol_g.png", dpi=150)
@@ -0,0 +1,32 @@
1
+ """The pilot of sobol_g.py, against what SALib measures at larger samples.
2
+
3
+ The crosses are the widest half-width SALib reports as the sample grows from
4
+ the 16 base samples of the pilot to 4,096.
5
+ Run from the repository root: python examples/sobol_g_measured.py
6
+ """
7
+
8
+ import matplotlib
9
+
10
+ matplotlib.use("Agg")
11
+
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ from SALib.analyze import sobol
15
+ from SALib.test_functions import Sobol_G
16
+
17
+ import saconfidence as sac
18
+ from saconfidence.plotting import scaling
19
+
20
+ problem = {"num_vars": 8, "names": [f"x{i + 1}" for i in range(8)], "bounds": [[0, 1]] * 8}
21
+
22
+ Y = Sobol_G.evaluate(sac.sample(problem, 4096, seed=1))
23
+ result = sac.estimate(problem, Y[: 16 * 18], seed=1) # the pilot: the first 16 base samples
24
+
25
+ sizes = 2 ** np.arange(5, 13)
26
+ measured = [sobol.analyze(problem, Y[: n * 18], seed=1) for n in sizes]
27
+ _, ax = plt.subplots(1, 3, figsize=(12, 3.6), layout="constrained")
28
+ for a, order in zip(ax, ("ST", "S1", "S2")):
29
+ scaling(result, order, a)
30
+ a.plot(sizes, [np.nanmax(s[order + "_conf"]) for s in measured], "kx", label="Measured")
31
+ a.legend(loc="upper right")
32
+ plt.savefig("docs/sobol_g_measured.png", dpi=150)
@@ -0,0 +1,25 @@
1
+ site_name: SAconfidence
2
+ repo_url: https://github.com/barneydobson/SAconfidence
3
+
4
+ theme:
5
+ name: material
6
+
7
+ markdown_extensions:
8
+ - pymdownx.highlight
9
+ - pymdownx.superfences
10
+
11
+ plugins:
12
+ - search
13
+ - include-markdown
14
+ - mkdocstrings:
15
+ handlers:
16
+ python:
17
+ options:
18
+ docstring_style: numpy
19
+ show_root_heading: true
20
+ show_source: false
21
+ members_order: source
22
+
23
+ nav:
24
+ - Home: index.md
25
+ - API: api.md
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "saconfidence"
7
+ dynamic = ["version"]
8
+ description = "How many model runs do Sobol sensitivity indices need? Estimated from a small pilot sample with SALib."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["SALib>=1.5", "numpy", "scipy", "pandas", "matplotlib>=3.6"]
12
+
13
+ [project.optional-dependencies]
14
+ dev = ["pytest", "pytest-cov", "pre-commit", "ruff"]
15
+ doc = ["mkdocs-material", "mkdocstrings[python]", "mkdocs-include-markdown-plugin"]
16
+
17
+ [project.urls]
18
+ Documentation = "https://barneydobson.github.io/SAconfidence"
19
+ Repository = "https://github.com/barneydobson/SAconfidence"
20
+
21
+ [tool.hatch.version]
22
+ source = "vcs" # the version is the git tag of the release
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/saconfidence"]
26
+
27
+ [tool.pytest.ini_options]
28
+ testpaths = ["tests"]
29
+ addopts = "--cov=saconfidence --cov-report=term-missing"
30
+
31
+ [tool.ruff]
32
+ line-length = 120
33
+
34
+ [tool.ruff.lint]
35
+ select = ["D", "E", "F", "I", "UP"]
36
+ pydocstyle.convention = "numpy"
37
+
38
+ [tool.ruff.lint.per-file-ignores]
39
+ "tests/*" = ["D"]
40
+ "examples/*" = ["D"]
@@ -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")
@@ -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,130 @@
1
+ """Tests on SALib's analytic test functions. They take a few seconds."""
2
+
3
+ import dataclasses
4
+
5
+ import matplotlib
6
+
7
+ matplotlib.use("Agg")
8
+
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pytest
12
+ from SALib.analyze import sobol
13
+ from SALib.test_functions import Ishigami, Sobol_G
14
+
15
+ import saconfidence as sac
16
+ from saconfidence.plotting import parameters, scaling
17
+
18
+ ISHIGAMI = {"num_vars": 3, "names": ["x1", "x2", "x3"], "bounds": [[-np.pi, np.pi]] * 3}
19
+ G = {"num_vars": 8, "names": [f"x{i + 1}" for i in range(8)], "bounds": [[0, 1]] * 8}
20
+
21
+
22
+ @pytest.fixture(scope="module")
23
+ def ishigami():
24
+ return sac.estimate(ISHIGAMI, Ishigami.evaluate(sac.sample(ISHIGAMI, 256, seed=1)), seed=1)
25
+
26
+
27
+ @pytest.fixture(scope="module")
28
+ def g():
29
+ return sac.estimate(G, Sobol_G.evaluate(sac.sample(G, 128, seed=1)), num_resamples=100, seed=1)
30
+
31
+
32
+ def test_sample_is_nested():
33
+ """The block analysis, and reuse of the pilot runs, rely on this."""
34
+ small, large = sac.sample(ISHIGAMI, 64, seed=3), sac.sample(ISHIGAMI, 256, seed=3)
35
+ assert np.array_equal(small, large[: len(small)])
36
+
37
+
38
+ def test_same_seed_same_result():
39
+ """SALib ignores a seed of 0, so the default seed must not reach it as 0."""
40
+ Y = Ishigami.evaluate(sac.sample(ISHIGAMI, 64))
41
+ assert np.array_equal(sac.sample(ISHIGAMI, 64), sac.sample(ISHIGAMI, 64))
42
+ assert sac.estimate(ISHIGAMI, Y).indices.equals(sac.estimate(ISHIGAMI, Y).indices)
43
+
44
+
45
+ def test_tables(ishigami):
46
+ assert ishigami.n == 256 and set(ishigami.tested["size"]) == {256, 128, 64, 32}
47
+ assert len(ishigami.tested) == 9 * (1 + 2 + 4 + 8)
48
+ ind = ishigami.indices
49
+ assert list(ind["order"].value_counts()[["ST", "S1", "S2"]]) == [3, 3, 3]
50
+ assert (ind["c_lo"] < ind["c"]).all() and (ind["c"] < ind["c_hi"]).all()
51
+ assert np.allclose(ind["c"], ind["halfwidth"] * 16)
52
+
53
+
54
+ def test_prediction_against_a_larger_sample(ishigami):
55
+ """A 256-sample pilot predicts the half-widths that SALib reports at 4,096."""
56
+ big = sac.sample(ISHIGAMI, 4096, seed=1)
57
+ s = sobol.analyze(ISHIGAMI, Ishigami.evaluate(big), num_resamples=500, seed=2)
58
+ measured = {"S1": s["S1_conf"].max(), "ST": s["ST_conf"].max(), "S2": np.nanmax(s["S2_conf"])}
59
+ widest = ishigami.widest()
60
+ for order, h in measured.items():
61
+ predicted = widest.loc[order, "c"] / 4096**0.5
62
+ assert 0.6 < predicted / h < 1.6, (order, predicted, h)
63
+
64
+
65
+ def test_target_and_runs(ishigami):
66
+ half = dataclasses.replace(ishigami, target=ishigami.target / 2)
67
+ assert np.allclose(half.widest()["n"], 4 * ishigami.widest()["n"])
68
+ runs = ishigami.runs().iloc[:2]
69
+ assert list(runs["design"]) == ["first and total order", "with second order"]
70
+ assert list(runs["runs"] / runs["n_pow2"]) == [5, 8]
71
+ assert (runs["n_pow2"] >= runs["n"]).all() and (runs["n_pow2"] < 2 * runs["n"]).all()
72
+
73
+
74
+ def test_fewer_parameters(g):
75
+ runs = g.runs()
76
+ second = runs[runs["design"] == "with second order"]
77
+ assert list(second["parameters"]) == [8, 7, 6, 5, 4, 3, 2]
78
+ assert second["runs"].is_monotonic_decreasing
79
+ # The G function's last four parameters have almost no effect, so they go first.
80
+ assert set(second["dropped"].iloc[1:5]) == {"x5", "x6", "x7", "x8"}
81
+ assert second["dropped_ST"].iloc[4] < 0.05
82
+ assert list(g.runs(drop=["x1"])["parameters"].unique()) == [8, 7]
83
+ assert "x1" not in " ".join(g.widest(keep=G["names"][1:])["label"])
84
+
85
+
86
+ def test_first_and_total_order_only():
87
+ Y = Ishigami.evaluate(sac.sample(ISHIGAMI, 128, calc_second_order=False, seed=1))
88
+ r = sac.estimate(ISHIGAMI, Y, calc_second_order=False, num_resamples=100, seed=1)
89
+ assert set(r.indices["order"]) == {"S1", "ST"}
90
+ assert list(r.runs()["parameters"]) == [3, 2, 1] and set(r.runs()["design"]) == {"first and total order"}
91
+ assert len(r.plot()) == 3
92
+
93
+
94
+ def test_groups():
95
+ problem = {**ISHIGAMI, "groups": ["a", "a", "b"]}
96
+ r = sac.estimate(problem, Ishigami.evaluate(sac.sample(problem, 64, seed=1)), num_resamples=100, seed=1)
97
+ assert r.names == ["a", "b"] and list(r.indices["label"]) == ["a", "b", "a", "b", "a × b"]
98
+
99
+
100
+ def test_bad_input():
101
+ rng = np.random.default_rng(0)
102
+ nan = rng.random(64 * 8)
103
+ nan[3] = np.nan
104
+ for Y in (np.zeros(100), rng.random(4 * 8), nan):
105
+ with pytest.raises(ValueError, match="at least 8 base samples of 8 runs"):
106
+ sac.estimate(ISHIGAMI, Y)
107
+
108
+
109
+ def test_small_pilots():
110
+ """A pilot of 16 is cut into two blocks of 8. A pilot of 8 is not cut, so it has no slope."""
111
+ Y = Ishigami.evaluate(sac.sample(ISHIGAMI, seed=1))
112
+ assert list(sac.estimate(ISHIGAMI, Y, seed=1).tested["size"].value_counts()[[16, 8]]) == [9, 18]
113
+ r = sac.estimate(ISHIGAMI, Y[: 8 * 8], seed=1)
114
+ assert set(r.tested["size"]) == {8} and r.indices["slope"].isna().all()
115
+ w = r.widest()
116
+ assert (0 < w["n_lo"]).all() and (w["n_lo"] < w["n"]).all() and (w["n"] < w["n_hi"]).all()
117
+ assert np.isfinite(w["n_hi"]).all() and len(r.plot()) == 4
118
+
119
+
120
+ def test_print_and_plot(g):
121
+ text = str(g)
122
+ assert text.startswith("Pilot of 128 base samples, 2,304 model runs. Target half-width 0.05.")
123
+ assert "with second order" in text
124
+ assert len(g.plot()) == 4
125
+
126
+
127
+ def test_plot_on_given_axes(g):
128
+ _, ax = plt.subplots(1, 2)
129
+ assert scaling(g, "S2", ax[0]) is ax[0] and len(ax[0].lines) > 1
130
+ assert parameters(g, ax[1], lines=3) is ax[1] and len(ax[1].get_legend().get_texts()) == 3