Skip to content

Commit a1b1464

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 3721224 commit a1b1464

3 files changed

Lines changed: 101 additions & 14 deletions

File tree

‎meegkit/asr.py‎

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

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

253254
# Clean data, using covariances weighted by sample_weight
254255
out, self.state_ = asr_process(X, X_filt, self.state_,
@@ -259,6 +260,23 @@ def transform(self, X, y=None, **kwargs):
259260
return out
260261

261262

263+
def _recency_weights(counter, sample_weight):
264+
"""Exponential recency weights for stored covariance blocks.
265+
266+
A block's weight is set by the number of MORE-RECENT samples that follow
267+
it (the suffix sum of ``counter``), so unequal chunk sizes are weighted by
268+
true recency. The most recent block gets ``sample_weight[-1]`` (== 1);
269+
older blocks decay toward 5%. ``counter`` is ordered oldest->newest.
270+
"""
271+
weights = []
272+
newer = 0
273+
for count in reversed(counter):
274+
idx = min(newer, len(sample_weight) - 1)
275+
weights.insert(0, sample_weight[-(idx + 1)])
276+
newer += count
277+
return weights
278+
279+
262280
def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
263281
win_len=.5, win_overlap=0.66, min_clean_fraction=0.25,
264282
max_dropout_fraction=0.1, show=False):
@@ -570,7 +588,8 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
570588
cov = mean_covariance(
571589
cov, metric="riemann", sample_weight=sample_weight)
572590
else:
573-
cov = geometric_median(cov.reshape((-1, nc * nc)))
591+
cov = geometric_median(cov.reshape((-1, nc * nc)),
592+
sample_weight=sample_weight)
574593
cov = cov.reshape((nc, nc))
575594

576595
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
@@ -330,11 +330,11 @@ def yulewalk_filter(X, sfreq, zi=None, ab=None, axis=-1):
330330
return out, zf
331331

332332

333-
def geometric_median(X, tol=1e-5, max_iter=500):
333+
def geometric_median(X, tol=1e-5, max_iter=500, sample_weight=None):
334334
"""Geometric median.
335335
336-
This code is adapted from [2]_ using the Vardi and Zhang algorithm
337-
described in [1]_.
336+
This code is adapted from [2]_ using the (optionally weighted) Vardi and
337+
Zhang algorithm described in [1]_.
338338
339339
Parameters
340340
----------
@@ -344,6 +344,10 @@ def geometric_median(X, tol=1e-5, max_iter=500):
344344
Tolerance (default=1.e-5)
345345
max_iter : int
346346
Max number of iterations (default=500):
347+
sample_weight : array, shape=(n_observations,) | None
348+
Per-observation weights (``eta_i`` in the Vardi-Zhang notation). If
349+
None (default), every observation is weighted equally and the
350+
iteration reduces exactly to the unweighted geometric median.
347351
348352
Returns
349353
-------
@@ -357,27 +361,33 @@ def geometric_median(X, tol=1e-5, max_iter=500):
357361
97(4), 1423-1426. https://doi.org/10.1073/pnas.97.4.1423
358362
.. [2] https://stackoverflow.com/questions/30299267/
359363
"""
360-
y = np.mean(X, 0) # initial value
364+
if sample_weight is None:
365+
w = np.ones(len(X))
366+
else:
367+
w = np.asarray(sample_weight, dtype=float)
368+
369+
y = np.average(X, axis=0, weights=w) # initial value
361370

362371
i = 0
363372
while i < max_iter:
364373
D = cdist(X, [y])
365374
nonzeros = (D != 0)[:, 0]
366375

367-
Dinv = 1. / D[nonzeros]
376+
Dinv = w[nonzeros][:, None] / D[nonzeros]
368377
Dinvs = np.sum(Dinv)
369378
W = Dinv / Dinvs
370379
T = np.sum(W * X[nonzeros], 0)
371380

372-
num_zeros = len(X) - np.sum(nonzeros)
373-
if num_zeros == 0:
381+
# weight mass of observations coincident with the current estimate
382+
eta = np.sum(w[~nonzeros])
383+
if eta == 0:
374384
y1 = T
375-
elif num_zeros == len(X):
385+
elif not nonzeros.any():
376386
return y
377387
else:
378388
R = (T - y) * Dinvs
379389
r = np.linalg.norm(R)
380-
rinv = 0 if r == 0 else num_zeros / r
390+
rinv = 0 if r == 0 else eta / r
381391
y1 = max(0, 1 - rinv) * T + min(1, rinv) * y
382392

383393
if euclidean(y, y1) < tol:

‎tests/test_asr.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,64 @@ def test_asr_class(method, reref, show=False):
258258
ASR(sfreq=125)
259259
ASR(Sfreq=150)
260260

261+
262+
def test_geometric_median_weighted():
263+
"""Weighted geometric median: uniform weights match the unweighted result, heavy weights bias toward the point."""
264+
from meegkit.utils.asr import geometric_median
265+
X = rng.standard_normal((5, 3))
266+
267+
# (a) uniform weights == default (unweighted) result
268+
gm_u = geometric_median(X)
269+
gm_ones = geometric_median(X, sample_weight=np.ones(5))
270+
assert np.allclose(gm_u, gm_ones)
271+
272+
# (b) heavily weighting one point pulls the median toward that point
273+
gm_w = geometric_median(X, sample_weight=[1., 1., 1., 1., 100.])
274+
assert np.linalg.norm(gm_w - X[4]) < np.linalg.norm(gm_u - X[4])
275+
assert not np.allclose(gm_u, gm_w)
276+
277+
278+
def test_asr_process_euclid_uses_weights():
279+
"""euclid asr_process output responds to sample_weight."""
280+
nc, ns = 4, 50
281+
# two clearly distinct covariance blocks
282+
B1 = rng.standard_normal((nc, ns))
283+
B2 = 3 * rng.standard_normal((nc, ns)) + 1
284+
covs = np.stack([B1 @ B1.T / ns, B2 @ B2.T / ns]) # (2, nc, nc)
285+
286+
X = rng.standard_normal((nc, ns))
287+
T = 0.1 * np.eye(nc) # small threshold so reconstruction actually triggers
288+
289+
def run(weights):
290+
state = dict(M=np.eye(nc), T=T, R=None)
291+
out, _ = asr_process(X, X, state, cov=covs, method="euclid",
292+
sample_weight=weights)
293+
return out
294+
295+
out_a = run([1., 1.])
296+
out_b = run([0.05, 1.])
297+
assert not np.allclose(out_a, out_b)
298+
299+
300+
def test_recency_weights_suffix_sum():
301+
"""Online recency weights use suffix (not prefix) sums."""
302+
from meegkit.asr import _recency_weights
303+
sw = np.geomspace(0.05, 1, 201)
304+
counter = [5, 10, 60, 100] # sum 175 < 200, ordered oldest->newest
305+
306+
# samples strictly newer than each block: [170, 160, 100, 0]
307+
new = _recency_weights(counter, sw)
308+
expected = [sw[-171], sw[-161], sw[-101], sw[-1]]
309+
assert np.allclose(new, expected)
310+
assert new[-1] == 1.0 # most-recent block keeps weight 1
311+
312+
# the old prefix-sum vector differs on interior blocks
313+
old = [1.]
314+
for c in np.cumsum(counter[1:]):
315+
old = [sw[-c]] + old
316+
assert not np.allclose(new, old)
317+
318+
261319
if __name__ == "__main__":
262320
pytest.main([__file__])
263321
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)