braindecode 2.1.0.dev181999048__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.
Files changed (53) hide show
  1. braindecode/augmentation/functional.py +1 -1
  2. braindecode/augmentation/transforms.py +1 -1
  3. braindecode/datasets/base.py +17 -12
  4. braindecode/datasets/bids/hub.py +13 -1
  5. braindecode/datautil/serialization.py +7 -0
  6. braindecode/functional/__init__.py +10 -0
  7. braindecode/functional/attention.py +12 -54
  8. braindecode/functional/channel_mask.py +18 -10
  9. braindecode/functional/channels.py +282 -0
  10. braindecode/models/__init__.py +7 -0
  11. braindecode/models/attn_sleep.py +40 -6
  12. braindecode/models/base.py +50 -13
  13. braindecode/models/biot.py +10 -8
  14. braindecode/models/brainmodule.py +1 -13
  15. braindecode/models/cbramod.py +9 -5
  16. braindecode/models/codebrain.py +14 -19
  17. braindecode/models/csbrain.py +12 -9
  18. braindecode/models/eegpt.py +1 -1
  19. braindecode/models/eegtcnet.py +31 -4
  20. braindecode/models/emg2qwerty.py +8 -2
  21. braindecode/models/fnirs4d.py +761 -0
  22. braindecode/models/fnirs_cnn1d.py +339 -0
  23. braindecode/models/fnirs_t.py +785 -0
  24. braindecode/models/fnirsnet.py +374 -0
  25. braindecode/models/geonirs.py +1545 -0
  26. braindecode/models/guetschel2026.py +1 -1
  27. braindecode/models/jung_mae.py +596 -0
  28. braindecode/models/labram.py +4 -18
  29. braindecode/models/luna.py +43 -33
  30. braindecode/models/mapa.py +4 -5
  31. braindecode/models/model.html.jinja +24 -9
  32. braindecode/models/msvtnet.py +1 -2
  33. braindecode/models/mtrenirs.py +1053 -0
  34. braindecode/models/patchedtransformer.py +26 -15
  35. braindecode/models/reve.py +1 -4
  36. braindecode/models/signal_jepa.py +5 -6
  37. braindecode/models/sleepfm.py +98 -23
  38. braindecode/models/summary.csv +8 -0
  39. braindecode/models/util.py +144 -1
  40. braindecode/models/zuna.py +11 -24
  41. braindecode/modules/attention.py +9 -9
  42. braindecode/modules/channels.py +170 -30
  43. braindecode/modules/layers.py +2 -8
  44. braindecode/preprocessing/preprocess.py +4 -0
  45. braindecode/preprocessing/windowers.py +14 -6
  46. braindecode/util.py +21 -28
  47. braindecode/version.py +1 -1
  48. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
  49. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +53 -45
  50. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +16 -0
  51. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
  52. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
  53. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,374 @@
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
2
+ #
3
+ # License: Apache-2.0
4
+ # Adapted from https://github.com/wzhlearning/fNIRSNet (Apache-2.0).
5
+ """fNIRSNet: Rethinking Delayed Hemodynamic Responses for fNIRS Classification."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import OrderedDict
10
+
11
+ import torch
12
+ from einops.layers.torch import Rearrange
13
+ from torch import nn
14
+
15
+ from braindecode.models.base import EEGModuleMixin
16
+ from braindecode.models.util import _disable_batch_norm_training_if_batch_size_one
17
+ from braindecode.modules import DepthwiseConv2d
18
+
19
+
20
+ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
21
+ r"""fNIRSNet from Wang et al. (2023).
22
+
23
+ :bdg-success:`Convolution`
24
+
25
+ .. figure:: https://braindecode.org/dev/_static/model/fnirsnet.png
26
+ :align: center
27
+ :alt: fNIRSNet architecture
28
+
29
+ Fig. 2 of Wang et al. (2023), cropped
30
+ (`CC BY 4.0 <https://creativecommons.org/licenses/by/4.0/>`_): "(a)
31
+ Overview architecture of fNIRSNet. (b) Schema of receptive fields. The
32
+ green and yellow feature maps are the output of DHRConv and DWConv,
33
+ respectively. [...] (c) Depthwise separable convolution."
34
+
35
+ Changes of oxygenated and deoxygenated hemoglobin (HbO, HbR) are "a slow
36
+ metabolic process manifested as delayed hemodynamic responses", and the
37
+ paper :footcite:`wang2023fnirsnet` argues that deep networks for fNIRS
38
+ ignore them: "A small kernel with a limited receptive field is
39
+ challenging to extract the features of delayed hemodynamic responses
40
+ because there is no significant change in HbO and HbR in small
41
+ neighborhoods. However, stacking more convolutional layers to obtain
42
+ larger receptive fields may cause overfitting on limited fNIRS data"
43
+ (Section I).
44
+
45
+ fNIRSNet answers with "two core ideas: 1) delayed hemodynamic responses
46
+ as domain knowledge should be introduced into fNIRS classification
47
+ models; 2) a simple and efficient model is beneficial to practical
48
+ applications on limited fNIRS data". It has "three convolutional layers
49
+ and one fully connected (FC) layer without pooling, dropout, and other
50
+ complicated structures": a convolution whose kernel spans the whole
51
+ window of one row, then one whose kernel spans all rows. With 4 and 8
52
+ filters it has 498 parameters on mental arithmetic (Table III).
53
+
54
+ .. rubric:: Architecture Overview
55
+
56
+ "fNIRSNet consists of a delayed hemodynamic response module (DHR Module)
57
+ and a global module" (Section II-B, Table I). With :math:`C` =
58
+ ``n_chans`` rows, :math:`S` = ``n_times`` samples, :math:`F_1` and
59
+ :math:`F_2` filters, and :math:`S' = S - k + 1` (1 for the paper's
60
+ kernel width :math:`k = S`)::
61
+
62
+ input (batch, C, S)
63
+ to_fnirs_tensor (batch, 1, C, S)
64
+ DHR Module: conv1 (1 x k), bn1, sigmoid (batch, F_1, C, S')
65
+ Global Module:
66
+ conv2.depth_conv (C x 1) (batch, F_1, 1, S')
67
+ conv2.point_conv (1 x 1), bn2, sigmoid (batch, F_2, 1, S')
68
+ flatten, final_layer (FC) (batch, n_outputs)
69
+
70
+ .. rubric:: Macro Components
71
+
72
+ - ``conv1``, ``bn1`` **DHR Module.** "Delayed hemodynamic response
73
+ convolutions (DHRConv) extract the channel-level features of delayed
74
+ hemodynamic responses." DHRConv is a standard convolution with
75
+ :math:`F_1` filters of :math:`1 \times S`: "the width of this kernel
76
+ equals the number of input sampling points" (Guideline 1). It stays a
77
+ standard convolution because "the depthwise separable convolution
78
+ performs poorly in low-dimensional space (the first layer)"
79
+ (Guideline 2). Batch normalization and a sigmoid follow.
80
+ - ``conv2``, ``bn2`` **Global Module.** A depthwise separable
81
+ convolution: DWConv, one :math:`C \times 1` filter per DHRConv map,
82
+ "can directly obtain global receptive fields without stacking layers",
83
+ and "the :math:`1 \times 1` PWConv projects the output of DWConv into
84
+ a new channel space" with :math:`F_2` filters; then batch
85
+ normalization and a sigmoid. Guideline 2 motivates the factorization
86
+ by the cost of a standard convolution against a depthwise separable
87
+ one, for a :math:`K_h \times K_w` kernel, :math:`F_{in}` input and
88
+ :math:`F_{out}` output channels and an :math:`M_h \times M_w` map
89
+ (Eqs. (2) and (3)):
90
+
91
+ .. math::
92
+
93
+ K_h K_w F_{in} F_{out} M_h M_w
94
+ \quad \text{vs.} \quad
95
+ K_h K_w F_{in} M_h M_w + F_{in} F_{out} M_h M_w ,
96
+
97
+ so the global module costs :math:`F_1 (C + F_2)` instead of
98
+ :math:`F_1 C F_2`, and "increasing the length of input signals only
99
+ increases the computational cost of DHRConv".
100
+ - ``activation`` **Saturating activations.** Guideline 3: "Activation
101
+ functions with saturated negative values can alleviate information
102
+ loss in the first layer"; sigmoid, tanh and ELU beat ReLU and leaky
103
+ ReLU in the ablation of Table VI, and the paper uses the sigmoid.
104
+ - ``final_layer`` **Classifier.** "The feature maps are flattened to 1D
105
+ vectors and then fed into an FC layer", without dropout; the paper's
106
+ softmax is left to the loss, and the module returns logits.
107
+
108
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
109
+
110
+ - *Temporal:* one 3 s window of :math:`S = f \times T` samples (30 at
111
+ 10 Hz on MA, 40 at 13.3 Hz on UFFT). DHRConv covers all of it, because
112
+ the response it targets is long: the paper models it with the
113
+ canonical hemodynamic response function of three gamma functions
114
+ (Section II-A, Eq. (1)), whose :math:`A`, :math:`\alpha` and
115
+ :math:`\beta` "control the height and direction, shape, and scale of
116
+ hemodynamic responses":
117
+
118
+ .. math::
119
+
120
+ h(t) = \sum_{i=1}^{3} A_i \frac{t^{\alpha_i - 1}
121
+ \beta_i^{\alpha_i} e^{-\beta_i t}}{\Gamma(\alpha_i)} .
122
+
123
+ The kernel counts samples, so the model takes no sampling rate.
124
+ - *Spatial:* no montage or optode geometry. DWConv mixes all rows at
125
+ once, since "DHRConv alone cannot aggregate spatial information from
126
+ multi-channel fNIRS". ``chs_info`` is not read: the row order must be
127
+ the one used in training.
128
+ - *Chromophores:* :math:`C` "is twice (two chromophores: HbO and HbR) the
129
+ number of fNIRS channels" (Section II-B); as in Fig. 2(a) and the
130
+ authors' loaders, all HbO rows come first, then all HbR rows.
131
+ - *Spectral:* none in the model; the paper band-passes the
132
+ concentration changes to 0.01-0.1 Hz first (Section III-B).
133
+
134
+ .. rubric:: Pretrained Weights
135
+
136
+ None: the authors release code, not weights, and the paper trains one
137
+ model per subject or per left-out subject.
138
+
139
+ .. rubric:: Differences from the reference implementation
140
+
141
+ ``x`` is ``(batch, n_chans, n_times)``; ``to_fnirs_tensor`` adds the
142
+ depth axis of the authors' ``(batch, 1, C, S)`` input. The modules keep
143
+ the authors' names except ``fc``, now ``final_layer``; ``mapping``
144
+ renames ``fc.*``, so their ``state_dict`` loads with ``strict=True``.
145
+ Table I lists :math:`F_2` filters for DWConv, but the authors'
146
+ ``DWSConv`` and the cost :math:`F_1 (C + F_2)` above have :math:`F_1`
147
+ depthwise filters and an :math:`F_1 \to F_2` PWConv; this module
148
+ follows the code, which gives Table III's parameter counts. Two
149
+ additions: ``dhr_kernel_length`` may be shorter than the window (the
150
+ authors' FC layer only fits :math:`k = S`), and ``activation`` replaces
151
+ the fixed sigmoid. A training batch of one sample runs the BN layers on
152
+ their running statistics, and ``ch_mask`` raises a ``ValueError``.
153
+
154
+ Parameters
155
+ ----------
156
+ n_dhr_filters : int, default=4
157
+ :math:`F_1`, the DHRConv filters (the authors' ``num_DHRConv``): 4
158
+ subject-specific, 16 subject-independent (Section III-D; the
159
+ authors' ``LOSO_Train.py`` uses 8). "Except for the number of
160
+ filters :math:`F_1` and :math:`F_2`, fNIRSNet has almost no other
161
+ hyperparameters."
162
+ n_pw_filters : int, default=8
163
+ :math:`F_2`, the PWConv filters (the authors' ``num_DWConv``): 8
164
+ subject-specific, 32 subject-independent (``LOSO_Train.py``: 16).
165
+ The paper recommends "setting the value of :math:`F_2` to at least
166
+ twice that of :math:`F_1`" (Section IV-F).
167
+ dhr_kernel_length : int or None, default=None
168
+ DHRConv width :math:`k`, ``1 <= k <= n_times``; ``None`` uses
169
+ :math:`S` (Guideline 1). Table IV also tries :math:`k` = 10, 20 and
170
+ 30 on UFFT; the FC layer then reads :math:`F_2 (S - k + 1)` values.
171
+ activation : type[nn.Module], default=nn.Sigmoid
172
+ Activation after each BN (the authors' ``act``).
173
+
174
+ Notes
175
+ -----
176
+ Protocol (Section III, details from the authors' code): MA
177
+ :footcite:`shin2017openaccess` (2 classes, 29 subjects, 10 Hz) and UFFT
178
+ :footcite:`bak2019ufft` (3 classes, 30 subjects, 13.3 Hz), band-passed
179
+ 0.01-0.1 Hz, baseline-corrected, cut into 3 s windows with a 1 s step
180
+ and z-scored. Subject-specific runs use 5-fold CV over trial blocks for
181
+ 120 epochs, subject-independent runs leave one subject out for 30
182
+ epochs; AdamW (lr 0.001), label smoothing 0.1, last-epoch test metrics.
183
+ Table III gives 498 and 419 parameters for the subject-specific sizes
184
+ (MA :math:`C = 72, S = 30`; UFFT :math:`C = S = 40`) and 2,370 and 2,051
185
+ for the subject-independent ones; this module gives the same counts.
186
+
187
+ On UFFT, in the authors' training loops (seeds 0-2), the port and the
188
+ authors' ``fNIRSNet`` agree within 0.01 point (accuracy / macro-F1 in %;
189
+ the LOSO runs use the authors' :math:`F_1 = 8`, :math:`F_2 = 16`):
190
+
191
+ =================== =============== ============= =============
192
+ UFFT Paper, Table II This port Authors' code
193
+ =================== =============== ============= =============
194
+ Subject-specific 68.67 / 68.02 67.68 / 66.83 67.68 / 66.83
195
+ Subject-independent 64.43 / 63.57 64.52 / 63.67 64.51 / 63.67
196
+ =================== =============== ============= =============
197
+
198
+ .. versionadded:: 2.1
199
+
200
+ `License <https://github.com/wzhlearning/fNIRSNet/blob/11d9dad96308c65c039a0978b7eaf8a845065421/LICENSE>`_
201
+
202
+ References
203
+ ----------
204
+ .. footbibliography::
205
+ """
206
+
207
+ def __init__(
208
+ self,
209
+ # Braindecode parameters
210
+ n_outputs: int | None = None,
211
+ n_chans: int | None = None,
212
+ chs_info: list[dict] | None = None,
213
+ n_times: int | None = None,
214
+ input_window_seconds: float | None = None,
215
+ sfreq: float | None = None,
216
+ *,
217
+ # Model-specific parameters
218
+ n_dhr_filters: int = 4,
219
+ n_pw_filters: int = 8,
220
+ dhr_kernel_length: int | None = None,
221
+ activation: type[nn.Module] = nn.Sigmoid,
222
+ ) -> None:
223
+ super().__init__(
224
+ n_outputs=n_outputs,
225
+ n_chans=n_chans,
226
+ chs_info=chs_info,
227
+ n_times=n_times,
228
+ input_window_seconds=input_window_seconds,
229
+ sfreq=sfreq,
230
+ )
231
+ del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
232
+
233
+ # The authors' head is named ``fc``: their state_dict loads as is
234
+ self.mapping = {f"fc.{k}": f"final_layer.{k}" for k in ("weight", "bias")}
235
+
236
+ # Parameters
237
+ # Guideline 1: the DHRConv kernel is as wide as the window (k = S)
238
+ kernel_length = self.n_times if dhr_kernel_length is None else dhr_kernel_length
239
+ # Samples left after DHRConv, S' = S - k + 1 (1 with the paper's k = S)
240
+ n_times_dhr = self.n_times - kernel_length + 1
241
+
242
+ # Checkers
243
+ # A kernel longer than the window has no valid position, and an empty
244
+ # one reads nothing
245
+ if not 1 <= kernel_length <= self.n_times:
246
+ raise ValueError(
247
+ f"dhr_kernel_length must be in [1, n_times={self.n_times}], "
248
+ f"got {dhr_kernel_length}."
249
+ )
250
+
251
+ # Layers
252
+ # Following paper nomenclature (Section II-B, Table I)
253
+ # The authors' input has a depth axis: (batch, 1, C, S)
254
+ self.to_fnirs_tensor = Rearrange("batch chans time -> batch 1 chans time")
255
+
256
+ # Delayed hemodynamic response module (DHR Module)
257
+ # DHRConv: F1 standard convolutions of 1 x k, so that one filter reads
258
+ # the whole slow response of one channel (Guidelines 1 and 2)
259
+ self.conv1 = nn.Conv2d(
260
+ in_channels=1,
261
+ out_channels=n_dhr_filters,
262
+ kernel_size=(1, kernel_length),
263
+ )
264
+ self.bn1 = nn.BatchNorm2d(n_dhr_filters)
265
+
266
+ # Global module: a depthwise separable convolution
267
+ self.conv2 = nn.Sequential(
268
+ OrderedDict(
269
+ # DWConv: one C x 1 filter per DHRConv map, a global receptive
270
+ # field over the channels without stacking layers
271
+ depth_conv=DepthwiseConv2d(
272
+ in_channels=n_dhr_filters,
273
+ depth_multiplier=1,
274
+ kernel_size=(self.n_chans, 1),
275
+ ),
276
+ # PWConv: 1 x 1, projects the F1 maps into F2 new ones
277
+ point_conv=nn.Conv2d(
278
+ in_channels=n_dhr_filters,
279
+ out_channels=n_pw_filters,
280
+ kernel_size=1,
281
+ ),
282
+ )
283
+ )
284
+ self.bn2 = nn.BatchNorm2d(n_pw_filters)
285
+
286
+ # Guideline 3: an activation that saturates for negative inputs
287
+ # (sigmoid in the paper), used after both batch normalizations
288
+ self.activation = activation()
289
+
290
+ # Flatten layer
291
+ self.flatten = Rearrange("batch filters 1 time -> batch (filters time)")
292
+
293
+ # Final fully connected layer, without pooling or dropout
294
+ self.final_layer = nn.Linear(
295
+ in_features=n_pw_filters * n_times_dhr,
296
+ out_features=self.n_outputs,
297
+ )
298
+
299
+ def reset_head(self, n_outputs: int) -> None:
300
+ self._set_n_outputs(n_outputs)
301
+ self.final_layer = nn.Linear(self.final_layer.in_features, n_outputs)
302
+
303
+ @_disable_batch_norm_training_if_batch_size_one
304
+ def forward(
305
+ self,
306
+ x: torch.Tensor,
307
+ return_features: bool = False,
308
+ ch_mask: torch.Tensor | None = None,
309
+ ) -> torch.Tensor | dict[str, torch.Tensor | None]:
310
+ """Forward pass of the fNIRSNet model.
311
+
312
+ Parameters
313
+ ----------
314
+ x : torch.Tensor
315
+ Input tensor with shape ``(batch_size, n_chans, n_times)``.
316
+ return_features : bool, default=False
317
+ If True, return the flattened features that feed the FC layer.
318
+ ch_mask : torch.Tensor or None
319
+ Not supported: DWConv has one weight per channel.
320
+
321
+ Returns
322
+ -------
323
+ torch.Tensor or dict
324
+ Logits with shape ``(batch_size, n_outputs)``, or with
325
+ ``return_features=True`` the dict ``{"features", "cls_token"}``,
326
+ ``features`` of shape ``(batch_size, n_pw_filters * time')`` and
327
+ ``cls_token`` None.
328
+ """
329
+ # DWConv has one weight per channel: a subset of the channels is
330
+ # another model
331
+ if ch_mask is not None:
332
+ raise ValueError("FNIRSNet does not accept ch_mask: DWConv spans n_chans.")
333
+
334
+ # Below, F1 = n_dhr_filters, F2 = n_pw_filters, C = n_chans, S = n_times
335
+ # and S' = S - dhr_kernel_length + 1 (1 with the paper's kernel)
336
+
337
+ # Depth axis of the authors' input
338
+ # (batch, C, S) -> (batch, 1, C, S)
339
+ x = self.to_fnirs_tensor(x)
340
+
341
+ # DHR Module. Delayed hemodynamic response convolution (DHRConv,
342
+ # Guideline 1): each of the F1 filters reads the whole window of one
343
+ # channel, the channel-level feature of its slow response
344
+ # (batch, 1, C, S) -> (batch, F1, C, S')
345
+ x = self.conv1(x)
346
+ # Batch normalization of the F1 maps; shape unchanged
347
+ x = self.bn1(x)
348
+ # Saturating activation (Guideline 3: no information lost in the
349
+ # first layer for negative inputs); shape unchanged
350
+ x = self.activation(x)
351
+
352
+ # Global Module. DWConv: one C x 1 filter per DHRConv map aggregates
353
+ # all channels at once (global receptive field in space)
354
+ # (batch, F1, C, S') -> (batch, F1, 1, S')
355
+ x = self.conv2.depth_conv(x)
356
+ # PWConv: 1 x 1 projection of the F1 maps into F2 new ones
357
+ # (batch, F1, 1, S') -> (batch, F2, 1, S')
358
+ x = self.conv2.point_conv(x)
359
+ # Batch normalization of the F2 maps; shape unchanged
360
+ x = self.bn2(x)
361
+ # Same saturating activation as after DHRConv; shape unchanged
362
+ x = self.activation(x)
363
+
364
+ # "The feature maps are flattened to 1D vectors"
365
+ # (batch, F2, 1, S') -> (batch, F2 * S')
366
+ features = self.flatten(x)
367
+
368
+ if return_features:
369
+ return {"features": features, "cls_token": None}
370
+
371
+ # FC layer; the paper's softmax is left to the loss
372
+ # (batch, F2 * S') -> (batch, n_outputs)
373
+ x = self.final_layer(features)
374
+ return x