Skip to content

Commit f71758d

Browse files
authored
[FIX] ASR: apply online recency weights on the euclid path (weighted geometric median) (#112)
Two coupled fixes to the online covariance weighting in `ASR.transform()`: - **The euclid path discarded its recency weights.** `transform()` builds an exponential recency weight vector and passes it to `asr_process(sample_weight=...)`, but on the default `method="euclid"` path `asr_process` called `geometric_median()` with no weights (and the function had no weight parameter), so the weights were computed and silently dropped — only the riemann branch ever used them. Generalize `geometric_median()` to an optional `sample_weight` using the weighted Vardi-Zhang iteration; with `sample_weight=None` (or all ones) it reduces exactly to the previous unweighted algorithm, so `asr_calibrate` (which calls it unweighted) is numerically unchanged. Pass `sample_weight` through the euclid branch of `asr_process`. - **The recency weight vector used prefix sums instead of suffix sums.** A block's recency is the number of more-recent samples that follow it, i.e. the suffix sum of the per-block sample counts; the previous prefix-sum index mis-weighted interior blocks whenever chunk sizes differed. Add a `_recency_weights` helper that accumulates the suffix sample count newest→oldest. ### Testing Adds regression tests for the weighted median (uniform == unweighted), the euclid wiring, and the suffix-sum weights. Full `tests/test_asr.py` passes; `ruff` clean.
1 parent 8e53091 commit f71758d

3 files changed

Lines changed: 107 additions & 14 deletions

File tree

‎meegkit/asr.py‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -256,10 +256,11 @@ def transform(self, X, y=None, **kwargs):
256256
break
257257

258258
# Exponential covariance weights – the most recent covariance has a
259-
# weight of 1, while the oldest one in memory has a weight of 5%
260-
weights = [1, ]
261-
for c in np.cumsum(self._counter[1:]):
262-
weights = [self.sample_weight[-c]] + weights
259+
# weight of 1, while the oldest one in memory has a weight of ~5%. A
260+
# block's weight is set by the number of MORE-RECENT samples following
261+
# it (a suffix sum of per-block sample counts), so that unequal chunk
262+
# sizes are weighted by their true recency.
263+
weights = _recency_weights(self._counter, self.sample_weight)
263264

264265
# Clean data, using covariances weighted by sample_weight
265266
out, self.state_ = asr_process(X, X_filt, self.state_,
@@ -270,6 +271,23 @@ def transform(self, X, y=None, **kwargs):
270271
return out
271272

272273

274+
def _recency_weights(counter, sample_weight):
275+
"""Exponential recency weights for stored covariance blocks.
276+
277+
A block's weight is set by the number of MORE-RECENT samples that follow
278+
it (the suffix sum of ``counter``), so unequal chunk sizes are weighted by
279+
true recency. The most recent block gets ``sample_weight[-1]`` (== 1);
280+
older blocks decay toward 5%. ``counter`` is ordered oldest->newest.
281+
"""
282+
weights = []
283+
newer = 0
284+
for count in reversed(counter):
285+
idx = min(newer, len(sample_weight) - 1)
286+
weights.insert(0, sample_weight[-(idx + 1)])
287+
newer += count
288+
return weights
289+
290+
273291
def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
274292
win_len=.5, win_overlap=0.66, min_clean_fraction=0.25,
275293
max_dropout_fraction=0.1, show=False):
@@ -610,7 +628,8 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
610628
cov = mean_covariance(
611629
cov, metric="riemann", sample_weight=sample_weight)
612630
else:
613-
cov = geometric_median(cov.reshape((-1, nc * nc)))
631+
cov = geometric_median(cov.reshape((-1, nc * nc)),
632+
sample_weight=sample_weight)
614633
cov = cov.reshape((nc, nc))
615634

616635
maxdims = int(np.floor(0.66 * nc + 0.5)) # constant TODO make param

‎meegkit/utils/asr.py‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -333,11 +333,11 @@ def yulewalk_filter(X, sfreq, zi=None, ab=None, axis=-1):
333333
return out, zf
334334

335335

336-
def geometric_median(X, tol=1e-5, max_iter=500):
336+
def geometric_median(X, tol=1e-5, max_iter=500, sample_weight=None):
337337
"""Geometric median.
338338
339-
This code is adapted from [2]_ using the Vardi and Zhang algorithm
340-
described in [1]_.
339+
This code is adapted from [2]_ using the (optionally weighted) Vardi and
340+
Zhang algorithm described in [1]_.
341341
342342
Parameters
343343
----------
@@ -347,6 +347,10 @@ def geometric_median(X, tol=1e-5, max_iter=500):
347347
Tolerance (default=1.e-5)
348348
max_iter : int
349349
Max number of iterations (default=500):
350+
sample_weight : array, shape=(n_observations,) | None
351+
Per-observation weights (``eta_i`` in the Vardi-Zhang notation). If
352+
None (default), every observation is weighted equally and the
353+
iteration reduces exactly to the unweighted geometric median.
350354
351355
Returns
352356
-------
@@ -360,27 +364,33 @@ def geometric_median(X, tol=1e-5, max_iter=500):
360364
97(4), 1423-1426. https://doi.org/10.1073/pnas.97.4.1423
361365
.. [2] https://stackoverflow.com/questions/30299267/
362366
"""
363-
y = np.mean(X, 0) # initial value
367+
if sample_weight is None:
368+
w = np.ones(len(X))
369+
else:
370+
w = np.asarray(sample_weight, dtype=float)
371+
372+
y = np.average(X, axis=0, weights=w) # initial value
364373

365374
i = 0
366375
while i < max_iter:
367376
D = cdist(X, [y])
368377
nonzeros = (D != 0)[:, 0]
369378

370-
Dinv = 1. / D[nonzeros]
379+
Dinv = w[nonzeros][:, None] / D[nonzeros]
371380
Dinvs = np.sum(Dinv)
372381
W = Dinv / Dinvs
373382
T = np.sum(W * X[nonzeros], 0)
374383

375-
num_zeros = len(X) - np.sum(nonzeros)
376-
if num_zeros == 0:
384+
# weight mass of observations coincident with the current estimate
385+
eta = np.sum(w[~nonzeros])
386+
if eta == 0:
377387
y1 = T
378-
elif num_zeros == len(X):
388+
elif not nonzeros.any():
379389
return y
380390
else:
381391
R = (T - y) * Dinvs
382392
r = np.linalg.norm(R)
383-
rinv = 0 if r == 0 else num_zeros / r
393+
rinv = 0 if r == 0 else eta / r
384394
y1 = max(0, 1 - rinv) * T + min(1, rinv) * y
385395

386396
if euclidean(y, y1) < tol:

‎tests/test_asr.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,70 @@ def test_rms_window_offsets_rounds_each_start():
600600
offsets[:7], np.array([0, 42, 85, 127, 170, 212, 255]))
601601

602602

603+
def test_geometric_median_weighted():
604+
"""Weighted geometric median: uniform weights match the unweighted result, heavy weights bias toward the point."""
605+
from meegkit.utils.asr import geometric_median
606+
X = rng.standard_normal((5, 3))
607+
608+
# (a) uniform weights == default (unweighted) result
609+
gm_u = geometric_median(X)
610+
gm_ones = geometric_median(X, sample_weight=np.ones(5))
611+
assert np.allclose(gm_u, gm_ones)
612+
613+
# (b) heavily weighting one point pulls the median toward that point
614+
gm_w = geometric_median(X, sample_weight=[1., 1., 1., 1., 100.])
615+
assert np.linalg.norm(gm_w - X[4]) < np.linalg.norm(gm_u - X[4])
616+
assert not np.allclose(gm_u, gm_w)
617+
618+
619+
def test_asr_process_euclid_uses_weights():
620+
"""euclid asr_process forwards sample_weight to geometric_median."""
621+
nc, ns = 4, 50
622+
# two clearly distinct covariance blocks
623+
B1 = rng.standard_normal((nc, ns))
624+
B2 = 3 * rng.standard_normal((nc, ns)) + 1
625+
covs = np.stack([B1 @ B1.T / ns, B2 @ B2.T / ns]) # (2, nc, nc)
626+
627+
X = rng.standard_normal((nc, ns))
628+
T = 0.1 * np.eye(nc)
629+
630+
def run(weights):
631+
state = dict(M=np.eye(nc), T=T, R=None)
632+
with patch(
633+
"meegkit.asr.geometric_median",
634+
side_effect=lambda arr, sample_weight=None: np.average(
635+
arr, axis=0, weights=sample_weight),
636+
) as gm:
637+
out, _ = asr_process(X, X, state, cov=covs, method="euclid",
638+
sample_weight=weights)
639+
forwarded = gm.call_args.kwargs["sample_weight"]
640+
np.testing.assert_allclose(forwarded, weights)
641+
return out
642+
643+
out_a = run([1., 1.])
644+
out_b = run([0.05, 1.])
645+
assert out_a.shape == out_b.shape
646+
647+
648+
def test_recency_weights_suffix_sum():
649+
"""Online recency weights use suffix (not prefix) sums."""
650+
from meegkit.asr import _recency_weights
651+
sw = np.geomspace(0.05, 1, 201)
652+
counter = [5, 10, 60, 100] # sum 175 < 200, ordered oldest->newest
653+
654+
# samples strictly newer than each block: [170, 160, 100, 0]
655+
new = _recency_weights(counter, sw)
656+
expected = [sw[-171], sw[-161], sw[-101], sw[-1]]
657+
assert np.allclose(new, expected)
658+
assert new[-1] == 1.0 # most-recent block keeps weight 1
659+
660+
# the old prefix-sum vector differs on interior blocks
661+
old = [1.]
662+
for c in np.cumsum(counter[1:]):
663+
old = [sw[-c]] + old
664+
assert not np.allclose(new, old)
665+
666+
603667
if __name__ == "__main__":
604668
pytest.main([__file__])
605669
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)