feat(sobol): the number of classes with draws, for the expectation without an effect

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-13 18:47:03 +01:00
commit 925df404a0
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
2 changed files with 20 additions and 5 deletions

View file

@ -6,7 +6,7 @@ the draws are put in classes by the value of X, and the variance between the
class averages is held against the variance over all the draws.
The estimate is biased upwards: without any effect its expectation is about
(M - 1) / (N - 1) with M classes and N draws (``forventning_uten_virkning``).
(K - 1) / (N - 1) with N draws in K classes (``forventning_uten_virkning``).
Nothing is corrected for it. Total indices cannot be estimated from given
draws without a surrogate model and are not given.
@ -42,10 +42,20 @@ def klasser(x: Sequence[float], M: int) -> list[int]:
return [M * lavere[v] // N for v in x]
def forventning_uten_virkning(N: int, M: int | None = None) -> float:
"""What the estimate is expected to be for a quantity without any effect."""
M = antall_klasser(N) if M is None else M
return (M - 1) / (N - 1)
def klasser_med_trekninger(x: Sequence[float], M: int | None = None) -> int:
"""K, the number of classes that have draws: below M for a quantity with few values."""
return len(set(klasser(x, antall_klasser(len(x)) if M is None else M)))
def forventning_uten_virkning(N: int, K: int | None = None) -> float:
"""What the estimate is expected to be for a quantity without any effect: (K - 1) / (N - 1).
``K`` is the number of classes that have draws (``klasser_med_trekninger``); left out,
it is the number of classes for N draws, which is K for a continuous quantity
(clarification 114 g).
"""
K = antall_klasser(N) if K is None else K
return (K - 1) / (N - 1)
def indeks(x: Sequence[float], y: Sequence[float], *, M: int | None = None) -> float | None:

View file

@ -251,4 +251,9 @@ def test_forventningen_uten_virkning_er_om_lag_M_minus_1_over_N_minus_1() -> Non
indekser = [sobol.indeks(rng.normal(size=N).tolist(), y) for _ in range(300)]
snitt = math.fsum(i for i in indekser if i is not None) / 300
assert sobol.forventning_uten_virkning(N) == 9 / 399
# a quantity with few values has fewer classes with draws, and a lower expectation
x = [0.0] * 100 + [1.0] * 100 + [2.0] * 200
assert sobol.klasser_med_trekninger(x) == 3
assert sobol.klasser_med_trekninger(rng.normal(size=N).tolist()) == 10
assert sobol.forventning_uten_virkning(N, 3) == 2 / 399
assert snitt == pytest.approx(9 / 399, abs=0.002)