-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
2376 lines (1948 loc) · 79 KB
/
utils.py
File metadata and controls
2376 lines (1948 loc) · 79 KB
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
"""Utility functions for analyzing the sampling paradigm."""
import itertools
import multiprocessing
import os
import warnings
from collections import OrderedDict
from functools import partial
import mne
import numpy as np
import pandas as pd
import scipy
import scipy.signal
import scipy.stats
from scipy.spatial.distance import pdist, squareform
from scipy.stats.stats import _kendall_dis
import statsmodels.api as sm
from sklearn.covariance import LedoitWolf
from sklearn.discriminant_analysis import _cov
from tqdm.auto import tqdm
# Adjust this path to where the bids directory is stored
home = os.path.expanduser("~")
if "stefanappelhoff" in home:
BIDS_ROOT = os.path.join("/", "home", "stefanappelhoff", "Desktop", "sp_data")
elif "appelhoff" in home:
BIDS_ROOT = os.path.join("/", "home", "appelhoff", "appelhoff", "sp_data")
# There are 5 types of tasks, in the datafiles the markers
# are always the same. We prepare a dict to distinguish them
# when we concatenate datafiles
TASK_BASED_INCREMENTS = {
task: increment
for task, increment in zip(
["ActiveFixed", "ActiveVariable", "YokedFixed", "YokedVariable", "description"],
range(100, 999, 100),
)
}
TASK_NAME_MAP = {
"ActiveFixed": "AF",
"ActiveVariable": "AV",
"YokedFixed": "YF",
"YokedVariable": "YV",
"description": "DESC",
}
# Define dimensions along which we want to know about the events
EVENT_PARAMS = OrderedDict()
EVENT_PARAMS["sampling"] = ("active", "yoked")
EVENT_PARAMS["stopping"] = ("fixed", "variable")
EVENT_PARAMS["direction"] = ("left", "right")
EVENT_PARAMS["outcome"] = tuple(["out{}".format(ii) for ii in range(1, 10)])
EVENT_PARAMS["outcome_bin"] = tuple(["bin{}".format(ii) for ii in range(1, 10)])
EVENT_PARAMS["outcome_bin_orth"] = tuple(
["orthbin{}".format(ii) for ii in range(1, 10)]
)
EVENT_PARAMS["timing"] = ("early", "mid", "late", "mixed_timing")
EVENT_PARAMS["switch"] = ("pre_switch", "post_switch", "no_switch", "mixed_switch")
EVENT_PARAMS["order"] = ("first", "midth", "last", "mixed_order")
EVENT_PARAMS["half"] = ("first_half", "second_half", "mixed_half")
# Form an EVENT_ID out of all possible combinations
_all_codes = list(itertools.product(*EVENT_PARAMS.values()))
_all_codes = ["/".join(ii) for ii in _all_codes]
EVENT_ID = dict(zip(_all_codes, range(1, len(_all_codes) + 1)))
def get_ibin_for_sample(n_samples, sample, min_n_samples, memo):
"""Calculate which bin idx a sample falls into.
Parameters
----------
n_samples : int
Overall number of samples in this trial.
sample : int
Index of the current sample to be binned. Zero indexed, sample must
be < n_samples.
min_n_samples : int
Minimum number of samples in each trial. This determins the bins by
np.linspace(0, 1, min_n_samples).
memo : dict
Previously computed results assuming the same `min_n_samples`
parameter. Each key is a tuple in the form
(`n_samples`, `sample`, `min_n_samples`) with a value `sample_ibin`.
Returns
-------
sample_ibin : int
The bin idx of the current `sample`.
memo : dict
Previously computed results updated with current result.
Notes
-----
Bins include the right bin edge: ``bins[i-1] < x <= bins[i]``
Examples
--------
>>> min_n_samples = 6
>>> sample_ibin, memo = get_ibin_for_sample(6, 0, min_n_samples, {})
0
>>> sample_ibin, memo = get_ibin_for_sample(6, 5, min_n_samples, memo)
5
>>> sample_ibin, memo = get_ibin_for_sample(12, 11, min_n_samples, memo)
5
"""
# If we have memoized this result, return early
if (n_samples, sample, min_n_samples) in memo:
return memo[(n_samples, sample, min_n_samples)], memo
# Else, check and start computing
if n_samples < min_n_samples:
raise RuntimeError('n_samples must be >= min_n_samples')
if sample >= n_samples:
raise RuntimeError('sample must be < n_samples')
data = np.arange(n_samples) / (n_samples-1)
bins = np.linspace(0, 1, min_n_samples)
bin_idxs = np.digitize(data, bins, right=True)
for isample, ibin in zip(np.arange(n_samples), bin_idxs):
memo[(n_samples, isample, min_n_samples)] = ibin
sample_ibin = memo[(n_samples, sample, min_n_samples)]
return sample_ibin, memo
def get_df_bnt(BIDS_ROOT):
"""Get Berlin Numeracy Test data frame."""
# mapping between paper "task" 1, 2a, 2b, 3 and this experiment "task" 1, 2, 3, 4:
bnt_map = {
"q1": "q1_correct",
"q2a": "q4_correct",
"q2b": "q2_correct",
"q3": "q3_correct",
}
# Read data
fname_bnt = os.path.join(BIDS_ROOT, "phenotype", "berlin_numeracy_test.tsv")
# Make sure the result columns are read as booleans
result_columns = ["q{}_correct".format(i) for i in range(1, 5)]
dtypes = {i: bool for i in result_columns}
df_bnt = pd.read_csv(fname_bnt, sep="\t", dtype=dtypes)
# Get "subject" column: sub-01 -> 1
df_bnt["subject"] = df_bnt["participant_id"].str.lstrip("sub-").to_numpy(dtype=int)
def classify_bnt(df_bnt):
"""Classify participants into quartiles for the BNT.
Use adaptive scoring method as described in:
https://doi.org/10.1037/t45862-000
"""
# triage the quartile for each subject
quartiles = list()
for idx, row in df_bnt.iterrows():
# Got q1 right
if row[bnt_map["q1"]]:
# Can be 3rd or 4th quartile
# Got q1 and q2b right
if row[bnt_map["q2b"]]:
# is 4th quartile
quartiles.append(4)
continue
# Got q1 right, but q2b wrong
else:
# Can still be 3d or 4th quartile
if row[bnt_map["q3"]]:
# q1 correct, q2b wrong, but q3 correct
# is 4th quartile
quartiles.append(4)
continue
else:
# q1 correct, q2b wrong, q3 wrong
# is 3rd quartile
quartiles.append(3)
continue
# Got q1 wrong
else:
# Can be 1st or 2nd quartile
if not row[bnt_map["q2a"]]:
# Got q1 wrong, q2a wrong
# is first quartile
quartiles.append(1)
continue
else:
# Got q1 wrong, but q2a right
# is 2nd quartile
quartiles.append(2)
continue
return quartiles
# Add evaluated columns to DF
df_bnt["bnt_quartile"] = classify_bnt(df_bnt)
df_bnt["bnt_n_correct"] = np.sum(df_bnt[result_columns].to_numpy(dtype=int), axis=1)
return df_bnt
def extract_sample_frequencies(df, with_sides):
"""Extract sample frequencies from `df`'s 'action' and 'outcome' cols.
Parameters
----------
df : pandas.DataFrame
The behavioral data.
with_sides : bool
If True, get the sampling frequencies for left (1-9) and right (1-9)
in that order. If False, get sampling frequencies for 1-9 collapsed
over sides (left, right).
Returns
-------
sample_frequencies : ndarray
The sample frequencies.
"""
# get frequencies from 1 to 9 for each side
sample_frequencies = df.groupby("action")["outcome"].value_counts(sort=False)
# sanity check ordering of 'outcome' is 1-9 for each side
outcome_order = np.array([i[1] for i in sample_frequencies.index])
check_outcome_order = np.tile(np.arange(1, 10), 2)
assert np.array_equal(outcome_order, check_outcome_order)
# sanity check that ordering of 'action' is left, then right (0, then 1)
level_vals = (
df.groupby("action")["outcome"]
.value_counts(sort=False)
.index.get_level_values("action")
)
assert level_vals[0] == 0
assert level_vals[-1] == 1
# if collapsed over sides is wanted, we simply take the sum
sample_frequencies = sample_frequencies.to_numpy()
if not with_sides:
sample_frequencies = sample_frequencies.reshape(2, 9).sum(0)
return sample_frequencies
def _kendall_tau_a(x, y):
"""Compute Kendall's Tau metric, A-variant.
Taken from scipy.stats.kendalltau and modified to be the tau-a variant.
Same as in the mne-rsa package by @wmvanvliet. See:
https://github.com/wmvanvliet/mne-rsa/blob/0c92eaf64c8d05676879b0da7ffc96ad6ac2d12e/mne_rsa/rsa.py#L15
https://github.com/scipy/scipy/pull/9361/commits/4d85c35f57cd577a0322becef0d8c7ccb6fdec39
Practically, this line changes:
tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
to
tau = con_minus_dis / tot
See: https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient#Tau-a
Tested against R package DescTools:KendallTauA
Tested against pyrsa (https://github.com/rsagroup/pyrsa)
Notes
-----
When comparing model RDMs that predict tied ranks (e.g., category
models) with model RDMs that make more detailed predictions
(e.g., brain RDMs), Kendall's tau A correlation is recommended,
because unlike Pearson and Spearman correlations, it does *not*
prefer simple model RDMs (those that contain tied ranks). [1]_ [2]_
References
----------
.. [1] https://doi.org/10.1016/j.jmp.2016.10.007
.. [2] https://doi.org/10.1371/journal.pcbi.1003553
"""
x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
if x.size != y.size:
raise ValueError(
"All inputs to `kendalltau` must be of the same size,"
" found x-size %s and y-size %s" % (x.size, y.size)
)
elif not x.size or not y.size:
return np.nan # Return NaN if arrays are empty
def count_rank_tie(ranks):
cnt = np.bincount(ranks).astype("int64", copy=False)
cnt = cnt[cnt > 1]
return (
(cnt * (cnt - 1) // 2).sum(),
(cnt * (cnt - 1.0) * (cnt - 2)).sum(),
(cnt * (cnt - 1.0) * (2 * cnt + 5)).sum(),
)
size = x.size
perm = np.argsort(y) # sort on y and convert y to dense ranks
x, y = x[perm], y[perm]
y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
# stable sort on x and convert x to dense ranks
perm = np.argsort(x, kind="mergesort")
x, y = x[perm], y[perm]
x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
dis = _kendall_dis(x, y) # discordant pairs
obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
cnt = np.diff(np.nonzero(obs)[0]).astype("int64", copy=False)
ntie = (cnt * (cnt - 1) // 2).sum() # joint ties
xtie, x0, x1 = count_rank_tie(x) # ties in x, stats
ytie, y0, y1 = count_rank_tie(y) # ties in y, stats
tot = (size * (size - 1)) // 2
if xtie == tot or ytie == tot:
return np.nan
# Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
# = con + dis + xtie + ytie - ntie
con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
tau = con_minus_dis / tot
# Limit range to fix computational errors
tau = min(1.0, max(-1.0, tau))
return tau
def split_dict(erp_dict):
"""Split an erp_dict into AF, AV, YF, YV.
An erp_dict that contains `sampling_styles` and `stopping_styles` is
split up into a new, nested erp_dict: `newd`, where the first level of
keys are all combinations of sampling and stopping styles, and the second
level of keys are as they were in the original `erp_dict`
Parameters
----------
erp_dict : dict
The ERP dict with mne.evoked objects. Must be a dict with keys that
start with `active/fixed`, or similar.
Returns
-------
newd : dict
The `erp_dict` split up into a two level nested dict
"""
sampling_styles = ("active", "yoked")
stopping_styles = ("fixed", "variable")
newd = dict()
for key, val in erp_dict.items():
keycomponents = key.split("/")
assert keycomponents[0] in sampling_styles + stopping_styles
assert keycomponents[1] in sampling_styles + stopping_styles
remaining_facs_len = len(keycomponents) - 2
for sampling_style in sampling_styles:
for stopping_style in stopping_styles:
if all(
style in keycomponents for style in [sampling_style, stopping_style]
):
style = "{}/{}".format(sampling_style, stopping_style)
newd[style] = newd.get(style, dict())
newkey = "/".join(keycomponents[-remaining_facs_len:])
newd[style][newkey] = val
return newd
def bin_outcomes(vec, nbins):
"""Turn `vec` into `nbins` even-sized bins starting with 1."""
# Get bin edges through percentiles to ensure each bin contains an
# approximately equal number of observations
bin_edges = np.zeros(nbins)
for nth in range(1, nbins + 1):
bin_edges[nth - 1] = np.percentile(vec, q=(100 / nbins) * nth)
# bin the data, including the right edge, i.e. from minimum of data until
# first edge (inclusive) is the first bin ... etc.
vec_binned = np.digitize(vec, bins=bin_edges, right=True)
# Make sure the bins are 1-indexed
vec_binned += 1
return vec_binned
def add_binned_outcomes_to_df(df):
"""Add outcome columns to the behavioral data.
Normalize each outcome by the mean_outcome of the trial that outcome
occurred in. Then digitize the resulting vector so that we have as many
bins as we have "number" outcomes (1 to 9). Binned outcomes have a very
high correlation with outcomes, so we also partial out outcomes from
binned outcomes, and add these "orthogonalized" binned outcomes.
In this process, the following columns will be added:
- outcome_mean, the mean outcome for a trial
- outcome_norm, the sample outcome when normalized by trial mean outcome
- outcome_bin, the bin that the sample outcome is in, considering all trials
- outcome_bin_orth, outcome_bin but with "outcome" partialled out
As such, "outcome_bin_orth" represents the local information in a single
trial, whereas "outcome" represents the global information over the
whole experiment.
See also
--------
bin_outcomes
"""
already_in_df = []
msg = f"Cannot run function, because several columns to be added are already in df: {already_in_df}"
for col in ["outcome_mean", "outcome_norm", "outcome_bin", "outcome_bin_orth"]:
if col in df:
already_in_df.append(col)
if len(already_in_df) > 0:
raise ValueError(msg)
# work on a copy
df = df.copy()
# Get mean outcome per subject, task, and trial
df_mean_outcome = (
df.groupby(["subject", "task", "trial"])
.mean()["outcome"]
.reset_index()
.rename(columns={"outcome": "outcome_mean"})
)
# Merge mean_outcome column onto this DF
df = df.merge(df_mean_outcome, on=["subject", "task", "trial"], validate="m:1")
# Normalized outcomes
df["outcome_norm"] = df["outcome"] - df["outcome_mean"]
# Add binned outcomes
df["outcome_bin"] = bin_outcomes(df["outcome_norm"].to_numpy(), nbins=9)
# Partial out outcomes from binned outcomes
X = df[["outcome", "outcome_bin"]].to_numpy()
X_orth = spm_orth(X)
# Make sure that `spm_orth` did not change the first column
assert np.array_equal(X_orth[:, 0], df["outcome"].to_numpy())
# however, the second column was orthogonalized with respect to first
assert not np.array_equal(X_orth[:, 1], df["outcome_bin"].to_numpy())
# bin the orthogonalized vector again
df["outcome_bin_orth"] = bin_outcomes(X_orth[:, 1], nbins=9)
return df
def spm_orth(X, opt="pad"):
"""Perform a recursive Gram-Schmidt orthogonalisation of basis functions.
This function was translated from Matlab to Python using the code from
the SPM MATLAB toolbox on ``spm_orth.m`` [1]_.
.. warning:: For arrays of shape(1, m) the results are not equivalent
to what the original ``spm_orth.m`` produces.
Parameters
----------
X : numpy.ndarray, shape(n, m)
Data to perform the orthogonalization on. Will be performed on the
columns.
opt : {"pad", "norm"}, optional
If ``"norm"``, perform a euclidean normalization according to
``spm_en.m`` [2]_. If ``"pad"``, ensure that the output is of the
same size as the input. Defaults to ``"pad"``.
Returns
-------
X : numpy.ndarray
The orthogonalized data.
References
----------
.. [1] https://github.com/spm/spm12/blob/master/spm_orth.m
.. [2] https://github.com/spm/spm12/blob/master/spm_en.m
"""
assert X.ndim == 2, "This function only operates on 2D numpy arrays."
n, m = X.shape
X = X[:, np.any(X, axis=0)] # drop all "all-zero" columns
rank_x = np.linalg.matrix_rank(X)
x = X[:, np.newaxis, 0]
j = [0]
for i in range(1, X.shape[-1]):
D = X[:, np.newaxis, i]
D = D - np.dot(x, np.dot(np.linalg.pinv(x), D))
if np.linalg.norm(D, 1) > np.exp(-32):
x = np.concatenate([x, D], axis=1)
j.append(i)
if len(j) == rank_x:
break
if opt == "pad":
# zero padding of null space (if present)
X = np.zeros((n, m))
X[:, np.asarray(j)] = x
elif opt == "norm":
# Euclidean normalization, based on "spm_en.m", see docstring.
for i in range(X.shape[-1]):
if np.any(X[:, i]):
X[:, i] = X[:, i] / np.sqrt(np.sum(X[:, i] ** 2))
else:
# spm_orth.m does "X = x" here. We raise an error, because
# this option is not documented in spm_orth.m
# X = x
raise ValueError("opt must be one of ['pad', 'norm'].")
return X
def _check_nsubjs(erp_dict):
"""Check that number of subjs in dict is consistent.
Parameters
----------
erp_dict : dict
Each key is an ERP contrast with a list of ERPs as
value. The list contains MNE-Python evoked objects
or np.nan.
Returns
-------
nsubjs : int
Number of subjects for each list of ERPs.
Raises
------
RuntimeError
if `nsubjs` is not consistent across all lists of ERPs.
"""
DUMMY_NSUBJS = -1
nsubjs = DUMMY_NSUBJS
for key in erp_dict:
this_nsubjs = len(erp_dict[key])
# If this is the first nsubjs we encounter, store it
if nsubjs == DUMMY_NSUBJS:
nsubjs = this_nsubjs
# make sure all nsubjs are the same
if this_nsubjs != nsubjs:
raise RuntimeError("Encountered different amounts of subjs.")
return nsubjs
def _check_erp_shape(erp_dict):
"""Check the shape of ERPs in dict is consistent.
Parameters
----------
erp_dict : dict
Each key is an ERP contrast with a list of ERPs as
value. The list contains MNE-Python evoked objects
or np.nan.
Returns
-------
erp_shape : tuple
Shape of the ERPs.
Raises
------
RuntimeError
if the `erp_shape` is not consistent across all ERPs.
"""
DUMMY_SHAPE = (-1, -1)
erp_shape = DUMMY_SHAPE
for key in erp_dict:
erp_list = erp_dict[key]
# Go over all list entries that are not NaN
erp_idxs = np.nonzero(~pd.isna(erp_list))[0]
for idx in erp_idxs:
this_shape = erp_list[idx].data.shape
# If this is the first ERP we encounter, store its shape
if erp_shape == DUMMY_SHAPE:
erp_shape = this_shape
# Check that all ERPs have the same shape
if this_shape != erp_shape:
raise RuntimeError("Encountered ERPs with different shape.")
return erp_shape
def dict2arr(erp_dict, scaling=1e6):
"""Convert erp_dict to erp_arr.
Parameters
----------
erp_dict : dict
Each key is an ERP contrast with a list of ERPs as
value. The list contains MNE-Python evoked objects
or np.nan.
scaling : float
Amount by which to scale the data. Defaults to 1e6, which
will result in units "microVolt".
Returns
-------
erp_arr : ndarray
The ERP data from the `erp_dict` scaled by `scaling`. This
array is of shape (n_keys, n_channels, n_timepoints, n_subjects).
For subjects that did not have an ERP for this dict's key (np.nan),
the array will be np.nan for erp_arr[..., subj].
"""
nsubjs = _check_nsubjs(erp_dict)
erp_shape = _check_erp_shape(erp_dict)
erp_arr = np.nan * np.zeros((len(erp_dict), *erp_shape, nsubjs))
for key_i, key in enumerate(erp_dict):
erp_list = erp_dict[key]
# Go over all list entries that are not NaN
# leave the rest as NaN
erp_idxs = np.nonzero(~pd.isna(erp_list))[0]
for idx in erp_idxs:
erp_arr[key_i, ..., idx] = erp_list[idx].data * scaling
return erp_arr
def find_time_idxs(window, times):
"""Find time indices corresponding to a window onset and offset.
Parameters
----------
window : tuple of len 2
The beginning and end of a time window in a unit corresponding to
`times`.
times : ndarray
The time samples in some unit.
Returns
-------
time_idxs : ndarray
The time indices into `times` corresponding to `window`.
"""
tol = np.mean(np.diff(times))
time_idxs = list()
for idx in window:
if np.abs(times - idx).min() > tol:
raise RuntimeWarning("`window` is not within `times`.")
time_idxs.append((np.abs(times - idx)).argmin())
assert len(time_idxs) == 2
if time_idxs[0] == time_idxs[1]:
return np.atleast_1d(time_idxs[0])
assert time_idxs[0] < time_idxs[1]
time_idxs = np.arange(*time_idxs)
return time_idxs
def arr2df(erp_arr, group, window, key_names, ch_names, times):
"""Convert erp_arr to df.
Parameters
----------
erp_arr : ndarray
The ERP data of shape (n_keys, n_channels, n_timepoints, n_subjects).
group : list of str
A list of channel names over which to average.
window : tuple of float
A tuple of length two, determining the start and end ot the time
window over which to average.
key_names : list of str
The names of the different conditions, corresponding to the first
dimension of `erp_arr`.
ch_names : list of str
The channel names, corresponding to the second dimension of
`erp_arr`.
times : ndarray
The time samples, corresponding to the third dimension of `erp_arr`.
Returns
-------
df : pandas.DataFrame
A dataframe of ERP amplitudes over a `group` of channels, and over a
`window` of timepoints. Organized by keys and subjects.
Examples
--------
>>> # for using this with the array output of `calc_timecourse`
>>> corr_arr = np.expand_dims(corr_arr, (0, 1))
>>> arr2df(corr_arr, ['dummy'], window, ['dummy'], ['dummy'], times)
"""
# Find channel idxs for group to average
ch_idxs = np.array([ch_names.index(ch) for ch in group])
# Find time idxs for window to average over
time_idxs = find_time_idxs(window, times)
# Extract mean amplitudes
nkeys, nchans, ntimes, nsubjs = erp_arr.shape
keys = list()
subjs = list()
amps = list()
for ikey, key_name in enumerate(key_names):
key_erp_arr = erp_arr[ikey, ...]
chn_mean = np.mean(key_erp_arr[ch_idxs, ...], axis=0)
time_mean = np.mean(chn_mean[time_idxs], axis=0)
assert time_mean.shape[0] == nsubjs
keys += [key_name] * nsubjs
subjs += list(range(nsubjs))
amps += list(time_mean)
# Form data frame
df = pd.DataFrame((keys, subjs, amps)).T
df.columns = ("key", "subj_repr", "mean_amp")
df["mean_amp"] = np.asarray(df["mean_amp"].values, dtype=float)
return df
def get_mahalanobis_rdm_times(
subj,
df,
epochs,
preproc_settings,
samp,
half,
zscore_before_regress=True,
add_constant=False,
do_full_mnn=False,
outcome_column_name="outcome",
):
"""Calculate the mahalanobis RDM per timepoint for a subject.
Based on performing a ordinary least squares multiple regression across
trials for each channel/time bin of the EEG data. Each trial is predicted
by the condition of the trial, thus the coefficients resemble the
condition wise ERPs, but subtracted with the overall ERP due to the
constant term in the regression (or due to zscoring the dependent
variable prior to regression, or due to both, depending on your
settings of `zscore_before_regress` and `add_constant`).
To form an RDM, we go over each timepoint and calculate the
mahalanobis distance between coefficients
(shape nconditions x nchannels), normalized by the inverse covariance
matrix (shape nchannels x nchannels) that we obtain through the
Ledoit & Wolf method from the regression residuals
(shape ntrials x nchannels).
Parameters
----------
subj : int
The subject ID.
df : pandas.DataFrame
The behavioral data.
epochs : mne.Epochs
The epochs data associated with subj.
preproc_settings : dict
Dict with settings for preprocessing. Accepts keys "crop", "smooth",
"tshift", "baseline".
samp : str
Which kind of sampling epochs to use, can be "active" or "yoked".
half : str
Which half of the epochs to use, can be "both", "first_half", or
"second_half".
zscore_before_regress : bool
Whether or not to zscore the channel/time binned EEG data across
trials prior to regression. Defaults to True.
add_constant : bool
Whether or not to add a constant term to the design matrix for
regression. If True, design matrix will be rank deficient, if False,
`zscore_before_regress` must be True so that regression data is
centered. Defaults to False.
do_full_mnn : bool
Whether or not to do a multivariate noise normalization based on
both sampling types (active AND yoked). If False (default), calculate
noise correction only for the sampling type that is specified via
the `samp` parameter.
outcome_column_name : str
The kind of condition to use for constructing the RDMs. Most often,
this is "outcome", referring to the numeric samples. But it can also
be "outcome_bin", or "outcome_bin_orth" to use binned outcomes after
normalizing them with their trial specific outcome mean, or to
use them after orthogonalization with the normal "outcomes".
Returns
-------
rdm_times : ndarray, shape(nconditions, nconditions, ntimes)
The mahalanobis RDM per timepoint.
coefs : ndarray, shape(ntrials, nchannels, ntimes)
The regression coefficients from the OLS model on preprocessed epochs
predicted by the outcomes of each trial. Can be used for double
checking for similarity against overall mean-subtracted ERPs.
Notes
-----
The design matrix with added constant term is rank deficient, because the
constant term is a linear combination of all other columns (sum). The
software packages will warn about that, however the results will be
relatively stable anyhow. Nevertheless, it is recommended to run
with ``zscore_before_regress=True`` and ``add_constant=False``.
That will center the data, but avoid rendering the design matrix
rank deficient.
"""
# Check options
if (not zscore_before_regress) and (not add_constant):
raise ValueError(
"One or both of `zscore_before_regress` and `add_constant` must be True."
)
good_outcome_cols = ["outcome", "outcome_bin", "outcome_bin_orth"]
if outcome_column_name not in good_outcome_cols:
raise ValueError(f"outcome_column_name must be one of '{good_outcome_cols}'")
# Make sure only EEG channels have been picked
epochs = epochs.pick_types(meg=False, eeg=True)
# Select the half split we are interested in (or "both")
if half != "both":
assert half in ["first_half", "second_half"]
epochs = epochs[f"{half}"]
if not do_full_mnn:
epochs = epochs[f"{samp}"]
# Preprocess EEG data
assert set(preproc_settings.keys()) == set(("crop", "smooth", "baseline", "tshift"))
epochs = prep_epochs(epochs, **preproc_settings, crossvalidate=False, average=False)
# Get outcome vector from behavioral data
# optionally use "outcome_bin" or "outcome_bin_orth"
# look into epochs.drop_log to drop those rows in behavioral data where
# epochs have been rejected. Afterwards, the outcome vector must be of
# same length as the epochs (each epoch associated with one outcome)
kept_epos = np.asarray([False if len(i) > 0 else True for i in epochs.drop_log])
all_outcomes = df[(df["subject"] == subj) & (df["task"] != "DESC")][
outcome_column_name
].to_numpy()
outcomes = all_outcomes[kept_epos]
unique_outcomes = np.unique(outcomes)
if not len(unique_outcomes) == 9:
raise RuntimeError(
f"No 9 outcomes ({outcome_column_name}) for {subj}/{samp}/{half}: {unique_outcomes}"
)
# similarly: get sample type vector (but from epochs data)
inv_map = {v: k for k, v in epochs.event_id.items()}
assert len(inv_map) == len(epochs.event_id)
event_types = [inv_map[i] for i in epochs.events[:, -1]]
assert len(event_types) == len(epochs)
sampling_types = ("active", "yoked")
samplings = []
for event_type in event_types:
sampling = event_type.split("/")[0]
assert sampling in sampling_types
samplings.append(sampling)
samplings = np.array(samplings)
# prepare design matrix
# ---------------------
ntrials = len(outcomes)
assert ntrials == len(epochs)
if do_full_mnn:
# full mnn over each task and outcome
conditions = list(itertools.product(sampling_types, unique_outcomes))
else:
# if we do the MNN over a specific task,
# the predictors are only the outcomes
conditions = unique_outcomes
# each column is a predictor
# the sum over columns for each row is always 1 ... that is, each epoch
# is predicted by its condition
# ntrials x nconditions (no "constant" yet, potentially added later)
# nconditions is either 9 (outcomes),
# or 18 (active x outcomes + yoked x outcomes)
nconditions = len(conditions)
design_matrix = np.zeros((ntrials, nconditions))
for icondi, condi in enumerate(conditions):
if do_full_mnn:
assert isinstance(condi, tuple)
sampling, outcome = condi
outcome_idxs = outcomes == outcome
sampling_idxs = samplings == sampling
idxs = np.logical_and(outcome_idxs, sampling_idxs)
else:
assert isinstance(condi, np.int64)
idxs = outcomes == condi
design_matrix[idxs, icondi] = 1
# sanity check that sum of each row is 1
assert np.sum(design_matrix.sum(axis=1) == 1) == len(epochs)
# add constant
# design matrix X is now ntrials x (nconditions+1)
if add_constant:
X = sm.add_constant(design_matrix, has_constant="raise")
else:
X = design_matrix
# get EEG data and scale to micro Volts
# ntrials x nchannels x ntimes
eeg_data_uV = epochs.get_data() * 1e6
# fit ordinary least squares multiple regression for each channel/time bin
_, nchs, ntimes = eeg_data_uV.shape
assert _ == ntrials
coefs = np.zeros((nconditions, nchs, ntimes))
resids = np.zeros_like(eeg_data_uV)
for ichannel in range(nchs):
for itime in range(ntimes):
data = eeg_data_uV[..., ichannel, itime]
if zscore_before_regress:
y = scipy.stats.zscore(data)
else:
y = data
model = sm.OLS(endog=y, exog=X, missing="raise")
results = model.fit()
if add_constant:
# drop intercept term
coefs[..., ichannel, itime] = results.params[1:]
else:
coefs[..., ichannel, itime] = results.params
resids[..., ichannel, itime] = results.resid
# If we did a full MNN, we need to subselect the "sampling type" we
# are interested in
# NOTE: this turns the nconditions from 18 to 9, fixed to EITHER active
# OR yoked
if do_full_mnn:
# get which part of "coefs" are for active, and which are for yoked
coef_idxs = {}
start = 0
stop = len(np.unique(outcomes))
assert stop == 9
for sampling in sampling_types:
coef_idxs[sampling] = tuple(range(start, stop))
start += stop
stop += stop
# get either only active, or only yoked coefficients
# NOTE: residuals stay the same for MNN: no subselecting there
coefs = coefs[np.array(coef_idxs[samp]), ...]
nconditions = coefs.shape[0]
assert nconditions == 9
# Calculate pairwise mahalanobis distance between regression coefficients
# for each condition, normalized with covariance matrix from regression
# residuals
# done for each timepoint, ending up with rdm
# nconditions x nconditions x ntimes
rdm_times = np.zeros((nconditions, nconditions, ntimes))
for itime in range(ntimes):
response = coefs[..., itime]
residuals = resids[..., itime]