Files
models/tests/tea/test_spikes_counts.py

143 lines
8.7 KiB
Python

"""What this module covers: the count reference of spike candidates (`_baseline.CountRate` of both spikes modules)
and how `Spikes` / `LegacySpikes` use it: the aggregate rate and its dispersion, a child's z from the tail of its
own count in its own minutes, NaN without exposure, the per-electrode zone scale, and which features it serves.
Fixtures: `count_rate`, parametrized over the modern and legacy `CountRate` classes; `reference`, 200 invented
children of 16 to 36 months with 5 to 15 clean NREM minutes and Poisson candidates at 0.02 per minute (most have
none), as rates.
"""
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from tea.biomarkers.spikes import _baseline as modern_baseline
from tea.biomarkers.spikes import api as modern
from tea.legacy.biomarkers.spikes import _baseline as legacy_baseline
from tea.legacy.biomarkers.spikes import api as legacy
@pytest.fixture(params=["modern", "legacy"])
def count_rate(request):
"""The implementation's `CountRate` class."""
return {"modern": modern_baseline, "legacy": legacy_baseline}[request.param].CountRate
@pytest.fixture
def reference():
"""(rates, ages, minutes) of 200 children with Poisson candidates at 0.02 per minute."""
rng = np.random.default_rng(3)
minutes = rng.uniform(5, 15, 200).round(2)
counts = rng.poisson(0.02 * minutes)
return counts / minutes, rng.uniform(16, 36, 200), minutes
def test_the_reference_is_the_aggregate_rate_with_its_dispersion(count_rate):
"""Pins down: the rate is all candidates over all minutes of the children within the ages (one child of 50
months left out) and the dispersion is the research code's moments estimate, Poisson (inf) without excess.
Fails if the rate becomes a mean of per-child rates, the age range stops filtering, or the moments change."""
rates = np.array([0, 0.1, 0.2, 0])
b = count_rate().fit(rates, np.array([20, 20, 30, 50.0]), exposure=np.array([10, 10, 20, 30.0]))
assert b.state["rate"] == pytest.approx(5 / 40) and b.state["reference"] == 3 and b.state["events"] == 5
n, mu = np.array([0, 1, 4]), 5 / 40 * np.array([10, 10, 20])
excess = ((n - mu) ** 2 - n).sum()
assert b.state["k"] == (pytest.approx((mu ** 2).sum() / excess) if excess > 0 else np.inf)
flat = count_rate().fit(np.array([0.1, 0.1]), np.array([20, 20.0]), exposure=np.array([10, 10.0]))
assert flat.state["k"] == np.inf
def test_a_count_is_judged_in_its_own_minutes(count_rate, reference):
"""Pins down: no candidates is a mildly negative z (never -inf), the same one candidate is rarer in fewer
minutes, many candidates in few minutes are outside +1 with a large z, and z is the normal quantile of the mid-p
tail. Fails if z stops using the child's minutes, the mid-p correction, or the 0.05 cut for `outside`."""
b = count_rate().fit(*reference[:2], exposure=reference[2])
outside, z = b.deviation(np.array([0.0, 1 / 5, 1 / 40, 8 / 5]), np.full(4, 24.0),
exposure=np.array([10.0, 5.0, 40.0, 5.0]))
assert -1 < z[0] < 0
assert z[1] > z[2]
assert outside.tolist() == [0.0, 0.0, 0.0, 1.0] and z[3] > 3
mu = b.state["rate"] * 5.0
tail = stats.poisson.sf(0, mu) if np.isinf(b.state["k"]) else stats.nbinom.sf(0, b.state["k"],
b.state["k"] / (b.state["k"] + mu))
at = (stats.poisson.pmf(1, mu) if np.isinf(b.state["k"])
else stats.nbinom.pmf(1, b.state["k"], b.state["k"] / (b.state["k"] + mu)))
assert z[1] == pytest.approx(stats.norm.ppf(1 - (tail - at / 2)))
def test_no_exposure_value_age_or_reference_is_nan(count_rate, reference):
"""Pins down: without minutes, with zero minutes, without a value, at an age outside the range, or against a
reference with no minutes, z and outside are NaN, and a reference with no candidates at all clips z instead of
reaching infinity. Fails if any of them reads as within the reference, or `inf` leaves the baseline."""
b = count_rate().fit(*reference[:2], exposure=reference[2])
outside, z = b.deviation(np.array([0.1, 0.1, np.nan, 0.1]), np.array([24, 24, 24, 60.0]),
exposure=np.array([np.nan, 0.0, 10.0, 10.0]))
assert np.isnan(z).all() and np.isnan(outside).all()
assert np.isnan(b.deviation(np.array([0.1]), np.array([24.0]))[1]).all()
empty = count_rate().fit(np.array([0.1]), np.array([24.0]), exposure=np.array([np.nan]))
assert np.isnan(empty.deviation(np.array([0.1]), np.array([24.0]), exposure=np.array([10.0]))[1]).all()
none = count_rate().fit(np.zeros(5), np.full(5, 24.0), exposure=np.full(5, 10.0))
assert none.deviation(np.array([0.5]), np.array([24.0]), exposure=np.array([10.0]))[1][0] == count_rate.Z_MAX
def test_the_reference_range_is_the_rates_expected_in_the_childs_minutes(count_rate, reference):
"""Pins down: the p5, median and p95 of a count reference are the reference count's quantiles in the child's own
minutes (times the zone scale) as rates, ordered, narrower in rate with more minutes, and NaN where z is NaN.
Fails if the range stops using the child's minutes or the scale, or a child without minutes gets one (the
patient summary shows it as the metric's reference)."""
b = count_rate(scale=2.0).fit(*reference[:2], exposure=reference[2])
out = b.percentiles(np.array([24.0, 24.0, 24.0, 60.0]), np.array([5.0, 400.0, np.nan, 10.0]))
mu, k = b.state["rate"] * 400.0 * 2.0, b.state["k"]
p95 = stats.poisson.ppf(0.95, mu) if np.isinf(k) else stats.nbinom.ppf(0.95, k, k / (k + mu))
assert out[1, 2] == pytest.approx(p95 / 800.0)
assert (np.diff(out[:2], axis=1) >= 0).all()
assert out[1, 2] - out[1, 0] < out[0, 2] - out[0, 0] or out[0, 2] == 0
assert np.isnan(out[2:]).all()
def test_round_trip_and_scale(count_rate, reference):
"""Pins down: `to_dict` / `from_dict` keep the state and the scale, and a per-electrode zone value is counted
back through its electrodes (0.1 per minute per electrode over 3 electrodes in 10 minutes is 3 candidates).
Fails if the scale is lost on save or not applied."""
b = count_rate(scale=3.0).fit(*reference[:2], exposure=reference[2])
again = count_rate.from_dict(b.to_dict())
args = (np.array([0.1]), np.array([24.0]))
assert again.deviation(*args, exposure=np.array([10.0]))[1] == pytest.approx(
b.deviation(*args, exposure=np.array([10.0]))[1])
assert again.scale == 3.0
counts, exposure = b._counts(np.array([0.1]), np.array([10.0]))
assert counts.tolist() == [3.0] and exposure.tolist() == [30.0]
@pytest.mark.parametrize("module", [modern, legacy], ids=["modern", "legacy"])
def test_the_rates_are_counted_against_their_minutes(module, reference):
"""Pins down: every rate and density feature (overall, per electrode, per zone, unnormalised zone, inherited)
has a count baseline whose exposure is the minutes of its own state and variant, the minutes themselves have no
baseline, and the other spike features keep the configured one; a table without the minutes gives NaN for the
counted features. Fails if a rate falls back to centile curves (collapsed at 0 in the reference) or reads
another state's minutes."""
spikes = (module.Spikes if module is modern else module.LegacySpikes)()
assert set(module.EXPOSURE) == {f for f in module.FEATURES if f.startswith(
("spike_rate_", "spike_density_", "spike_zone_", "spike_inherited_rate_", "spike_inherited_zone_"))}
assert all(module.EXPOSURE[f].endswith(("_nrem" if "nrem" in f else "_awake")) for f in module.EXPOSURE)
assert not set(module.MINUTES) & set(module.FEATURES)
assert {spikes.baselines[f].name for f in module.EXPOSURE} == {"count_rate"}
assert spikes.baselines["spike_laterality"].name == "curves"
rates, ages, minutes = reference
table = pd.DataFrame({"spike_rate_nrem": rates, "spike_minutes_nrem": minutes, "age_months": ages})
spikes.train(table)
out = spikes.predict(table.iloc[:3]).set_index("feature")
assert out.loc["spike_rate_nrem", "z"].notna().all()
blind = spikes.predict(table.iloc[:3].drop(columns="spike_minutes_nrem")).set_index("feature")
assert blind.loc["spike_rate_nrem", "z"].isna().all()
def test_legacy_and_modern_count_alike(reference):
"""Pins down: both implementations' count baselines give the same reference and the same z. Fails if one copy
of `CountRate` drifts from the other."""
rates, ages, minutes = reference
a = modern_baseline.CountRate().fit(rates, ages, exposure=minutes)
b = legacy_baseline.CountRate().fit(rates, ages, exposure=minutes)
assert a.state == b.state
np.testing.assert_array_equal(a.deviation(rates, ages, exposure=minutes)[1],
b.deviation(rates, ages, exposure=minutes)[1])