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
|
@@ -1030,7 +1030,7 @@ def sensors_rotation(
|
|
|
1030
1030
|
``mne`` through::
|
|
1031
1031
|
|
|
1032
1032
|
>>> ten_twenty_montage = mne.channels.make_standard_montage(
|
|
1033
|
-
... '
|
|
1033
|
+
... 'colin27_1020'
|
|
1034
1034
|
... ).get_positions()['ch_pos']
|
|
1035
1035
|
axis : 'x' | 'y' | 'z'
|
|
1036
1036
|
Axis around which to rotate.
|
|
@@ -740,7 +740,7 @@ class SensorsRotation(Transform):
|
|
|
740
740
|
`mne` through::
|
|
741
741
|
|
|
742
742
|
>>> ten_twenty_montage = mne.channels.make_standard_montage(
|
|
743
|
-
... '
|
|
743
|
+
... 'colin27_1020'
|
|
744
744
|
... ).get_positions()['ch_pos']
|
|
745
745
|
|
|
746
746
|
axis : 'x' | 'y' | 'z', optional
|
braindecode/datasets/base.py
CHANGED
|
@@ -204,6 +204,19 @@ def _channel_info(mne_obj):
|
|
|
204
204
|
return n_ch, type_str, sfreq
|
|
205
205
|
|
|
206
206
|
|
|
207
|
+
def _check_window_targets(targets_from, info):
|
|
208
|
+
if targets_from not in ("metadata", "channels"):
|
|
209
|
+
raise ValueError("Wrong value for parameter `targets_from`.")
|
|
210
|
+
if targets_from == "channels":
|
|
211
|
+
if not isinstance(info, mne.Info): # lazy Zarr stores hold serialized Info
|
|
212
|
+
info = mne.Info.from_json_dict(info)
|
|
213
|
+
if "misc" not in info.get_channel_types():
|
|
214
|
+
raise ValueError(
|
|
215
|
+
"targets_from='channels' requires a misc channel in the selected channels."
|
|
216
|
+
)
|
|
217
|
+
return targets_from
|
|
218
|
+
|
|
219
|
+
|
|
207
220
|
def _compute_ch_pos(info, targets_from):
|
|
208
221
|
"""Return ``(n_ch, 3)`` float32 electrode positions aligned to ``X``'s rows.
|
|
209
222
|
|
|
@@ -870,9 +883,7 @@ class EEGWindowsDataset(_ZarrMixin, RecordDataset):
|
|
|
870
883
|
self.metadata = metadata
|
|
871
884
|
|
|
872
885
|
self.last_target_only = last_target_only
|
|
873
|
-
|
|
874
|
-
raise ValueError("Wrong value for parameter `targets_from`.")
|
|
875
|
-
self.targets_from = targets_from
|
|
886
|
+
self.targets_from = _check_window_targets(targets_from, raw.info)
|
|
876
887
|
self.crop_inds = metadata.loc[
|
|
877
888
|
:, ["i_window_in_trial", "i_start_in_trial", "i_stop_in_trial"]
|
|
878
889
|
].to_numpy()
|
|
@@ -899,9 +910,7 @@ class EEGWindowsDataset(_ZarrMixin, RecordDataset):
|
|
|
899
910
|
obj._raw = None
|
|
900
911
|
obj.metadata = metadata
|
|
901
912
|
obj.last_target_only = last_target_only
|
|
902
|
-
|
|
903
|
-
raise ValueError("Wrong value for parameter `targets_from`.")
|
|
904
|
-
obj.targets_from = targets_from
|
|
913
|
+
obj.targets_from = _check_window_targets(targets_from, info_dict)
|
|
905
914
|
obj.crop_inds = metadata.loc[
|
|
906
915
|
:, ["i_window_in_trial", "i_start_in_trial", "i_stop_in_trial"]
|
|
907
916
|
].to_numpy()
|
|
@@ -1133,9 +1142,7 @@ class WindowsDataset(_ZarrMixin, RecordDataset):
|
|
|
1133
1142
|
)
|
|
1134
1143
|
self.windows = windows
|
|
1135
1144
|
self.last_target_only = last_target_only
|
|
1136
|
-
|
|
1137
|
-
raise ValueError("Wrong value for parameter `targets_from`.")
|
|
1138
|
-
self.targets_from = targets_from
|
|
1145
|
+
self.targets_from = _check_window_targets(targets_from, windows.info)
|
|
1139
1146
|
|
|
1140
1147
|
metadata = self.windows.metadata
|
|
1141
1148
|
assert metadata is not None, "WindowsDataset requires windows with metadata."
|
|
@@ -1169,9 +1176,7 @@ class WindowsDataset(_ZarrMixin, RecordDataset):
|
|
|
1169
1176
|
obj.target_name = target_name
|
|
1170
1177
|
obj._fast_disk = False
|
|
1171
1178
|
obj.last_target_only = last_target_only
|
|
1172
|
-
|
|
1173
|
-
raise ValueError("Wrong value for parameter `targets_from`.")
|
|
1174
|
-
obj.targets_from = targets_from
|
|
1179
|
+
obj.targets_from = _check_window_targets(targets_from, info_dict)
|
|
1175
1180
|
obj.metadata = metadata
|
|
1176
1181
|
obj.crop_inds = metadata.loc[
|
|
1177
1182
|
:, ["i_window_in_trial", "i_start_in_trial", "i_stop_in_trial"]
|
braindecode/datasets/bids/hub.py
CHANGED
|
@@ -805,6 +805,8 @@ class HubDatasetMixin:
|
|
|
805
805
|
compressor,
|
|
806
806
|
target_name,
|
|
807
807
|
)
|
|
808
|
+
grp.attrs["targets_from"] = ds.targets_from
|
|
809
|
+
grp.attrs["last_target_only"] = ds.last_target_only
|
|
808
810
|
|
|
809
811
|
elif dataset_type == "EEGWindowsDataset":
|
|
810
812
|
# Get continuous raw data and metadata from EEGWindowsDataset
|
|
@@ -913,6 +915,9 @@ class HubDatasetMixin:
|
|
|
913
915
|
data, metadata, description, info_dict, target_name = (
|
|
914
916
|
_load_windows_from_zarr(grp, preload)
|
|
915
917
|
)
|
|
918
|
+
# Stores written before these attributes existed used metadata.
|
|
919
|
+
targets_from = grp.attrs.get("targets_from", "metadata")
|
|
920
|
+
last_target_only = grp.attrs.get("last_target_only", True)
|
|
916
921
|
|
|
917
922
|
if preload:
|
|
918
923
|
# Convert to MNE objects and create dataset
|
|
@@ -932,7 +937,12 @@ class HubDatasetMixin:
|
|
|
932
937
|
epochs = mne.EpochsArray(
|
|
933
938
|
data, info, events=events, metadata=metadata
|
|
934
939
|
)
|
|
935
|
-
ds = WindowsDataset(
|
|
940
|
+
ds = WindowsDataset(
|
|
941
|
+
epochs,
|
|
942
|
+
description,
|
|
943
|
+
targets_from=targets_from,
|
|
944
|
+
last_target_only=last_target_only,
|
|
945
|
+
)
|
|
936
946
|
if target_name is not None:
|
|
937
947
|
ds.target_name = target_name
|
|
938
948
|
else:
|
|
@@ -943,6 +953,8 @@ class HubDatasetMixin:
|
|
|
943
953
|
description=description,
|
|
944
954
|
info_dict=info_dict,
|
|
945
955
|
target_name=target_name,
|
|
956
|
+
targets_from=targets_from,
|
|
957
|
+
last_target_only=last_target_only,
|
|
946
958
|
)
|
|
947
959
|
|
|
948
960
|
elif dataset_type == "EEGWindowsDataset":
|
|
@@ -305,6 +305,13 @@ def _load_parallel(path, i, preload, is_raw, has_stored_windows):
|
|
|
305
305
|
for kwargs in window_kwargs
|
|
306
306
|
if kwargs[0] in ("WindowsDataset", "EEGWindowsDataset")
|
|
307
307
|
]
|
|
308
|
+
if not windows_ds_kwargs:
|
|
309
|
+
# Older fixed-length Epochs stores only recorded the windower arguments.
|
|
310
|
+
windows_ds_kwargs = [
|
|
311
|
+
params
|
|
312
|
+
for name, params in window_kwargs
|
|
313
|
+
if name == "create_fixed_length_windows"
|
|
314
|
+
]
|
|
308
315
|
windows_ds_kwargs = windows_ds_kwargs[0] if len(windows_ds_kwargs) == 1 else {}
|
|
309
316
|
if is_raw:
|
|
310
317
|
metadata = pd.read_pickle(path / i / "metadata_df.pkl")
|
|
@@ -6,6 +6,12 @@ from .channel_mask import (
|
|
|
6
6
|
pack_channels,
|
|
7
7
|
unpack_channels,
|
|
8
8
|
)
|
|
9
|
+
from .channels import (
|
|
10
|
+
derivation_matrix,
|
|
11
|
+
exact_derivation,
|
|
12
|
+
linear_channel_map,
|
|
13
|
+
spherical_spline_kernel,
|
|
14
|
+
)
|
|
9
15
|
from .functions import (
|
|
10
16
|
_get_gaussian_kernel1d,
|
|
11
17
|
apply_rotary,
|
|
@@ -41,12 +47,15 @@ __all__ = [
|
|
|
41
47
|
"apply_rotary",
|
|
42
48
|
"check_ch_mask",
|
|
43
49
|
"daubechies_filters",
|
|
50
|
+
"derivation_matrix",
|
|
44
51
|
"drop_path",
|
|
45
52
|
"dwt_max_level",
|
|
53
|
+
"exact_derivation",
|
|
46
54
|
"fft_conv1d",
|
|
47
55
|
"hilbert_freq",
|
|
48
56
|
"identity",
|
|
49
57
|
"iou_1d",
|
|
58
|
+
"linear_channel_map",
|
|
50
59
|
"masked_group_norm",
|
|
51
60
|
"masked_mean",
|
|
52
61
|
"pack_channels",
|
|
@@ -62,6 +71,7 @@ __all__ = [
|
|
|
62
71
|
"safe_log",
|
|
63
72
|
"scaled_dot_product_attention",
|
|
64
73
|
"sinusoidal_positional_encoding",
|
|
74
|
+
"spherical_spline_kernel",
|
|
65
75
|
"spectral_input",
|
|
66
76
|
"square",
|
|
67
77
|
"unpack_channels",
|
|
@@ -12,13 +12,6 @@ import torch.nn.functional as F
|
|
|
12
12
|
from torch import Tensor
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
@torch.jit.unused
|
|
16
|
-
def _hpu_lazy() -> bool:
|
|
17
|
-
from habana_frameworks.torch.utils.internal import is_lazy
|
|
18
|
-
|
|
19
|
-
return is_lazy()
|
|
20
|
-
|
|
21
|
-
|
|
22
15
|
def _sdpa_math_dropout(
|
|
23
16
|
query: Tensor,
|
|
24
17
|
key: Tensor,
|
|
@@ -81,8 +74,8 @@ def scaled_dot_product_attention(
|
|
|
81
74
|
-----
|
|
82
75
|
On Intel Gaudi, torch's SDPA runs op by op unless Habana's attention
|
|
83
76
|
setting is on; then the bridge's fused kernel runs it, with or without a
|
|
84
|
-
mask (:ref:`install_gaudi`)
|
|
85
|
-
keeps torch's math path
|
|
77
|
+
mask (:ref:`install_gaudi`), dropout included. On CPU, dropout on float32
|
|
78
|
+
or float64 inputs without a mask keeps torch's math path.
|
|
86
79
|
"""
|
|
87
80
|
if exact:
|
|
88
81
|
scores = torch.matmul(query, key.transpose(-2, -1))
|
|
@@ -104,12 +97,9 @@ def scaled_dot_product_attention(
|
|
|
104
97
|
and dropout_p > 0.0
|
|
105
98
|
and attn_mask is None
|
|
106
99
|
and (query.dtype == torch.float32 or query.dtype == torch.float64)
|
|
107
|
-
and
|
|
108
|
-
query.device.type == "cpu"
|
|
109
|
-
or (query.device.type == "hpu" and not _hpu_lazy())
|
|
110
|
-
)
|
|
100
|
+
and query.device.type == "cpu"
|
|
111
101
|
):
|
|
112
|
-
# CPU
|
|
102
|
+
# The CPU runs SDPA with dropout through the math path.
|
|
113
103
|
return _sdpa_math_dropout(query, key, value, dropout_p, scale)
|
|
114
104
|
if scale is None: # torch 2.0's signature has no ``scale``
|
|
115
105
|
return F.scaled_dot_product_attention(
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
# Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
|
|
2
|
+
#
|
|
3
|
+
# License: BSD (3-clause)
|
|
4
|
+
r"""Channels as linear measurements of the scalp potential.
|
|
5
|
+
|
|
6
|
+
Every channel is a linear combination of electrode potentials ``v``: ``A`` is
|
|
7
|
+
``V(A)`` against the recording reference, ``A-B`` is ``V(A) - V(B)``
|
|
8
|
+
(:func:`derivation_matrix`). The inputs are ``y = A v`` and the channels a
|
|
9
|
+
model wants are ``t = B v``, so re-montaging, re-referencing and interpolation
|
|
10
|
+
are all one linear estimate of ``B v`` from ``A v`` (:func:`linear_channel_map`).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import torch
|
|
17
|
+
from torch import Tensor
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def derivation_matrix(
|
|
21
|
+
ch_names: list[str],
|
|
22
|
+
electrodes: list[str] | None = None,
|
|
23
|
+
reference: str | None = None,
|
|
24
|
+
) -> tuple[Tensor, list[str]]:
|
|
25
|
+
"""Each channel as a row over electrode potentials.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
ch_names : list of str
|
|
30
|
+
``"A"`` is ``V(A)``, ``"A-B"`` is ``V(A) - V(B)``. Names are compared
|
|
31
|
+
ignoring case; any other name is one electrode.
|
|
32
|
+
electrodes : list of str, optional
|
|
33
|
+
Columns (lower case). Defaults to the electrodes of ``ch_names`` in
|
|
34
|
+
order of appearance; electrodes missing from the list are added.
|
|
35
|
+
reference : str, optional
|
|
36
|
+
Reference of the single-electrode channels: ``None`` (the recording's,
|
|
37
|
+
left implicit), an electrode name (``"Cz"``: ``A`` is ``V(A) - V(Cz)``)
|
|
38
|
+
or ``"average"`` (``A`` minus the mean of the single-electrode channels).
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
matrix : torch.Tensor
|
|
43
|
+
``(n_channels, n_electrodes)``, float64.
|
|
44
|
+
electrodes : list of str
|
|
45
|
+
The columns.
|
|
46
|
+
"""
|
|
47
|
+
parts = [
|
|
48
|
+
ends if len(ends := n.lower().split("-")) == 2 and all(ends) else [n.lower()]
|
|
49
|
+
for n in ch_names
|
|
50
|
+
]
|
|
51
|
+
if reference is not None and reference != "average":
|
|
52
|
+
parts = [p if len(p) == 2 else [p[0], reference.lower()] for p in parts]
|
|
53
|
+
electrodes = list(
|
|
54
|
+
dict.fromkeys([*(e.lower() for e in (electrodes or [])), *sum(parts, [])])
|
|
55
|
+
)
|
|
56
|
+
matrix = torch.zeros(len(ch_names), len(electrodes), dtype=torch.float64)
|
|
57
|
+
for row, ends in enumerate(parts):
|
|
58
|
+
matrix[row, electrodes.index(ends[0])] += 1.0
|
|
59
|
+
if len(ends) == 2:
|
|
60
|
+
matrix[row, electrodes.index(ends[1])] -= 1.0
|
|
61
|
+
if reference == "average":
|
|
62
|
+
single = torch.tensor([len(p) == 1 for p in parts])
|
|
63
|
+
matrix[single] -= matrix[single].mean(0)
|
|
64
|
+
return matrix, electrodes
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def linear_channel_map(
|
|
68
|
+
A: Tensor,
|
|
69
|
+
B: Tensor,
|
|
70
|
+
cov: Tensor,
|
|
71
|
+
noise: float = 0.0,
|
|
72
|
+
flat: Tensor | None = None,
|
|
73
|
+
match_gain: bool = False,
|
|
74
|
+
atol: float = 1e-9,
|
|
75
|
+
) -> tuple[Tensor, Tensor]:
|
|
76
|
+
r"""Best linear estimate of the channels ``B v`` from the channels ``A v``.
|
|
77
|
+
|
|
78
|
+
The electrode potentials :math:`v` have prior covariance :math:`\Sigma`
|
|
79
|
+
(``cov``), plus an unknown offset along each column of :math:`F`
|
|
80
|
+
(``flat``: a flat prior, e.g. the unknown recording reference). The inputs
|
|
81
|
+
are :math:`y = A v + \varepsilon` with :math:`\varepsilon \sim
|
|
82
|
+
\mathcal{N}(0, \sigma^2 I)` (``noise``) and the targets are :math:`t = B v`.
|
|
83
|
+
The best linear unbiased estimate :math:`\hat t = W y` solves
|
|
84
|
+
|
|
85
|
+
.. math::
|
|
86
|
+
|
|
87
|
+
\begin{bmatrix} A \Sigma A^\top + \sigma^2 I & A F \\ (A F)^\top & 0
|
|
88
|
+
\end{bmatrix}
|
|
89
|
+
\begin{bmatrix} W^\top \\ M \end{bmatrix} =
|
|
90
|
+
\begin{bmatrix} A \Sigma B^\top \\ (B F)^\top \end{bmatrix},
|
|
91
|
+
\qquad
|
|
92
|
+
\operatorname{var}(t_k - \hat t_k) = \big[B \Sigma B^\top
|
|
93
|
+
- W A \Sigma B^\top - (B F) M\big]_{kk},
|
|
94
|
+
|
|
95
|
+
which is kriging [Matheron1963]_, universal kriging when :math:`F` is
|
|
96
|
+
given [Matheron1969]_, and the posterior mean and variance of a Gaussian
|
|
97
|
+
process [Rasmussen2006]_. Without ``flat`` it is
|
|
98
|
+
:math:`W = B \Sigma A^\top (A \Sigma A^\top + \sigma^2 I)^{-1}`. The choice
|
|
99
|
+
of :math:`\Sigma` gives the known methods:
|
|
100
|
+
|
|
101
|
+
- :math:`\Sigma = 0` and :math:`F = I` (every potential unknown): the
|
|
102
|
+
exact derivations of :func:`exact_derivation`, ``W = B A^+``, such as
|
|
103
|
+
bipolar or Laplacian (source) derivations [Hjorth1975]_; a target is
|
|
104
|
+
exact when :math:`B F` lies in the span of :math:`A F`.
|
|
105
|
+
- the spherical-spline kernel (:func:`spherical_spline_kernel`), ``noise``
|
|
106
|
+
the regularisation and :math:`F = \mathbf 1` (the unknown reference):
|
|
107
|
+
spherical-spline interpolation [Perrin1989]_, which is spline smoothing on
|
|
108
|
+
the sphere [Wahba1981]_ and the Gaussian-process estimate with that kernel
|
|
109
|
+
[Kimeldorf1970]_.
|
|
110
|
+
- :math:`\Sigma = L L^\top` for a lead field :math:`L`: the minimum-norm
|
|
111
|
+
estimate [Hamalainen1994]_; with the targets taken against a point at
|
|
112
|
+
infinity (zero potential) it is REST re-referencing [Yao2001]_.
|
|
113
|
+
- a covariance fitted on dense recordings: the Wiener (linear MMSE) filter.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
A : torch.Tensor
|
|
118
|
+
``(n_inputs, n_electrodes)`` input channels (:func:`derivation_matrix`).
|
|
119
|
+
B : torch.Tensor
|
|
120
|
+
``(n_targets, n_electrodes)`` target channels.
|
|
121
|
+
cov : torch.Tensor
|
|
122
|
+
``(n_electrodes, n_electrodes)`` prior covariance :math:`\Sigma`.
|
|
123
|
+
noise : float
|
|
124
|
+
Input noise variance :math:`\sigma^2` (the regularisation).
|
|
125
|
+
flat : torch.Tensor, optional
|
|
126
|
+
``(n_electrodes, n_flat)`` directions :math:`F` with a flat prior.
|
|
127
|
+
match_gain : bool
|
|
128
|
+
Rescale the part of each row free of the flat constraint (so
|
|
129
|
+
:math:`W A F = B F` still holds) so that the estimate has, as closely as
|
|
130
|
+
that constraint allows, the prior variance of its
|
|
131
|
+
target, :math:`[W A \Sigma A^\top W^\top]_{kk} = [B \Sigma B^\top]_{kk}`:
|
|
132
|
+
the minimum-variance estimate shrinks the amplitude.
|
|
133
|
+
atol : float
|
|
134
|
+
Largest residual of :math:`B F` from the span of :math:`A F` for a
|
|
135
|
+
target to be estimable (the flat part alone, whatever :math:`\Sigma`).
|
|
136
|
+
|
|
137
|
+
Returns
|
|
138
|
+
-------
|
|
139
|
+
weight : torch.Tensor
|
|
140
|
+
``(n_targets, n_inputs)``, float64; rows of targets that cannot be
|
|
141
|
+
estimated (``W A F != B F``) are 0.
|
|
142
|
+
variance : torch.Tensor
|
|
143
|
+
``(n_targets,)`` posterior variance (of the estimate before
|
|
144
|
+
``match_gain``); ``inf`` where not estimable.
|
|
145
|
+
|
|
146
|
+
References
|
|
147
|
+
----------
|
|
148
|
+
.. [Matheron1963] Matheron, G. (1963). Principles of geostatistics.
|
|
149
|
+
Economic Geology, 58(8), 1246-1266. https://doi.org/10.2113/gsecongeo.58.8.1246
|
|
150
|
+
.. [Matheron1969] Matheron, G. (1969). Le krigeage universel. Cahiers du
|
|
151
|
+
Centre de Morphologie Mathématique, 1. École des Mines de Paris.
|
|
152
|
+
https://www.cg.minesparis.psl.eu/bibliotheque/public/MATHERON_Ouvrage_00131.pdf
|
|
153
|
+
.. [Kimeldorf1970] Kimeldorf, G. S., & Wahba, G. (1970). A correspondence
|
|
154
|
+
between Bayesian estimation on stochastic processes and smoothing by
|
|
155
|
+
splines. The Annals of Mathematical Statistics, 41(2), 495-502.
|
|
156
|
+
https://doi.org/10.1214/aoms/1177697089
|
|
157
|
+
.. [Hjorth1975] Hjorth, B. (1975). An on-line transformation of EEG scalp
|
|
158
|
+
potentials into orthogonal source derivations. Electroencephalography and
|
|
159
|
+
Clinical Neurophysiology, 39(5), 526-530.
|
|
160
|
+
https://doi.org/10.1016/0013-4694(75)90056-5
|
|
161
|
+
.. [Wahba1981] Wahba, G. (1981). Spline interpolation and smoothing on the
|
|
162
|
+
sphere. SIAM Journal on Scientific and Statistical Computing, 2(1), 5-16.
|
|
163
|
+
https://doi.org/10.1137/0902002
|
|
164
|
+
.. [Perrin1989] Perrin, F., Pernier, J., Bertrand, O., & Echallier, J. F.
|
|
165
|
+
(1989). Spherical splines for scalp potential and current density
|
|
166
|
+
mapping. Electroencephalography and Clinical Neurophysiology, 72(2),
|
|
167
|
+
184-187. https://doi.org/10.1016/0013-4694(89)90180-6
|
|
168
|
+
.. [Hamalainen1994] Hämäläinen, M. S., & Ilmoniemi, R. J. (1994).
|
|
169
|
+
Interpreting magnetic fields of the brain: minimum norm estimates.
|
|
170
|
+
Medical & Biological Engineering & Computing, 32(1), 35-42.
|
|
171
|
+
https://doi.org/10.1007/BF02512476
|
|
172
|
+
.. [Yao2001] Yao, D. (2001). A method to standardize a reference of scalp
|
|
173
|
+
EEG recordings to a point at infinity. Physiological Measurement, 22(4),
|
|
174
|
+
693-711. https://doi.org/10.1088/0967-3334/22/4/305
|
|
175
|
+
.. [Rasmussen2006] Rasmussen, C. E., & Williams, C. K. I. (2006). Gaussian
|
|
176
|
+
Processes for Machine Learning. MIT Press.
|
|
177
|
+
https://doi.org/10.7551/mitpress/3206.001.0001
|
|
178
|
+
"""
|
|
179
|
+
A, B, cov = (torch.as_tensor(t, dtype=torch.float64) for t in (A, B, cov))
|
|
180
|
+
F = A.new_zeros(len(cov), 0) if flat is None else torch.as_tensor(flat).to(A)
|
|
181
|
+
n, f = len(A), F.shape[1]
|
|
182
|
+
AF, BF, K, KyT = A @ F, B @ F, A @ cov @ A.T, A @ cov @ B.T
|
|
183
|
+
M = A.new_zeros(n + f, n + f)
|
|
184
|
+
M[:n, :n] = K + noise * torch.eye(n, dtype=A.dtype, device=A.device)
|
|
185
|
+
M[:n, n:], M[n:, :n] = AF, AF.T
|
|
186
|
+
sol = torch.linalg.pinv(M) @ torch.cat([KyT, BF.T]) # SVD cutoff, as scipy/MNE
|
|
187
|
+
W, mu = sol[:n].T, sol[n:]
|
|
188
|
+
prior = (B @ cov * B).sum(1)
|
|
189
|
+
var = prior - (W * KyT.T).sum(1) - (mu.T * BF).sum(1)
|
|
190
|
+
W0 = BF @ torch.linalg.pinv(AF) # the flat part: W0 A F = B F when estimable
|
|
191
|
+
ok = (
|
|
192
|
+
(W0 @ AF - BF).abs().amax(1) <= atol
|
|
193
|
+
if f
|
|
194
|
+
else torch.ones(len(B), dtype=torch.bool, device=A.device)
|
|
195
|
+
)
|
|
196
|
+
if match_gain: # (W0 + s D) K (W0 + s D)^T = prior, D = W - W0, per row
|
|
197
|
+
D = W - W0
|
|
198
|
+
a, b, c = ((D @ K) * D).sum(1), ((D @ K) * W0).sum(1), ((W0 @ K) * W0).sum(1)
|
|
199
|
+
root = (b**2 - a * (c - prior)).clamp_min(0).sqrt()
|
|
200
|
+
W = W0 + torch.where(a > 0, (root - b) / a, 1.0)[:, None] * D
|
|
201
|
+
return W * ok[:, None], torch.where(ok, var.clamp_min(0), torch.inf)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def spherical_spline_kernel(
|
|
205
|
+
pos_a: Tensor, pos_b: Tensor, stiffness: int = 4, n_terms: int = 50
|
|
206
|
+
) -> Tensor:
|
|
207
|
+
r"""Spherical-spline covariance :math:`g(\cos\gamma)` between two sets of positions.
|
|
208
|
+
|
|
209
|
+
:math:`g(x) = \frac{1}{4\pi}\sum_{n=1}^{N} \frac{2n + 1}{(n (n + 1))^m}
|
|
210
|
+
P_n(x)`, with :math:`P_n` the Legendre polynomials, :math:`\gamma` the
|
|
211
|
+
angle between the positions seen from the origin, :math:`m` the
|
|
212
|
+
``stiffness`` and :math:`N` the number of terms (MNE's defaults: 4 and 50), as
|
|
213
|
+
in [Perrin1989]_.
|
|
214
|
+
Positions are taken from the origin: subtract the head centre first. Pass
|
|
215
|
+
it, or any function with this signature, to
|
|
216
|
+
:class:`~braindecode.modules.ChannelLayer` as the strategy.
|
|
217
|
+
|
|
218
|
+
Parameters
|
|
219
|
+
----------
|
|
220
|
+
pos_a, pos_b : torch.Tensor
|
|
221
|
+
``(n_a, 3)`` and ``(n_b, 3)`` positions.
|
|
222
|
+
stiffness : int
|
|
223
|
+
:math:`m`.
|
|
224
|
+
n_terms : int
|
|
225
|
+
:math:`N`.
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
-------
|
|
229
|
+
torch.Tensor
|
|
230
|
+
``(n_a, n_b)``, float64.
|
|
231
|
+
|
|
232
|
+
References
|
|
233
|
+
----------
|
|
234
|
+
.. [Perrin1989] Perrin, F., Pernier, J., Bertrand, O., & Echallier, J. F.
|
|
235
|
+
(1989). Spherical splines for scalp potential and current density
|
|
236
|
+
mapping. Electroencephalography and Clinical Neurophysiology, 72(2),
|
|
237
|
+
184-187. https://doi.org/10.1016/0013-4694(89)90180-6
|
|
238
|
+
"""
|
|
239
|
+
a, b = (
|
|
240
|
+
torch.nn.functional.normalize(torch.as_tensor(p, dtype=torch.float64), dim=1)
|
|
241
|
+
for p in (pos_a, pos_b)
|
|
242
|
+
)
|
|
243
|
+
n = np.arange(1, n_terms + 1, dtype=float) # int64 overflows at stiffness >= 6
|
|
244
|
+
coef = np.r_[0.0, (2 * n + 1) / ((n * (n + 1)) ** stiffness * 4 * np.pi)]
|
|
245
|
+
return torch.as_tensor(
|
|
246
|
+
np.polynomial.legendre.legval((a @ b.T).clamp(-1, 1).numpy(), coef)
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def exact_derivation(
|
|
251
|
+
target: list[str], inputs: list[str], atol: float = 1e-9
|
|
252
|
+
) -> tuple[Tensor, Tensor]:
|
|
253
|
+
"""``W`` with ``W @ x`` the ``target`` channels, from the ``inputs`` ``x``.
|
|
254
|
+
|
|
255
|
+
A target is exact when its row of :func:`derivation_matrix` is a
|
|
256
|
+
combination of the input rows: ``F3-C3`` from ``C3-F3`` (weight ``-1``),
|
|
257
|
+
``F3-P3`` from ``F3-C3`` and ``C3-P3``, ``F3-C3`` from ``F3`` and ``C3``.
|
|
258
|
+
This is :func:`linear_channel_map` with every potential unknown, so ``W``
|
|
259
|
+
is the minimum-norm solution and duplicate measurements are averaged.
|
|
260
|
+
No reference is guessed: ``F3-C3`` is not exact from ``F3-R1`` and
|
|
261
|
+
``C3-R2``, and ``F3`` is not exact from bipolar channels alone.
|
|
262
|
+
|
|
263
|
+
Parameters
|
|
264
|
+
----------
|
|
265
|
+
target, inputs : list of str
|
|
266
|
+
Channel names, as in :func:`derivation_matrix`.
|
|
267
|
+
atol : float
|
|
268
|
+
Largest residual of an exact row.
|
|
269
|
+
|
|
270
|
+
Returns
|
|
271
|
+
-------
|
|
272
|
+
weight : torch.Tensor
|
|
273
|
+
``(len(target), len(inputs))``, float64; rows of non-exact targets are 0.
|
|
274
|
+
exact : torch.Tensor
|
|
275
|
+
``(len(target),)`` bool.
|
|
276
|
+
"""
|
|
277
|
+
R, electrodes = derivation_matrix(inputs)
|
|
278
|
+
T, electrodes = derivation_matrix(target, electrodes)
|
|
279
|
+
R = torch.nn.functional.pad(R, (0, T.shape[1] - R.shape[1]))
|
|
280
|
+
eye = torch.eye(T.shape[1], dtype=torch.float64)
|
|
281
|
+
weight, var = linear_channel_map(R, T, 0 * eye, flat=eye, atol=atol)
|
|
282
|
+
return weight.round(decimals=12) + 0.0, torch.isfinite(var) # -1.0, not -0.99..
|
braindecode/models/__init__.py
CHANGED
|
@@ -54,11 +54,16 @@ if TYPE_CHECKING:
|
|
|
54
54
|
from .fbcnet import FBCNet
|
|
55
55
|
from .fblightconvnet import FBLightConvNet
|
|
56
56
|
from .fbmsnet import FBMSNet
|
|
57
|
+
from .fnirs4d import FNIRS4D
|
|
58
|
+
from .fnirs_cnn1d import FNIRSCNN1D
|
|
59
|
+
from .fnirs_t import FNIRST, FNIRSPreT
|
|
57
60
|
from .fnirsnet import FNIRSNet
|
|
58
61
|
from .gcnsnet import GCNsNet
|
|
62
|
+
from .geonirs import GeoNIRS
|
|
59
63
|
from .guetschel2026 import Guetschel2026
|
|
60
64
|
from .hybrid import HybridNet
|
|
61
65
|
from .ifnet import IFNet
|
|
66
|
+
from .jung_mae import JungMAE
|
|
62
67
|
from .labram import Labram
|
|
63
68
|
from .luna import LUNA
|
|
64
69
|
from .mapa import MAPA
|
|
@@ -69,6 +74,7 @@ if TYPE_CHECKING:
|
|
|
69
74
|
from .mirepnet import MIRepNet
|
|
70
75
|
from .mscformer import MSCFormer
|
|
71
76
|
from .msvtnet import MSVTNet
|
|
77
|
+
from .mtrenirs import MtReNIRS
|
|
72
78
|
from .mvpformer import MVPFormer
|
|
73
79
|
from .neuropose import NeuroPose
|
|
74
80
|
from .neurorvq import NeuroRVQ
|
braindecode/models/attn_sleep.py
CHANGED
|
@@ -95,6 +95,12 @@ class AttnSleep(EEGModuleMixin, nn.Module):
|
|
|
95
95
|
Activation function class to apply in the multi-resolution CNN layer.
|
|
96
96
|
Should be a PyTorch activation module class like ``nn.ReLU`` or
|
|
97
97
|
``nn.GELU``. Default is ``nn.GELU``.
|
|
98
|
+
attn_query_norm : bool
|
|
99
|
+
If ``True``, apply the layer norm of the attention block to the query
|
|
100
|
+
before the attention, as braindecode 1.0 to 2.0 did. If ``False``
|
|
101
|
+
(default), attend with the raw query, as the authors' code does.
|
|
102
|
+
|
|
103
|
+
.. versionadded:: 2.1
|
|
98
104
|
|
|
99
105
|
References
|
|
100
106
|
----------
|
|
@@ -124,6 +130,7 @@ class AttnSleep(EEGModuleMixin, nn.Module):
|
|
|
124
130
|
chs_info=None,
|
|
125
131
|
n_chans=None,
|
|
126
132
|
n_times=None,
|
|
133
|
+
attn_query_norm=False,
|
|
127
134
|
):
|
|
128
135
|
if (
|
|
129
136
|
sum(value is not None for value in (n_times, sfreq, input_window_seconds))
|
|
@@ -190,7 +197,12 @@ class AttnSleep(EEGModuleMixin, nn.Module):
|
|
|
190
197
|
ff = _PositionwiseFeedForward(d_model, d_ff, drop_prob, activation=activation)
|
|
191
198
|
tce = _TCE(
|
|
192
199
|
_EncoderLayer(
|
|
193
|
-
d_model,
|
|
200
|
+
d_model,
|
|
201
|
+
deepcopy(attn),
|
|
202
|
+
deepcopy(ff),
|
|
203
|
+
after_reduced_cnn_size,
|
|
204
|
+
drop_prob,
|
|
205
|
+
attn_query_norm,
|
|
194
206
|
),
|
|
195
207
|
n_tce,
|
|
196
208
|
)
|
|
@@ -205,6 +217,11 @@ class AttnSleep(EEGModuleMixin, nn.Module):
|
|
|
205
217
|
if not return_feats:
|
|
206
218
|
self.final_layer = nn.Linear(self.len_last_layer, self.n_outputs)
|
|
207
219
|
|
|
220
|
+
@classmethod
|
|
221
|
+
def _fill_legacy_defaults(cls, kwargs):
|
|
222
|
+
super()._fill_legacy_defaults(kwargs)
|
|
223
|
+
kwargs.setdefault("attn_query_norm", True)
|
|
224
|
+
|
|
208
225
|
@staticmethod
|
|
209
226
|
def _feature_length(mrcnn, n_times):
|
|
210
227
|
training_states = [(module, module.training) for module in mrcnn.modules()]
|
|
@@ -473,11 +490,18 @@ class _MultiHeadedAttention(nn.Module):
|
|
|
473
490
|
class _ResidualLayerNormAttn(nn.Module):
|
|
474
491
|
r"""A residual connection followed by a layer norm."""
|
|
475
492
|
|
|
476
|
-
def __init__(self, size, dropout, fn_attn):
|
|
493
|
+
def __init__(self, size, dropout, fn_attn, norm_query):
|
|
477
494
|
super().__init__()
|
|
478
495
|
self.norm = nn.LayerNorm(size, eps=1e-6)
|
|
479
496
|
self.dropout = nn.Dropout(dropout)
|
|
480
497
|
self.fn_attn = fn_attn
|
|
498
|
+
self.norm_query = norm_query
|
|
499
|
+
|
|
500
|
+
def __setstate__(self, state):
|
|
501
|
+
# Full models pickled before the raw-query option normalized the
|
|
502
|
+
# query. Set the flag on the instance so TorchScript also sees it.
|
|
503
|
+
state.setdefault("norm_query", True)
|
|
504
|
+
super().__setstate__(state)
|
|
481
505
|
|
|
482
506
|
def forward(
|
|
483
507
|
self,
|
|
@@ -486,9 +510,10 @@ class _ResidualLayerNormAttn(nn.Module):
|
|
|
486
510
|
value: torch.Tensor,
|
|
487
511
|
) -> torch.Tensor:
|
|
488
512
|
"""Apply residual connection to any sublayer with the same size."""
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
513
|
+
# The reference attends with the raw query. ``norm_query`` keeps the
|
|
514
|
+
# braindecode 1.0 to 2.0 behaviour.
|
|
515
|
+
query = self.norm(x) if self.norm_query else x
|
|
516
|
+
out = self.fn_attn(query, key, value)
|
|
492
517
|
|
|
493
518
|
return x + self.dropout(out)
|
|
494
519
|
|
|
@@ -537,7 +562,15 @@ class _EncoderLayer(nn.Module):
|
|
|
537
562
|
Each of these sublayers have residual and layer norm, implemented by _ResidualLayerNorm.
|
|
538
563
|
"""
|
|
539
564
|
|
|
540
|
-
def __init__(
|
|
565
|
+
def __init__(
|
|
566
|
+
self,
|
|
567
|
+
size,
|
|
568
|
+
self_attn,
|
|
569
|
+
feed_forward,
|
|
570
|
+
after_reduced_cnn_size,
|
|
571
|
+
dropout,
|
|
572
|
+
attn_query_norm,
|
|
573
|
+
):
|
|
541
574
|
super().__init__()
|
|
542
575
|
self.size = size
|
|
543
576
|
self.self_attn = self_attn
|
|
@@ -547,6 +580,7 @@ class _EncoderLayer(nn.Module):
|
|
|
547
580
|
size=size,
|
|
548
581
|
dropout=dropout,
|
|
549
582
|
fn_attn=self_attn,
|
|
583
|
+
norm_query=attn_query_norm,
|
|
550
584
|
)
|
|
551
585
|
self.residual_ff = _ResidualLayerNormFF(
|
|
552
586
|
size=size,
|