-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoh_power.py
2158 lines (1866 loc) · 77 KB
/
coh_power.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
"""Classes for performing power analysis on data.
CLASSES
-------
PowerMorlet
- Performs power analysis on preprocessed data using Morlet wavelets.
"""
from copy import deepcopy
from typing import Union
from matplotlib import pyplot as plt
from fooof import FOOOF
from fooof_PLA import FOOOF as FOOOF_PLA
from fooof.analysis.periodic import get_band_peak
from mne import time_frequency
from numpy.typing import NDArray
import numpy as np
import coh_signal
from coh_exceptions import ProcessingOrderError
from coh_handle_entries import (
check_matching_entries,
ordered_list_from_dict,
rearrange_axes,
)
from coh_handle_objects import FillableObject
from coh_handle_plots import maximise_figure_windows
from coh_normalisation import norm_percentage_total
from coh_processing_methods import ProcMethod
from coh_saving import save_dict, save_object
class PowerStandard(ProcMethod):
"""Performs power analysis on data using Welch's method, multitapers, or
Morlet wavelets.
PARAMETERS
----------
signal : coh_signal.Signal
- A preprocessed Signal object whose data will be processed.
verbose : bool; Optional, default True
- Whether or not to print information about the information processing.
METHODS
-------
process
- Performs power analysis on the data.
save_object
- Saves the object as a .pkl file.
save_results
- Saves the results and additional information as a file.
results_as_dict
- Returns the power results and additional information as a dictionary.
"""
def __init__(self, signal: coh_signal.Signal, verbose: bool = True) -> None:
super().__init__(signal=signal, verbose=verbose)
# Initialises inputs of the PowerMorlet object.
self._sort_inputs()
# Initialises aspects of the ProcMethod object that will be filled with
# information as the data is processed.
self._power_method = None
# Initialises aspects of the PowerMorlet object that indicate which
# methods have been called (starting as 'False'), which can later be
# updated.
self._epochs_averaged = False
self._timepoints_averaged = False
self._segments_averaged = False
self._normalised = False
def _sort_inputs(self) -> None:
"""Checks the inputs to the PowerMorlet object to ensure that they
match the requirements for processing and assigns inputs.
RAISES
------
InputTypeError
- Raised if the Signal object input does not contain epoched data.
"""
if "epochs" not in self.signal.data_dimensions:
raise TypeError(
"The provided Signal object does not contain epoched data. "
"Epoched data is required for power analysis."
)
super()._sort_inputs()
def process_welch(
self,
fmin: Union[int, float] = 0,
fmax: Union[int, float] = np.inf,
n_fft: int = 256,
n_overlap: int = 0,
n_per_seg: Union[int, None] = None,
window_method: Union[str, float, tuple] = "hamming",
average_windows: bool = True,
average_epochs: bool = True,
average_segments: Union[str, None] = "mean",
n_jobs: int = 1,
) -> None:
"""Calculates the power spectral density of the data with Welch's
method, using the implementation in MNE
'time_frequency.psd_array_welch'.
Welch's method involves calculating periodograms for a sliding window
over time which are then averaged together for each channel/epoch.
PARAMETERS
----------
fmin : int | float; default 0
- The minimum frequency of interest.
fmax : int | float; default infinite
- The maximum frequency of interest.
n_fft : int; default 256
- The length of the FFT used. Must be >= 'n_per_seg'. If 'n_fft' >
'n_per_seg', the segments will be zero-padded.
n_overlap : int; default 0
- The number of points to overlap between segments, which will be
adjusted to be <= the number of time points in the data.
n_per_seg : int | None; default None
- The length of each Welch segment, windowed by a Hamming window. If
'None', 'n_per_seg' is set to equal 'n_fft', in which case 'n_fft'
must be <= the number of time points in the data.
window_method : str | float | tuple; default "hamming"
- The windowing function to use. See scipy's 'signal.get_window'
function.
average_windows : bool; default True
- Whether or not to average power results across data windows.
average_epochs : bool; default True
- Whether or not to average power results across epochs.
average_segments : str | None; default "mean"
- How to average segments. If "mean", the arithmetic mean is used. If
"median", the median is used, corrected for bias relative to the
mean. If 'None', the segments are unagreggated.
n_jobs : int; default 1
- The number of jobs to run in parallel. If '-1', this is set to the
number of CPU cores. Requires the 'joblib' package.
RAISES
------
ProcessingOrderError
- Raised if the data in the object has already been processed.
"""
if self._processed:
ProcessingOrderError(
"The data in this object has already been processed. "
"Initialise a new instance of the object if you want to "
"perform other analyses on the data."
)
if self.verbose:
print("Performing Welch's power analysis on the data.\n")
self._get_results_welch(
fmin=fmin,
fmax=fmax,
n_fft=n_fft,
n_overlap=n_overlap,
n_per_seg=n_per_seg,
window_method=window_method,
average_windows=average_windows,
average_epochs=average_epochs,
average_segments=average_segments,
n_jobs=n_jobs,
)
self._processed = True
self._power_method = "welch"
self.processing_steps["power_welch"] = {
"fmin": fmin,
"fmax": fmax,
"n_fft": n_fft,
"n_overlap": n_overlap,
"n_per_seg": n_per_seg,
"window_method": window_method,
"average_windows": average_windows,
"average_epochs": average_epochs,
"average_segments": average_segments,
}
def _get_results_welch(
self,
fmin: Union[int, float],
fmax: Union[int, float],
n_fft: int,
n_overlap: int,
n_per_seg: Union[int, None],
window_method: Union[str, float, tuple],
average_windows: bool,
average_epochs: bool,
average_segments: Union[str, None],
n_jobs: int,
) -> None:
"""Calculates the power spectral density of the data with Welch's
method, using the implementation in MNE
'time_frequency.psd_array_welch'.
Welch's method involves calculating periodograms for a sliding window
over time which are then averaged together for each channel/epoch.
PARAMETERS
----------
fmin : int | float; default 0
- The minimum frequency of interest.
fmax : int | float; default infinite
- The maximum frequency of interest.
n_fft : int; default 256
- The length of the FFT used. Must be >= 'n_per_seg'. If 'n_fft' >
'n_per_seg', the segments will be zero-padded.
n_overlap : int; default 0
- The number of points to overlap between segments, which will be
adjusted to be <= the number of time points in the data.
n_per_seg : int | None; default None
- The length of each Welch segment, windowed by a Hamming window. If
'None', 'n_per_seg' is set to equal 'n_fft', in which case 'n_fft'
must be <= the number of time points in the data.
window_method : str | float | tuple; default "hamming"
- The windowing function to use. See scipy's 'signal.get_window'
function.
average_windows : bool; default True
- Whether or not to average power results across data windows.
average_epochs : bool; default True
- Whether or not to average power results across epochs.
average_segments : str | None; default "mean"
- How to average segments. If "mean", the arithmetic mean is used. If
"median", the median is used, corrected for bias relative to the
mean. If 'None', the segments are unagreggated.
n_jobs : int; default 1
- The number of jobs to run in parallel. If '-1', this is set to the
number of CPU cores. Requires the 'joblib' package.
"""
results = []
ch_names = self.signal.data[0].ch_names
ch_types = self.signal.data[0].get_channel_types(picks=ch_names)
for i, data in enumerate(self.signal.data):
if self.verbose:
print(
f"\n---=== Computing power for window {i+1} of "
f"{len(self.signal.data)} ===---\n"
)
psds, freqs = time_frequency.psd_array_welch(
x=data.get_data(picks=ch_names),
sfreq=self.signal.data[0].info["sfreq"],
fmin=fmin,
fmax=fmax,
n_fft=n_fft,
n_overlap=n_overlap,
n_per_seg=n_per_seg,
n_jobs=n_jobs,
average=None,
window=window_method,
verbose=self.verbose,
)
results.append(
FillableObject(
attrs={
"data": psds,
"freqs": freqs,
"ch_names": ch_names,
"ch_types": ch_types,
}
)
)
self.results = results
self._results_dims = [
"windows",
"epochs",
"channels",
"frequencies",
"segments",
]
if average_windows:
self._average_results_dim("windows")
if average_epochs:
self._average_results_dim("epochs")
if average_segments:
self._average_results_dim("segments")
def process_multitaper(
self,
fmin: Union[int, float] = 0,
fmax: float = np.inf,
bandwidth: Union[float, None] = None,
adaptive: bool = False,
low_bias: bool = True,
normalization: str = "length",
average_windows: bool = True,
average_epochs: bool = True,
n_jobs: int = 1,
) -> None:
"""Calculates the power spectral density of the data with multitapers,
using the implementation in MNE 'time_frequency.psd_array_multitaper'.
The multitaper method involves calculating the spectral density for
orthogonal tapers and then averaging them together for each
channel/epoch.
PARAMETERS
----------
fmin : int | float; default 0
- The minimum frequency of interest.
fmax : int | float; default infinite
- The maximum frequency of interest.
bandwidth : float | None; default None
- The bandwidth of the multitaper windowing function, in Hz. If
'None', this is set to a window half-bandwidth of 4.
adaptive : bool; default False
- Whether or not to use adaptive weights to combine the tapered
spectra into the power spectral density.
low_bias : bool; default True.
- Whether or not to use only tapers with more than 90% spectral
concentration within bandwidth.
normalization : str; default "length"
- The normalisation strategy to use. If "length", the power spectra is
normalised by the length of the signal. If "full", the power spectra
is normalised by the sampling rate and the signal length.
average_windows : bool; default True
- Whether or not to average power results across data windows.
average_epochs : bool; default True
- Whether or not to average power results across epochs.
n_jobs : int; default 1
- The number of jobs to run in parallel. If '-1', this is set to the
number of CPU cores. Requires the 'joblib' package.
RAISES
------
ProcessingOrderError
- Raised if the data in the object has already been processed.
"""
if self._processed:
ProcessingOrderError(
"The data in this object has already been processed. "
"Initialise a new instance of the object if you want to "
"perform other analyses on the data."
)
if self.verbose:
print("Performing multitaper power analysis on the data.\n")
self._get_results_multitaper(
fmin=fmin,
fmax=fmax,
bandwidth=bandwidth,
adaptive=adaptive,
low_bias=low_bias,
normalization=normalization,
average_windows=average_windows,
average_epochs=average_epochs,
n_jobs=n_jobs,
)
self._processed = True
self._power_method = "multitaper"
self.processing_steps["power_multitaper"] = {
"fmin": fmin,
"fmax": fmax,
"bandwidth": bandwidth,
"adaptive": adaptive,
"low_bias": low_bias,
"normalization": normalization,
"average_windows": average_windows,
"average_epochs": average_epochs,
}
def _get_results_multitaper(
self,
fmin: Union[int, float],
fmax: float,
bandwidth: Union[float, None],
adaptive: bool,
low_bias: bool,
normalization: str,
average_windows: bool,
average_epochs: bool,
n_jobs: int,
) -> None:
"""Calculates the power spectral density of the data with multitapers,
using the implementation in MNE 'time_frequency.psd_array_multitaper'.
The multitaper method involves calculating the spectral density for
orthogonal tapers and then averaging them together for each
channel/epoch.
PARAMETERS
----------
fmin : int | float; default 0
- The minimum frequency of interest.
fmax : int | float; default infinite
- The maximum frequency of interest.
bandwidth : float | None; default None
- The bandwidth of the multitaper windowing function, in Hz. If
'None', this is set to a window half-bandwidth of 4.
adaptive : bool; default False
- Whether or not to use adaptive weights to combine the tapered
spectra into the power spectral density.
low_bias : bool; default True.
- Whether or not to use only tapers with more than 90% spectral
concentration within bandwidth.
normalization : str; default "length"
- The normalisation strategy to use. If "length", the power spectra is
normalised by the length of the signal. If "full", the power spectra
is normalised by the sampling rate and the signal length.
average_windows : bool; default True
- Whether or not to average power results across data windows.
average_epochs : bool; default True
- Whether or not to average power results across epochs.
n_jobs : int; default 1
- The number of jobs to run in parallel. If '-1', this is set to the
number of CPU cores. Requires the 'joblib' package.
"""
results = []
ch_names = self.signal.data[0].ch_names
ch_types = self.signal.data[0].get_channel_types(picks=ch_names)
for i, data in enumerate(self.signal.data):
if self.verbose:
print(
f"\n---=== Computing power for window {i+1} of "
f"{len(self.signal.data)} ===---\n"
)
psds, freqs = time_frequency.psd_array_multitaper(
x=data.get_data(picks=ch_names),
sfreq=self.signal.data[0].info["sfreq"],
fmin=fmin,
fmax=fmax,
bandwidth=bandwidth,
adaptive=adaptive,
low_bias=low_bias,
normalization=normalization,
n_jobs=n_jobs,
verbose=self.verbose,
)
results.append(
FillableObject(
attrs={
"data": psds,
"freqs": freqs,
"ch_names": ch_names,
"ch_types": ch_types,
}
)
)
self.results = results
self._results_dims = ["windows", "epochs", "channels", "frequencies"]
if average_windows:
self._average_results_dim("windows")
if average_epochs:
self._average_results_dim("epochs")
def process_morlet(
self,
freqs: list[Union[int, float]],
n_cycles: Union[int, float, list[Union[int, float]]],
use_fft: bool = False,
zero_mean: bool = True,
average_windows: bool = True,
average_epochs: bool = True,
average_timepoints: bool = True,
decim: Union[int, slice] = 1,
n_jobs: int = 1,
) -> None:
"""Calculates a time-frequency representation with Morlet wavelets,
using the implementation in MNE 'time_frequency.tfr_array_morlet'.
PARAMETERS
----------
freqs : list[int | float]
- The frequencies, in Hz, to analyse.
n_cycles : int | float | list[int | float]
- The number of cycles to use. If an int or float, this number of
cycles is used for all frequencies. If a list, each entry should
correspond to the number of cycles for an individual frequency.
use_fft : bool; default False
- Whether or not to use FFT-based convolution.
zero_mean : bool; default True
- Whether or not to set the mean of the wavelets to 0.
average_windows : bool; default True
- Whether or not to average the results across windows.
average_epochs : bool; default True
- Whether or not to average the results across epochs.
average_timepoints : bool; default True
- Whether or not to average the results across timepoints.
decim : int | slice : default 1
- The decimation factor to use after time-frequency decomposition to
reduce memory usage. If an int, returns [..., ::decim]. If a slice,
returns [..., decim].
n_jobs : int; default 1
- The number of jobs to run in paraller. If '-1', it is set to the
number of CPU cores. Requires the 'joblib' package.
RAISES
------
ProcessingOrderError
- Raised if the data in the object has already been processed.
"""
if self._processed:
ProcessingOrderError(
"The data in this object has already been processed. "
"Initialise a new instance of the object if you want to "
"perform other analyses on the data."
)
if self.verbose:
print("Performing Morlet wavelet power analysis on the data.\n")
self._get_results_morlet(
freqs=freqs,
n_cycles=n_cycles,
use_fft=use_fft,
zero_mean=zero_mean,
average_windows=average_windows,
average_epochs=average_epochs,
average_timepoints=average_timepoints,
decim=decim,
n_jobs=n_jobs,
)
self._processed = True
self._power_method = "morlet"
self.processing_steps["power_morlet"] = {
"freqs": freqs,
"n_cycles": n_cycles,
"use_fft": use_fft,
"zero_mean": zero_mean,
"average_windows": average_windows,
"average_epochs": average_epochs,
"average_timepoints": average_timepoints,
"decim": decim,
}
def _get_results_morlet(
self,
freqs: list[Union[int, float]],
n_cycles: Union[int, float, list[Union[int, float]]],
use_fft: bool,
zero_mean: bool,
average_windows: bool,
average_epochs: bool,
average_timepoints: bool,
decim: Union[int, slice],
n_jobs: int,
) -> None:
"""Calculates a time-frequency representation with Morlet wavelets,
using the implementation in MNE 'time_frequency.tfr_array_morlet'.
PARAMETERS
----------
freqs : list[int | float]
- The frequencies, in Hz, to analyse.
n_cycles : int | float | list[int | float]
- The number of cycles to use. If an int or float, this number of
cycles is used for all frequencies. If a list, each entry should
correspond to the number of cycles for an individual frequency.
use_fft : bool; default False
- Whether or not to use FFT-based convolution.
zero_mean : bool; default True
- Whether or not to set the mean of the wavelets to 0.
average_windows : bool; default True
- Whether or not to average the results across windows.
average_epochs : bool; default True
- Whether or not to average the results across epochs.
average_timepoints : bool; default True
- Whether or not to average the results across timepoints.
decim : int | slice : default 1
- The decimation factor to use after time-frequency decomposition to
reduce memory usage. If an int, returns [..., ::decim]. If a slice,
returns [..., decim].
n_jobs : int; default 1
- The number of jobs to run in paraller. If '-1', it is set to the
number of CPU cores. Requires the 'joblib' package.
"""
results = []
for i, data in enumerate(self.signal.data):
if self.verbose:
print(
f"\n---=== Computing power for window {i+1} of "
f"{len(self.signal.data)} ===---\n"
)
output = time_frequency.tfr_morlet(
inst=data,
freqs=freqs,
n_cycles=n_cycles,
use_fft=use_fft,
return_itc=False,
decim=decim,
n_jobs=n_jobs,
picks=np.arange(len(self.signal.data[0].ch_names)),
zero_mean=zero_mean,
average=False,
output="power",
verbose=self.verbose,
)
results.append(
FillableObject(
attrs={
"data": output.data,
"freqs": output.freqs,
"ch_names": output.ch_names,
"ch_types": output.get_channel_types(
picks=output.ch_names
),
}
)
)
self.results = results
self._results_dims = [
"windows",
"epochs",
"channels",
"frequencies",
"timepoints",
]
if average_windows:
self._average_results_dim("windows")
if average_epochs:
self._average_results_dim("epochs")
if average_timepoints:
self._average_results_dim("timepoints")
def _average_results_dim(self, dim: str) -> None:
"""Averages results of the analysis across a results dimension.
PARAMETERS
----------
dim : str
- The dimension of the results to average across. Recognised inputs
are: "window"; "epochs"; "frequencies"; and "timepoints".
RAISES
------
NotImplementedError
- Raised if the dimension is not supported.
ProcessingOrderError
- Raised if the dimension has already been averaged across.
ValueError
- Raised if the dimension is not present in the results to average
across.
"""
recognised_inputs = [
"windows",
"epochs",
"frequencies",
"timepoints",
"segments",
]
if dim not in recognised_inputs:
raise NotImplementedError(
f"The dimension '{dim}' is not supported for averaging. "
f"Supported dimensions are {recognised_inputs}."
)
if getattr(self, f"_{dim}_averaged"):
raise ProcessingOrderError(
f"Trying to average the results across {dim}, but this has "
"already been done."
)
if dim not in self._results_dims:
raise ValueError(
f"No {dim} are present in the results to average across."
)
if dim == "windows":
n_events = self._average_windows()
else:
dim_i = self.results_dims.index(dim)
n_events = np.shape(self.results[0].data)[dim_i]
for i, power in enumerate(self.results):
self.results[i].data = np.mean(power.data, axis=dim_i)
self._results_dims.pop(dim_i + 1)
setattr(self, f"_{dim}_averaged", True)
if self.verbose:
print(f"\nAveraging the data over {n_events} {dim}.")
def _average_windows(self) -> int:
"""Averages the power results across windows.
RETURNS
-------
n_windows : int
- The number of windows being averaged across.
"""
n_windows = len(self.results)
if n_windows > 1:
power = []
for results in self.results:
power.append(results.data)
self.results[0].data = np.asarray(power).mean(axis=0)
self.results = [self.results[0]]
return n_windows
def _sort_normalisation_inputs(
self,
norm_type: str,
within_dim: str,
exclude_line_noise_window: Union[int, float, None],
line_noise_freq: Union[int, float, None],
) -> None:
"""Sorts the user inputs for the normalisation of results.
PARAMETERS
----------
norm_type : str
- The type of normalisation to apply.
- Currently, only "percentage_total" is supported.
within_dim : str
- The dimension to apply the normalisation within.
exclusion_line_noise_window : int | float | None
- The size of the windows (in Hz) to exclude frequencies around the
line noise and harmonic frequencies from the calculations of what to
normalise the data by.
line_noise_freq : int | float | None
- Frequency (in Hz) of the line noise.
RAISES
------
NotImplementedError
- Raised if the requested normalisation type is not supported.
- Raised if the length of the results dimensions are greater than the
maximum number supported.
ValueError
- Raised if the dimension to normalise across is not present in the
results dimensions.
- Raised if a window of results are to be excluded from the
normalisation around the line noise, but no line noise frequency is
given.
"""
supported_norm_types = ["percentage_total"]
max_supported_n_dims = 2
if norm_type not in supported_norm_types:
raise NotImplementedError(
"Error when normalising the results of the Morlet power "
f"analysis:\nThe normalisation type '{norm_type}' is not "
"supported. The supported normalisation types are: "
f"{supported_norm_types}."
)
if len(self.results_dims) > max_supported_n_dims:
raise NotImplementedError(
"Error when normalising the results of the Morlet power "
"analysis:\nCurrently, normalising the values of results with "
f"at most {max_supported_n_dims} is supported, but the results "
f"have {len(self.results_dims)} dimensions."
)
if within_dim not in self.results_dims:
raise ValueError(
"Error when normalising the results of the Morlet power "
f"analysis:\nThe dimension '{within_dim}' is not present in "
f"the results of dimensions {self.results_dims}."
)
if line_noise_freq is None and exclude_line_noise_window is not None:
raise ValueError(
"Error when normalising the results of the Morlet power "
"analysis:\nYou have requested a window to be excluded around "
"the line noise, but no line noise frequency has been "
"provided."
)
def normalise(
self,
norm_type: str,
within_dim: str,
exclude_line_noise_window: Union[int, float, None] = None,
line_noise_freq: Union[int, float, None] = None,
freq_range: list[int | float] = None,
) -> None:
"""Normalises the results of the Morlet power analysis.
PARAMETERS
----------
norm_type : str
- The type of normalisation to apply.
- Currently, only "percentage_total" is supported.
within_dim : str
- The dimension to apply the normalisation within.
- E.g. if the data has dimensions "channels" and "frequencies",
setting 'within_dims' to "channels" would normalise the data across
the frequencies within each channel.
- Currently, normalising only two-dimensional data is supported.
exclusion_line_noise_window : int | float | None; default None
- The size of the windows (in Hz) to exclude frequencies around the
line noise and harmonic frequencies from the calculations of what to
normalise the data by.
- If None, no frequencies are excluded.
- E.g. if the line noise is 50 Hz and 'exclusion_line_noise_window' is
10, the results from 45 - 55 Hz would be omitted.
line_noise_freq : int | float | None; default None
- Frequency (in Hz) of the line noise.
- If None, 'exclusion_line_noise_window' must also be None.
freq_range : list of int or float | None; default None
Frequency range (in Hz) to use for computing the normalisation,
consisting of the lower and upper frequency, respectively.
RAISES
------
ProcessingOrderError
- Raised if the results have already been normalised.
"""
if self._normalised:
raise ProcessingOrderError(
"Error when normalising the results of the Morlet power "
"analysis:\nThe results have already been normalised."
)
self._sort_normalisation_inputs(
norm_type=norm_type,
within_dim=within_dim,
exclude_line_noise_window=exclude_line_noise_window,
line_noise_freq=line_noise_freq,
)
if norm_type == "percentage_total":
for i, power in enumerate(self.results):
self.results[i].data = norm_percentage_total(
data=deepcopy(power.data),
freqs=self.results[0].freqs,
data_dims=self._results_dims[1:],
within_dim=within_dim,
line_noise_freq=line_noise_freq,
exclusion_window=exclude_line_noise_window,
freq_range=freq_range,
)
self._normalised = True
self.processing_steps[f"power_{self._power_method}_normalisation"] = {
"normalisation_type": norm_type,
"within_dim": within_dim,
"exclude_line_noise_window": exclude_line_noise_window,
"line_noise_freq": line_noise_freq,
"freq_range": freq_range,
}
if self.verbose:
print(
f"Normalising results with type '{norm_type}' on the "
f"{within_dim} dimension in the range {freq_range[0]}-"
f"{freq_range[1]} Hz using a line noise exclusion window at "
f"{line_noise_freq} Hz of {exclude_line_noise_window} Hz."
)
def save_object(
self,
fpath: str,
ask_before_overwrite: Union[bool, None] = None,
) -> None:
"""Saves the PowerMorlet object as a .pkl file.
PARAMETERS
----------
fpath : str
- Location where the data should be saved. The filetype extension
(.pkl) can be included, otherwise it will be automatically added.
ask_before_overwrite : bool
- Whether or not the user is asked to confirm to overwrite a
pre-existing file if one exists.
"""
if ask_before_overwrite is None:
ask_before_overwrite = self.verbose
save_object(
to_save=self,
fpath=fpath,
ask_before_overwrite=ask_before_overwrite,
verbose=self.verbose,
)
def results_as_dict(self) -> dict:
"""Returns the power results and additional information as a dictionary.
RETURNS
-------
dict
- The results and additional information stored as a dictionary.
"""
dimensions = self._get_optimal_dims()
results = self.get_results(dimensions=dimensions)
results = {
f"power-{self._power_method}": results.tolist(),
f"power-{self._power_method}_dimensions": dimensions,
"freqs": self.results[0].freqs.tolist(),
"ch_names": self.results[0].ch_names,
"ch_types": self.results[0].ch_types,
"ch_coords": self.signal.get_coordinates(),
"ch_regions": ordered_list_from_dict(
self.results[0].ch_names, self.extra_info["ch_regions"]
),
"ch_subregions": ordered_list_from_dict(
self.results[0].ch_names, self.extra_info["ch_subregions"]
),
"ch_hemispheres": ordered_list_from_dict(
self.results[0].ch_names, self.extra_info["ch_hemispheres"]
),
"ch_reref_types": ordered_list_from_dict(
self.results[0].ch_names, self.extra_info["ch_reref_types"]
),
"samp_freq": self.signal.data[0].info["sfreq"],
"metadata": self.extra_info["metadata"],
"processing_steps": self.processing_steps,
"subject_info": self.signal.data[0].info["subject_info"],
}
return results
def get_results(self, dimensions: Union[list[str], None] = None) -> NDArray:
"""Extracts and returns results.
PARAMETERS
----------
dimensions : list[str] | None
- The order of the dimensions of the results to return. If 'None', the
current result dimensions are used.
RETURNS
-------
results : numpy array
- The results.
"""
ch_names = [self.signal.data[0].ch_names]
ch_names.extend([results.ch_names for results in self.results])
if not check_matching_entries(objects=ch_names):
raise ValueError(
"Error when getting the results:\nThe names and/or order of "
"names in the data and results do not match."
)
if self._windows_averaged:
results = self.results[0].data
else:
results = []
for mne_obj in self.results:
results.append(mne_obj.data)
results = np.asarray(results)
if dimensions is not None and dimensions != self.results_dims: