-
Notifications
You must be signed in to change notification settings - Fork 73
/
stats.py
1581 lines (1394 loc) · 70.9 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
"""Provide statistics functions."""
import copy as cp
import numpy as np
from . import idtxl_utils as utils
from . import idtxl_exceptions as ex
def ais_fdr(settings=None, *results):
"""Perform FDR-correction on results of network AIS estimation.
Perform correction of the false discovery rate (FDR) after estimation of
active information storage (AIS) for all processes in the network. FDR
correction is applied by correcting the AIS estimate's omnibus p-values for
individual processes/nodes in the network.
Input can be a list of partial results to combine results from parallel
analysis.
References:
- Genovese, C.R., Lazar, N.A., & Nichols, T. (2002). Thresholding of
statistical maps in functional neuroimaging using the false discovery
rate. Neuroimage, 15(4), 870-878.
Args:
settings : dict [optional]
parameters for statistical testing with entries:
- alpha_fdr : float [optional] - critical alpha level
(default=0.05)
- fdr_constant : int [optional] - choose one of two constants used
for calculating the FDR-thresholds according to Genovese (2002):
1 will divide alpha by 1, 2 will divide alpha by the sum_i(1/i);
see the paper for details on the assumptions (default=2)
results : instances of ResultsSingleProcessAnalysis
results of network AIS estimation, see documentation of
ResultsSingleProcessAnalysis()
Returns:
ResultsSingleProcessAnalysis instance
input results objects pruned of non-significant estimates
"""
if settings is None:
settings = {}
# Set defaults and get parameters from settings dictionary
alpha = settings.get('alpha_fdr', 0.05)
constant = settings.get('fdr_constant', 2)
# Combine results into single results dict.
if len(results) > 1:
results_comb = cp.deepcopy(results[0])
results_comb.combine_results(*results[1:])
else:
results_comb = cp.deepcopy(results[0])
# Collect p-values of whole processes (determined by the omnibus test).
pval = np.arange(0)
process_idx = np.arange(0).astype(int)
n_perm = np.arange(0).astype(int)
for process in results_comb.processes_analysed:
if results_comb._single_process[process].ais_sign:
pval = np.append(
pval, results_comb._single_process[process].ais_pval)
process_idx = np.append(process_idx, process)
n_perm = np.append(
n_perm, results_comb.settings.n_perm_mi)
if pval.size == 0:
print('FDR correction: no links in final results ...\n')
results_comb._add_fdr(fdr=None, alpha=alpha, constant=constant)
return results_comb
sign, thresh = _perform_fdr_corretion(pval, constant, alpha)
# If the number of permutations for calculating p-values for individual
# variables is too low, return without performing any correction.
if (1 / min(n_perm)) > thresh[0]:
print('WARNING: Number of permutations (''n_perm_max_seq'') for at '
'least one target is too low to allow for FDR correction '
'(FDR-threshold: {0:.4f}, min. theoretically possible p-value: '
'{1}).'.format(thresh[0], 1 / min(n_perm)))
results_comb._add_fdr(fdr=None, alpha=alpha, constant=constant)
return results_comb
# Go over list of all candidates and remove non-significant results from
# the results object. Create a copy of the results object to leave the
# original intact.
fdr = cp.deepcopy(results_comb._single_process)
for s in range(sign.shape[0]):
if not sign[s]:
t = process_idx[s]
fdr[t].selected_vars = []
fdr[t].ais_pval = 1
fdr[t].ais_sign = False
results_comb._add_fdr(fdr, alpha, constant)
return results_comb
def network_fdr(settings=None, *results):
"""Perform FDR-correction on results of network inference.
Perform correction of the false discovery rate (FDR) after network
analysis. FDR correction can either be applied at the target level
(by correcting omnibus p-values) or at the single-link level (by correcting
p-values of individual links between single samples and the target).
Input can be a list of partial results to combine results from parallel
analysis.
References:
- Genovese, C.R., Lazar, N.A., & Nichols, T. (2002). Thresholding of
statistical maps in functional neuroimaging using the false discovery
rate. Neuroimage, 15(4), 870-878.
Args:
settings : dict [optional]
parameters for statistical testing with entries:
- alpha_fdr : float [optional] - critical alpha level
(default=0.05)
- correct_by_target : bool [optional] - if true correct p-values on
on the target level (omnibus test p-values), otherwise correct
p_values for individual variables (sequential max stats p-values)
(default=True)
- fdr_constant : int [optional] - choose one of two constants used
for calculating the FDR-thresholds according to Genovese (2002):
1 will divide alpha by 1, 2 will divide alpha by the sum_i(1/i);
see the paper for details on the assumptions (default=2)
results : instances of ResultsNetworkInference
results of network inference, see documentation of
ResultsNetworkInference()
Returns:
ResultsNetworkInference instance
input object pruned of non-significant links
"""
if settings is None:
settings = {}
# Set defaults and get parameters from settings dictionary
alpha = settings.get('alpha_fdr', 0.05)
correct_by_target = settings.get('correct_by_target', True)
constant = settings.get('fdr_constant', 2)
# Combine results into single results dict.
if len(results) > 1:
results_comb = cp.deepcopy(results[0])
results_comb.combine_results(*results[1:])
else:
results_comb = cp.deepcopy(results[0])
# Collect significant source variables for all targets. Either correct
# p-value of whole target (all candidates), or correct p-value of
# individual source variables. Use targets with significant input only
# (determined by the omnibus test).
pval = np.arange(0)
target_idx = np.arange(0).astype(int)
n_perm = np.arange(0).astype(int)
cands = []
if correct_by_target: # whole target
for target in results_comb.targets_analysed:
if results_comb._single_target[target].omnibus_sign:
pval = np.append(
pval, results_comb._single_target[target].omnibus_pval)
target_idx = np.append(target_idx, target)
n_perm = np.append(
n_perm, results_comb.settings.n_perm_omnibus)
else: # individual variables
for target in results_comb.targets_analysed:
if results_comb._single_target[target].omnibus_sign:
n_sign = (results_comb._single_target[target].
selected_sources_pval.size)
pval = np.append(
pval, (results_comb._single_target[target].
selected_sources_pval))
target_idx = np.append(target_idx,
np.ones(n_sign) * target).astype(int)
cands = (cands +
(results_comb._single_target[target].
selected_vars_sources))
n_perm = np.append(
n_perm, results_comb.settings.n_perm_max_seq)
if pval.size == 0:
print('No links in final results ...')
results_comb._add_fdr(
fdr=None, alpha=alpha, correct_by_target=correct_by_target,
constant=constant)
return results_comb
sign, thresh = _perform_fdr_corretion(pval, constant, alpha)
# If the number of permutations for calculating p-values for individual
# variables is too low, return without performing any correction.
if (1 / min(n_perm)) > thresh[0]:
print('WARNING: Number of permutations (''n_perm_max_seq'') for at '
'least one target is too low to allow for FDR correction '
'(FDR-threshold: {0:.4f}, min. theoretically possible p-value: '
'{1}).'.format(thresh[0], 1 / min(n_perm)))
results_comb._add_fdr(
fdr=None, alpha=alpha, correct_by_target=correct_by_target,
constant=constant)
return results_comb
# Go over list of all candidates and remove non-significant results from
# the results object. Create a copy of the results object to leave the
# original intact.
fdr = cp.deepcopy(results_comb._single_target)
for s in range(sign.shape[0]):
if not sign[s]:
if correct_by_target:
t = target_idx[s]
fdr[t].selected_vars_full = cp.deepcopy(
results_comb._single_target[t].selected_vars_target)
fdr[t].selected_sources_te = None
fdr[t].selected_sources_pval = None
fdr[t].selected_vars_sources = []
fdr[t].omnibus_pval = 1
fdr[t].omnibus_sign = False
else:
t = target_idx[s]
cand = cands[s]
cand_ind = (fdr[t].selected_vars_sources.index(cand))
fdr[t].selected_vars_sources.pop(cand_ind)
fdr[t].selected_sources_pval = np.delete(
fdr[t].selected_sources_pval, cand_ind)
fdr[t].selected_sources_te = np.delete(
fdr[t].selected_sources_te, cand_ind)
fdr[t].selected_vars_full.pop(
fdr[t].selected_vars_full.index(cand))
results_comb._add_fdr(fdr, alpha, correct_by_target, constant)
return results_comb
def _perform_fdr_corretion(pval, constant, alpha):
"""Calculate sequential threshold for FDR-correction.
Calculate sequential thresholds for FDR-correction of p-values. The
constant defines how the threshold is calculated. See Genovese (2002) for
details.
References:
- Genovese, C.R., Lazar, N.A., & Nichols, T. (2002). Thresholding of
statistical maps in functional neuroimaging using the false discovery
rate. Neuroimage, 15(4), 870-878.
Args:
pval : numpy array
p-values to be corrected
alpha : float
critical alpha level
fdr_constant : int
one of two constants used for calculating the FDR-thresholds
according to Genovese (2002): 1 will divide alpha by 1, 2 will
divide alpha by the sum_i(1/i); see the paper for details on the
assumptions (default=2)
Returns:
array of bools
significance of p-values
array of floats
FDR-thresholds for each p-value
"""
# Sort all p-values in ascending order.
sort_idx = np.argsort(pval)
pval.sort()
# Calculate threshold
n = pval.size
if constant == 2: # pick the requested constant (see Genovese, p.872)
if n < 1000:
const = sum(1 / np.arange(1, n + 1))
else:
const = np.log(n) + np.e # aprx. harmonic sum with Euler's number
elif constant == 1:
# This is less strict than the other one and corresponds to a
# Bonoferroni-correction for the first p-value, however, it makes more
# strict assumptions on the distribution of p-values, while constant 2
# works for any joint distribution of the p-values.
const = 1
thresh = (np.arange(1, n + 1) / n) * alpha / const
# Compare data to threshold.
sign = pval <= thresh
if np.invert(sign).any():
first_false = np.where(np.invert(sign))[0][0]
sign[first_false:] = False # avoids false positives due to equal pvals
sign = sign[sort_idx] # restore original ordering of significance values
return sign, thresh
def omnibus_test(analysis_setup, data):
"""Perform an omnibus test on identified conditional variables.
Test the joint information transfer from all identified sources to the
current value conditional on candidates in the target's past. To test for
significance, this is repeated for shuffled realisations of the sources.
The distribution of values from shuffled data is then used as test
distribution.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_omnibus : int [optional] - number of permutations
(default=500)
- alpha_omnibus : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
Returns:
bool
statistical significance
float
the test's p-value
float
the estimated test statisic, i.e., the information transfer from
all sources into the target
Raises:
ex.AlgorithmExhaustedError
Raised from estimate() calls when calculation cannot be made
"""
# Set defaults and get parameters from settings dictionary
analysis_setup.settings.setdefault('n_perm_omnibus', 500)
n_permutations = analysis_setup.settings['n_perm_omnibus']
analysis_setup.settings.setdefault('alpha_omnibus', 0.05)
alpha = analysis_setup.settings['alpha_omnibus']
permute_in_time = _check_permute_in_time(analysis_setup, data,
n_permutations)
assert analysis_setup.selected_vars_sources, 'No sources to test.'
# Create temporary variables b/c realisations for sources and targets are
# created on the fly, which is costly, so we want to re-use them after
# creation. (This does not apply to the current value realisations).
# If there was no target variable selected (e.g., if MI is used for network
# inference), set conditional to None such that the MI instead of the CMI
# estimator is used when calculating the statistic.
cond_source_realisations = (analysis_setup
._selected_vars_sources_realisations)
if analysis_setup._selected_vars_target:
cond_target_realisations = (analysis_setup
._selected_vars_target_realisations)
else:
cond_target_realisations = None
statistic = analysis_setup._cmi_estimator.estimate(
var1=cond_source_realisations,
var2=analysis_setup._current_value_realisations,
conditional=cond_target_realisations)
# Create the surrogate distribution by permuting the conditional sources.
if analysis_setup.settings['verbose']:
print('omnibus test, n_perm: {0}'.format(n_permutations))
if (analysis_setup._cmi_estimator.is_analytic_null_estimator() and
permute_in_time):
# Generate the surrogates analytically
analysis_setup.settings['analytical_surrogates'] = True
surr_distribution = (analysis_setup._cmi_estimator.
estimate_surrogates_analytic(
n_perm=n_permutations,
var1=cond_source_realisations,
var2=analysis_setup._current_value_realisations,
conditional=cond_target_realisations))
else:
analysis_setup.settings['analytical_surrogates'] = False
surr_cond_real = _get_surrogates(data,
analysis_setup.current_value,
analysis_setup.selected_vars_sources,
n_permutations,
analysis_setup.settings)
surr_distribution = analysis_setup._cmi_estimator.estimate_parallel(
n_chunks=n_permutations,
re_use=['var2', 'conditional'],
var1=surr_cond_real,
var2=analysis_setup._current_value_realisations,
conditional=cond_target_realisations)
[significance, pvalue] = _find_pvalue(statistic, surr_distribution,
alpha, 'one_bigger')
if analysis_setup.settings['verbose']:
if significance:
print(' -- significant\n')
else:
print(' -- not significant\n')
return significance, pvalue, statistic
def max_statistic(analysis_setup, data, candidate_set, te_max_candidate,
conditional):
"""Perform maximum statistics for one candidate source.
Test if a transfer entropy value is significantly bigger than the maximum
values obtained from surrogates of all remanining candidates.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_max_stat : int [optional] - number of permutations
(default=200)
- alpha_max_stat : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
candidate_set : list of tuples
list of indices of remaning candidates
te_max_candidate : float
transfer entropy value to be tested
conditional : numpy array
realisations of conditional, 2D numpy array where array dimensions
represent [realisations x variable dimension]
Returns:
bool
statistical significance
float
the test's p-value
numpy array
surrogate table
Raises:
ex.AlgorithmExhaustedError
Raised from _create_surrogate_table() when calculation cannot be
made
"""
# Set defaults and get parameters from settings dictionary
analysis_setup.settings.setdefault('n_perm_max_stat', 200)
n_perm = analysis_setup.settings['n_perm_max_stat']
analysis_setup.settings.setdefault('alpha_max_stat', 0.05)
alpha = analysis_setup.settings['alpha_max_stat']
_check_permute_in_time(analysis_setup, data, n_perm)
assert(candidate_set), 'The candidate set is empty.'
if analysis_setup.settings['verbose']:
print('maximum statistic, n_perm: {0}'.format(
analysis_setup.settings['n_perm_max_stat']))
# todo pass correct conditioning set
surr_table = _create_surrogate_table(analysis_setup, data, candidate_set,
n_perm, conditional)
max_distribution = _find_table_max(surr_table)
[significance, pvalue] = _find_pvalue(statistic=te_max_candidate,
distribution=max_distribution,
alpha=alpha,
tail='one_bigger')
return significance, pvalue, surr_table
def max_statistic_sequential(analysis_setup, data):
"""Perform sequential maximum statistics for a set of candidate sources.
Test multivariate/bivariate MI/TE values against surrogates. Test highest
TE/MI value against distribution of highest surrogate values, second
highest against distribution of second highest, and so forth. Surrogates
are created from each candidate in the candidate set, including the
candidate that is currently tested. Surrogates are then sorted over
candidates. This is repeated n_perm_max_seq times. Stop comparison if a
TE/MI value is not significant compared to the distribution of surrogate
values of the same rank. All smaller values are considered non-significant
as well.
The conditional for estimation of MI/TE is taken from the current set of
conditional variables in the analysis setup. For multivariate MI or TE
surrogate creation, the full set of conditional variables is used. For
bivariate MI or TE surrogate creation, the conditioning set has to be
restricted to a subset of the current set of conditional variables: for
bivariate MI no conditioning set is required, for bivariate TE only the
past variables from the target are required (not the variables selected
from other relevant sources).
This function will re-use the surrogate table created in the last min-stats
round if that table is in the analysis_setup. This saves the complete
calculation of surrogates for this statistic.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_max_seq : int [optional] - number of permutations
(default='n_perm_min_stat'|500)
- alpha_max_seq : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
Returns:
numpy array, bool
statistical significance of each source
numpy array, float
the test's p-values for each source
numpy array, float
TE values for individual sources
"""
# Set defaults and get test parameters.
analysis_setup.settings.setdefault('n_perm_max_seq', 500)
n_permutations = analysis_setup.settings['n_perm_max_seq']
analysis_setup.settings.setdefault('alpha_max_seq', 0.05)
alpha = analysis_setup.settings['alpha_max_seq']
_check_permute_in_time(analysis_setup, data, n_permutations)
permute_in_time = analysis_setup.settings['permute_in_time']
if analysis_setup.settings['verbose']:
print('sequential maximum statistic, n_perm: {0}, testing {1} selected'
' sources'.format(n_permutations,
len(analysis_setup.selected_vars_sources)))
assert analysis_setup.selected_vars_sources, 'No sources to test.'
idx_conditional = analysis_setup.selected_vars_full
conditional_realisations = np.empty(
(data.n_realisations(analysis_setup.current_value) *
len(analysis_setup.selected_vars_sources),
len(idx_conditional) - 1)).astype(data.data_type)
candidate_realisations = np.empty(
(data.n_realisations(analysis_setup.current_value) *
len(analysis_setup.selected_vars_sources), 1)).astype(data.data_type)
# Calculate TE for each candidate in the conditional source set, i.e.,
# calculate the conditional MI between each candidate and the current
# value, conditional on all selected variables in the conditioning set,
# excluding the current source. Calculate surrogates for each candidate by
# shuffling the candidate realisations n_perm times. Afterwards, sort the
# estimated TE values.
i_1 = 0
i_2 = data.n_realisations(analysis_setup.current_value)
surr_table = np.zeros((len(analysis_setup.selected_vars_sources),
n_permutations))
# Collect data for each candidate and the corresponding conditioning set.
# Use realisations for parallel estimation of the test statistic later.
for idx_c, candidate in enumerate(analysis_setup.selected_vars_sources):
[conditional_realisations_current,
candidate_realisations_current] = analysis_setup._separate_realisations(
idx_conditional, candidate)
# The following may happen if either the requested conditing is 'none'
# or if the conditiong set that is tested consists only of a single
# candidate.
if conditional_realisations_current is None:
conditional_realisations = None
re_use = ['var2', 'conditional']
else:
conditional_realisations[i_1:i_2, ] = conditional_realisations_current
re_use = ['var2']
candidate_realisations[i_1:i_2, ] = candidate_realisations_current
i_1 = i_2
i_2 += data.n_realisations(analysis_setup.current_value)
# Generate surrogates for the current candidate.
if (analysis_setup._cmi_estimator.is_analytic_null_estimator() and
permute_in_time):
# Generate the surrogates analytically
surr_table[idx_c, :] = (
analysis_setup._cmi_estimator.estimate_surrogates_analytic(
n_perm=n_permutations,
var1=data.get_realisations(analysis_setup.current_value,
[candidate])[0],
var2=analysis_setup._current_value_realisations,
conditional=conditional_realisations_current))
else:
analysis_setup.settings['analytical_surrogates'] = False
surr_candidate_realisations = _get_surrogates(
data,
analysis_setup.current_value,
[candidate],
n_permutations,
analysis_setup.settings)
try:
surr_table[idx_c, :] = (
analysis_setup._cmi_estimator.estimate_parallel(
n_chunks=n_permutations,
re_use=['var2', 'conditional'],
var1=surr_candidate_realisations,
var2=analysis_setup._current_value_realisations,
conditional=conditional_realisations_current))
except ex.AlgorithmExhaustedError as aee:
# The aglorithm cannot continue here, so
# we'll terminate the max sequential stats test,
# and declare all not significant
print('AlgorithmExhaustedError encountered in estimations: {}.'.format(
aee.message))
print('Stopping sequential max stats at candidate with rank 0')
return \
(np.zeros(len(analysis_setup.selected_vars_sources)).astype(bool),
np.ones(len(analysis_setup.selected_vars_sources)),
np.zeros(len(analysis_setup.selected_vars_sources)))
# Calculate original statistic (multivariate/bivariate TE/MI)
try:
individual_stat = analysis_setup._cmi_estimator.estimate_parallel(
n_chunks=len(analysis_setup.selected_vars_sources),
re_use=re_use,
var1=candidate_realisations,
var2=analysis_setup._current_value_realisations,
conditional=conditional_realisations)
except ex.AlgorithmExhaustedError as aee:
# The aglorithm cannot continue here, so
# we'll terminate the max sequential stats test,
# and declare all not significant
print('AlgorithmExhaustedError encountered in estimations: {}.'.format(
aee.message))
print('Stopping sequential max stats at candidate with rank 0')
# For now we don't need a stack trace:
# traceback.print_tb(aee.__traceback__)
# Return (signficance, pvalue, TEs):
return \
(np.zeros(len(analysis_setup.selected_vars_sources)).astype(bool),
np.ones(len(analysis_setup.selected_vars_sources)),
np.zeros(len(analysis_setup.selected_vars_sources)))
selected_vars_order = utils.argsort_descending(individual_stat)
individual_stat_sorted = utils.sort_descending(individual_stat)
max_distribution = _sort_table_max(surr_table)
# Compare each original value with the distribution of the same rank,
# starting with the highest value.
significance = np.zeros(individual_stat.shape[0]).astype(bool)
pvalue = np.ones(individual_stat.shape[0])
for c in range(individual_stat.shape[0]):
[s, p] = _find_pvalue(individual_stat_sorted[c],
max_distribution[c, ], alpha, tail='one_bigger')
significance[c] = s
pvalue[c] = p
if not s: # break as soon as a candidate is no longer significant
if analysis_setup.settings['verbose']:
print('\nStopping sequential max stats at candidate with rank '
'{0}.'.format(c))
break
# Get back original order and return results.
significance = significance[selected_vars_order]
pvalue = pvalue[selected_vars_order]
return significance, pvalue, individual_stat
def max_statistic_sequential_bivariate(analysis_setup, data):
"""Perform sequential maximum statistics for a set of candidate sources.
Test multivariate/bivariate MI/TE values against surrogates. Test highest
TE/MI value against distribution of highest surrogate values, second
highest against distribution of second highest, and so forth. Surrogates
are created from each candidate in the candidate set, including the
candidate that is currently tested. Surrogates are then sorted over
candidates. This is repeated n_perm_max_seq times. Stop comparison if a
TE/MI value is not significant compared to the distribution of surrogate
values of the same rank. All smaller values are considered non-significant
as well.
The conditional for estimation of MI/TE is taken from the current set of
conditional variables in the analysis setup. For multivariate MI or TE
surrogate creation, the full set of conditional variables is used. For
bivariate MI or TE surrogate creation, the conditioning set has to be
restricted to a subset of the current set of conditional variables: for
bivariate MI no conditioning set is required, for bivariate TE only the
past variables from the target are required (not the variables selected
from other relevant sources).
This function will re-use the surrogate table created in the last min-stats
round if that table is in the analysis_setup. This saves the complete
calculation of surrogates for this statistic.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_max_seq : int [optional] - number of permutations
(default='n_perm_min_stat'|500)
- alpha_max_seq : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
Returns:
numpy array, bool
statistical significance of each source
numpy array, float
the test's p-values for each source
numpy array, float
TE values for individual sources
"""
# Set defaults and get test parameters.
analysis_setup.settings.setdefault('n_perm_max_seq', 500)
n_permutations = analysis_setup.settings['n_perm_max_seq']
analysis_setup.settings.setdefault('alpha_max_seq', 0.05)
alpha = analysis_setup.settings['alpha_max_seq']
_check_permute_in_time(analysis_setup, data, n_permutations)
permute_in_time = analysis_setup.settings['permute_in_time']
if analysis_setup.settings['verbose']:
print('sequential maximum statistic, n_perm: {0}, testing {1} selected'
' sources'.format(n_permutations,
len(analysis_setup.selected_vars_sources)))
assert analysis_setup.selected_vars_sources, 'No sources to test.'
# Check if target variables were selected to distinguish between TE and MI
# analysis.
if len(analysis_setup._selected_vars_target) == 0:
conditional_realisations_target = None
else:
conditional_realisations_target = analysis_setup._selected_vars_target_realisations
# Test all selected sources separately. This way, the conditioning
# uses past variables from the current source only (opposed to past
# variables from all sources as in multivariate network inference).
significant_sources = np.unique(
[s[0] for s in analysis_setup.selected_vars_sources])
significance = np.zeros(
len(analysis_setup.selected_vars_sources)).astype(bool)
pvalue = np.ones(len(analysis_setup.selected_vars_sources))
stat = np.zeros(len(analysis_setup.selected_vars_sources))
for source in significant_sources:
# Find selected past variables for current source
source_vars = [s for s in analysis_setup.selected_vars_sources if
s[0] == source]
# Determine length of conditioning set and allocate memory.
idx_conditional = source_vars.copy()
if conditional_realisations_target is not None:
idx_conditional += analysis_setup.selected_vars_target
conditional_realisations = np.empty(
(data.n_realisations(analysis_setup.current_value) *
len(source_vars),
len(idx_conditional) - 1)).astype(data.data_type)
candidate_realisations = np.empty(
(data.n_realisations(analysis_setup.current_value) *
len(source_vars), 1)).astype(data.data_type)
# Calculate TE/MI for each candidate in the conditional source set,
# i.e., calculate the conditional MI between each candidate and the
# current value, conditional on all selected variables in the
# conditioning set. Then sort the estimated TE/MI values.
i_1 = 0
i_2 = data.n_realisations(analysis_setup.current_value)
surr_table = np.zeros((len(source_vars), n_permutations))
# Collect data for each candidate and the corresponding conditioning set.
for idx_c, candidate in enumerate(source_vars):
temp_cond = data.get_realisations(
analysis_setup.current_value,
set(source_vars).difference(set([candidate])))[0]
temp_cand = data.get_realisations(
analysis_setup.current_value, [candidate])[0]
# The following may happen if either the requested conditing is
# 'none' or if the conditiong set that is tested consists only of
# a single candidate.
if temp_cond is None:
conditional_realisations = conditional_realisations_target
re_use = ['var2', 'conditional']
else:
re_use = ['var2']
if conditional_realisations_target is None:
conditional_realisations[i_1:i_2, ] = temp_cond
else:
conditional_realisations[i_1:i_2, ] = np.hstack((
temp_cond, conditional_realisations_target))
candidate_realisations[i_1:i_2, ] = temp_cand
i_1 = i_2
i_2 += data.n_realisations(analysis_setup.current_value)
# Generate surrogates for the current candidate.
if (analysis_setup._cmi_estimator.is_analytic_null_estimator() and
permute_in_time):
# Generate the surrogates analytically
surr_table[idx_c, :] = (
analysis_setup._cmi_estimator.estimate_surrogates_analytic(
n_perm=n_permutations,
var1=data.get_realisations(analysis_setup.current_value,
[candidate])[0],
var2=analysis_setup._current_value_realisations,
conditional=temp_cond))
else:
analysis_setup.settings['analytical_surrogates'] = False
surr_candidate_realisations = _get_surrogates(
data,
analysis_setup.current_value,
[candidate],
n_permutations,
analysis_setup.settings)
try:
surr_table[idx_c, :] = (
analysis_setup._cmi_estimator.estimate_parallel(
n_chunks=n_permutations,
re_use=['var2', 'conditional'],
var1=surr_candidate_realisations,
var2=analysis_setup._current_value_realisations,
conditional=temp_cond))
except ex.AlgorithmExhaustedError as aee:
# The aglorithm cannot continue here, so
# we'll terminate the max sequential stats test,
# and declare all not significant
print('AlgorithmExhaustedError encountered in estimations: {}.'.format(
aee.message))
print('Stopping sequential max stats at candidate with rank 0')
return \
(np.zeros(len(analysis_setup.selected_vars_sources)).astype(bool),
np.ones(len(analysis_setup.selected_vars_sources)),
np.zeros(len(analysis_setup.selected_vars_sources)))
# Calculate original statistic (multivariate/bivariate TE/MI)
try:
individual_stat = analysis_setup._cmi_estimator.estimate_parallel(
n_chunks=len(source_vars),
re_use=re_use,
var1=candidate_realisations,
var2=analysis_setup._current_value_realisations,
conditional=conditional_realisations)
except ex.AlgorithmExhaustedError as aee:
# The aglorithm cannot continue here, so
# we'll terminate the max sequential stats test,
# and declare all not significant
print('AlgorithmExhaustedError encountered in '
'estimations: {}.'.format(aee.message))
print('Stopping sequential max stats at candidate with rank 0')
# For now we don't need a stack trace:
# traceback.print_tb(aee.__traceback__)
# Return (signficance, pvalue, TEs):
return (
np.zeros(len(analysis_setup.selected_vars_sources)).astype(bool),
np.ones(len(analysis_setup.selected_vars_sources)),
np.zeros(len(analysis_setup.selected_vars_sources)))
selected_vars_order = utils.argsort_descending(individual_stat)
individual_stat_sorted = utils.sort_descending(individual_stat)
max_distribution = _sort_table_max(surr_table)
# Compare each original value with the distribution of the same rank,
# starting with the highest value.
for c in range(individual_stat.shape[0]):
[s, p] = _find_pvalue(individual_stat_sorted[c],
max_distribution[c, ],
alpha, tail='one_bigger')
# Write results into an array with the same order as the set of
# selected sources from all process. Find the currently tested
# variable and its index in the list of all selected variables.
current_var = source_vars[selected_vars_order[c]]
for ind, v in enumerate(analysis_setup.selected_vars_sources):
if v == current_var:
break
significance[ind] = s
pvalue[ind] = p
stat[ind] = individual_stat_sorted[c]
if not s: # break as soon as a candidate is no longer significant
if analysis_setup.settings['verbose']:
print('\nStopping sequential max stats at candidate with '
'rank {0}.'.format(c))
break
return significance, pvalue, stat
def min_statistic(analysis_setup, data, candidate_set, te_min_candidate,
conditional=None):
"""Perform minimum statistics for one candidate source.
Test if a transfer entropy value is significantly bigger than the minimum
values obtained from surrogates of all remanining candidates.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_min_stat : int [optional] - number of permutations
(default=500)
- alpha_min_stat : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
candidate_set : list of tuples
list of indices of remaning candidates
te_min_candidate : float
transfer entropy value to be tested
conditional : numpy array [optional]
realisations of conditional, 2D numpy array where array dimensions
represent [realisations x variable dimension] (default=None, no
conditioning performed)
Returns:
bool
statistical significance
float
the test's p-value
numpy array
surrogate table
Raises:
ex.AlgorithmExhaustedError
Raised from _create_surrogate_table() when calculation cannot be
made
"""
# Set defaults and get parameters from settings dictionary
analysis_setup.settings.setdefault('n_perm_min_stat', 500)
n_perm = analysis_setup.settings['n_perm_min_stat']
analysis_setup.settings.setdefault('alpha_min_stat', 0.05)
alpha = analysis_setup.settings['alpha_min_stat']
_check_permute_in_time(analysis_setup, data, n_perm)
if analysis_setup.settings['verbose']:
print('minimum statistic, n_perm: {0}'.format(
analysis_setup.settings['n_perm_min_stat']))
assert(candidate_set), 'The candidate set is empty.'
surr_table = _create_surrogate_table(analysis_setup, data, candidate_set,
n_perm, conditional)
min_distribution = _find_table_min(surr_table)
[significance, pvalue] = _find_pvalue(statistic=te_min_candidate,
distribution=min_distribution,
alpha=alpha,
tail='one_bigger')
return significance, pvalue, surr_table
def mi_against_surrogates(analysis_setup, data):
"""Test estimated mutual information for significance against surrogate data.
Shuffle realisations of the current value (point to be predicted) and re-
calculate mutual information (MI) for shuffled data. The actual estimated
MI is then compared against this distribution of MI values from surrogate
data.
Args:
analysis_setup : MultivariateTE instance
information on the current analysis, can have an optional attribute
'settings', a dictionary with parameters for statistical testing:
- n_perm_mi : int [optional] - number of permutations
(default=500)
- alpha_mi : float [optional] - critical alpha level
(default=0.05)
- permute_in_time : bool [optional] - generate surrogates by
shuffling samples in time instead of shuffling whole replications
(default=False)
data : Data instance
raw data
Returns:
float
estimated MI value
bool
statistical significance
float
p_value for estimated MI value
Raises:
ex.AlgorithmExhaustedError
Raised from estimate() methods when calculation cannot be made
"""
analysis_setup.settings.setdefault('n_perm_mi', 500)
n_perm = analysis_setup.settings['n_perm_mi']
analysis_setup.settings.setdefault('alpha_mi', 0.05)
alpha = analysis_setup.settings['alpha_mi']
permute_in_time = _check_permute_in_time(analysis_setup, data, n_perm)
if analysis_setup.settings['verbose']:
print('mi permutation test against surrogates, n_perm: {0}'.format(
analysis_setup.settings['n_perm_mi']))
'''
surr_realisations = np.empty(
(data.n_realisations(analysis_setup.current_value) *
(n_perm + 1), 1))
i_1 = 0
i_2 = data.n_realisations(analysis_setup.current_value)
# The first chunk holds the original data
surr_realisations[i_1:i_2, ] = analysis_setup._current_value_realisations
# Create surrogate data by shuffling the realisations of the current value.
for perm in range(n_perm):
i_1 = i_2
i_2 += data.n_realisations(analysis_setup.current_value)
# Check the permutation type for the current candidate.
if permute_over_replications:
surr_temp = data.permute_data(analysis_setup.current_value,
[analysis_setup.current_value])[0]