Skip to content

Commit a7985ed

Browse files
committed
[FIX] ASR: apply online recency weights on the euclid path (weighted geometric median)
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; the most recent block keeps weight 1 and older blocks decay toward ~5%. Adds regression tests for the weighted median, the euclid wiring, and the suffix-sum weights.
1 parent 107cd1b commit a7985ed

3 files changed

Lines changed: 100 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):
@@ -600,7 +618,8 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
600618
cov = mean_covariance(
601619
cov, metric="riemann", sample_weight=sample_weight)
602620
else:
603-
cov = geometric_median(cov.reshape((-1, nc * nc)))
621+
cov = geometric_median(cov.reshape((-1, nc * nc)),
622+
sample_weight=sample_weight)
604623
cov = cov.reshape((nc, nc))
605624

606625
maxdims = int(np.fix(0.66 * nc)) # 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: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,63 @@ def test_clean_windows_offset_phase_drift():
418418
assert abs(int(offsets_raw[-1]) - int(offsets_truncated[-1])) >= 10
419419

420420

421+
def test_geometric_median_weighted():
422+
"""Weighted geometric median: uniform weights match the unweighted result, heavy weights bias toward the point."""
423+
from meegkit.utils.asr import geometric_median
424+
X = rng.standard_normal((5, 3))
425+
426+
# (a) uniform weights == default (unweighted) result
427+
gm_u = geometric_median(X)
428+
gm_ones = geometric_median(X, sample_weight=np.ones(5))
429+
assert np.allclose(gm_u, gm_ones)
430+
431+
# (b) heavily weighting one point pulls the median toward that point
432+
gm_w = geometric_median(X, sample_weight=[1., 1., 1., 1., 100.])
433+
assert np.linalg.norm(gm_w - X[4]) < np.linalg.norm(gm_u - X[4])
434+
assert not np.allclose(gm_u, gm_w)
435+
436+
437+
def test_asr_process_euclid_uses_weights():
438+
"""euclid asr_process output responds to sample_weight."""
439+
nc, ns = 4, 50
440+
# two clearly distinct covariance blocks
441+
B1 = rng.standard_normal((nc, ns))
442+
B2 = 3 * rng.standard_normal((nc, ns)) + 1
443+
covs = np.stack([B1 @ B1.T / ns, B2 @ B2.T / ns]) # (2, nc, nc)
444+
445+
X = rng.standard_normal((nc, ns))
446+
T = 0.1 * np.eye(nc) # small threshold so reconstruction actually triggers
447+
448+
def run(weights):
449+
state = dict(M=np.eye(nc), T=T, R=None)
450+
out, _ = asr_process(X, X, state, cov=covs, method="euclid",
451+
sample_weight=weights)
452+
return out
453+
454+
out_a = run([1., 1.])
455+
out_b = run([0.05, 1.])
456+
assert not np.allclose(out_a, out_b)
457+
458+
459+
def test_recency_weights_suffix_sum():
460+
"""Online recency weights use suffix (not prefix) sums."""
461+
from meegkit.asr import _recency_weights
462+
sw = np.geomspace(0.05, 1, 201)
463+
counter = [5, 10, 60, 100] # sum 175 < 200, ordered oldest->newest
464+
465+
# samples strictly newer than each block: [170, 160, 100, 0]
466+
new = _recency_weights(counter, sw)
467+
expected = [sw[-171], sw[-161], sw[-101], sw[-1]]
468+
assert np.allclose(new, expected)
469+
assert new[-1] == 1.0 # most-recent block keeps weight 1
470+
471+
# the old prefix-sum vector differs on interior blocks
472+
old = [1.]
473+
for c in np.cumsum(counter[1:]):
474+
old = [sw[-c]] + old
475+
assert not np.allclose(new, old)
476+
477+
421478
if __name__ == "__main__":
422479
pytest.main([__file__])
423480
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)