-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_processing.py
1536 lines (1304 loc) · 63.6 KB
/
data_processing.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
"""To replace in tigramite. Include bootstrap and confidence measure method for Tigramite"""
# License: GNU General Public License v3.0
from __future__ import print_function
from collections import defaultdict, OrderedDict
import sys
import warnings
from copy import deepcopy
import math
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
from scipy import stats
from numba import jit
class DataFrame():
"""Data object containing single or multiple time series arrays and optional
mask.
Parameters
----------
data : array-like
if analysis_mode == 'single':
1) Numpy array of shape (observations T, variables N)
OR
2) Dictionary with a single entry whose value is a numpy array of
shape (observations T, variables N)
if analysis_mode == 'multiple':
1) Numpy array of shape (multiple datasets M, observations T,
variables N)
OR
2) Dictionary whose values are numpy arrays of shape
(observations T_i, variables N), where the number of observations
T_i may vary across the multiple datasets but the number of variables
N is fixed.
mask : array-like, optional (default: None)
Optional mask array, must be of same format and shape as data.
type_mask : array-like
Binary data array of same shape as array which describes whether
individual samples in a variable (or all samples) are continuous
or discrete: 0s for continuous variables and 1s for discrete variables.
missing_flag : number, optional (default: None)
Flag for missing values in dataframe. Dismisses all time slices of
samples where missing values occur in any variable. For
remove_missing_upto_maxlag=True also flags samples for all lags up to
2*tau_max (more precisely, this depends on the cut_off argument in
self.construct_array(), see further below). This avoids biases, see
section on masking in Supplement of [1]_.
vector_vars : dict
Dictionary of vector variables of the form,
Eg. {0: [(0, 0), (1, 0)], 1: [(2, 0)], 2: [(3, 0)], 3: [(4, 0)]}
The keys are the new vectorized variables and respective tuple values
are the individual components of the vector variables. In the method of
construct_array(), the individual components are parsed from vector_vars
and added (accounting for lags) to the list that creates X, Y and Z for
conditional independence test.
var_names : list of strings, optional (default: range(N))
Names of variables, must match the number of variables. If None is
passed, variables are enumerated as [0, 1, ...]
datatime : array-like, optional (default: None)
Timelabel array. If None, range(T) is used.
remove_missing_upto_maxlag : bool, optional (default: False)
Whether to remove not only missing samples, but also all neighboring
samples up to max_lag (as given by cut_off in construct_array).
analysis_mode : string, optional (default: 'single')
Must be 'single' or 'multiple'.
Determines whether data contains a single (potentially multivariate)
time series (--> 'single') or multiple time series (--> 'multiple').
reference_points : None, int, or list (or 1D array) of integers,
optional (default:None)
Determines the time steps --- relative to the shared time axis as
defined by the optional time_offset argument (see below) --- that are
used to create samples for conditional independence testing.
Set to [0, 1, ..., T_max-1] if None is passed, where T_max is
self.largest_time_step, see below.
All values smaller than 0 and bigger than T_max-1 will be ignored.
At least one value must be in [0, 1, ..., T_max-1].
time_offsets : None or dict, optional (default: None)
if analysis_mode == 'single':
Must be None.
Shared time axis defined by the time indices of the single time series
if analysis_mode == 'multiple' and data is numpy array:
Must be None.
All datasets are assumed to be already aligned in time with
respect to a shared time axis, which is the time axis of data
if analysis_mode == 'multiple' and data is dictionary:
Must be dictionary of the form {key(m): time_offset(m), ...} whose
set of keys agrees with the set of keys of data and whose values are
non-negative integers, at least one of which is 0. The value
time_offset(m) defines the time offset of dataset m with
respect to a shared time axis.
Attributes
----------
self._initialized_from : string
Specifies the data format in which data was given at instantiation.
Possible values: '2d numpy array', '3d numpy array', 'dict'.
self.values : dictionary
Dictionary holding the observations given by data internally mapped to a
dictionary representation as follows:
If analysis_mode == 'single':
If self._initialized_from == '2d numpy array':
Is {0: data}
If self._initialized_from == 'dict':
Is data
If analysis_mode == 'multiple':
If self._initialized_from == '3d numpy array':
Is {m: data[m, :, :] for m in range(data.shape[0])}
If self._initialized_from == 'dict':
Is data
self.datasets: list
List of the keys identifiying the multiple datasets, i.e.,
list(self.values.keys())
self.mask : dictionary
Mask internally mapped to a dictionary representation in the same way as
data is mapped to self.values
self.type_mask : array-like
Binary data array of same shape as array which describes whether
individual samples in a variable (or all samples) are continuous
or discrete: 0s for continuous variables and 1s for discrete variables.
self.missing_flag:
Is missing_flag
self.var_names:
If var_names is not None:
Is var_names
If var_names is None:
Is {i: i for i in range(self.N)}
self.datatime : dictionary
Time axis for each of the multiple datasets.
self.analysis_mode : string
Is analysis_mode
self.reference_points: array-like
If reference_points is not None:
1D numpy array holding all specified reference_points, less those
smaller than 0 and larger than self.largest_time_step-1
If reference_points is None:
Is np.array(range(self.largest_time_step))
self.time_offsets : dictionary
If time_offsets is not None:
Is time_offsets
If time_offsets is None:
Is {key: 0 for key in self.values.keys()}
self.M : int
Number of datasets
self.N : int
Number of variables (constant across datasets)
self.T : dictionary
Dictionary {key(m): T(m), ...}, where T(m) is the time length of
datasets m and key(m) its identifier as in self.values
self.largest_time_step : int
max_{0 <= m <= M} [ T(m) + time_offset(m)], i.e., the largest (latest)
time step relative to the shared time axis for which at least one
observation exists in the dataset.
self.bootstrap : dictionary
Whether to use bootstrap. Must be a dictionary with keys random_state,
boot_samples, and boot_blocklength.
"""
def __init__(self, data, mask=None, missing_flag=None, vector_vars=None, var_names=None,
type_mask=None, datatime=None, analysis_mode ='single', reference_points=None,
time_offsets=None, remove_missing_upto_maxlag=False):
# Check that a valid analysis mode, specified by the argument
# 'analysis_mode', has been chosen
if analysis_mode in ['single', 'multiple']:
self.analysis_mode = analysis_mode
else:
raise ValueError("'analysis_mode' is '{}', must be 'single' or "\
"'multiple'.".format(analysis_mode))
# Check for correct type and format of 'data', internally cast to the
# analysis mode 'multiple' case in dictionary representation
if self.analysis_mode == 'single':
# In this case the 'time_offset' functionality must not be used
if time_offsets is not None:
raise ValueError("'time_offsets' must be None in analysis "\
"mode'single'.")
# 'data' must be either
# - np.ndarray of shape (T, N)
# - np.ndarray of shape (1, T, N)
# - a dictionary with one element whose value is a np.ndarray of
# shape (T, N)
if isinstance(data, np.ndarray):
_data_shape = data.shape
if len(_data_shape) == 2:
self.values = {0: np.copy(data)}
self._initialized_from = "2d numpy array"
elif len(_data_shape) == 3 and _data_shape[0] == 1:
self.values = {0: np.copy(data[0, :, :])}
self._initialized_from = "3d numpy array"
else:
raise TypeError("In analysis mode 'single', 'data' given "\
"as np.ndarray. 'data' is of shape {}, must be of "\
"shape (T, N) or (1, T, N).".format(_data_shape))
elif isinstance(data, dict):
if len(data) == 1:
_data = next(iter(data.values()))
if isinstance(_data, np.ndarray):
if len(_data.shape) == 2:
self.values = data.copy()
self._initialized_from = "dict"
else:
raise TypeError("In analysis mode 'single', "\
"'data'given as dictionary. The single value "\
"is a np.ndarray of shape {}, must be of "\
"shape (T, N).".format(_data.shape))
else:
raise TypeError("In analysis mode 'single', 'data' "\
"given as dictionary. The single value is of type "\
"{}, must be np.ndarray.".format(type(_data)))
else:
raise ValueError("In analysis mode 'single', 'data' given "\
"as dictionary. There are {} entries in 'data', there "\
"must be exactly one entry.".format(len(data)))
else:
raise TypeError("In analysis mode 'single'. 'data' is of type "\
"{}, must be np.ndarray or dict.".format(type(data)))
elif self.analysis_mode == 'multiple':
# 'data' must either be a
# - np.ndarray of shape (M, T, N)
# - dict whose values of are np.ndarray of shape (T_i, N), where T_i
# may vary across the values
if isinstance(data, np.ndarray):
_data_shape = data.shape
if len(_data_shape) == 3:
self.values = {i: np.copy(data[i, :, :]) for i in range(_data_shape[0])}
self._initialized_from = "3d numpy array"
else:
raise TypeError("In analysis mode 'multiple', 'data' "\
"given as np.ndarray. 'data' is of shape {}, must be "\
"of shape (M, T, N).".format(_data_shape))
# In this case the 'time_offset' functionality must not be used
if time_offsets is not None:
raise ValueError("In analysis mode 'multiple'. Since "\
"'data' is given as np.ndarray, 'time_offsets' must "\
"be None.")
elif isinstance(data, dict):
_N_list = set()
for dataset_key, dataset_data in data.items():
if isinstance(dataset_data, np.ndarray):
_dataset_data_shape = dataset_data.shape
if len(_dataset_data_shape) == 2:
_N_list.add(_dataset_data_shape[1])
else:
raise TypeError("In analysis mode 'multiple', "\
"'data' given as dictionary. 'data'[{}] is of "\
"shape {}, must be of shape (T_i, N).".format(
dataset_key, _dataset_data_shape))
else:
raise TypeError("In analysis mode 'multiple', 'data' "\
"given as dictionary. 'data'[{}] is of type {}, "\
"must be np.ndarray.".format(dataset_key,
type(dataset_data)))
if len(_N_list) == 1:
self.values = data.copy()
self._initialized_from = "dict"
else:
raise ValueError("In analysis mode 'multiple', 'data' "\
"given as dictionary. All entries must be np.ndarrays "\
"of shape (T_i, N), where T_i may vary across the "\
"entries while N must not vary. In the given 'data' N "\
"varies.")
else:
raise TypeError("In analysis mode 'multiple'. 'data' is of "\
"type {}, must be np.ndarray or dict.".format(type(data)))
# Store the keys of the datasets in a separated attribute
self.datasets = list(self.values.keys())
# Save the data format and check for NaNs:
self.M = len(self.values) # (Number of datasets)
self.T = dict() # (Time lengths of the individual datasets)
for dataset_key, dataset_data in self.values.items():
if np.isnan(dataset_data).sum() != 0:
raise ValueError("NaNs in the data.")
_dataset_data_shape = dataset_data.shape
self.T[dataset_key] = _dataset_data_shape[0]
self.Ndata = _dataset_data_shape[1] # (Number of variables)
# N does not vary across the datasets
# Setup dictionary of variables for vector mode
self.vector_vars = vector_vars
if self.vector_vars is None:
self.vector_vars = dict(zip(range(self.Ndata), [[(i, 0)]
for i in range(self.Ndata)]))
self.N = len(self.vector_vars)
# Warnings
if self.analysis_mode == 'single' and self.N > next(iter(self.T.values())):
warnings.warn("In analysis mode 'single', 'data'.shape = ({}, {});"\
" is it of shape (observations, variables)?".format(self.T[0],
self.N))
if self.analysis_mode == 'multiple' and self.M == 1:
warnings.warn("In analysis mode 'multiple'. There is just a "\
"single dataset, is this as intended?'")
# Save the variable names. If unspecified, use the default
if var_names is None:
self.var_names = {i: i for i in range(self.N)}
else:
self.var_names = var_names
self.mask = None
if mask is not None:
self.mask = self._check_mask(mask = mask)
self.type_mask = None
if type_mask is not None:
self.type_mask = self._check_mask(mask = type_mask, check_type_mask=True)
# Check and prepare the time offsets
self._check_and_set_time_offsets(time_offsets)
self.time_offsets_is_none = time_offsets is None
# Set the default datatime if unspecified
if datatime is None:
self.datatime = {m: np.arange(self.time_offsets[m],
self.time_offsets[m] + self.T[m]) for m in self.values.keys()}
else:
if not isinstance(datatime, dict):
self.datatime = {0: datatime}
else:
self.datatime = datatime
# Save the largest/smallest relevant time step
self.largest_time_step = np.add(np.asarray(list(self.T.values())), np.asarray(list(self.time_offsets.values()))).max()
self.smallest_time_step = np.add(np.asarray(list(self.T.values())), np.asarray(list(self.time_offsets.values()))).min()
# Check and prepare the reference points
self._check_and_set_reference_points(reference_points)
self.reference_points_is_none = reference_points is None
# Save the 'missing_flag' value
self.missing_flag = missing_flag
if self.missing_flag is not None:
for dataset_key in self.values:
self.values[dataset_key][self.values[dataset_key] == self.missing_flag] = np.nan
self.remove_missing_upto_maxlag = remove_missing_upto_maxlag
# If PCMCI.run_bootstrap_of is called, then the
# bootstrap random draw can be set here
self.bootstrap = None
def _check_mask(self, mask, check_type_mask=False):
"""Checks that the mask is:
* The same shape as the data
* Is an numpy ndarray (or subtype)
* Does not contain any NaN entries
"""
# Check that there is a mask if required
_use_mask = mask
# If we have a mask, check it
if _use_mask is not None:
# Check data type and generic format of 'mask', map to multiple datasets mode
# dictionary representation
if isinstance(_use_mask, np.ndarray):
if len(_use_mask.shape) == 2:
_use_mask_dict = {0: _use_mask}
elif len(_use_mask.shape) == 3:
if _use_mask.shape[0] == self.M:
_use_mask_dict = {i: _use_mask[i, :, :] for i in range(self.M)}
else:
raise ValueError("Shape mismatch: {} datasets "\
" in 'data' but {} in 'mask', must be "\
"identical.".format(self.M, _use_mask.shape[0]))
else:
raise TypeError("'data' given as 3d np.ndarray. "\
"'mask' is np.ndarray of shape {}, must be of "\
"shape (M, T, N).".format(_use_mask.shape))
elif isinstance(_use_mask, dict):
if len(_use_mask) == self.M:
for dataset_key in self.values.keys():
if _use_mask.get(dataset_key) is None:
raise ValueError("'data' has key {} (type {}) "\
"but 'mask' does not, keys must be "\
"identical.".format(dataset_key,
type(dataset_key)))
_use_mask_dict = _use_mask
else:
raise ValueError("Shape mismatch: {} datasets "\
"in 'data' but {} in 'mask', must be "\
"identical.".format(self.M, len(_use_mask)))
else:
raise TypeError("'mask' is of type "\
"{}, must be dict or array.".format(type(_use_mask)))
# Check for consistency with shape of 'self.values' and for NaNs
for dataset_key, dataset_data in self.values.items():
_use_mask_dict_data = _use_mask_dict[dataset_key]
if _use_mask_dict_data.shape == dataset_data.shape:
if np.sum(np.isnan(_use_mask_dict_data)) != 0:
raise ValueError("NaNs in the data mask")
if check_type_mask:
if not set(np.unique(_use_mask_dict_data)).issubset(set([0, 1])):
raise ValueError("Type mask contains other values than 0 and 1")
else:
if self.analysis_mode == 'single':
raise ValueError("Shape mismatch: 'data' is of shape "\
"{}, 'mask' is of shape {}. Must be "\
"identical.".format(dataset_data.shape,
_use_mask_dict_data.shape))
elif self.analysis_mode == 'multiple':
raise ValueError("Shape mismatch: dataset {} "\
"is of shape {} in 'data' and of shape {} in "\
"'mask'. Must be identical.".format(dataset_key,
dataset_data.shape,
_use_mask_dict_data.shape))
# Return the mask in dictionary format
return _use_mask_dict
def _check_and_set_time_offsets(self, time_offsets):
"""Check the argument 'time_offsets' for consistency and bring into
canonical format"""
if time_offsets is not None:
assert self.analysis_mode == 'multiple'
assert self._initialized_from == 'dict'
# Check data type and generic format of 'time_offsets', map to
# dictionary representation
if isinstance(time_offsets, dict):
if len(time_offsets) == self.M:
for dataset_key in self.values.keys():
if time_offsets.get(dataset_key) is None:
raise ValueError("'data' has key {} (type {}) but "\
"'time_offsets' does not, keys must be "\
"identical.".format(dataset_key,
type(dataset_key)))
self.time_offsets = time_offsets
else:
raise ValueError("Shape mismatch: {} datasets in "\
"'data' but {} in 'time_offsets', must be "\
"identical.".format(self.M, len(time_offsets)))
else:
raise TypeError("'time_offsets' is of type {}, must be "\
"dict.".format(type(time_offsets)))
# All time offsets must be non-negative integers, at least one of
# which is zero
found_zero_time_offset = False
for time_offset in self.time_offsets.values():
if np.issubdtype(type(time_offset), np.integer):
if time_offset >= 0:
if time_offset == 0:
found_zero_time_offset = True
else:
raise ValueError("A dataset has time offset "\
"{}, must be non-negative.".format(time_offset))
else:
raise TypeError("There is a time offset of type {}, must "\
"be int.".format(type(time_offset)))
if not found_zero_time_offset:
raise ValueError("At least one time offset must be 0.")
else:
# If no time offsets are specified, all of them are zero
self.time_offsets = {dataset_key: 0 for dataset_key in self.values.keys()}
def _check_and_set_reference_points(self, reference_points):
"""Check the argument 'reference_point' for consistency and bring into
canonical format"""
# Check type of 'reference_points' and its elements
if reference_points is None:
# If no reference point is specified, use as many reference points
# as possible
self.reference_points = np.array(range(self.largest_time_step))
elif isinstance(reference_points, int):
# If a single reference point is specified as an int, convert it to
# a single element numpy array
self.reference_points = np.array([reference_points])
elif isinstance(reference_points, np.ndarray):
# Check that all reference points are ints
for ref_point in reference_points:
if not np.issubdtype(type(ref_point), np.integer):
raise TypeError("All reference points must be integers.")
self.reference_points = reference_points
elif isinstance(reference_points, list):
# Check that all reference points are ints
for ref_point in reference_points:
if not isinstance(ref_point, int):
raise TypeError("All reference points must be integers.")
# If given as a list, cast to numpy array
self.reference_points = np.asarray(reference_points)
else:
raise TypeError("Unsupported data type of 'reference_points': Is "\
"{}, must be None or int or a list or np.ndarray of "\
"ints.".format(type(reference_points)))
# Remove negative reference points
if np.sum(self.reference_points < 0) > 0:
warnings.warn("Some reference points were negative. These are "\
"removed.")
self.reference_points = self.reference_points[self.reference_points >= 0]
# Remove reference points that are larger than the largest time step
if np.sum(self.reference_points >= self.largest_time_step) > 0:
warnings.warn("Some reference points were larger than the largest "\
"relevant time step, which here is {}. These are "\
"removed.".format(self.largest_time_step - 1))
self.reference_points = self.reference_points[self.reference_points < self.largest_time_step]
# Raise an error if no valid reference points was specified
if len(self.reference_points) == 0:
raise ValueError("No valid reference point.")
def construct_array(self, X, Y, Z, tau_max,
extraZ=None,
mask=None,
mask_type=None,
type_mask=None,
return_cleaned_xyz=False,
do_checks=True,
remove_overlaps=True,
cut_off='2xtau_max',
verbosity=0):
"""Constructs array from variables X, Y, Z from data.
Data is of shape (T, N) if analysis_mode == 'single', where T is the
time series length and N the number of variables, and of (n_ens, T, N)
if analysis_mode == 'multiple'.
Parameters
----------
X, Y, Z, extraZ : list of tuples
For a dependence measure I(X;Y|Z), X, Y, Z can be multivariate of
the form [(var1, -lag), (var2, -lag), ...]. At least one varlag in Y
has to be at lag zero. extraZ is only used in CausalEffects class.
tau_max : int
Maximum time lag. This may be used to make sure that estimates for
different lags in X and Z all have the same sample size.
mask : array-like, optional (default: None)
Optional mask array, must be of same shape as data. If it is set,
then it overrides the self.mask assigned to the dataframe. If it is
None, then the self.mask is used, if it exists.
mask_type : {None, 'y','x','z','xy','xz','yz','xyz'}
Masking mode: Indicators for which variables in the dependence
measure I(X; Y | Z) the samples should be masked. If None, the mask
is not used. Explained in tutorial on masking and missing values.
type_mask : array-like
Binary data array of same shape as array which describes whether
individual samples in a variable (or all samples) are continuous
or discrete: 0s for continuous variables and 1s for discrete variables.
If it is set, then it overrides the self.type_mask assigned to the dataframe.
return_cleaned_xyz : bool, optional (default: False)
Whether to return cleaned X,Y,Z, where possible duplicates are
removed.
do_checks : bool, optional (default: True)
Whether to perform sanity checks on input X,Y,Z
remove_overlaps : bool, optional (default: True)
Whether to remove variables from Z/extraZ if they overlap with X or Y.
cut_off : {'2xtau_max', 'tau_max', 'max_lag', 'max_lag_or_tau_max',
2xtau_max_future}
If cut_off == '2xtau_max':
- 2*tau_max samples are cut off at the beginning of the time
series ('beginning' here refers to the temporally first time
steps). This guarantees that (as long as no mask is used) all
MCI tests are conducted on the same samples, independent of X,
Y, and Z.
- If at time step t_missing a data value is missing, then the
time steps t_missing, ..., t_missing + 2*tau_max are cut out.
The latter part only holds if remove_missing_upto_maxlag=True.
If cut_off == 'max_lag':
- max_lag(X, Y, Z) samples are cut off at the beginning of the
time series, where max_lag(X, Y, Z) is the maximum lag of all
nodes in X, Y, and Z. These are all samples that can in
principle be used.
- If at time step t_missing a data value is missing, then the
time steps t_missing, ..., t_missing + max_lag(X, Y, Z) are cut
out.
The latter part only holds if remove_missing_upto_maxlag=True.
If cut_off == 'max_lag_or_tau_max':
- max(max_lag(X, Y, Z), tau_max) are cut off at the beginning.
This may be useful for modeling by comparing multiple models on
the same samples.
- If at time step t_missing a data value is missing, then the
time steps
t_missing, ..., t_missing + max(max_lag(X, Y, Z), tau_max)
are cut out.
The latter part only holds if remove_missing_upto_maxlag=True.
If cut_off == 'tau_max':
- tau_max samples are cut off at the beginning.
This may be useful for modeling by comparing multiple models on
the same samples.
- If at time step t_missing a data value is missing, then the
time steps
t_missing, ..., t_missing + max(max_lag(X, Y, Z), tau_max)
are cut out.
The latter part only holds if remove_missing_upto_maxlag=True.
If cut_off == '2xtau_max_future':
First, the relevant time steps are determined as for cut_off ==
'max_lag'. Then, the temporally latest time steps are removed
such that the same number of time steps remains as there would
be for cut_off == '2xtau_max'. This may be useful when one is
mostly interested in the temporally first time steps and would
like all MCI tests to be performed on the same *number* of
samples. Note, however, that while the *number* of samples is
the same for all MCI tests, the samples themselves may be
different.
verbosity : int, optional (default: 0)
Level of verbosity.
Returns
-------
array, xyz [,XYZ], type_mask : Tuple of data array of shape (dim, n_samples),
xyz identifier array of shape (dim,) identifying which row in array
corresponds to X, Y, and Z, and the type mask that indicates which samples
are continuous or discrete. For example:: X = [(0, -1)],
Y = [(1, 0)], Z = [(1, -1), (0, -2)] yields an array of shape
(4, n_samples) and xyz is xyz = numpy.array([0,1,2,2]). If
return_cleaned_xyz is True, also outputs the cleaned XYZ lists.
"""
# # This version does not yet work with bootstrap
# try:
# assert self.bootstrap is None
# except AssertionError:
# print("This version does not yet work with bootstrap.")
# raise
if extraZ is None:
extraZ = []
# If vector-valued variables exist, add them
def vectorize(varlag):
vectorized_var = []
for (var, lag) in varlag:
for (vector_var, vector_lag) in self.vector_vars[var]:
vectorized_var.append((vector_var, vector_lag + lag))
return vectorized_var
X = vectorize(X)
Y = vectorize(Y)
Z = vectorize(Z)
extraZ = vectorize(extraZ)
# Remove duplicates in X, Y, Z, extraZ
X = list(OrderedDict.fromkeys(X))
Y = list(OrderedDict.fromkeys(Y))
Z = list(OrderedDict.fromkeys(Z))
extraZ = list(OrderedDict.fromkeys(extraZ))
if remove_overlaps:
# If a node in Z occurs already in X or Y, remove it from Z
Z = [node for node in Z if (node not in X) and (node not in Y)]
extraZ = [node for node in extraZ if (node not in X) and (node not in Y) and (node not in Z)]
XYZ = X + Y + Z + extraZ
dim = len(XYZ)
# Check that all lags are non-positive and indices are in [0,N-1]
if do_checks:
self._check_nodes(Y, XYZ, self.Ndata, dim)
# Use the mask, override if needed
_mask = mask
if _mask is None:
_mask = self.mask
else:
_mask = self._check_mask(mask = _mask)
_type_mask = type_mask
if _type_mask is None:
_type_mask = self.type_mask
else:
_type_mask = self._check_mask(mask = _type_mask, check_type_mask=True)
# Figure out what cut off we will be using
if cut_off == '2xtau_max':
max_lag = 2*tau_max
elif cut_off == 'max_lag':
max_lag = abs(np.array(XYZ)[:, 1].min())
elif cut_off == 'tau_max':
max_lag = tau_max
elif cut_off == 'max_lag_or_tau_max':
max_lag = max(abs(np.array(XYZ)[:, 1].min()), tau_max)
elif cut_off == '2xtau_max_future':
max_lag = abs(np.array(XYZ)[:, 1].min())
else:
raise ValueError("max_lag must be in {'2xtau_max', 'tau_max', 'max_lag', "\
"'max_lag_or_tau_max', '2xtau_max_future'}")
# Setup XYZ identifier
index_code = {'x' : 0,
'y' : 1,
'z' : 2,
'e' : 3}
xyz = np.array([index_code[name]
for var, name in zip([X, Y, Z, extraZ], ['x', 'y', 'z', 'e'])
for _ in var])
# Run through all datasets and fill a dictionary holding the
# samples taken from the individual datasets
samples_datasets = dict()
type_masks = dict()
self.use_indices_dataset_dict = dict()
for dataset_key, dataset_data in self.values.items():
# Apply time offset to the reference points
ref_points_here = self.reference_points - self.time_offsets[dataset_key]
# Remove reference points that are out of bounds or are to be
# excluded given the choice of 'cut_off'
ref_points_here = ref_points_here[ref_points_here >= max_lag]
ref_points_here = ref_points_here[ref_points_here < self.T[dataset_key]]
# Keep track of which reference points would have remained for
# max_lag == 2*tau_max
if cut_off == '2xtau_max_future':
ref_points_here_2_tau_max = self.reference_points - self.time_offsets[dataset_key]
ref_points_here_2_tau_max = ref_points_here_2_tau_max[ref_points_here_2_tau_max >= 2*tau_max]
ref_points_here_2_tau_max = ref_points_here_2_tau_max[ref_points_here_2_tau_max < self.T[dataset_key]]
# Sort the valid reference points (not needed, but might be useful
# for detailed debugging)
ref_points_here = np.sort(ref_points_here)
# For cut_off == '2xtau_max_future' reduce the samples size the
# number of samples that would have been obtained for cut_off ==
# '2xtau_max', removing the temporally latest ones
if cut_off == '2xtau_max_future':
n_to_cut_off = len(ref_points_here) - len(ref_points_here_2_tau_max)
assert n_to_cut_off >= 0
if n_to_cut_off > 0:
ref_points_here = np.sort(ref_points_here)
ref_points_here = ref_points_here[:-n_to_cut_off]
# If no valid reference points are left, continue with the next dataset
if len(ref_points_here) == 0:
continue
if self.bootstrap is not None:
boot_blocklength = self.bootstrap['boot_blocklength']
if boot_blocklength == 'cube_root':
boot_blocklength = max(1, int(len(ref_points_here)**(1/3)))
elif type(boot_blocklength) is int and boot_blocklength > 0:
pass
else:
raise ValueError("boot_blocklength must be integer > 0, 'cube_root', or 'from_autocorrelation'")
# Chooses THE SAME random seed for every dataset, maybe that's what we want...
random_state = deepcopy(self.bootstrap['random_state'])
# Determine the number of blocks total, rounding up for non-integer
# amounts
n_blks = int(math.ceil(float(len(ref_points_here))/boot_blocklength))
if n_blks < 10:
raise ValueError("Only %d block(s) for block-sampling," %n_blks +
"choose smaller boot_blocklength!")
# Get the starting indices for the blocks
blk_strt = random_state.choice(np.arange(len(ref_points_here) - boot_blocklength), size=n_blks, replace=True)
# Get the empty array of block resampled values
boot_draw = np.zeros(n_blks*boot_blocklength, dtype='int')
# Fill the array of block resamples
for i in range(boot_blocklength):
boot_draw[i::boot_blocklength] = ref_points_here[blk_strt + i]
# Cut to proper length
ref_points_here = boot_draw[:len(ref_points_here)]
# Construct the data array holding the samples taken from the
# current dataset
samples_datasets[dataset_key] = np.zeros((dim, len(ref_points_here)), dtype = dataset_data.dtype)
for i, (var, lag) in enumerate(XYZ):
samples_datasets[dataset_key][i, :] = dataset_data[ref_points_here + lag, var]
# Build the mask array corresponding to this dataset
if _mask is not None:
mask_dataset = np.zeros((dim, len(ref_points_here)), dtype = 'bool')
for i, (var, lag) in enumerate(XYZ):
mask_dataset[i, :] = _mask[dataset_key][ref_points_here + lag, var]
# Take care of masking
use_indices_dataset = np.ones(len(ref_points_here), dtype = 'int')
# Build the type mask array corresponding to this dataset
if _type_mask is not None:
type_mask_dataset = np.zeros((dim, len(ref_points_here)), dtype = 'bool')
for i, (var, lag) in enumerate(XYZ):
type_mask_dataset[i, :] = _type_mask[dataset_key][ref_points_here + lag, var]
type_masks[dataset_key] = type_mask_dataset
# Remove all values that have missing value flag, and optionally as well the time
# slices that occur up to max_lag after
if self.missing_flag is not None:
missing_anywhere = np.array(np.where(np.any(np.isnan(samples_datasets[dataset_key]), axis=0))[0])
if self.remove_missing_upto_maxlag:
idx_to_remove = set(idx + tau for idx in missing_anywhere for tau in range(max_lag + 1))
else:
idx_to_remove = set(idx for idx in missing_anywhere)
use_indices_dataset[np.array(list(idx_to_remove), dtype='int')] = 0
if _mask is not None:
# Remove samples with mask == 1 conditional on which mask_type
# is used
# Iterate over defined mapping from letter index to number index,
# i.e. 'x' -> 0, 'y' -> 1, 'z'-> 2, 'e'-> 3
for idx, cde in index_code.items():
# Check if the letter index is in the mask type
if (mask_type is not None) and (idx in mask_type):
# If so, check if any of the data that correspond to the
# letter index is masked by taking the product along the
# node-data to return a time slice selection, where 0
# means the time slice will not be used
slice_select = np.prod(mask_dataset[xyz == cde, :] == False, axis=0)
use_indices_dataset *= slice_select
# Accordingly update the data array
samples_datasets[dataset_key] = samples_datasets[dataset_key][:, use_indices_dataset == 1]
## end for dataset_key, dataset_data in self.values.items()
# Save used indices as attribute
if len(ref_points_here) > 0:
self.use_indices_dataset_dict[dataset_key] = ref_points_here[use_indices_dataset==1]
else:
self.use_indices_dataset_dict[dataset_key] = []
# Concatenate the arrays of all datasets
array = np.concatenate(tuple(samples_datasets.values()), axis = 1)
if _type_mask is not None:
type_array = np.concatenate(tuple(type_masks.values()), axis = 1)
else:
type_array = None
# print(np.where(np.isnan(array)))
# print(array.shape)
# Check whether there is any valid sample
if array.shape[1] == 0:
raise ValueError("No valid samples")
# Print information about the constructed array
if verbosity > 2:
self.print_array_info(array, X, Y, Z, self.missing_flag, mask_type, type_array, extraZ)
# Return the array and xyz and optionally (X, Y, Z)
if return_cleaned_xyz:
return array, xyz, (X, Y, Z), type_array
return array, xyz, type_array
def _check_nodes(self, Y, XYZ, N, dim):
"""
Checks that:
* The requests XYZ nodes have the correct shape
* All lags are non-positive
* All indices are less than N
* One of the Y nodes has zero lag
Parameters
----------
Y : list of tuples
Of the form [(var, -tau)], where var specifies the variable
index and tau the time lag.
XYZ : list of tuples
List of nodes chosen for current independence test
N : int
Total number of listed nodes
dim : int
Number of nodes excluding repeated nodes
"""
if np.array(XYZ).shape != (dim, 2):
raise ValueError("X, Y, Z must be lists of tuples in format"
" [(var, -lag),...], eg., [(2, -2), (1, 0), ...]")
if np.any(np.array(XYZ)[:, 1] > 0):
raise ValueError("nodes are %s, " % str(XYZ) +
"but all lags must be non-positive")
if (np.any(np.array(XYZ)[:, 0] >= N)
or np.any(np.array(XYZ)[:, 0] < 0)):
raise ValueError("var indices %s," % str(np.array(XYZ)[:, 0]) +
" but must be in [0, %d]" % (N - 1))
# if np.all(np.array(Y)[:, 1] != 0):
# raise ValueError("Y-nodes are %s, " % str(Y) +
# "but one of the Y-nodes must have zero lag")
def print_array_info(self, array, X, Y, Z, missing_flag, mask_type, type_mask=None, extraZ=None):
"""
Print info about the constructed array
Parameters
----------
array : Data array of shape (dim, T)
Data array.
X, Y, Z, extraZ : list of tuples
For a dependence measure I(X;Y|Z), Y is of the form [(varY, 0)],
where var specifies the variable index. X typically is of the form
[(varX, -tau)] with tau denoting the time lag and Z can be
multivariate [(var1, -lag), (var2, -lag), ...] .
missing_flag : number, optional (default: None)
Flag for missing values. Dismisses all time slices of samples where
missing values occur in any variable and also flags samples for all
lags up to 2*tau_max. This avoids biases, see section on masking in
Supplement of [1]_.
mask_type : {'y','x','z','xy','xz','yz','xyz'}
Masking mode: Indicators for which variables in the dependence
measure I(X; Y | Z) the samples should be masked. If None, the mask
is not used. Explained in tutorial on masking and missing values.
type_mask : array-like
Binary data array of same shape as array which describes whether
individual samples in a variable (or all samples) are continuous
or discrete: 0s for continuous variables and 1s for discrete variables.
"""
if extraZ is None:
extraZ = []
indt = " " * 12
print(indt + "Constructed array of shape %s from"%str(array.shape) +
"\n" + indt + "X = %s" % str(X) +
"\n" + indt + "Y = %s" % str(Y) +
"\n" + indt + "Z = %s" % str(Z))
if extraZ is not None:
print(indt + "extraZ = %s" % str(extraZ))
if self.mask is not None and mask_type is not None:
print(indt+"with masked samples in %s removed" % mask_type)
if self.type_mask is not None:
print(indt+"with %s % discrete values" % np.sum(type_mask)/type_mask.size)
if self.missing_flag is not None:
print(indt+"with missing values = %s removed" % self.missing_flag)
def get_acf(series, max_lag=None):
"""Returns autocorrelation function.
Parameters
----------
series : 1D-array
data series to compute autocorrelation from
max_lag : int, optional (default: None)
maximum lag for autocorrelation function. If None is passed, 10% of
the data series length are used.
Returns
-------
autocorr : array of shape (max_lag + 1,)
Autocorrelation function.
"""
# Set the default max lag
if max_lag is None:
max_lag = int(max(5, 0.1*len(series)))
# Initialize the result
autocorr = np.ones(max_lag + 1)
# Iterate over possible lags
for lag in range(1, max_lag + 1):
# Set the values
y1_vals = series[lag:]
y2_vals = series[:len(series) - lag]
# Calculate the autocorrelation
autocorr[lag] = np.corrcoef(y1_vals, y2_vals, ddof=0)[0, 1]
return autocorr
def get_block_length(array, xyz, mode):
"""Returns optimal block length for significance and confidence tests.