-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoh_signal.py
3239 lines (2833 loc) · 123 KB
/
coh_signal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A class for loading, preprocessing, and epoching an mne.io.Raw object.
CLASSES
-------
Signal
- Class for loading, preprocessing, and epoching an mne.io.Raw object.
"""
from copy import deepcopy
from typing import Any, Optional, Union
from numpy.typing import NDArray
from mne import concatenate_epochs
import mne
import mne_bids
import numpy as np
import pandas as pd
from pyparrm import PARRM
from coh_exceptions import (
ChannelAttributeError,
EntryLengthError,
ProcessingOrderError,
UnavailableProcessingError,
)
from coh_rereference import (
Reref,
RerefBipolar,
RerefCommonAverage,
RerefPseudo,
)
from coh_handle_entries import (
check_lengths_list_identical,
check_repeated_vals,
ordered_dict_keys_from_list,
ordered_list_from_dict,
rearrange_axes,
get_eligible_idcs_lists,
get_group_names_idcs,
)
from coh_handle_files import (
check_annots_empty,
check_annots_orig_time,
check_ftype_present,
identify_ftype,
)
from coh_handle_objects import (
create_extra_info,
create_mne_data_object,
extra_info_keys,
)
from coh_saving import check_before_overwrite, save_as_json, save_as_pkl
class Signal:
"""Class for loading, preprocessing, and epoching an mne.io.Raw object.
PARAMETERS
----------
verbose : bool; default True
- Whether or not to print information about the information processing.
METHODS
-------
order_channels
- Orders channels in the mne.io.Raw or mne.Epochs object based on a
given order.
get_coordinates
- Extracts coordinates of the channels from the mne.io.Raw or mne.Epochs
object.
set_coordinates
- Assigns coordinates to the channels in the mne.io.Raw or mne.Epochs
object.
get_data
- Extracts the data array from the mne.io.Raw or mne.Epochs object,
excluding data based on the annotations.
load_raw
- Loads an mne.io.Raw object, loads it into memory, and sets it as the
data, also assigning rereferencing types in 'extra_info' for the
channels present in the mne.io.Raw object to 'none'.
load_annotations
- Loads annotations corresponding to the mne.io.Raw object.
pick_channels
- Retains only certain channels in the mne.io.Raw or mne.Epochs object,
also retaining only entries for these channels from the 'extra_info'.
bandpass_filter
- Bandpass filters the mne.io.Raw or mne.Epochs object.
notch_filter
- Notch filters the mne.io.Raw or mne.Epochs object.
resample
- Resamples the mne.io.Raw or mne.Epochs object.
combine_channels
- Combines the data of multiple channels in the mne.io.Raw object through
addition and adds this combined data as a new channel.
drop_unrereferenced_channels
- Drops channels that have not been rereferenced from the mne.io.Raw or
mne.Epochs object, also discarding entries for these channels from
'extra_info'.
rereference_bipolar
- Bipolar rereferences channels in the mne.io.Raw object.
rereference_common_average
- Common-average rereferences channels in the mne.io.Raw object.
rereference_pseudo
- Pseudo rereferences channels in the mne.io.Raw object.
- This allows e.g. rereferencing types, channel coordinates, etc... to be
assigned to the channels without any rereferencing occurring.
- This is useful if e.g. the channels were already hardware rereferenced.
epoch
- Divides the mne.io.Raw object into epochs of a specified duration.
save_object
- Saves the Signal object as a .pkl file.
save_signals
- Saves the time-series data and additional information as a file.
"""
def __init__(self, verbose: bool = True) -> None:
# Initialises aspects of the Signal object that will be filled with
# information as the data is processed.
self.processing_steps = {"preprocessing": {}}
self._processing_step_number = 1
self.extra_info = {}
self.data = [None]
self._path_raw = None
self._data_dimensions = None
# Initialises inputs of the Signal object.
self._verbose = verbose
# Initialises aspects of the Signal object that indicate which methods
# have been called (starting as 'False'), which can later be updated.
self._data_loaded = False
self._annotations_loaded = False
self._channels_picked = False
self._coordinates_set = False
self._regions_set = False
self._subregions_set = False
self._hemispheres_set = False
self._bandpass_filtered = False
self._notch_filtered = False
self._resampled = False
self._rereferenced = False
self._rereferenced_bipolar = False
self._rereferenced_common_average = False
self._rereferenced_pseudo = False
self._z_scored = False
self._windowed = False
self._pseudo_windowed = False
self._epoched = False
self._bootstrapped = False
self._shuffled = False
def _update_processing_steps(self, step_name: str, step_value: Any) -> None:
"""Updates the 'preprocessing' entry of the 'processing_steps'
dictionary of the Signal object with new information consisting of a
key:value pair in which the key is numbered based on the applied steps.
PARAMETERS
----------
step_name : str
- The name of the processing step.
step_value : Any
- A value representing what processing has taken place.
"""
step_name = f"{self._processing_step_number}.{step_name}"
self.processing_steps["preprocessing"][step_name] = step_value
self._processing_step_number += 1
def add_metadata(self, metadata: dict) -> None:
"""Adds information about the data being preprocessed to the extra_info
aspect.
PARAMETERS
----------
metadata : dict
- Information about the data being preprocessed.
"""
self.extra_info["metadata"] = metadata
def _order_extra_info(self, order: list[str]) -> None:
"""Order channels in 'extra_info'.
PARAMETERS
----------
order : list[str]
- The order in which the channels should appear in the attributes of
the 'extra_info' dictionary.
"""
to_order = [
"ch_reref_types",
"ch_regions",
"ch_subregions",
"ch_hemispheres",
"ch_epoch_orders",
]
for key in to_order:
if key in self.extra_info.keys():
self.extra_info[key] = ordered_dict_keys_from_list(
dict_to_order=self.extra_info[key], keys_order=order
)
def order_channels(self, ch_names: list[str]) -> None:
"""Orders channels in the mne.io.Raw or mne.Epochs objects, as well as
the 'extra_info' dictionary, based on a given order.
PARAMETERS
----------
ch_names : list[str]
- A list of channel names in the mne.io.Raw or mne.Epochs object in
the order that you want the channels to be ordered.
"""
# get names actually in data
ch_names = [name for name in ch_names if name in self.data[0].ch_names]
# get names in data missing from order
missing_names = [
name for name in self.data[0].ch_names if name not in ch_names
]
if self._verbose:
print("Reordering the channels in the following order:")
[print(name) for name in ch_names]
print(f"Removing the unlisted channels: {missing_names}\n")
for data in self.data:
data.drop_channels(missing_names)
data.reorder_channels(ch_names)
if missing_names != []:
self._drop_extra_info(missing_names)
self._order_extra_info(order=ch_names)
def get_coordinates(
self, picks: Union[str, list, slice, None] = None
) -> list[list[Union[int, float]]]:
"""Extracts coordinates of the channels from the mne.io.Raw or
mne.Epochs objects.
PARAMETERS
----------
picks : str | list | slice | None; default None
- Selects which channels' coordinates should be returned.
- If 'None', returns coordinates for all good channels.
RETURNS
-------
list[list[int or float]]
- List of the channel coordinates, with each list entry containing the
x, y, and z coordinates of each channel.
"""
picks = mne.io.pick._picks_to_idx(self.data[0].info, picks)
chs = self.data[0].info["chs"]
coords = np.array([chs[k]["loc"][:3] for k in picks])
# for ch_i, ch_coords in enumerate(coords):
# if np.all(ch_coords == 0):
# coords[ch_i] = np.full((3,), np.nan)
return coords.copy().tolist()
def _discard_missing_coordinates(
self, ch_names: list[str], ch_coords: list[list[Union[int, float]]]
) -> tuple[list, list]:
"""Removes empty sublists from a parent list of channel coordinates
(also removes them from the corresponding entries of channel names)
before applying the coordinates to the mne.io.Raw or mne.Epochs objects.
PARAMETERS
----------
ch_names : list[str]
- Names of the channels corresponding to the coordinates in
'ch_coords'.
ch_coords : list[empty list | list[int | float]]
- Coordinates of the channels, with each entry consisting of a sublist
containing the x, y, and z coordinates of the corresponding channel
specified in 'ch_names', or being empty.
RETURNS
-------
empty list | list[str]
- Names of the channels corresponding to the coordinates in
'ch_coords', with those names corresponding to empty sublists (i.e
missing coordinates) in 'ch_coords' having been removed.
empty list |list[list[int | float]]
- Coordinates of the channels corresponding the the channel names in
'ch_names', with the empty sublists (i.e missing coordinates) having
been removed.
"""
keep_i = [i for i, coords in enumerate(ch_coords) if coords != []]
return (
[name for i, name in enumerate(ch_names) if i in keep_i],
[coords for i, coords in enumerate(ch_coords) if i in keep_i],
)
def set_coordinates(
self, ch_names: list[str], ch_coords: list[list[Union[int, float]]]
) -> None:
"""Assigns coordinates to the channels in the mne.io.Raw or mne.Epochs
object.
PARAMETERS
----------
ch_names : list[str]
- The names of the channels corresponding to the coordinates in
'ch_coords'.
ch_coords : list[empty list | list[int | float]]
- Coordinates of the channels, with each entry consisting of a sublist
containing the x, y, and z coordinates of the corresponding channel
specified in 'ch_names'.
"""
ch_names, ch_coords = self._discard_missing_coordinates(
ch_names, ch_coords
)
for data in self.data:
data._set_channel_positions(ch_coords, ch_names)
self._coordinates_set = True
if self._verbose:
print("Setting channel coordinates to:")
[
print(f"{ch_names[i]}: {ch_coords[i]}")
for i in range(len(ch_names))
]
def set_regions(self, ch_names: list[str], ch_regions: list[str]) -> None:
"""Adds channel regions (e.g. prefrontal, parietal) to the extra_info
dictionary.
PARAMETERS
----------
ch_names : list[str]
- Names of the channels.
ch_regions : list[str]
- Regions of the channels.
"""
if len(ch_names) != len(ch_regions):
raise EntryLengthError(
"The channel names and regions do not have the same length "
f"({len(ch_names)} and {len(ch_regions)}, respectively)."
)
for i, ch_name in enumerate(ch_names):
self.extra_info["ch_regions"][ch_name] = ch_regions[i]
self._regions_set = True
if self._verbose:
print("Setting channel regions to:")
[
print(f"{ch_names[i]}: {ch_regions[i]}")
for i in range(len(ch_names))
]
def set_subregions(
self, ch_names: list[str], ch_subregions: list[str]
) -> None:
"""Adds channel subregions (e.g. prefrontal, parietal) to the extra_info
dictionary.
PARAMETERS
----------
ch_names : list[str]
- Names of the channels.
ch_subregions : list[str]
- Subregions of the channels.
"""
if len(ch_names) != len(ch_subregions):
raise EntryLengthError(
"The channel names and subregions do not have the same length "
f"({len(ch_names)} and {len(ch_subregions)}, respectively)."
)
for i, ch_name in enumerate(ch_names):
self.extra_info["ch_subregions"][ch_name] = ch_subregions[i]
self._subregions_set = True
if self._verbose:
print("Setting channel subregions to:")
[
print(f"{ch_names[i]}: {ch_subregions[i]}")
for i in range(len(ch_names))
]
def set_hemispheres(
self, ch_names: list[str], ch_hemispheres: list[str]
) -> None:
"""Adds channel hemispheres to the extra_info dictionary.
PARAMETERS
----------
ch_names : list[str]
- Names of the channels.
ch_hemispheres : list[str]
- Hemispheres of the channels.
"""
if len(ch_names) != len(ch_hemispheres):
raise EntryLengthError(
"The channel names and hemispheres do not have the same length "
f"({len(ch_names)} and {len(ch_hemispheres)}, respectively)."
)
for i, ch_name in enumerate(ch_names):
self.extra_info["ch_hemispheres"][ch_name] = ch_hemispheres[i]
self._hemispheres_set = True
if self._verbose:
print("Setting channel hemispheres to:")
[
print(f"{ch_names[i]}: {ch_hemispheres[i]}")
for i in range(len(ch_names))
]
@property
def data_dimensions(self) -> list[str]:
"""Returns the dimensions of the data you would get if you called
'get_data'.
RETURNS
-------
dims : list[str]
- Dimensions of the data.
"""
if self._windowed:
return deepcopy(self._data_dimensions)
return deepcopy(self._data_dimensions[1:])
def get_data(self) -> np.array:
"""Extracts the data array from the mne.io.Raw or mne.Epochs objects,
excluding data based on the annotations if the data is an MNE Raw
object.
RETURNS
-------
data_arr : numpy array
- The data in array form.
"""
data_arr = np.empty(len(self.data))
for i, data in enumerate(self.data):
if isinstance(data, mne.io.Raw):
data_arr[i] = data.get_data(reject_by_annotation="omit").copy()
else:
data_arr[i] = data.get_data().copy()
if self._windowed:
return data_arr[0, :, :]
return data_arr
def _initialise_additional_info(self) -> None:
"""Fills the extra_info dictionary with placeholder information. This
should only be called when the data is initially loaded."""
info_to_set = [
"ch_reref_types",
"ch_regions",
"ch_subregions",
"ch_hemispheres",
]
for info in info_to_set:
self.extra_info[info] = {
ch_name: None for ch_name in self.data[0].info["ch_names"]
}
self._data_dimensions = ["windows", "channels", "timepoints"]
def _fix_coords(self) -> None:
"""Fixes the units of the channel coordinates in the data by multiplying
them by 1,000."""
raise NotImplementedError(
"Fixing the coordinates with this method does not currently "
"function correctly, and so should not be called!"
)
ch_coords = self.get_coordinates()
for ch_i, coords in enumerate(ch_coords):
ch_coords[ch_i] = [coord * 1000 for coord in coords]
self.set_coordinates(
ch_names=self.data[0].ch_names, ch_coords=ch_coords
)
def raw_from_fpath(self, path_raw: mne_bids.BIDSPath) -> None:
"""Loads an mne.io.Raw object from a filepath, loads it into memory, and
sets it as the data, also assigning additional information in
'extra_info' for the channels present in the mne.io.Raw object to
'none'.
PARAMETERS
----------
path_raw : mne_bids.BIDSPath
- The path of the raw data to be loaded.
RAISES
------
ProcessingOrderError
- Raised if the user attempts to load data if data has already been
loaded.
"""
if self._data_loaded:
raise ProcessingOrderError(
"Error when trying to load raw data: data has already been "
"loaded."
)
self._path_raw = path_raw
self.data[0] = mne_bids.read_raw_bids(
bids_path=self._path_raw, verbose=False
)
self.data[0].load_data()
self._initialise_additional_info()
# self._fix_coords()
self._data_loaded = True
if self._verbose:
print(f"Loading the data from the filepath:\n{path_raw}.\n")
def data_from_objects(
self,
data: Union[
mne.io.Raw, mne.Epochs, list[Union[mne.io.Raw, mne.Epochs]]
],
processing_steps: Union[dict, None] = None,
extra_info: Union[dict, None] = None,
) -> None:
"""Sets the data, its dimensions, processing steps, and additional
information from their respective objects.
PARAMETERS
----------
data : MNE Raw | MNE Epochs | list of MNE Raw or MNE Epochs
- Data to load, stored in MNE objects. If the data is a list of MNE
objects, the data is assumed to be windowed. Data must be of the
same type (i.e. all Raw or all Epochs objects).
processing_steps : dict | None; default None
- Information about the processing that has been applied to the data.
extra_info : dict | None; default None
- Additional information about the data not included in the MNE
objects.
RAISES
------
ProcessingOrderError
- Raised if data has already been loaded.
TypeError
- Raised if data of multiple types is being supplied.
- Raised if the data is not stored in MNE Raw or MNE Epochs objects.
"""
if self._data_loaded:
raise ProcessingOrderError(
"Error when trying to load data:\nData has already been loaded "
"into the object."
)
data_windowed = False
data_epoched = False
if isinstance(data, list):
if not all(isinstance(window, type(data[0])) for window in data):
raise TypeError(
"Only one form of MNE data can be loaded into a single "
"Signal object, but data of multiple types are being "
"loaded."
)
data_type = type(data[0])
data_windowed = True
else:
data_type = type(data)
data = [data]
if not isinstance(data[0], mne.io.BaseRaw) and not isinstance(
data[0], mne.BaseEpochs
):
raise TypeError(
"The data to load must be an MNE Raw or Epochs object, but it "
f"is of type '{data_type}'."
)
if isinstance(data[0], mne.BaseEpochs):
data_epoched = True
[window_data.load_data() for window_data in data]
data_dimensions = ["channels", "timepoints"]
if data_epoched:
data_dimensions = ["epochs", *data_dimensions]
self._epoched = True
if data_windowed:
self._windowed = True
data_dimensions = [
"windows",
*data_dimensions,
] # leading "windows" tag
# will be ignored when self._windowed == False
self.data = data
self._data_dimensions = data_dimensions
self._instantiate_processing_steps(processing_steps)
self._instantiate_extra_info(extra_info)
self._set_method_bools()
self._data_loaded = True
if self._verbose:
print(f"Loading the {data_type} data from MNE objects.\n")
def _instantiate_processing_steps(
self, processing_steps: Union[dict, None]
) -> None:
"""Instantiates the processing steps when preprocessed data is being
loaded into the Signal object.
PARAMETERS
----------
processing_steps : dict | None
- The processing steps that have been performed on the data.
"""
if processing_steps is not None:
if not isinstance(processing_steps, dict):
raise TypeError("The processing steps must be a dict.")
self.processing_steps = processing_steps
else:
self.processing_steps = {}
if "preprocessing" not in self.processing_steps.keys():
self.processing_steps = {"preprocessing": {}}
def _instantiate_extra_info(self, extra_info: Union[dict, None]) -> None:
"""Instantiates extra information about the data not stored in he data
itself when preprocessed data is being loaded into the Signal object.
PARAMETERS
----------
extra_info : dict | None
- The extra information about the data.
"""
if extra_info is not None:
self.extra_info = extra_info
for key in extra_info_keys:
if key not in extra_info.keys():
self.extra_info[key] = None
else:
self.extra_info = {key: None for key in extra_info_keys}
def _set_method_bools(self) -> None:
"""Sets the markers for methods that have been called on the data based
on the processing steps and extra information dictionaries."""
for steps in self.processing_steps.values():
if steps is not None:
for step in steps:
if "rereferencing_common_average" in step:
self._rereferenced_common_average = True
self._rereferenced = True
elif "rereferencing_bipolar" in step:
self._rereferenced_bipolar = True
self._rereferenced = True
elif "rereferencing_pseudo" in step:
self._rereferenced_pseudo = True
self._rereferenced = True
elif "annotations_loaded" in step:
self._annotations_loaded = True
elif "bandpass_filter" in step:
self._bandpass_filtered = True
elif "notch_filter" in step:
self._notch_filtered = True
elif "resample" in step:
self._resampled = True
elif "shuffle_data" in step:
self._shuffled = True
if self.extra_info["ch_regions"] is not None:
self._regions_set = True
if self.extra_info["ch_subregions"] is not None:
self._subregions_set = True
if self.extra_info["ch_hemispheres"] is not None:
self._hemispheres_set = True
def _remove_bad_annotations(
self, labels: list[str] | None = None
) -> tuple[mne.annotations.Annotations, mne.annotations.Annotations]:
"""Removes segments annotated as 'bad' from the Annotations object.
Parameters
----------
labels : list of str | None (default None)
Labels of the bad segments to remove.
RETURNS
-------
bad_annotations
- The bad annotations which should be removed.
good_annotations
- The good annotations which should be retained.
"""
annotations = deepcopy(self.data[0].annotations)
bad_annot_idcs = []
for annot_i, annot_name in enumerate(annotations.description):
if labels is None:
if annot_name[:3] == "BAD":
bad_annot_idcs.append(annot_i)
elif set([annot_name]).issubset(labels):
bad_annot_idcs.append(annot_i)
bad_annotations = annotations.copy()
bad_annotations.delete(
[i for i in range(len(bad_annotations)) if i not in bad_annot_idcs]
)
good_annotations = annotations.copy()
good_annotations.delete(bad_annot_idcs)
return bad_annotations, good_annotations
def remove_bad_segments(self, labels: list[str] | None = None) -> None:
"""Removes segments annotated as 'bad' from the Raw object.
Parameters
----------
labels : list of str | None (default None)
Labels of the bad segments to remove.
"""
if self._epoched:
raise ProcessingOrderError(
"Error when removing bad segments from the data:\nBad segments "
"should be removed from the raw data, however the data in this "
"class has been epoched."
)
if not isinstance(labels, list) and labels is not None:
raise TypeError("`labels` must be a list of str or None.")
bad_annotations, good_annotations = self._remove_bad_annotations(labels)
self.data[0].set_annotations(bad_annotations)
new_data = self.data[0].get_data(reject_by_annotation="omit")
self.data[0] = mne.io.RawArray(data=new_data, info=self.data[0].info)
for bad_annot_i in range(len(bad_annotations)):
for good_annot_i in range(len(good_annotations)):
if (
good_annotations.onset[good_annot_i]
> bad_annotations.onset[bad_annot_i]
):
good_annotations.onset[
good_annot_i
] -= bad_annotations.duration[bad_annot_i]
good_annotations = mne.Annotations(
good_annotations.onset,
good_annotations.duration,
good_annotations.description,
)
self.data[0].set_annotations(annotations=good_annotations)
if self._verbose:
print(
f"Removing {len(bad_annotations)} bad segment(s) from the "
"data."
)
def load_annotations(self, fpath: str) -> None:
"""Loads annotations corresponding to the mne.io.Raw object.
PARAMETERS
----------
fpath : str
- The filepath of the annotations to load.
RAISES
------
ProcessingOrderError
- Raised if the user attempts to load annotations into the data after
it has been windowed.
- Raised if the user attempts to load annotations into the data after
it has been epoched.
- Annotations should be loaded before epoching has occurred, when the
data is in the form of an mne.io.Raw object rather than an
mne.Epochs object.
Notes
-----
"BAD_recording_start" and "BAD_recording_end" annotations are removed
when loaded. Other BAD annotations must be removed by calling
`remove_bad_segments`.
"""
if self._windowed:
raise ProcessingOrderError(
"Error when adding annotations to the data:\nAnnotations "
"should be added to the raw data, however the data in this "
"class has been windowed."
)
if self._epoched:
raise ProcessingOrderError(
"Error when adding annotations to the data:\nAnnotations "
"should be added to the raw data, however the data in this "
"class has been epoched."
)
if self._verbose:
print(
"Applying annotations to the data from the filepath:\n"
f"{fpath}."
)
if check_annots_empty(fpath):
print("There are no events to read from the annotations file.")
else:
self.data[0].set_annotations(
check_annots_orig_time(mne.read_annotations(fpath))
)
self.remove_bad_segments(
labels=["BAD_recording_start", "BAD_recording_end"]
)
self._annotations_loaded = True
self._update_processing_steps(
step_name="annotations_loaded", step_value=True
)
def _pick_extra_info(self, ch_names: list[str]) -> None:
"""Retains entries for selected channels in 'extra_info', discarding
those for the remaining channels.
PARAMETERS
----------
ch_names : list[str]
- The names of the channels whose entries should be retained.
"""
for key in self.extra_info.keys():
new_entry = {
ch_name: self.extra_info[key][ch_name] for ch_name in ch_names
}
self.extra_info[key] = new_entry
def _drop_extra_info(self, ch_names: list[str]) -> None:
"""Removes entries for selected channels in 'extra_info', retaining
those for the remaining channels.
PARAMETERS
----------
ch_names : list[str]
- The names of the channels whose entries should be discarded.
"""
for key in self.extra_info.keys():
[self.extra_info[key].pop(name) for name in ch_names]
def _drop_channels(self, ch_names: list[str]) -> None:
"""Removes channels from the mne.io.Raw or mne.Epochs objects, as well
as from entries in 'extra_info'.
PARAMETERS
----------
ch_names : list[str]
- The names of the channels that should be discarded.
"""
self._drop_extra_info(ch_names)
extra_info_keys = ["ch_regions", "ch_subregions", "ch_hemispheres"]
for i, data in enumerate(self.data):
self.data[i] = data.drop_channels(ch_names)
for key in extra_info_keys:
setattr(self.data[i], key, self.extra_info[key])
def drop_channels(self, eligible_entries: dict, conditions: dict) -> None:
"""Drop channels from the object based on criteria."""
features = self._features_to_df()
possible_channels = []
for key, value in eligible_entries.items():
feature = features[key].tolist()
possible_channels.extend(
[i for i, val in enumerate(feature) if val in value]
)
possible_channels = np.unique(possible_channels).tolist()
bad_channels = []
for key, value in conditions.items():
feature = features[key].tolist()
bad_channels.extend(
[
i
for i, val in zip(
possible_channels,
[feature[ch_i] for ch_i in possible_channels],
)
if val in value
]
)
bad_channels = np.unique(bad_channels).tolist()
self._drop_channels([self.data[0].ch_names[i] for i in bad_channels])
def pick_channels(self, ch_names: list[str]) -> None:
"""Retains only certain channels in the mne.io.Raw or mne.Epochs
objects, also retaining only entries for these channels from the
'extra_info'.
PARAMETERS
----------
ch_names : list[str]
- The names of the channels that should be retained.
"""
self._pick_extra_info(ch_names)
for data in self.data:
data.pick(ch_names)
self._channels_picked = True
self._update_processing_steps("channel_picks", ch_names)
if self._verbose:
print(
"Picking specified channels from the data.\nChannels: "
f"{ch_names}."
)
def bandpass_filter(
self,
highpass_freq: Union[int, float],
lowpass_freq: Union[int, float],
picks: Union[list, None] = None,
) -> None:
"""Bandpass filters the mne.io.Raw or mne.Epochs objects.
PARAMETERS
----------
highpass_freq : int | float
- The frequency (Hz) at which to highpass filter the data.
lowpass_freq : int | float
- The frequency (Hz) at which to lowpass filter the data.
picks : list | None
- The channels to filter (including bad channels). Can either consist
of channel names, or channel types. If None, all channels are
used.
"""
ch_names = self.data[0].ch_names
if not picks:
ch_picks = ch_names
else:
if not set(picks).issubset(ch_names):
ch_types = self.data[0].get_channel_types(picks=ch_names)
ch_picks = [
name
for ch_i, name in enumerate(ch_names)
if ch_types[ch_i] in picks
]
else:
ch_picks = picks
picked_types = np.unique(self.data[0].get_channel_types(picks=ch_picks))
for data in self.data:
data.filter(highpass_freq, lowpass_freq, picks=ch_picks)
self._bandpass_filtered = True
step_name = (
"bandpass_filter-"
+ "".join(f"{ch_type}_" for ch_type in picked_types)[:-1]
)
self._update_processing_steps(step_name, [highpass_freq, lowpass_freq])
if self._verbose:
print(
f"Bandpass filtering the data:\n- Channels: {ch_picks}\n- "
f"Frequencies: {highpass_freq} - {lowpass_freq} Hz."
)
def notch_filter(
self,
base_freq: Union[int, float],
notch_width: Union[int, float, None] = None,
) -> None:
"""Notch filters the mne.io.Raw or mne.Epochs object.
PARAMETERS
----------
base_freq : int | float
- The base frequency (Hz) for which the notch filter, including
the harmonics, is produced.
notch_width : int | float | None
- Width of the stop band in Hz. If 'None', the frequencies at which
the notch filter is applied divided by 200 is used.
"""
freqs = np.arange(
base_freq,
self.data[0].info["lowpass"],
base_freq,
dtype=int,
).tolist()
for data in self.data:
data.notch_filter(freqs, notch_widths=notch_width)
self._notch_filtered = True