braindecode 2.1.0.dev181714115__py3-none-any.whl → 2.1.0.dev182154342__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braindecode/augmentation/functional.py +1 -1
- braindecode/augmentation/transforms.py +1 -1
- braindecode/datasets/base.py +17 -12
- braindecode/datasets/bids/hub.py +13 -1
- braindecode/datautil/serialization.py +7 -0
- braindecode/functional/__init__.py +10 -0
- braindecode/functional/attention.py +4 -14
- braindecode/functional/channels.py +282 -0
- braindecode/models/__init__.py +6 -0
- braindecode/models/attn_sleep.py +40 -6
- braindecode/models/base.py +50 -13
- braindecode/models/biot.py +10 -8
- braindecode/models/brainmodule.py +1 -13
- braindecode/models/codebrain.py +14 -19
- braindecode/models/eegpt.py +1 -1
- braindecode/models/eegtcnet.py +31 -4
- braindecode/models/emg2qwerty.py +8 -2
- braindecode/models/fnirs4d.py +761 -0
- braindecode/models/fnirs_cnn1d.py +339 -0
- braindecode/models/fnirs_t.py +785 -0
- braindecode/models/fnirsnet.py +268 -86
- braindecode/models/geonirs.py +1545 -0
- braindecode/models/guetschel2026.py +1 -1
- braindecode/models/jung_mae.py +596 -0
- braindecode/models/luna.py +43 -33
- braindecode/models/mapa.py +4 -5
- braindecode/models/model.html.jinja +24 -9
- braindecode/models/msvtnet.py +1 -2
- braindecode/models/mtrenirs.py +1053 -0
- braindecode/models/patchedtransformer.py +26 -15
- braindecode/models/reve.py +1 -4
- braindecode/models/signal_jepa.py +5 -6
- braindecode/models/sleepfm.py +98 -23
- braindecode/models/summary.csv +7 -0
- braindecode/models/util.py +139 -1
- braindecode/models/zuna.py +11 -24
- braindecode/modules/attention.py +9 -8
- braindecode/modules/channels.py +170 -30
- braindecode/modules/layers.py +2 -8
- braindecode/preprocessing/preprocess.py +4 -0
- braindecode/preprocessing/windowers.py +14 -6
- braindecode/util.py +21 -28
- braindecode/version.py +1 -1
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +49 -42
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +6 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
braindecode/modules/attention.py
CHANGED
|
@@ -22,7 +22,6 @@ from torch import Tensor, nn
|
|
|
22
22
|
|
|
23
23
|
from braindecode.functional import _get_gaussian_kernel1d, scaled_dot_product_attention
|
|
24
24
|
from braindecode.functional.attention import ( # noqa: F401 (re-exported)
|
|
25
|
-
_hpu_lazy,
|
|
26
25
|
_sdpa_math_dropout,
|
|
27
26
|
)
|
|
28
27
|
|
|
@@ -861,7 +860,7 @@ class TimmAttention(nn.Module):
|
|
|
861
860
|
timm's op order, ``softmax((q * scale) @ k^T) @ v``, bit-identical to
|
|
862
861
|
the reference implementations (see
|
|
863
862
|
:func:`braindecode.functional.scaled_dot_product_attention`); otherwise
|
|
864
|
-
torch's kernels
|
|
863
|
+
torch's kernels.
|
|
865
864
|
|
|
866
865
|
Examples
|
|
867
866
|
--------
|
|
@@ -930,9 +929,7 @@ class TimmAttention(nn.Module):
|
|
|
930
929
|
q * self.scale, k, v, dropout_p=dropout_p, scale=1.0, exact=True
|
|
931
930
|
)
|
|
932
931
|
else:
|
|
933
|
-
y = scaled_dot_product_attention(
|
|
934
|
-
q, k, v, dropout_p=dropout_p, fused_in_lazy=True
|
|
935
|
-
)
|
|
932
|
+
y = scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
|
|
936
933
|
return self.proj_drop(self.proj(y.transpose(1, 2).flatten(2)))
|
|
937
934
|
|
|
938
935
|
|
|
@@ -960,6 +957,9 @@ class MultiHeadAttention(nn.Module):
|
|
|
960
957
|
qk_norm : bool, optional
|
|
961
958
|
Apply a :class:`~torch.nn.LayerNorm` over ``head_dim`` to the queries
|
|
962
959
|
and keys of each head (as in LaBraM and Du-IN). Default ``False``.
|
|
960
|
+
qkv_bias : bool, optional
|
|
961
|
+
Give the query, key and value projections a bias (fNIRS-T has none).
|
|
962
|
+
Default ``True``.
|
|
963
963
|
|
|
964
964
|
Examples
|
|
965
965
|
--------
|
|
@@ -980,6 +980,7 @@ class MultiHeadAttention(nn.Module):
|
|
|
980
980
|
scale: float | None = None,
|
|
981
981
|
head_dim: int | None = None,
|
|
982
982
|
qk_norm: bool = False,
|
|
983
|
+
qkv_bias: bool = True,
|
|
983
984
|
):
|
|
984
985
|
super().__init__()
|
|
985
986
|
if num_heads < 1 or (head_dim is not None and head_dim < 1):
|
|
@@ -997,9 +998,9 @@ class MultiHeadAttention(nn.Module):
|
|
|
997
998
|
self.num_heads = num_heads
|
|
998
999
|
self.head_dim = head_dim
|
|
999
1000
|
self.scale = scale
|
|
1000
|
-
self.keys = nn.Linear(emb_size, inner_dim)
|
|
1001
|
-
self.queries = nn.Linear(emb_size, inner_dim)
|
|
1002
|
-
self.values = nn.Linear(emb_size, inner_dim)
|
|
1001
|
+
self.keys = nn.Linear(emb_size, inner_dim, bias=qkv_bias)
|
|
1002
|
+
self.queries = nn.Linear(emb_size, inner_dim, bias=qkv_bias)
|
|
1003
|
+
self.values = nn.Linear(emb_size, inner_dim, bias=qkv_bias)
|
|
1003
1004
|
self.q_norm = nn.LayerNorm(head_dim) if qk_norm else None
|
|
1004
1005
|
self.k_norm = nn.LayerNorm(head_dim) if qk_norm else None
|
|
1005
1006
|
self.att_drop = dropout
|
braindecode/modules/channels.py
CHANGED
|
@@ -6,9 +6,15 @@
|
|
|
6
6
|
Every strategy is a matrix ``W`` (K x C) from the C input channels to the K
|
|
7
7
|
target channels. Names are copied first (case-insensitive, then legacy names
|
|
8
8
|
such as T3 = T7); an input whose name MNE does not know is copied to a target
|
|
9
|
-
within 15 mm.
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
within 15 mm. A channel named ``A-B`` is ``V(A) - V(B)`` (BIOT), so a target
|
|
10
|
+
that is a combination of measured channels is computed exactly
|
|
11
|
+
(:func:`braindecode.functional.exact_derivation`): ``F3-C3`` from ``C3-F3``,
|
|
12
|
+
``F3-P3`` from ``F3-C3`` and ``C3-P3``, ``F3-C3`` from ``F3`` and ``C3``. The
|
|
13
|
+
strategy fills the other targets that have a position from the positioned
|
|
14
|
+
inputs; a target without a position (BENDR's ``SCALE``) is zero. ``spline``,
|
|
15
|
+
``wiener`` and a kernel passed as the strategy are one Gaussian estimate
|
|
16
|
+
(:func:`braindecode.functional.linear_channel_map`), which also gives each
|
|
17
|
+
target's posterior variance.
|
|
12
18
|
"""
|
|
13
19
|
|
|
14
20
|
from __future__ import annotations
|
|
@@ -18,6 +24,7 @@ import re
|
|
|
18
24
|
import warnings
|
|
19
25
|
from collections import OrderedDict
|
|
20
26
|
from functools import lru_cache
|
|
27
|
+
from typing import cast
|
|
21
28
|
from unittest import mock
|
|
22
29
|
|
|
23
30
|
import mne
|
|
@@ -29,6 +36,11 @@ from scipy.linalg import solve
|
|
|
29
36
|
from scipy.spatial.distance import cdist
|
|
30
37
|
from torch import Tensor, nn
|
|
31
38
|
|
|
39
|
+
from braindecode.functional import (
|
|
40
|
+
exact_derivation,
|
|
41
|
+
linear_channel_map,
|
|
42
|
+
spherical_spline_kernel,
|
|
43
|
+
)
|
|
32
44
|
from braindecode.util import resolve_montage_name
|
|
33
45
|
|
|
34
46
|
STRATEGIES = (
|
|
@@ -234,8 +246,32 @@ def _source(src_pos, tgt_pos, n_parcels=64, lam=0.1, grid_mm=15.0):
|
|
|
234
246
|
return L[k:] - L[:k].mean(0), S
|
|
235
247
|
|
|
236
248
|
|
|
249
|
+
def _head_origin(src_pos) -> np.ndarray:
|
|
250
|
+
"""Centre of the sphere fitted to ``src_pos``, as ``interpolate_to(origin="auto")``."""
|
|
251
|
+
names = [f"S{i}" for i in range(len(src_pos))]
|
|
252
|
+
info = mne.create_info(names, 100.0, "eeg")
|
|
253
|
+
info.set_montage(
|
|
254
|
+
mne.channels.make_dig_montage(dict(zip(names, src_pos)), coord_frame="head")
|
|
255
|
+
)
|
|
256
|
+
return mne.bem.fit_sphere_to_headshape(info, units="m", verbose="ERROR")[1]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _kriging(cov, k, noise, match_gain=False, flat=True):
|
|
260
|
+
"""Rows ``k:`` of ``cov`` from rows ``:k`` (``linear_channel_map``): ``(W, var)``."""
|
|
261
|
+
eye = torch.eye(len(cov), dtype=torch.float64)
|
|
262
|
+
W, var = linear_channel_map(
|
|
263
|
+
eye[:k],
|
|
264
|
+
eye[k:],
|
|
265
|
+
torch.as_tensor(cov),
|
|
266
|
+
noise,
|
|
267
|
+
eye.sum(1, keepdim=True) if flat else None,
|
|
268
|
+
match_gain,
|
|
269
|
+
) # flat: the unknown recording reference
|
|
270
|
+
return W.numpy(), var.numpy()
|
|
271
|
+
|
|
272
|
+
|
|
237
273
|
def _mixing(
|
|
238
|
-
name
|
|
274
|
+
name,
|
|
239
275
|
src_pos,
|
|
240
276
|
tgt_pos,
|
|
241
277
|
reg=None,
|
|
@@ -244,11 +280,18 @@ def _mixing(
|
|
|
244
280
|
radius=None,
|
|
245
281
|
cov=None,
|
|
246
282
|
dense_pos=None,
|
|
283
|
+
match_gain=False,
|
|
247
284
|
**source_kw,
|
|
248
|
-
)
|
|
249
|
-
"""``(M, k)`` matrix filling ``M`` target positions from ``k`` input positions
|
|
285
|
+
):
|
|
286
|
+
"""``(M, k)`` matrix filling ``M`` target positions from ``k`` input positions,
|
|
287
|
+
and the targets' posterior variance (``None`` without a prior covariance)."""
|
|
288
|
+
if name == "spline" or callable(name): # positions from MNE's fitted head centre
|
|
289
|
+
k = torch.as_tensor(np.vstack([src_pos, tgt_pos]) - _head_origin(src_pos))
|
|
290
|
+
kernel = spherical_spline_kernel if name == "spline" else name
|
|
291
|
+
cov = np.asarray(kernel(k, k), float)
|
|
292
|
+
return _kriging(cov, len(src_pos), 1e-3 if reg is None else reg, match_gain)
|
|
250
293
|
if name in ("zero", "latent"): # latent: the attention fills these rows
|
|
251
|
-
return np.zeros((len(tgt_pos), len(src_pos)))
|
|
294
|
+
return np.zeros((len(tgt_pos), len(src_pos))), None
|
|
252
295
|
if name == "wiener": # C_to (C_oo + noise * tr / k * I)^-1
|
|
253
296
|
if cov is None or not len(cov):
|
|
254
297
|
raise ValueError("The 'wiener' strategy needs a covariance: call fit().")
|
|
@@ -259,26 +302,24 @@ def _mixing(
|
|
|
259
302
|
f"'wiener': positions {both[d.min(1) > 0.015].round(3).tolist()} have no electrode of the fitted dense montage within 15 mm."
|
|
260
303
|
)
|
|
261
304
|
jo, jt = np.split(d.argmin(1), [len(src_pos)])
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
return
|
|
305
|
+
sigma2 = noise * np.trace(cov[np.ix_(jo, jo)]) / len(jo)
|
|
306
|
+
j = np.r_[jo, jt]
|
|
307
|
+
return _kriging(cov[np.ix_(j, j)], len(jo), sigma2, match_gain, flat=False)
|
|
265
308
|
if name == "region": # mean within radius (default 1.5 x median input spacing)
|
|
266
309
|
if radius is None:
|
|
267
310
|
nn_d = cdist(src_pos, src_pos) + np.diag(np.full(len(src_pos), np.inf))
|
|
268
311
|
radius = 1.5 * np.median(nn_d.min(1))
|
|
269
312
|
w = (cdist(tgt_pos, src_pos) <= radius).astype(float)
|
|
270
|
-
return w / np.maximum(w.sum(1, keepdims=True), 1.0)
|
|
313
|
+
return w / np.maximum(w.sum(1, keepdims=True), 1.0), None
|
|
271
314
|
if name in ("nearest", "idw"):
|
|
272
315
|
w = np.maximum(cdist(tgt_pos, src_pos), 1e-6) ** -p
|
|
273
316
|
w = w == w.max(1, keepdims=True) if name == "nearest" else w
|
|
274
|
-
return w / w.sum(1, keepdims=True)
|
|
275
|
-
if name == "spline":
|
|
276
|
-
return _interp("spline", src_pos, tgt_pos, 1e-3 if reg is None else reg)
|
|
317
|
+
return w / w.sum(1, keepdims=True), None
|
|
277
318
|
if name == "field": # MNE maps average-referenced data: keep the input reference
|
|
278
319
|
W = _interp("MNE", src_pos, tgt_pos, 0.0 if reg is None else reg)
|
|
279
|
-
return W + (1.0 - W.sum(1, keepdims=True)) / W.shape[1]
|
|
320
|
+
return W + (1.0 - W.sum(1, keepdims=True)) / W.shape[1], None
|
|
280
321
|
Lt, S = _source(src_pos, tgt_pos, **source_kw)
|
|
281
|
-
return Lt @ S + 1.0 / len(src_pos) # rows sum to 1: the input's
|
|
322
|
+
return Lt @ S + 1.0 / len(src_pos), None # rows sum to 1: the input's reference
|
|
282
323
|
|
|
283
324
|
|
|
284
325
|
class ChannelLayer(nn.Module):
|
|
@@ -290,7 +331,7 @@ class ChannelLayer(nn.Module):
|
|
|
290
331
|
----------
|
|
291
332
|
target : list of dict
|
|
292
333
|
Channels the backbone consumes (``ch_name``, optional ``loc``).
|
|
293
|
-
strategy : str
|
|
334
|
+
strategy : str or callable
|
|
294
335
|
``"exact"`` (a missing target is an error), ``"zero"``, ``"nearest"``,
|
|
295
336
|
``"idw"`` (``p``), ``"spline"`` (``reg=1e-3``), ``"field"`` (``reg=0``)
|
|
296
337
|
or ``"source"`` (``n_parcels=64``, ``lam=0.1``, ``grid_mm=15``,
|
|
@@ -299,10 +340,43 @@ class ChannelLayer(nn.Module):
|
|
|
299
340
|
(mean within ``radius``, default 1.5 x the median input spacing) or
|
|
300
341
|
``"latent"`` (``d_model=64``, ``n_freqs=8``: learned cross-attention from
|
|
301
342
|
each missing target's position over the inputs' positions and statistics).
|
|
343
|
+
A callable ``kernel(pos_a, pos_b) -> (n_a, n_b)`` covariance of the
|
|
344
|
+
potentials at two sets of positions (metres, from the centre of the
|
|
345
|
+
sphere fitted to the inputs, as ``"spline"``), e.g.
|
|
346
|
+
:func:`~braindecode.functional.spherical_spline_kernel`, fills them with
|
|
347
|
+
:func:`~braindecode.functional.linear_channel_map` (``reg``: the noise
|
|
348
|
+
variance, default 1e-3; the recording reference is left unknown).
|
|
349
|
+
``spline`` and ``wiener`` are that estimate with their own covariance;
|
|
350
|
+
``match_gain=True`` gives each reconstructed target its prior variance.
|
|
302
351
|
chs_info : list of dict, optional
|
|
303
352
|
Montage used when :meth:`forward` gets none.
|
|
304
353
|
drop_non_eeg : bool
|
|
305
354
|
Ignore input channels that are not electrodes instead of raising.
|
|
355
|
+
reference : str, optional
|
|
356
|
+
Reference of the backbone's single-electrode targets: ``None`` (the
|
|
357
|
+
input's), an electrode name (``"Cz"``: target ``A`` is ``V(A) -
|
|
358
|
+
V(Cz)``, with ``Cz`` copied or reconstructed like any target) or
|
|
359
|
+
``"average"`` (minus their mean). Bipolar targets need none.
|
|
360
|
+
|
|
361
|
+
Attributes
|
|
362
|
+
----------
|
|
363
|
+
variance : torch.Tensor
|
|
364
|
+
Posterior variance of each target for the current montage: 0 when
|
|
365
|
+
measured or exact, from the estimate (before ``match_gain``) for a
|
|
366
|
+
single-electrode target of ``spline``, ``wiener`` or a kernel, ``nan``
|
|
367
|
+
when not computed (other strategies, or a target mixing several
|
|
368
|
+
reconstructed channels, as with ``reference="average"``).
|
|
369
|
+
|
|
370
|
+
Notes
|
|
371
|
+
-----
|
|
372
|
+
``forward`` also takes one montage per sample (``chs_info`` a list of
|
|
373
|
+
montages, ``x`` padded to the largest and ``ch_mask`` the real channels),
|
|
374
|
+
for the strategies without trained state (not ``latent`` or ``trainable``);
|
|
375
|
+
``observed`` is then ``(batch, n_targets)`` and the buffers (``weight``,
|
|
376
|
+
``variance``) are those of the last sample.
|
|
377
|
+
A model with a ``channel_strategy`` builds these montages from the ``pos`` and
|
|
378
|
+
``ch_mask`` of :func:`~braindecode.datasets.pad_channels_collate`. A function
|
|
379
|
+
strategy is not saved by ``save_pretrained``: pass it again when loading.
|
|
306
380
|
"""
|
|
307
381
|
|
|
308
382
|
def __init__(
|
|
@@ -313,10 +387,11 @@ class ChannelLayer(nn.Module):
|
|
|
313
387
|
*,
|
|
314
388
|
drop_non_eeg=False,
|
|
315
389
|
trainable=False,
|
|
390
|
+
reference=None,
|
|
316
391
|
**kwargs,
|
|
317
392
|
):
|
|
318
393
|
super().__init__()
|
|
319
|
-
if strategy not in STRATEGIES:
|
|
394
|
+
if not callable(strategy) and strategy not in STRATEGIES:
|
|
320
395
|
close = difflib.get_close_matches(strategy, STRATEGIES, n=3)
|
|
321
396
|
raise ValueError(
|
|
322
397
|
f"Unknown channel strategy {strategy!r}. Did you mean {close}? Available: {STRATEGIES}."
|
|
@@ -326,15 +401,23 @@ class ChannelLayer(nn.Module):
|
|
|
326
401
|
c if g or np.isnan(p).any() else {**c, "loc": np.r_[p, np.zeros(9)]}
|
|
327
402
|
for c, p, g in zip(target, pos, given)
|
|
328
403
|
]
|
|
329
|
-
self.strategy, self.chs_info = strategy, chs_info
|
|
404
|
+
self.strategy, self.chs_info, self.reference = strategy, chs_info, reference
|
|
330
405
|
self.drop_non_eeg, self.kwargs = drop_non_eeg, kwargs
|
|
331
406
|
# Per-montage maps: LRU of device tensors; the current one is the buffers.
|
|
332
407
|
self._cache, self._key, self._chs = OrderedDict(), None, None
|
|
333
408
|
self.register_buffer("weight", torch.zeros(0, 0), persistent=False)
|
|
334
409
|
tnames = [str(c["ch_name"]) for c in self.target]
|
|
410
|
+
named = {n: c for n, c in zip(tnames, self.target) if "-" not in n}
|
|
411
|
+
# referenced: single-electrode targets with a position (not BENDR's SCALE)
|
|
412
|
+
self._referenced = np.array(
|
|
413
|
+
["-" not in n and np.isfinite(p).all() for n, p in zip(tnames, pos)]
|
|
414
|
+
)
|
|
415
|
+
if reference not in (None, "average"): # target A is the derivation A-ref
|
|
416
|
+
tnames = [
|
|
417
|
+
f"{n}-{reference}" if r else n for n, r in zip(tnames, self._referenced)
|
|
418
|
+
]
|
|
335
419
|
# A-B is copied when measured, else derived from A and B (both columns).
|
|
336
420
|
mono = list(dict.fromkeys(m for n in tnames for m in (n, *n.split("-"))))
|
|
337
|
-
named = {n: c for n, c in zip(tnames, self.target) if "-" not in n}
|
|
338
421
|
_, tpos, tstd, *_ = _resolve([named.get(m, {"ch_name": m}) for m in mono])
|
|
339
422
|
self._whole = [mono.index(n) for n in tnames]
|
|
340
423
|
D = np.array(
|
|
@@ -401,16 +484,31 @@ class ChannelLayer(nn.Module):
|
|
|
401
484
|
alias = np.nan_to_num(cdist(tstd, std), nan=np.inf) < 1e-6
|
|
402
485
|
dist = np.nan_to_num(cdist(tpos, pos), nan=np.inf)
|
|
403
486
|
near = np.where(np.isnan(std).any(1), dist, np.inf)
|
|
487
|
+
# Names before positions: B-A shares the midpoint of A-B but needs -1.
|
|
488
|
+
kept = np.flatnonzero(keep)
|
|
489
|
+
derived, exact = exact_derivation(mono, [names[j] for j in kept])
|
|
404
490
|
W = np.zeros((len(mono), len(names)))
|
|
405
491
|
for k, m in enumerate(mono):
|
|
406
|
-
|
|
492
|
+
direct = (low == m.lower()) & keep
|
|
493
|
+
if direct.any():
|
|
494
|
+
j = np.flatnonzero(direct)
|
|
495
|
+
W[k, j[np.argmin(near[k][j])]] = 1.0
|
|
496
|
+
continue
|
|
497
|
+
if exact[k]: # a combination of measured channels
|
|
498
|
+
W[k, kept] = derived[k].numpy()
|
|
499
|
+
continue
|
|
500
|
+
for hit in (alias[k], near[k] <= 0.015):
|
|
407
501
|
if (hit & keep).any():
|
|
408
502
|
j = np.flatnonzero(hit & keep)
|
|
409
503
|
W[k, j[np.argmin(near[k][j])]] = 1.0
|
|
410
504
|
break
|
|
411
|
-
observed = W.sum(1) > 0
|
|
505
|
+
observed = np.abs(W).sum(1) > 0
|
|
412
506
|
copied = observed[self._whole][:, None] # a measured A-B target: copy it
|
|
413
507
|
D = np.where(copied, np.eye(len(mono))[self._whole], self._D)
|
|
508
|
+
measured = (np.abs(D) @ ~observed == 0).any() # before re-referencing
|
|
509
|
+
ref = self._referenced
|
|
510
|
+
if self.reference == "average" and ref.any(): # minus their mean
|
|
511
|
+
D[ref] -= D[ref].mean(0)
|
|
414
512
|
missing = ~observed & np.abs(D).any(0)
|
|
415
513
|
todo = missing & np.isfinite(tpos).all(1)
|
|
416
514
|
if self.strategy == "exact" and todo.any():
|
|
@@ -418,7 +516,7 @@ class ChannelLayer(nn.Module):
|
|
|
418
516
|
f"Strategy 'exact': target channels {[m for m, t in zip(mono, todo) if t]} are not in the input montage {names}; use a reconstructing strategy (e.g. 'spline') or supply them."
|
|
419
517
|
)
|
|
420
518
|
seen = np.abs(D) @ missing == 0
|
|
421
|
-
if not
|
|
519
|
+
if not measured and (self.strategy == "zero" or not todo.any()):
|
|
422
520
|
raise ValueError(
|
|
423
521
|
f"No target channel of {[c['ch_name'] for c in self.target]} is in the input montage {names}, and strategy {self.strategy!r} reconstructs none: the model would see only zeros. Supply matching names or positions, or a reconstructing strategy (e.g. 'spline')."
|
|
424
522
|
)
|
|
@@ -429,19 +527,22 @@ class ChannelLayer(nn.Module):
|
|
|
429
527
|
stacklevel=4,
|
|
430
528
|
)
|
|
431
529
|
use = keep & np.isfinite(pos).all(1)
|
|
432
|
-
|
|
530
|
+
need = _MIN_POSITIONS.get(self.strategy, 4) # a kernel: as spline
|
|
531
|
+
if todo.any() and use.sum() < need:
|
|
433
532
|
raise ValueError(
|
|
434
|
-
f"Strategy {self.strategy!r} needs at least {
|
|
533
|
+
f"Strategy {self.strategy!r} needs at least {need} channels with a position; got {int(use.sum())} of {names}. Supply 'loc' or standard 10-05 names."
|
|
435
534
|
)
|
|
436
535
|
fitted = { # wiener: device-safe float64 copies
|
|
437
536
|
k: getattr(self, k).detach().cpu().double().numpy()
|
|
438
537
|
for k in ("cov", "dense_pos")
|
|
439
538
|
if hasattr(self, k)
|
|
440
539
|
}
|
|
540
|
+
var = np.where(observed, 0.0, np.nan)
|
|
441
541
|
if todo.any():
|
|
442
|
-
W[np.ix_(todo, use)] = _mixing(
|
|
542
|
+
W[np.ix_(todo, use)], v = _mixing(
|
|
443
543
|
self.strategy, pos[use], tpos[todo], **self.kwargs, **fitted
|
|
444
544
|
)
|
|
545
|
+
var[todo] = np.nan if v is None else v
|
|
445
546
|
gain = np.abs(W[todo]).sum(1).max()
|
|
446
547
|
if gain > 2:
|
|
447
548
|
warnings.warn(
|
|
@@ -450,7 +551,12 @@ class ChannelLayer(nn.Module):
|
|
|
450
551
|
stacklevel=4,
|
|
451
552
|
)
|
|
452
553
|
dev, dt = self.weight.device, self.weight.dtype # built where the module is
|
|
453
|
-
|
|
554
|
+
# one reconstructed entry in a row: its variance times its weight squared
|
|
555
|
+
hit = (D != 0) & missing
|
|
556
|
+
j, rows = hit.argmax(1), np.arange(len(D))
|
|
557
|
+
own = D[rows, j] ** 2 * var[j]
|
|
558
|
+
variance = np.where(seen, 0.0, np.where(hit.sum(1) == 1, own, np.nan))
|
|
559
|
+
maps = dict(weight=D @ W, variance=variance)
|
|
454
560
|
if self.trainable: # nothing to reconstruct: zero correction, no inverse
|
|
455
561
|
n = self.parcel_mix.shape[0]
|
|
456
562
|
Lt, S = (
|
|
@@ -506,19 +612,53 @@ class ChannelLayer(nn.Module):
|
|
|
506
612
|
super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
|
|
507
613
|
|
|
508
614
|
def forward(
|
|
509
|
-
self,
|
|
615
|
+
self,
|
|
616
|
+
x: Tensor,
|
|
617
|
+
chs_info: list[dict] | list[list[dict]] | None = None,
|
|
618
|
+
ch_mask: Tensor | None = None,
|
|
510
619
|
) -> tuple[Tensor, Tensor]:
|
|
511
|
-
"""Map ``x`` (B, C, T) recorded with ``chs_info
|
|
620
|
+
"""Map ``x`` (B, C, T) recorded with ``chs_info``, or with one montage per
|
|
621
|
+
sample whose channels are the ``True`` entries of ``ch_mask`` (B, C)
|
|
622
|
+
(default: the first ones, as :func:`~braindecode.datasets.pad_channels_collate`
|
|
623
|
+
pads); return ``(x, observed)``."""
|
|
512
624
|
chs = chs_info if chs_info is not None else self.chs_info
|
|
513
625
|
if chs is None:
|
|
514
626
|
raise ValueError(
|
|
515
627
|
f"No montage: pass chs_info to the model (or to forward) so channel strategy {self.strategy!r} knows the input channels."
|
|
516
628
|
)
|
|
629
|
+
if chs and isinstance(chs[0], (list, tuple)): # one montage per sample
|
|
630
|
+
big = max(map(len, chs)) > x.shape[1]
|
|
631
|
+
if self.trainable or self.strategy == "latent" or len(chs) != len(x) or big:
|
|
632
|
+
raise ValueError(
|
|
633
|
+
f"One montage per sample needs a strategy without trained state and one montage of at most {x.shape[1]} channels for each of the {len(x)} samples; got {self.strategy!r} and {len(chs)} montages."
|
|
634
|
+
)
|
|
635
|
+
weights, observed = [], []
|
|
636
|
+
# ponytail: one map per distinct montage, LRU of 16; a batch of many
|
|
637
|
+
# recordings rebuilds maps on the host, cache by montage if it shows.
|
|
638
|
+
for b, c in enumerate(cast(list[list[dict]], chs)):
|
|
639
|
+
self._use(c)
|
|
640
|
+
cols = (
|
|
641
|
+
ch_mask[b].nonzero().squeeze(1)
|
|
642
|
+
if ch_mask is not None
|
|
643
|
+
else torch.arange(len(c), device=x.device)
|
|
644
|
+
)
|
|
645
|
+
if len(cols) != len(c):
|
|
646
|
+
raise ValueError(
|
|
647
|
+
f"Sample {b}: ch_mask has {len(cols)} channels, its montage {len(c)}."
|
|
648
|
+
)
|
|
649
|
+
w = self.weight.new_zeros(len(self.weight), x.shape[1])
|
|
650
|
+
w[:, cols] = self.weight
|
|
651
|
+
weights.append(w)
|
|
652
|
+
observed.append(self.observed)
|
|
653
|
+
return torch.stack(weights) @ x, torch.stack(observed)
|
|
654
|
+
if ch_mask is not None:
|
|
655
|
+
raise ValueError("ch_mask needs one montage per sample in chs_info.")
|
|
517
656
|
if x.shape[1] != len(chs):
|
|
518
657
|
raise ValueError(
|
|
519
658
|
f"Input has {x.shape[1]} channels but the montage has {len(chs)}; they must match."
|
|
520
659
|
)
|
|
521
|
-
|
|
660
|
+
# steady state: no host work, every map already on device
|
|
661
|
+
self._use(cast(list[dict], chs))
|
|
522
662
|
out = self.weight @ x
|
|
523
663
|
if self.trainable:
|
|
524
664
|
out = out + self.lead @ (self.parcel_mix @ (self.inverse @ x))
|
braindecode/modules/layers.py
CHANGED
|
@@ -567,14 +567,8 @@ class ChannelMerger(nn.Module):
|
|
|
567
567
|
scores = torch.einsum("bcd,bod->boc", [embedding, heads])
|
|
568
568
|
scores = scores + score_offset[:, None]
|
|
569
569
|
weights = torch.softmax(scores, dim=2).nan_to_num() # over n_chans
|
|
570
|
-
# (B, out, n_chans) @ (B, n_chans, T) -> (B, out, T)
|
|
571
|
-
# (
|
|
572
|
-
# ``weights @ x`` feeding a convolution's backward.
|
|
573
|
-
if x.device.type == "hpu":
|
|
574
|
-
out = (x.transpose(1, 2) @ weights.transpose(1, 2)).transpose(1, 2)
|
|
575
|
-
else:
|
|
576
|
-
out = weights @ x
|
|
577
|
-
return out # (B, out_channels, T)
|
|
570
|
+
# (B, out, n_chans) @ (B, n_chans, T) -> (B, out, T)
|
|
571
|
+
return weights @ x # (B, out_channels, T)
|
|
578
572
|
|
|
579
573
|
|
|
580
574
|
@torch.jit.unused
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
# Léo Burgund <leo.burgund@gmail.com>
|
|
9
9
|
# Sarthak Tayal <sarthaktayal2@gmail.com>
|
|
10
10
|
# Anton Soloviev <anton@praviel.com>
|
|
11
|
+
# sixty-66 <puzhexin@foxmail.com>
|
|
11
12
|
#
|
|
12
13
|
# License: BSD (3-clause)
|
|
13
14
|
|
|
@@ -656,6 +657,9 @@ def filterbank(
|
|
|
656
657
|
]
|
|
657
658
|
|
|
658
659
|
info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sampling_freq)
|
|
660
|
+
for channel, filtered_channel in zip(info["chs"], filtered.info["chs"]):
|
|
661
|
+
channel["loc"] = filtered_channel["loc"].copy()
|
|
662
|
+
channel["coord_frame"] = filtered_channel["coord_frame"]
|
|
659
663
|
|
|
660
664
|
# Copy fields from original info if they exist
|
|
661
665
|
for field in fields_to_preserve:
|
|
@@ -540,6 +540,12 @@ def create_fixed_length_windows(
|
|
|
540
540
|
flat: dict | None
|
|
541
541
|
Epoch rejection parameters based on flatness of signals. If None, no
|
|
542
542
|
rejection based on flatness is done. See mne.Epochs.
|
|
543
|
+
targets_from : {"metadata", "channels"}
|
|
544
|
+
Read targets from the recording description or from the selected
|
|
545
|
+
channels of type ``misc``. The latter are removed from the inputs.
|
|
546
|
+
last_target_only : bool
|
|
547
|
+
When reading targets from channels, return the last sample of each
|
|
548
|
+
target channel. If False, return the full target time series.
|
|
543
549
|
lazy_metadata: bool
|
|
544
550
|
If True, metadata is not computed immediately, but only when accessed
|
|
545
551
|
by using the _LazyDataFrame (experimental). Cannot be used together
|
|
@@ -1102,14 +1108,10 @@ def _create_fixed_length_windows(
|
|
|
1102
1108
|
windows_ds = WindowsDataset(
|
|
1103
1109
|
mne_epochs,
|
|
1104
1110
|
ds.description,
|
|
1111
|
+
targets_from=targets_from,
|
|
1112
|
+
last_target_only=last_target_only,
|
|
1105
1113
|
)
|
|
1106
1114
|
else:
|
|
1107
|
-
window_kwargs.append(
|
|
1108
|
-
(
|
|
1109
|
-
EEGWindowsDataset.__name__,
|
|
1110
|
-
{"targets_from": targets_from, "last_target_only": last_target_only},
|
|
1111
|
-
)
|
|
1112
|
-
)
|
|
1113
1115
|
windows_ds = EEGWindowsDataset(
|
|
1114
1116
|
ds.raw,
|
|
1115
1117
|
metadata=metadata,
|
|
@@ -1117,6 +1119,12 @@ def _create_fixed_length_windows(
|
|
|
1117
1119
|
targets_from=targets_from,
|
|
1118
1120
|
last_target_only=last_target_only,
|
|
1119
1121
|
)
|
|
1122
|
+
window_kwargs.append(
|
|
1123
|
+
(
|
|
1124
|
+
type(windows_ds).__name__,
|
|
1125
|
+
{"targets_from": targets_from, "last_target_only": last_target_only},
|
|
1126
|
+
)
|
|
1127
|
+
)
|
|
1120
1128
|
# add window_kwargs and raw_preproc_kwargs to windows dataset
|
|
1121
1129
|
setattr(windows_ds, "window_kwargs", window_kwargs)
|
|
1122
1130
|
kwargs_name = "raw_preproc_kwargs"
|
braindecode/util.py
CHANGED
|
@@ -340,48 +340,34 @@ def create_mne_dummy_raw(
|
|
|
340
340
|
return raw, save_fname
|
|
341
341
|
|
|
342
342
|
|
|
343
|
-
# MNE 1.13 renamed these
|
|
344
|
-
#
|
|
345
|
-
# ``mne>=1.11``, the spelling has to be resolved against the installed MNE
|
|
346
|
-
# version instead of being hard-coded. The rename does not change electrode
|
|
347
|
-
# positions: the new montage files are byte-identical to the legacy ones.
|
|
343
|
+
# MNE 1.13 renamed these montages (mne-python#13903); the legacy names warn and
|
|
344
|
+
# will raise in MNE 1.14. The positions are unchanged.
|
|
348
345
|
_RENAMED_STANDARD_MONTAGES = {
|
|
349
346
|
"standard_1005": "colin27_1005",
|
|
350
347
|
"standard_1020": "colin27_1020",
|
|
348
|
+
"standard_alphabetic": "colin27_alphabetic",
|
|
349
|
+
"standard_postfixed": "colin27_postfixed",
|
|
350
|
+
"standard_prefixed": "colin27_prefixed",
|
|
351
|
+
"standard_primed": "colin27_primed",
|
|
351
352
|
}
|
|
352
353
|
|
|
353
354
|
|
|
354
355
|
def resolve_montage_name(name):
|
|
355
|
-
"""
|
|
356
|
-
|
|
357
|
-
MNE 1.13 renamed the ``standard_1005`` and ``standard_1020`` montages to
|
|
358
|
-
``colin27_1005`` and ``colin27_1020`` and deprecated the legacy names,
|
|
359
|
-
which will raise in MNE 1.14 [1]_. As braindecode supports ``mne>=1.11``,
|
|
360
|
-
this helper returns the spelling understood by the installed MNE version,
|
|
361
|
-
so that neither a ``FutureWarning`` (MNE >= 1.13) nor a ``ValueError``
|
|
362
|
-
(MNE < 1.13, new names unknown) can occur.
|
|
356
|
+
"""Return the current MNE name for a standard montage.
|
|
363
357
|
|
|
364
358
|
Parameters
|
|
365
359
|
----------
|
|
366
360
|
name : str
|
|
367
|
-
|
|
368
|
-
|
|
361
|
+
A standard montage name. The legacy ``standard_*`` names that MNE
|
|
362
|
+
1.13 renamed to ``colin27_*`` are also accepted.
|
|
369
363
|
|
|
370
364
|
Returns
|
|
371
365
|
-------
|
|
372
366
|
str
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
is returned.
|
|
376
|
-
|
|
377
|
-
References
|
|
378
|
-
----------
|
|
379
|
-
.. [1] https://github.com/mne-tools/mne-python/pull/13903
|
|
367
|
+
The corresponding MNE montage name, with the ``colin27_*`` name used
|
|
368
|
+
for each renamed montage.
|
|
380
369
|
"""
|
|
381
|
-
|
|
382
|
-
if new_name is not None and new_name in mne.channels.get_builtin_montages():
|
|
383
|
-
return new_name
|
|
384
|
-
return name
|
|
370
|
+
return _RENAMED_STANDARD_MONTAGES.get(name, name)
|
|
385
371
|
|
|
386
372
|
|
|
387
373
|
def _looks_like_channel_mask(tensor):
|
|
@@ -424,7 +410,14 @@ class ThrowAwayIndexLoader(object):
|
|
|
424
410
|
module = self.net.module_
|
|
425
411
|
if self._forward_params is None:
|
|
426
412
|
self._forward_params = inspect.signature(module.forward).parameters
|
|
427
|
-
|
|
413
|
+
# a channel_strategy wraps forward as (*args, **kwargs): name the
|
|
414
|
+
# signal after the class forward's first input
|
|
415
|
+
self._signal_name = next(
|
|
416
|
+
n
|
|
417
|
+
for n in inspect.signature(type(module).forward).parameters
|
|
418
|
+
if n != "self"
|
|
419
|
+
)
|
|
420
|
+
params, signal_name = self._forward_params, self._signal_name
|
|
428
421
|
any_kwarg = any(p.kind is p.VAR_KEYWORD for p in params.values())
|
|
429
422
|
hints = {
|
|
430
423
|
"ch_mask": "this model needs a constant channel count; do not use "
|
|
@@ -436,7 +429,7 @@ class ThrowAwayIndexLoader(object):
|
|
|
436
429
|
raise ValueError(
|
|
437
430
|
f"{type(module).__name__}.forward takes no {name}: {hints[name]}."
|
|
438
431
|
)
|
|
439
|
-
return {
|
|
432
|
+
return {signal_name: signal, **extras}
|
|
440
433
|
|
|
441
434
|
def __iter__(
|
|
442
435
|
self,
|
braindecode/version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "2.1.0.
|
|
1
|
+
__version__ = "2.1.0.dev182154342"
|