-
Notifications
You must be signed in to change notification settings - Fork 42
/
stats.py
2571 lines (2071 loc) · 94.4 KB
/
stats.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
"""
NeuroLearn Statistics Tools
===========================
Tools to help with statistical analyses.
"""
__all__ = [
"pearson",
"zscore",
"fdr",
"holm_bonf",
"threshold",
"multi_threshold",
"winsorize",
"trim",
"calc_bpm",
"downsample",
"upsample",
"fisher_r_to_z",
"fisher_z_to_r",
"one_sample_permutation",
"two_sample_permutation",
"correlation_permutation",
"matrix_permutation",
"make_cosine_basis",
"summarize_bootstrap",
"regress",
"procrustes",
"procrustes_distance",
"align",
"find_spikes",
"correlation",
"distance_correlation",
"transform_pairwise",
"double_center",
"u_center",
"_bootstrap_isc",
"isc",
"isc_group",
"isfc",
"isps",
"_compute_matrix_correlation",
"_phase_mean_angle",
"_phase_vector_length",
"_butter_bandpass_filter",
"_phase_rayleigh_p",
"_compute_isc_group",
"_permute_isc_group",
"align_states",
]
import numpy as np
from numpy.fft import fft, ifft
import pandas as pd
from scipy.stats import pearsonr, spearmanr, kendalltau, norm
from scipy.stats import t as t_dist
from scipy.spatial.distance import squareform, pdist
from scipy.linalg import orthogonal_procrustes
from scipy.spatial import procrustes as procrust
from scipy.signal import hilbert, butter, filtfilt
from scipy.optimize import linear_sum_assignment
from copy import deepcopy
import nibabel as nib
from scipy.interpolate import interp1d
import warnings
import itertools
from joblib import Parallel, delayed
from .utils import attempt_to_import, check_square_numpy_matrix
from .external.srm import SRM, DetSRM
from sklearn.utils import check_random_state
from sklearn.metrics import pairwise_distances
MAX_INT = np.iinfo(np.int32).max
# Optional dependencies
sm = attempt_to_import("statsmodels.tsa.arima.model", name="sm")
def pearson(x, y):
"""Correlates row vector x with each row vector in 2D array y.
From neurosynth.stats.py - author: Tal Yarkoni
"""
data = np.vstack((x, y))
ms = data.mean(axis=1)[(slice(None, None, None), None)]
datam = data - ms
datass = np.sqrt(np.sum(datam * datam, axis=1))
# datass = np.sqrt(ss(datam, axis=1))
temp = np.dot(datam[1:], datam[0].T)
return temp / (datass[1:] * datass[0])
def zscore(df):
"""zscore every column in a pandas dataframe or series.
Args:
df: (pd.DataFrame) Pandas DataFrame instance
Returns:
z_data: (pd.DataFrame) z-scored pandas DataFrame or series instance
"""
if isinstance(df, pd.DataFrame):
return df.apply(lambda x: (x - x.mean()) / x.std())
elif isinstance(df, pd.Series):
return (df - np.mean(df)) / np.std(df)
else:
raise ValueError("Data is not a Pandas DataFrame or Series instance")
def fdr(p, q=0.05):
"""Determine FDR threshold given a p value array and desired false
discovery rate q. Written by Tal Yarkoni
Args:
p: (np.array) vector of p-values
q: (float) false discovery rate level
Returns:
fdr_p: (float) p-value threshold based on independence or positive
dependence
"""
if not isinstance(p, np.ndarray):
raise ValueError("Make sure vector of p-values is a numpy array")
if any(p < 0) or any(p > 1):
raise ValueError("array contains p-values that are outside the range 0-1")
if np.any(p > 1) or np.any(p < 0):
raise ValueError("Does not include valid p-values.")
s = np.sort(p)
nvox = p.shape[0]
null = np.array(range(1, nvox + 1), dtype="float") * q / nvox
below = np.where(s <= null)[0]
return s[max(below)] if len(below) else -1
def holm_bonf(p, alpha=0.05):
"""Compute corrected p-values based on the Holm-Bonferroni method, i.e. step-down procedure applying iteratively less correction to highest p-values. A bit more conservative than fdr, but much more powerful thanvanilla bonferroni.
Args:
p: (np.array) vector of p-values
alpha: (float) alpha level
Returns:
bonf_p: (float) p-value threshold based on bonferroni
step-down procedure
"""
if not isinstance(p, np.ndarray):
raise ValueError("Make sure vector of p-values is a numpy array")
s = np.sort(p)
nvox = p.shape[0]
null = 0.05 / (nvox - np.arange(1, nvox + 1) + 1)
below = np.where(s <= null)[0]
return s[max(below)] if len(below) else -1
def threshold(stat, p, thr=0.05, return_mask=False):
"""Threshold test image by p-value from p image
Args:
stat: (Brain_Data) Brain_Data instance of arbitrary statistic metric
(e.g., beta, t, etc)
p: (Brain_Data) Brain_data instance of p-values
threshold: (float) p-value to threshold stat image
return_mask: (bool) optionall return the thresholding mask; default False
Returns:
out: Thresholded Brain_Data instance
"""
from nltools.data import Brain_Data
if not isinstance(stat, Brain_Data):
raise ValueError("Make sure stat is a Brain_Data instance")
if not isinstance(p, Brain_Data):
raise ValueError("Make sure p is a Brain_Data instance")
# Create Mask
mask = deepcopy(p)
if thr > 0:
mask.data = (mask.data < thr).astype(int)
else:
mask.data = np.zeros(len(mask.data), dtype=int)
# Apply Threshold Mask
out = deepcopy(stat)
if np.sum(mask.data) > 0:
out = out.apply_mask(mask)
out.data = out.data.squeeze()
else:
out.data = np.zeros(len(mask.data), dtype=int)
if return_mask:
return out, mask
else:
return out
def multi_threshold(t_map, p_map, thresh):
"""Threshold test image by multiple p-value from p image
Args:
stat: (Brain_Data) Brain_Data instance of arbitrary statistic metric
(e.g., beta, t, etc)
p: (Brain_Data) Brain_data instance of p-values
threshold: (list) list of p-values to threshold stat image
Returns:
out: Thresholded Brain_Data instance
"""
from nltools.data import Brain_Data
if not isinstance(t_map, Brain_Data):
raise ValueError("Make sure stat is a Brain_Data instance")
if not isinstance(p_map, Brain_Data):
raise ValueError("Make sure p is a Brain_Data instance")
if not isinstance(thresh, list):
raise ValueError("Make sure thresh is a list of p-values")
affine = t_map.to_nifti().affine
pos_out = np.zeros(t_map.to_nifti().shape)
neg_out = deepcopy(pos_out)
for thr in thresh:
t = threshold(t_map, p_map, thr=thr)
t_pos = deepcopy(t)
t_pos.data = np.zeros(len(t_pos.data))
t_neg = deepcopy(t_pos)
t_pos.data[t.data > 0] = 1
t_neg.data[t.data < 0] = 1
pos_out = pos_out + t_pos.to_nifti().get_fdata()
neg_out = neg_out + t_neg.to_nifti().get_fdata()
pos_out = pos_out + neg_out * -1
return Brain_Data(nib.Nifti1Image(pos_out, affine))
def winsorize(data, cutoff=None, replace_with_cutoff=True):
"""Winsorize a Pandas DataFrame or Series with the largest/lowest value not considered outlier
Args:
data: (pd.DataFrame, pd.Series) data to winsorize
cutoff: (dict) a dictionary with keys {'std':[low,high]} or
{'quantile':[low,high]}
replace_with_cutoff: (bool) If True, replace outliers with cutoff.
If False, replaces outliers with closest
existing values; (default: False)
Returns:
out: (pd.DataFrame, pd.Series) winsorized data
"""
return _transform_outliers(
data, cutoff, replace_with_cutoff=replace_with_cutoff, method="winsorize"
)
def trim(data, cutoff=None):
"""Trim a Pandas DataFrame or Series by replacing outlier values with NaNs
Args:
data: (pd.DataFrame, pd.Series) data to trim
cutoff: (dict) a dictionary with keys {'std':[low,high]} or
{'quantile':[low,high]}
Returns:
out: (pd.DataFrame, pd.Series) trimmed data
"""
return _transform_outliers(data, cutoff, replace_with_cutoff=None, method="trim")
def _transform_outliers(data, cutoff, replace_with_cutoff, method):
"""This function is not exposed to user but is called by either trim
or winsorize.
Args:
data: (pd.DataFrame, pd.Series) data to transform
cutoff: (dict) a dictionary with keys {'std':[low,high]} or
{'quantile':[low,high]}
replace_with_cutoff: (bool) If True, replace outliers with cutoff.
If False, replaces outliers with closest
existing values. (default: False)
method: 'winsorize' or 'trim'
Returns:
out: (pd.DataFrame, pd.Series) transformed data
"""
df = data.copy() # To not overwrite data make a copy
def _transform_outliers_sub(data, cutoff, replace_with_cutoff, method="trim"):
if not isinstance(data, pd.Series):
raise ValueError(
"Make sure that you are applying winsorize to a pandas dataframe or series."
)
if isinstance(cutoff, dict):
# calculate cutoff values
if "quantile" in cutoff:
q = data.quantile(cutoff["quantile"])
elif "std" in cutoff:
std = [
data.mean() - data.std() * cutoff["std"][0],
data.mean() + data.std() * cutoff["std"][1],
]
q = pd.Series(index=cutoff["std"], data=std)
# if replace_with_cutoff is false, replace with true existing values closest to cutoff
if method == "winsorize" and not replace_with_cutoff:
q.iloc[0] = data[data > q.iloc[0]].min()
q.iloc[1] = data[data < q.iloc[1]].max()
else:
raise ValueError("cutoff must be a dictionary with quantile or std keys.")
if method == "trim":
data[data < q.iloc[0]] = np.nan
data[data > q.iloc[1]] = np.nan
elif method == "winsorize":
if isinstance(q, pd.Series) and len(q) == 2:
data[data < q.iloc[0]] = q.iloc[0]
data[data > q.iloc[1]] = q.iloc[1]
return data
# transform each column if a dataframe, if series just transform data
if isinstance(df, pd.DataFrame):
for col in df.columns:
df.loc[:, col] = _transform_outliers_sub(
df.loc[:, col],
cutoff=cutoff,
replace_with_cutoff=replace_with_cutoff,
method=method,
)
return df
elif isinstance(df, pd.Series):
return _transform_outliers_sub(
df, cutoff=cutoff, replace_with_cutoff=replace_with_cutoff, method=method
)
else:
raise ValueError("Data must be a pandas DataFrame or Series")
def calc_bpm(beat_interval, sampling_freq):
"""Calculate instantaneous BPM from beat to beat interval
Args:
beat_interval: (int) number of samples in between each beat
(typically R-R Interval)
sampling_freq: (float) sampling frequency in Hz
Returns:
bpm: (float) beats per minute for time interval
"""
return 60 * sampling_freq * (1 / (beat_interval))
def downsample(
data, sampling_freq=None, target=None, target_type="samples", method="mean"
):
"""Downsample pandas to a new target frequency or number of samples
using averaging.
Args:
data: (pd.DataFrame, pd.Series) data to downsample
sampling_freq: (float) Sampling frequency of data in hertz
target: (float) downsampling target
target_type: type of target can be [samples,seconds,hz]
method: (str) type of downsample method ['mean','median'],
default: mean
Returns:
out: (pd.DataFrame, pd.Series) downsmapled data
"""
if not isinstance(data, (pd.DataFrame, pd.Series)):
raise ValueError("Data must by a pandas DataFrame or Series instance.")
if not (method == "median") | (method == "mean"):
raise ValueError("Metric must be either 'mean' or 'median' ")
if target_type == "samples":
n_samples = target
elif target_type == "seconds":
n_samples = target * sampling_freq
elif target_type == "hz":
n_samples = sampling_freq / target
else:
raise ValueError('Make sure target_type is "samples", "seconds", ' ' or "hz".')
idx = np.sort(np.repeat(np.arange(1, data.shape[0] / n_samples, 1), n_samples))
# if data.shape[0] % n_samples:
if data.shape[0] > len(idx):
idx = np.concatenate([idx, np.repeat(idx[-1] + 1, data.shape[0] - len(idx))])
if method == "mean":
return data.groupby(idx).mean().reset_index(drop=True)
elif method == "median":
return data.groupby(idx).median().reset_index(drop=True)
def upsample(
data, sampling_freq=None, target=None, target_type="samples", method="linear"
):
"""Upsample pandas to a new target frequency or number of samples using interpolation.
Args:
data: (pd.DataFrame, pd.Series) data to upsample
(Note: will drop non-numeric columns from DataFrame)
sampling_freq: Sampling frequency of data in hertz
target: (float) upsampling target
target_type: (str) type of target can be [samples,seconds,hz]
method: (str) ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic']
where 'zero', 'slinear', 'quadratic' and 'cubic'
refer to a spline interpolation of zeroth, first,
second or third order (default: linear)
Returns:
upsampled pandas object
"""
methods = ["linear", "nearest", "zero", "slinear", "quadratic", "cubic"]
if method not in methods:
raise ValueError(
"Method must be 'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'"
)
if target_type == "samples":
n_samples = target
elif target_type == "seconds":
n_samples = target * sampling_freq
elif target_type == "hz":
n_samples = float(sampling_freq) / float(target)
else:
raise ValueError('Make sure target_type is "samples", "seconds", or "hz".')
orig_spacing = np.arange(0, data.shape[0], 1)
new_spacing = np.arange(0, data.shape[0] - 1, n_samples)
if isinstance(data, pd.Series):
interpolate = interp1d(orig_spacing, data, kind=method)
return interpolate(new_spacing)
elif isinstance(data, pd.DataFrame):
numeric_data = data._get_numeric_data()
if data.shape[1] != numeric_data.shape[1]:
warnings.warn(
"Dropping %s non-numeric columns"
% (data.shape[1] - numeric_data.shape[1]),
UserWarning,
)
out = pd.DataFrame(columns=numeric_data.columns, index=None)
for i, x in numeric_data.items():
interpolate = interp1d(orig_spacing, x, kind=method)
out.loc[:, i] = interpolate(new_spacing)
return out
else:
raise ValueError("Data must by a pandas DataFrame or Series instance.")
def fisher_r_to_z(r):
"""Use Fisher transformation to convert correlation to z score"""
# return .5*np.log((1 + r)/(1 - r))
return np.arctanh(r)
def fisher_z_to_r(z):
"""Use Fisher transformation to convert correlation to z score"""
return np.tanh(z)
def correlation(data1, data2, metric="pearson"):
"""This function calculates the correlation between data1 and data2
Args:
data1: (np.array) x
data2: (np.array) y
metric: (str) type of correlation ["spearman" or "pearson" or "kendall"]
Returns:
r: (np.array) correlations
p: (float) p-value
"""
if metric == "spearman":
func = spearmanr
elif metric == "pearson":
func = pearsonr
elif metric == "kendall":
func = kendalltau
else:
raise ValueError('metric must be "spearman" or "pearson" or "kendall"')
return func(data1, data2)
def _permute_sign(data, random_state=None):
random_state = check_random_state(random_state)
return np.mean(data * random_state.choice([1, -1], len(data)))
def _permute_group(data, random_state=None):
random_state = check_random_state(random_state)
perm_label = random_state.permutation(data["Group"])
return np.mean(data.loc[perm_label == 1, "Values"]) - np.mean(
data.loc[perm_label == 0, "Values"]
)
def _permute_func(data1, data2, metric, how, include_diag=False, random_state=None):
"""Helper function for matrix_permutation.
Can take a functon, that would be repeated for calculation.
Args:
data1: (np.array) squareform matrix
data2: flattened np array (same size upper triangle of data1)
metric: similarity/distance function from scipy.stats (e.g., spearman, pearson, kendall etc)
random_state: random_state instance for permutation
Returns:
r: r value of function
"""
random_state = check_random_state(random_state)
data_row_id = range(data1.shape[0])
permuted_ix = random_state.permutation(data_row_id)
new_fmri_dist = data1.iloc[permuted_ix, permuted_ix].values
if how == "upper":
new_fmri_dist = new_fmri_dist[np.triu_indices(new_fmri_dist.shape[0], k=1)]
elif how == "lower":
new_fmri_dist = new_fmri_dist[np.tril_indices(new_fmri_dist.shape[0], k=-1)]
elif how == "full":
if include_diag:
new_fmri_dist = new_fmri_dist.ravel()
else:
new_fmri_dist = np.concatenate(
[
new_fmri_dist[np.triu_indices(new_fmri_dist.shape[0], k=1)],
new_fmri_dist[np.tril_indices(new_fmri_dist.shape[0], k=-1)],
]
)
return correlation(new_fmri_dist, data2, metric=metric)[0]
def _calc_pvalue(all_p, stat, tail):
"""Calculates p value based on distribution of correlations
This function is called by the permutation functions
all_p: list of correlation values from permutation
stat: actual value being tested, i.e., stats['correlation'] or stats['mean']
tail: (int) either 2 or 1 for two-tailed p-value or one-tailed
"""
denom = float(len(all_p)) + 1
if tail == 1:
numer = np.sum(all_p >= stat) + 1 if stat >= 0 else np.sum(all_p <= stat) + 1
elif tail == 2:
numer = np.sum(np.abs(all_p) >= np.abs(stat)) + 1
else:
raise ValueError("tail must be either 1 or 2")
return numer / denom
def one_sample_permutation(
data, n_permute=5000, tail=2, n_jobs=-1, return_perms=False, random_state=None
):
"""One sample permutation test using randomization.
Args:
data: (pd.DataFrame, pd.Series, np.array) data to permute
n_permute: (int) number of permutations
tail: (int) either 1 for one-tail or 2 for two-tailed test (default: 2)
n_jobs: (int) The number of CPUs to use to do the computation.
-1 means all CPUs.
return_parms: (bool) Return the permutation distribution along with the p-value; default False
random_state: (int, None, or np.random.RandomState) Initial random seed (default: None)
Returns:
stats: (dict) dictionary of permutation results ['mean','p']
"""
random_state = check_random_state(random_state)
seeds = random_state.randint(MAX_INT, size=n_permute)
data = np.array(data)
stats = {"mean": np.nanmean(data)}
all_p = Parallel(n_jobs=n_jobs)(
delayed(_permute_sign)(data, random_state=seeds[i]) for i in range(n_permute)
)
stats["p"] = _calc_pvalue(all_p, stats["mean"], tail)
if return_perms:
stats["perm_dist"] = all_p
return stats
def two_sample_permutation(
data1,
data2,
n_permute=5000,
tail=2,
n_jobs=-1,
return_perms=False,
random_state=None,
):
"""Independent sample permutation test.
Args:
data1: (pd.DataFrame, pd.Series, np.array) dataset 1 to permute
data2: (pd.DataFrame, pd.Series, np.array) dataset 2 to permute
n_permute: (int) number of permutations
tail: (int) either 1 for one-tail or 2 for two-tailed test (default: 2)
n_jobs: (int) The number of CPUs to use to do the computation.
-1 means all CPUs.
return_parms: (bool) Return the permutation distribution along with the p-value; default False
Returns:
stats: (dict) dictionary of permutation results ['mean','p']
"""
random_state = check_random_state(random_state)
seeds = random_state.randint(MAX_INT, size=n_permute)
stats = {"mean": np.nanmean(data1) - np.nanmean(data2)}
data = pd.DataFrame(data={"Values": data1, "Group": np.ones(len(data1))})
data = pd.concat(
[data, pd.DataFrame(data={"Values": data2, "Group": np.zeros(len(data2))})]
)
all_p = Parallel(n_jobs=n_jobs)(
delayed(_permute_group)(data, random_state=seeds[i]) for i in range(n_permute)
)
stats["p"] = _calc_pvalue(all_p, stats["mean"], tail)
if return_perms:
stats["perm_dist"] = all_p
return stats
def correlation_permutation(
data1,
data2,
method="permute",
n_permute=5000,
metric="spearman",
tail=2,
n_jobs=-1,
return_perms=False,
random_state=None,
):
"""Compute correlation and calculate p-value using permutation methods.
'permute' method randomly shuffles one of the vectors. This method is recommended
for independent data. For timeseries data we recommend using 'circle_shift' or
'phase_randomize' methods.
Args:
data1: (pd.DataFrame, pd.Series, np.array) dataset 1 to permute
data2: (pd.DataFrame, pd.Series, np.array) dataset 2 to permute
n_permute: (int) number of permutations
metric: (str) type of association metric ['spearman','pearson',
'kendall']
method: (str) type of permutation ['permute', 'circle_shift', 'phase_randomize']
random_state: (int, None, or np.random.RandomState) Initial random seed (default: None)
tail: (int) either 1 for one-tail or 2 for two-tailed test (default: 2)
n_jobs: (int) The number of CPUs to use to do the computation.
-1 means all CPUs.
return_parms: (bool) Return the permutation distribution along with the p-value; default False
Returns:
stats: (dict) dictionary of permutation results ['correlation','p']
"""
if len(data1) != len(data2):
raise ValueError("Make sure that data1 is the same length as data2")
if method not in ["permute", "circle_shift", "phase_randomize"]:
raise ValueError(
"Make sure that method is ['permute', 'circle_shift', 'phase_randomize']"
)
random_state = check_random_state(random_state)
data1 = np.array(data1)
data2 = np.array(data2)
stats = {"correlation": correlation(data1, data2, metric=metric)[0]}
if method == "permute":
all_p = Parallel(n_jobs=n_jobs)(
delayed(correlation)(random_state.permutation(data1), data2, metric=metric)
for _ in range(n_permute)
)
elif method == "circle_shift":
all_p = Parallel(n_jobs=n_jobs)(
delayed(correlation)(
circle_shift(data1, random_state=random_state), data2, metric=metric
)
for _ in range(n_permute)
)
elif method == "phase_randomize":
all_p = Parallel(n_jobs=n_jobs)(
delayed(correlation)(
phase_randomize(data1, random_state=random_state),
phase_randomize(data2),
metric=metric,
)
for _ in range(n_permute)
)
all_p = [x[0] for x in all_p]
stats["p"] = _calc_pvalue(all_p, stats["correlation"], tail)
if return_perms:
stats["perm_dist"] = all_p
return stats
def matrix_permutation(
data1,
data2,
n_permute=5000,
metric="spearman",
how="upper",
include_diag=False,
tail=2,
n_jobs=-1,
return_perms=False,
random_state=None,
):
"""Permute 2-dimensional matrix correlation (mantel test).
Chen, G. et al. (2016). Untangling the relatedness among correlations,
part I: nonparametric approaches to inter-subject correlation analysis
at the group level. Neuroimage, 142, 248-259.
Args:
data1: (pd.DataFrame, np.array) square matrix
data2: (pd.DataFrame, np.array) square matrix
n_permute: (int) number of permutations
metric: (str) type of association metric ['spearman','pearson',
'kendall']
how: (str) whether to use the 'upper' (default), 'lower', or 'full' matrix. The
default of 'upper' assumes both matrices are symmetric
include_diag (bool): only applies if `how='full'`. Whether to include the
diagonal elements in the comparison
tail: (int) either 1 for one-tail or 2 for two-tailed test
(default: 2)
n_jobs: (int) The number of CPUs to use to do the computation.
-1 means all CPUs.
return_parms: (bool) Return the permutation distribution along with the p-value; default False
Returns:
stats: (dict) dictionary of permutation results ['correlation','p']
"""
random_state = check_random_state(random_state)
seeds = random_state.randint(MAX_INT, size=n_permute)
sq_data1 = check_square_numpy_matrix(data1)
sq_data2 = check_square_numpy_matrix(data2)
if how == "upper":
data1 = sq_data1[np.triu_indices(sq_data1.shape[0], k=1)]
data2 = sq_data2[np.triu_indices(sq_data2.shape[0], k=1)]
elif how == "lower":
data1 = sq_data1[np.tril_indices(sq_data1.shape[0], k=-1)]
data2 = sq_data2[np.tril_indices(sq_data2.shape[0], k=-1)]
elif how == "full":
if include_diag:
data1 = sq_data1.ravel()
data2 = sq_data2.ravel()
else:
data1 = np.concatenate(
[
sq_data1[np.triu_indices(sq_data1.shape[0], k=1)],
sq_data1[np.tril_indices(sq_data1.shape[0], k=-1)],
]
)
data2 = np.concatenate(
[
sq_data2[np.triu_indices(sq_data2.shape[0], k=1)],
sq_data2[np.tril_indices(sq_data2.shape[0], k=-1)],
]
)
stats = {"correlation": correlation(data1, data2, metric=metric)[0]}
all_p = Parallel(n_jobs=n_jobs)(
delayed(_permute_func)(
pd.DataFrame(sq_data1),
data2,
metric=metric,
how=how,
include_diag=include_diag,
random_state=seeds[i],
)
for i in range(n_permute)
)
stats["p"] = _calc_pvalue(all_p, stats["correlation"], tail)
if return_perms:
stats["perm_dist"] = all_p
return stats
def make_cosine_basis(nsamples, sampling_freq, filter_length, unit_scale=True, drop=0):
"""Create a series of cosine basis functions for a discrete cosine
transform. Based off of implementation in spm_filter and spm_dctmtx
because scipy dct can only apply transforms but not return the basis
functions. Like SPM, does not add constant (i.e. intercept), but does
retain first basis (i.e. sigmoidal/linear drift)
Args:
nsamples (int): number of observations (e.g. TRs)
sampling_freq (float): sampling frequency in hertz (i.e. 1 / TR)
filter_length (int): length of filter in seconds
unit_scale (true): assure that the basis functions are on the normalized range [-1, 1]; default True
drop (int): index of which early/slow bases to drop if any; default is
to drop constant (i.e. intercept) like SPM. Unlike SPM, retains
first basis (i.e. linear/sigmoidal). Will cumulatively drop bases
up to and inclusive of index provided (e.g. 2, drops bases 1 and 2)
Returns:
out (ndarray): nsamples x number of basis sets numpy array
"""
# Figure out number of basis functions to create
order = int(np.fix(2 * (nsamples * sampling_freq) / filter_length + 1))
n = np.arange(nsamples)
# Initialize basis function matrix
C = np.zeros((len(n), order))
# Add constant
C[:, 0] = np.ones((1, len(n))) / np.sqrt(nsamples)
# Insert higher order cosine basis functions
for i in range(1, order):
C[:, i] = np.sqrt(2.0 / nsamples) * np.cos(
np.pi * (2 * n + 1) * i / (2 * nsamples)
)
# Drop intercept ala SPM
C = C[:, 1:]
if C.size == 0:
raise ValueError(
"Basis function creation failed! nsamples is too small for requested filter_length."
)
if unit_scale:
C *= 1.0 / C[0, 0]
C = C[:, drop:]
return C
def transform_pairwise(X, y):
"""Transforms data into pairs with balanced labels for ranking
Transforms a n-class ranking problem into a two-class classification
problem. Subclasses implementing particular strategies for choosing
pairs should override this method.
In this method, all pairs are choosen, except for those that have the
same target value. The output is an array of balanced classes, i.e.
there are the same number of -1 as +1
Reference: "Large Margin Rank Boundaries for Ordinal Regression",
R. Herbrich, T. Graepel, K. Obermayer. Authors: Fabian Pedregosa
<fabian@fseoane.net> Alexandre Gramfort <alexandre.gramfort@inria.fr>
Args:
X: (np.array), shape (n_samples, n_features)
The data
y: (np.array), shape (n_samples,) or (n_samples, 2)
Target labels. If it's a 2D array, the second column represents
the grouping of samples, i.e., samples with different groups will
not be considered.
Returns:
X_trans: (np.array), shape (k, n_feaures)
Data as pairs, where k = n_samples * (n_samples-1)) / 2 if grouping
values were not passed. If grouping variables exist, then returns
values computed for each group.
y_trans: (np.array), shape (k,)
Output class labels, where classes have values {-1, +1}
If y was shape (n_samples, 2), then returns (k, 2) with groups on
the second dimension.
"""
X_new, y_new, y_group = [], [], []
y_ndim = y.ndim
if y_ndim == 1:
y = np.c_[y, np.ones(y.shape[0])]
comb = itertools.combinations(range(X.shape[0]), 2)
for k, (i, j) in enumerate(comb):
if y[i, 0] == y[j, 0] or y[i, 1] != y[j, 1]:
# skip if same target or different group
continue
X_new.append(X[i] - X[j])
y_new.append(np.sign(y[i, 0] - y[j, 0]))
y_group.append(y[i, 1])
# output balanced classes
if y_new[-1] != (-1) ** k:
y_new[-1] = -y_new[-1]
X_new[-1] = -X_new[-1]
if y_ndim == 1:
return np.asarray(X_new), np.asarray(y_new).ravel()
elif y_ndim == 2:
return np.asarray(X_new), np.vstack((np.asarray(y_new), np.asarray(y_group))).T
def _robust_estimator(vals, X, robust_estimator="hc0", nlags=1):
"""
Computes robust sandwich estimators for standard errors used in OLS computation. Types include:
'hc0': Huber (1980) sandwich estimator to return robust standard error estimates.
'hc3': MacKinnon and White (1985) HC3 sandwich estimator. Provides more robustness in smaller samples than HC0 Long & Ervin (2000)
'hac': Newey-West (1987) estimator for robustness to heteroscedasticity as well as serial auto-correlation at given lags.
Refs: https://www.wikiwand.com/en/Heteroscedasticity-consistent_standard_errors
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/regression/linear_model.py
https://cran.r-project.org/web/packages/sandwich/vignettes/sandwich.pdf
https://www.stata.com/manuals13/tsnewey.pdf
Args:
vals (np.ndarray): 1d array of residuals
X (np.ndarray): design matrix used in OLS, e.g. Brain_Data().X
robust_estimator (str): estimator type, 'hc0' (default), 'hc3', or 'hac'
nlags (int): number of lags, only used with 'hac' estimator, default is 1
Returns:
stderr (np.ndarray): 1d array of standard errors with length == X.shape[1]
"""
if robust_estimator not in ["hc0", "hc3", "hac"]:
raise ValueError("robust_estimator must be one of hc0, hc3 or hac")
# Make a sandwich!
# First we need bread
bread = np.linalg.pinv(np.dot(X.T, X))
# Then we need meat
if robust_estimator == "hc0":
V = np.diag(vals**2)
meat = np.dot(np.dot(X.T, V), X)
elif robust_estimator == "hc3":
V = np.diag(vals**2) / (1 - np.diag(np.dot(X, np.dot(bread, X.T)))) ** 2
meat = np.dot(np.dot(X.T, V), X)
elif robust_estimator == "hac":
weights = 1 - np.arange(nlags + 1.0) / (nlags + 1.0)
# First compute lag 0
V = np.diag(vals**2)
meat = weights[0] * np.dot(np.dot(X.T, V), X)
# Now loop over additional lags
for l in range(1, nlags + 1):
V = np.diag(vals[l:] * vals[:-l])
meat_1 = np.dot(np.dot(X[l:].T, V), X[:-l])
meat_2 = np.dot(np.dot(X[:-l].T, V), X[l:])
meat += weights[l] * (meat_1 + meat_2)
# Then we make a sandwich
vcv = np.dot(np.dot(bread, meat), bread)
return np.sqrt(np.diag(vcv))
def summarize_bootstrap(data, save_weights=False):
"""Calculate summary of bootstrap samples
Args:
sample: (Brain_Data) Brain_Data instance of samples
save_weights: (bool) save bootstrap weights
Returns:
output: (dict) dictionary of Brain_Data summary images
"""
# Calculate SE of bootstraps
wstd = data.std()
wmean = data.mean()
wz = deepcopy(wmean)
wz.data = wmean.data / wstd.data
wp = deepcopy(wmean)
wp.data = 2 * (1 - norm.cdf(np.abs(wz.data)))
# Create outputs
output = {"Z": wz, "p": wp, "mean": wmean}
if save_weights:
output["samples"] = data
return output
def _arma_func(X, Y, idx=None, **kwargs):
"""
Fit an ARMA(p,q) model. If Y is a matrix and not a vector, expects an idx argument that refers to columns of Y. Used by regress().
"""
method = kwargs.pop("method", "css-mle")