-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNetworkInference.py
More file actions
2046 lines (1656 loc) · 75.9 KB
/
NetworkInference.py
File metadata and controls
2046 lines (1656 loc) · 75.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 29 18:25:12 2025
@author: jefis
"""
from sklearn.neighbors import KernelDensity
from sklearn.linear_model import LinearRegression
import scipy as sp
from scipy.spatial import distance
from scipy.spatial.distance import cdist
from scipy.special import gamma as Gamma
from scipy.special import digamma as Digamma
from sklearn.linear_model import LassoLarsIC
from sklearn.linear_model import LassoCV
import scipy.stats as SStats
import numpy as np
import itertools
import copy
import datetime
import glob
from matplotlib import pyplot as plt
from matplotlib import rc
import time
from joblib import Parallel, delayed
import multiprocessing
"""Written by Jeremie Fish,
Last Update: Feb 10th 2026
Depending on method used please cite the appropriate papers..."""
class NetworkInference:
"""A class for NetworkInference. Version number 0.3"""
def __init__(self):
#Version
self.VersionNum = 0.3
#conditional (causation entropy) return stuff
self.conditional_returns_set = 'existing_edges'
#for potential multiprocessing
self.num_processes = np.max([multiprocessing.cpu_count()-1,1]) #default to cpus-1 unless only 1 cpu...
self.parallel_shuffles = False
self.parallel_nodes = False
#Time series stuff
self.n = 100
self.T = 200
#Initialize time series to nothing, this must be entered or generated
self.X = None
self.Y = None
self.Z = None
self.XY = None
#Network stuff
self.NetworkAdjacency = None
self.NetworkType = None
self.Lin_Stoch_Gaussian_Adjacency = None
self.Logistic_Adjacency = None
#Rho, which is effectively how "noise dominated" the system is
#It is the spectral radius of the input matrix
self.Rho = None
#Inference Stuff
self.Overall_Inference_Method = 'Standard_oCSE'
self.InferenceMethod_oCSE = 'Gaussian'
self.KernelBandWidth = None
self.KernelType = 'gaussian'
self.KNN_K = 10
self.KNN_dist_metric = 'minkowski'
self.Tau = int(1) #Tau is assumed to be 1 always but can be changed
#oCSE stuff
self.Num_Shuffles_oCSE = 100
self.Forward_oCSE_alpha = 0.02
self.Backward_oCSE_alpha = 0.02
#Information Informed LASSO stuff
self.IIkfold = 10 #For crossfold validation when num data points small
self.II_InfCriterion = 'bic' #can be aic or bic, bic does better
self.max_num_lambdas = 100
#Miscellaneous
self.Pedeli_PoissonAlphas = None
self.Correlation_XY = None
self.Prctile = None
self.Dict = None
self.Sinit = None
self.Sfinal = None
#TO DO,Add all of the other listed methods. These will become available in future renditions of the software.
self.Available_Inference_Methods = ['Standard_oCSE', 'Alternative_oCSE', 'InformationInformed_LASSO', 'LASSO']#['Standard_oCSE', 'Alternative_oCSE', 'Lasso', 'Graphical_Lasso',
# 'GLM_Lasso', 'Kernel_Lasso','Entropic_Regression','Convergent_Cross_Mapping',
# 'PCMCI','PCMCIplus','LPMCI','Partial_Correlation','GPDC']
self.DataType = 'Continuous'
self.font = None
#Dynamics stuff
self.Gaussian_Epsilon = None
self.Logistic_parameter_r = None
self.Logistic_Coupling = None
self.Armillotta_Poisson_Betas = None
self.Armillotta_Poisson_Lambda_0 = None
#For Error computation
self.B = None # The estimated Adjacency matrix
self.TPR = None
self.FPR = None
self.AUC = None
self.Xshuffle = False
#For student t distribution
self.StudentT_nu = 5
#Potentially handle data issue, set to true to adjust correlation matrix to handle 0's
self.adjust_correlation = False
self.correlation_adjustment_factor = 1e-5
def set_adjust_correlation(self,adjust):
self.adjust_correlation = adjust
def set_correlation_adjustment_factor(self,caf):
self.correlation_adjustment_factor = caf
def set_conditional_returns_set(self,cond_ret_type):
self.conditional_returns_set = cond_ret_type
def set_KNN_dist_metric(self,metric):
self.KNN_dist_metric = metric
def set_parallel_nodes(self,truth_val):
self.parallel_nodes = truth_val
def set_parallel_shuffles(self,truth_val):
self.parallel_shuffles = truth_val
def set_num_processes(self,num):
self.num_processes = num
def set_II_InfCriterion(self,criterion):
"""Should be a string either 'aic' or 'bic' the only two options """
self.II_InfCriterion = criterion
def set_IIkfold(self,num):
"""Should be a positive integer!"""
self.IIkfold = num
def set_Xshuffle(self,TF=False):
self.Xshuffle = TF
def set_font(self,font):
self.font = font
def set_AUC(self,AUC):
self.AUC = AUC
def set_FPR(self,FPR):
self.FPR = FPR
def set_TPR (self,TPR):
self.TPR = TPR
def set_B(self,B):
self.B = B
def set_Tau(self,Tau):
self.Tau = int(Tau)
def set_DataType(self,Type):
Types = ['Discrete', 'Continuous']
if Type not in Types:
raise ValueError("Sorry the only types allowed for DataType are: ", Types)
self.DataType = Type
def set_Available_Inference_Methods(self,Methods):
self.Available_Inference_Methods = Methods
def set_Armillotta_Poisson_Betas(self,Betas):
self.Armillotta_Poisson_Betas = Betas
def set_Armillotta_Poisson_Lambda_0(self,Lam0):
self.Armillotta_Poisson_Lambda_0 = Lam0
def set_Lin_Stoch_Gaussian_Adjacency(self,A):
self.Lin_Stoch_Gaussian_Adjacency = A
def set_Logistic_Adjacency(self,A):
self.Logistic_Adjacency = A
def set_Pedeli_PoissonAlphas(self,alphas):
self.Pedeli_PoissonAlphas = alphas
def set_Prctile(self,Prctile):
self.Prctile = Prctile
def set_Dict(self,Dict):
self.Dict = Dict
def set_Sinit(self,Sin):
self.Sinit = Sin
def set_Sfinal(self,Sfin):
self.Sfinal = Sfin
def set_Gaussian_Epsilon(self,Eps):
self.Gaussian_Epsilon = Eps
def set_Logistic_parameter_r(self,r):
self.Logistic_parameter_r = r
def set_Logistic_Coupling(self,Sigma):
self.Logistic_Coupling = Sigma
def set_n(self,n):
self.n = n
def set_T(self,T):
self.T = T
def set_X(self,X):
"""The time series (T x n) which is the set of predictors"""
self.X = X
self.T = X.shape[0]
def set_Y(self,Y):
"""The time series (T x m) of target variable(s)
(note m usually is equal to 1 but for generalized
interactions between many nodes it may be useful
to have m>1) """
self.Y = Y
if self.Y is not None:
self.T = Y.shape[0]
def set_Z(self,Z):
"""Set the conditioning set of variables. It is possible that
you do not want to condition on anything in which case it
is fine that Z is None"""
self.Z = Z
def set_XY(self,XY):
self.XY = XY
if self.XY is not None:
self.T = XY.shape[0]
self.n = XY.shape[1]
def set_Forward_oCSE_alpha(self,alpha):
self.Forward_oCSE_alpha = alpha
def set_Num_Shuffles_oCSE(self,Num_Shuffles):
self.Num_Shuffles_oCSE = Num_Shuffles
def set_Backward_oCSE_alpha(self,alpha):
self.Backward_oCSE_alpha = alpha
def set_Correlation_XY(self,Correlation_XY):
self.Correlation_XY = Correlation_XY
def set_Overall_Inference_Method(self,Method):
self.Overall_Inference_Method = Method
def set_InferenceMethod_oCSE(self,Method):
self.InferenceMethod_oCSE = Method
def set_KernelBandWidth(self,Bandwidth):
self.KernelBandWidth = Bandwidth
def set_KernelType(self,Type):
self.KernelType = Type
def set_KNN_K(self,K):
self.KNN_K = K
def set_NetworkAdjacency(self,A):
"""Adjacency matrix assumed to be (n x n)"""
self.NetworkAdjacency = A
self.n = A.shape[0]
def set_NetworkType(self,Type):
self.NetworkType = Type
def set_Rho(self,Rho):
self.Rho = Rho
def set_StudentT_nu(self, nu):
"Set degrees of freedom for Student-t CMI estimator"
if nu <= 0:
raise ValueError("Student-t degrees of freedom must be positive.")
self.StudentT_nu = nu
def return_StudentT_nu(self):
return self.StudentT_nu
def return_conditional_returns_set(self):
return self.conditional_returns_set
def return_KNN_dist_metric(self):
return self.KNN_dist_metric
def return_parallel_nodes(self):
return self.parallel_nodes
def return_parallel_shuffles(self):
return self.parallel_shuffles
def return_num_processes(self):
return self.num_processes
def return_Xshuffle(self):
return self.Xshuffle
def return_II_InfCriterion(self):
return self.II_InfCriterion
def return_IIkfold(self):
return self.IIkfold
def return_font(self):
return self.font
def return_DataType(self):
return self.DataType
def return_VersionNum(self):
return self.VersionNum
def return_Available_Inference_Methods(self):
return self.Available_Inference_Methods
def return_n(self):
return self.n
def return_T(self):
return self.T
def return_Num_Shuffles_oCSE(self):
return self.Num_Shuffles_oCSE
def return_Z(self):
return self.Z
def return_X(self):
return self.X
def return_Y(self):
return self.Y
def return_XY(self):
return self.XY
def return_NetworkAdjacency(self):
return self.NetworkAdjacency
def return_NetworkType(self):
return self.NetworkType
def return_Rho(self):
return self.Rho
def return_Overall_Inference_Method(self):
return self.Overall_Inference_Method
def return_InferenceMethod_oCSE(self):
return self.InferenceMethod_oCSE
def return_KernelBandWidth(self):
return self.KernelBandWidth
def return_KernelType(self):
return self.KernelType
def return_KNN_K(self):
return self.KNN_K
def return_Tau(self):
return self.Tau
def return_Forward_oCSE_alpha(self):
return self.Forward_oCSE_alpha
def return_Backward_oCSE_alpha(self):
return self.Backward_oCSE_alpha
def return_Pedeli_PoissonAlphas(self):
return self.Pedeli_PoissonAlphas
def return_Correlation_XY(self):
return self.Correlation_XY
def return_Prctile(self):
return self.Prctile
def return_Sinit(self):
return self.Sinit
def return_Sfinal(self):
return self.Sfinal
def return_Dict(self):
return self.Dict
def return_Lin_Stoch_Gaussian_Adjacency(self):
return self.Lin_Stoch_Gaussian_Adjacency
def return_Logistic_Adjacency(self):
return self.Logistic_Adjacency
def return_Gaussian_Epsilon(self):
return self.Gaussian_Epsilon
def return_Logistic_parameter_r(self):
return self.Logistic_parameter_r
def return_Logistic_Coupling(self):
return self.Logistic_Coupling
def return_Armillotta_Poisson_Betas(self):
return self.Armillotta_Poisson_Betas
def return_Armillotta_Poisson_Lambda_0(self):
return self.Armillotta_Poisson_Lambda_0
def return_B(self):
return self.B
def return_TPR(self):
return self.TPR
def return_FPR(self):
return self.FPR
def return_AUC(self):
return self.AUC
def return_adjust_correlation(self):
return self.adjust_correlation
def return_correlation_adjustment_factor(self):
return self.correlation_adjustment_factor
def save_state(self):
VersionNum = self.VersionNum
Save_Dict = {}
Save_Dict['VersionNum'] = self.VersionNum
Save_Dict['T'] = self.T
Save_Dict['n'] = self.n
Save_Dict['X'] = self.X
Save_Dict['Y'] = self.Y
Save_Dict['Z'] = self.Z
Save_Dict['XY'] = self.XY
Save_Dict['NetworkAdjacency'] = self.NetworkAdjacency
Save_Dict['NetworkType'] = self.NetworkType
Save_Dict['Lin_Stoch_Gaussian_Adjacency'] = self.Lin_Stoch_Gaussian_Adjacency
Save_Dict['Logistic_Adjacency'] = self.Logistic_Adjacency
Save_Dict['Rho'] = self.Rho
Save_Dict['Overall_Inference_Method'] = self.Overall_Inference_Method
Save_Dict['InferenceMethod_oCSE'] = self.InferenceMethod_oCSE
Save_Dict['KernelBandWidth'] = self.KernelBandWidth
Save_Dict['KernelType'] = self.KernelType
Save_Dict['KNN_K'] = self.KNN_K
Save_Dict['Tau'] = self.Tau
Save_Dict['Num_Shuffles_oCSE'] = self.Num_Shuffles_oCSE
Save_Dict['Forward_oCSE_alpha'] = self.Forward_oCSE_alpha
Save_Dict['Backward_oCSE_alpha'] = self.Backward_oCSE_alpha
Save_Dict['Pedeli_PoissonAlphas'] = self.Pedeli_PoissonAlphas
Save_Dict['Correlation_XY'] = self.Correlation_XY
Save_Dict['Prctile'] = self.Prctile
Save_Dict['Dict'] = self.Dict
Save_Dict['Sinit'] = self.Sinit
Save_Dict['Sfinal'] = self.Sfinal
Save_Dict['DataType'] = self.DataType
Save_Dict['Gaussian_Epsilon'] = self.Gaussian_Epsilon
Save_Dict['Logistic_parameter_r'] = self.Logistic_parameter_r
Save_Dict['Logistic_Coupling'] = self.Logistic_Coupling
Save_Dict['Armillotta_Poisson_Betas'] = self.Armillotta_Poisson_Betas
Save_Dict['Armillotta_Poisson_Lambda_0'] = self.Armillotta_Poisson_Lambda_0
Save_Dict['Available_Inference_Methods'] = self.Available_Inference_Methods
Save_Dict['font'] = self.font
Save_Dict['B'] = self.B
Save_Dict['TPR'] = self.TPR
Save_Dict['FPR'] = self.FPR
Save_Dict['AUC'] = self.AUC
Save_Dict['Xshuffle'] = self.Xshuffle
Save_Dict['IIkfold'] = self.IIkfold
Save_Dict['II_InfCriterion'] = self.II_InfCriterion
Save_Dict['num_processes'] = self.num_processes
Save_Dict['parallel_shuffles'] = self.parallel_shuffles
Save_Dict['parallel_nodes'] = self.parallel_nodes
Save_Dict['KNN_dist_metric'] = self.KNN_dist_metric
Save_Dict['conditional_returns_set'] = self.condtional_returns_set
Save_Dict['StudentT_nu'] = self.StudentT_nu
Save_Dict['adjust_correlation'] = self.adjust_correlation
Save_Dict['correlation_adjustment_factor'] = self.correlation_adjustment_factor
Date = datetime.datetime.today().strftime('%Y-%m-%d')
F = glob.glob('NetworkInference_version_'+str(VersionNum)+'_Date_'+Date+'*.npz')
num = len(F)+1
np.savez('NetworkInference_version_'+str(VersionNum)+'_Date_'+Date+'_num_'+str(num),Save_Dict)
def load_state(self,Date=None,Num=None,Version=None):
if Date is None:
#Default to today's date for attempt at loading
Date = datetime.datetime.today().strftime('%Y-%m-%d')
if Version is None:
VersionNum = self.VersionNum
if Num is None:
#Try finding the local file
F = glob.glob('NetworkInference_version_'+str(VersionNum)+'_Date_'+Date+'*.npz')
if len(F) == 0:
raise ValueError("Sorry no NetworkInference file with date: ",Date, " can be found in the current directory, please specify the date!")
else:
#If the number is unspecified, then always choose the most recent (largests number)
NumList = []
for i in range(len(F)):
StringNum = F[i].split('_')[-1].split('.npz')[0]
NumList.append(int(StringNum))
Num = max(NumList)
if len(F)>1:
print("There were multiple files discovered for date: ",Date, " the most recent one was used by default")
print("If you wish to use a different filenumber please specify the file number to use")
Filename = "NetworkInference_version_"+str(VersionNum)+"_Date_"+Date+"_num_"+str(Num)+".npz"
npz = np.load(Filename,allow_pickle=True)
Load_Dict = npz['arr_0'][()]
#Now set all values to the loaded states
self.set_T(Load_Dict['T'])
self.set_n(Load_Dict['n'])
self.set_X(Load_Dict['X'])
self.set_Y(Load_Dict['Y'])
self.set_Z(Load_Dict['Z'])
self.set_XY(Load_Dict['XY'])
self.set_NetworkAdjacency(Load_Dict['NetworkAdjacency'])
self.set_NetworkType(Load_Dict['NetworkType'])
self.set_Lin_Stoch_Gaussian_Adjacency(Load_Dict['Lin_Stoch_Gaussian_Adjacency'])
self.set_Logistic_Adjacency(Load_Dict['Logistic_Adjacency'])
self.set_Rho(Load_Dict['Rho'])
self.set_Overall_Inference_Method(Load_Dict['Overall_Inference_Method'])
self.set_InferenceMethod_oCSE(Load_Dict['InferenceMethod_oCSE'])
self.set_KernelBandWidth(Load_Dict['KernelBandWidth'])
self.set_KernelType(Load_Dict['KernelType'])
self.set_KNN_K(Load_Dict['KNN_K'])
self.set_Tau(Load_Dict['Tau'])
self.set_Num_Shuffles_oCSE(Load_Dict['Num_Shuffles_oCSE'])
self.set_Forward_oCSE_alpha(Load_Dict['Forward_oCSE_alpha'])
self.set_Backward_oCSE_alpha(Load_Dict['Backward_oCSE_alpha'])
self.set_Pedeli_PoissonAlphas(Load_Dict['Pedeli_PoissonAlphas'])
self.set_Correlation_XY(Load_Dict['Correlation_XY'])
self.set_Prctile(Load_Dict['Prctile'])
self.set_Dict(Load_Dict['Dict'])
self.set_Sinit(Load_Dict['Sinit'])
self.set_Sfinal(Load_Dict['Sfinal'])
self.set_DataType(Load_Dict['DataType'])
self.set_Gaussian_Epsilon(Load_Dict['Gaussian_Epsilon'])
self.set_Logistic_parameter_r(Load_Dict['Logistic_parameter_r'])
self.set_Logistic_Coupling(Load_Dict['Logistic_Coupling'])
self.set_Armillotta_Poisson_Betas(Load_Dict['Armillotta_Poisson_Betas'])
self.set_Armillotta_Poisson_Lambda_0(Load_Dict['Armillotta_Poisson_Lambda_0'])
self.set_Available_Inference_Methods(Load_Dict['Available_Inference_Methods'])
self.set_font(Load_Dict['font'])
self.set_B(Load_Dict['B'])
self.set_TPR(Load_Dict['TPR'])
self.set_FPR(Load_Dict['FPR'])
self.set_AUC(Load_Dict['AUC'])
self.set_Xshuffle(Load_Dict['Xshuffle'])
self.set_IIkfold(Load_Dict['IIkfold'])
self.set_II_InfCriterion(Load_Dict['II_InfCriterion'])
self.set_num_processes(Load_Dict['num_processes'])
self.set_parallel_shuffles(Load_Dict['parallel_shuffles'])
self.set_parallel_nodes(Load_Dict['parallel_nodes'])
self.set_KNN_dist_metric(Load_Dict['KNN_dist_metric'])
self.set_conditional_returns_set(Load_Dict['conditional_returns_set'])
self.set_StudentT_nu(Load_Dict['StudentT_nu'])
self.set_adjust_correlation(Load_Dict['adjust_correlation'])
self.set_correlation_adjustment_factor(Load_Dict['correlation_adjustment_factor'])
def nchoosek(self,n,k):
Range = range(1,n+1)
comb = list(itertools.combinations(Range,k))
return np.array(comb)
def PermutationMatrix(self):
p = int(self.n)
Zp = int(p*(p-1)/2)
P = np.zeros((p,Zp))
NK = self.nchoosek(p,2)
for i in range(p):
Z = np.zeros(Zp)
Wh = np.where(NK-1==i)
Z[Wh[0]] = 1;
P[i,:] = Z
return P
def sub2ind(self,Size,Arr):
return np.ravel_multi_index(Arr,Size,order='F')
def Logistic_Map(self,X,r):
return r*X*(1-X)
def Gen_Logistic_Dynamics(self,r=3.99,sigma=0.1):
"""Network coupled logistic map, r is the logistic map parameter
and sigma is the coupling strength between oscillators"""
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
T = self.T
self.Logistic_parameter_r = r
self.Logistic_Coupling = sigma
A = self.NetworkAdjacency
#Must adjust the adjacency matrix so that dynamics stay in [0,1]
A = A/np.sum(A,axis=1)
A = A.T
A[np.isnan(A)] = 0
A[np.isinf(A)] = 0
#Since the row sums equal to 1 the Laplacian matrix is easy...
L = np.eye(self.n)-A
L = np.array(L)
self.Logistic_Adjacency = A
XY = np.zeros((T,self.n))
XY[0,:] = np.random.rand(self.n)
for i in range(1,T):
XY[i,:] = self.Logistic_Map(XY[i-1,:],r)-sigma*np.dot(L,self.Logistic_Map(XY[i-1,:],r)).T
self.XY = XY
def Gen_Stochastic_Gaussian(self,Epsilon=1e-1):
"""Linear stochastic Gaussian process"""
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
if self.Rho is None:
raise ValueError("Missing Rho, please set it using set_Rho")
self.Gaussian_Epsilon = Epsilon
R = 2*(np.random.rand(self.n,self.n)-0.5)
A = np.array(self.NetworkAdjacency) * R
A = A/np.max(np.abs(np.linalg.eigvals(A)))
A = A*self.Rho
self.Lin_Stoch_Gaussian_Adjacency = A
XY = np.zeros((self.T,self.n))
XY[0,:] = Epsilon*np.random.randn(1,self.n)
for i in range(1,self.T):
Xi = np.dot(A,np.matrix(XY[i-1,:]).T) + Epsilon*np.random.randn(self.n,1)
XY[i,:] = Xi.T
self.XY = XY
def Gen_Poisson_Data(self,Epsilon=1,noiseLevel=1):
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
p = int(self.n)
noiseLam = noiseLevel*np.ones((p,1))
Zp = int(p*(p-1)/2)
lambdas = Epsilon*np.ones((p+Zp,1))
P = self.PermutationMatrix()
One_p = np.ones((p,1))
NK = self.nchoosek(p,2)
#Size = (p,p)
Tr = np.matrix(self.NetworkAdjacency[NK[:,0]-1,NK[:,1]-1])
I_p = np.eye(p)
T_p = np.dot(One_p,Tr)
PTP = np.array(P)*np.array(T_p)
B = np.concatenate((I_p,PTP),axis=1)
B = B.T
Lambs = lambdas.T*np.ones((self.T,Zp+p))
Y = np.random.poisson(Lambs)
Lambs = noiseLam.T*np.ones((self.T,p))
E = np.random.poisson(Lambs)
X = np.dot(Y,B)+E
return X
def Gen_Stochastic_Poisson_Pedeli(self,noiseLevel=0):
"""Stochastic Poisson process -
Structure comes from the paper:
'Some properties of multivariate INAR(1) processes'
By Pedeli and Karlis
"""
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
if self.Rho is None:
raise ValueError("Missing Rho, please set it using set_Rho")
p = self.n
alpha = self.Rho*np.random.rand(p)
self.PoissonAlphas = alpha
X = np.zeros((self.T,self.n))
X.astype('int32')
T = self.T
self.T = 1
X[0,:] = self.Gen_Poisson_Data(noiseLevel=noiseLevel).astype('int32')
for i in range(1,T):
S = self.Gen_Poisson_Data(noiseLevel=noiseLevel)
B = np.random.binomial(X[i-1,:].astype('int32'),alpha)
X[i,:] = B.astype('int32')+S.astype('int32')
self.XY = X
self.T = T
def Gen_Stochastic_Poisson_Armillotta(self,Lambda_0=1,Betas=np.array([0.2,0.3,0.2])):
"""Stochastic Poisson process which is generally known as
an INteger AutoRegressive (INAR) Process from the paper
on Network INAR or in this case PNAR... The name of the paper is:
Poisson network autoregression
and it is written by Armillotta and Fokianos"""
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
if len(Betas)!=3:
raise ValueError("The Armillotta version of Stochastic Poisson only currently allows for exactly 3 beta values, and thus only allows Tau = 1...")
beta_0, beta_1, beta_2 = Betas
A = self.NetworkAdjacency
self.Armillotta_Poisson_Betas= Betas
self.Armillotta_Poisson_Lambda_0 = Lambda_0
Y_init = np.random.poisson(Lambda_0,(self.n,1))
#To ensure we don't get NaN's do below steps
D = np.sum(A,axis=1)
D[np.where(D==0)]=1
C = A/D
lam_0 = beta_0 + (beta_1*np.dot(C,Y_init)).T + beta_2*Y_init.T
X = np.zeros((self.T,self.n))
X[0,:] = np.random.poisson(lam_0)
for i in range(1,self.T):
lam_t = beta_0 + (beta_1*np.dot(C,X[i-1,:])) + beta_2*X[i-1,:]
X[i,:] = np.random.poisson(lam_t)
self.XY = X
def Gen_Stochastic_StudentT(self, nu=5):
"""
Generate a network-coupled multivariate Student-t VAR(1) process:
X_t = A X_{t-1} + eps_t
where eps_t ~ multivariate Student-t(df=nu, scale=Epsilon^2 I).
This mirrors Gen_Stochastic_Gaussian but with heavy-tailed noise.
"""
if self.NetworkAdjacency is None:
raise ValueError("Missing adjacency matrix, please add this using set_NetworkAdjacency")
if self.Rho is None:
raise ValueError("Missing Rho, please set it using set_Rho")
# Store degrees of freedom
self.StudentT_nu = nu
# Build stable adjacency matrix A
R = 2 * (np.random.rand(self.n, self.n) - 0.5)
A = np.array(self.NetworkAdjacency) * R
A = A / np.max(np.abs(np.linalg.eigvals(A)))
A = A * self.Rho
self.StudentT_Adjacency = A
# Initialize output
XY = np.zeros((self.T, self.n))
# Initial state: Student-t noise
w0 = np.random.chisquare(nu)
z0 = np.random.randn(self.n)
XY[0, :] = z0 / np.sqrt(w0 / nu)
# Iterate dynamics
for t in range(1, self.T):
# Gaussian part
z = np.random.randn(self.n)
# Chi-square scaling
w = np.random.chisquare(nu)
# Student-t noise
eps = z / np.sqrt(w / nu)
# VAR(1) update
XY[t, :] = A @ XY[t-1, :] + eps
self.XY = XY
def Compute_CMI_Gaussian_Fast(self,X):
"""An implementation of the Gaussian conditional mutual information from
the paper by Sun, Taylor and Bollt entitled:
Causal network inference by optimal causation entropy"""
#print(self.Xshuffle)
#if self.Xshuffle:
# return self.Compute_CMI_Gaussian(X)
#else:
TupleX = X.shape
TupleY = self.Y.shape
#Fix this in a moment
if not self.Xshuffle:
self.XYInd = np.hstack((self.indX,self.indY))
else:
self.XYInd = np.hstack((self.shuffX,self.shuffY))
if len(TupleX)==1:
SX = [[1]]
else:
if TupleX[1] == 1:
SX = [[1]]
else:
if not self.Xshuffle:
SX = self.bigCorr[self.indX,:]
SX = SX[:,self.indX]
else:
SX = self.shuffCorr[self.shuffX,:]
SX = SX[:,self.shuffX]
if len(TupleY) ==1:
SY = [[1]]
else:
if TupleY[1] == 1:
SY = [[1]]
else:
if not self.Xshuffle:
SY = self.bigCorr[self.indY,:]
SY = SY[:,self.indY]
else:
SY = self.shuffCorr[self.shuffY,:]
SY = SY[:,self.shuffY]
SX = np.linalg.det(SX)
SY = np.linalg.det(SY)
if self.Z is None:
if not self.Xshuffle:
XY = self.bigCorr[self.XYInd,:]
else:
XY = self.shuffCorr[self.XYInd,:]
XY = XY[:,self.XYInd]
#print(XY)
SXY = np.linalg.det(XY)
return 0.5*np.log((SX*SY)/SXY)
else:
if not self.Xshuffle:
self.bigInd = np.hstack((self.indX,self.indY,self.indZ))
self.XZInd = np.hstack((self.indX,self.indZ))
else:
#print("This is self.Z: ", self.Z)
self.bigInd = np.hstack((self.shuffX,self.shuffY,self.shuffZ))
self.XZInd = np.hstack((self.shuffX,self.shuffZ))
TupleZ = self.Z.shape
if len(TupleZ)==1:
SZ = [[1]]
else:
if TupleZ[1]==1:
SZ = [[1]]
else:
if not self.Xshuffle:
SZ = self.bigCorr[self.indZ,:]
SZ = SZ[:,self.indZ]
else:
SZ = self.shuffCorr[self.shuffZ,:]
SZ = SZ[:,self.shuffZ]
SZ = np.linalg.det(SZ)
if not self.Xshuffle:
self.YZInd = np.hstack((self.indY,self.indZ))
self.XYZInd = np.hstack((self.indX,self.indY,self.indZ))
XZ = self.bigCorr[self.XZInd,:]
XZ = XZ[:,self.XZInd]
#print(XZ)
YZ = self.bigCorr[self.YZInd,:]
YZ = YZ[:,self.YZInd]
XYZ = self.bigCorr[self.XYZInd,:]
XYZ = XYZ[:,self.XYZInd]
else:
#print("This is self.Z: ", self.Z)
self.YZInd = np.hstack((self.shuffY,self.shuffZ))
self.XYZInd = np.hstack((self.shuffX,self.shuffY,self.shuffZ))
XZ = self.shuffCorr[self.XZInd,:]
XZ = XZ[:,self.XZInd]
#print(XZ)
YZ = self.shuffCorr[self.YZInd,:]
YZ = YZ[:,self.YZInd]
XYZ = self.shuffCorr[self.XYZInd,:]
XYZ = XYZ[:,self.XYZInd]
SXZ = np.linalg.det(XZ)
SYZ = np.linalg.det(YZ)
SXYZ = np.linalg.det(XYZ)
return 0.5*np.log((SXZ*SYZ)/(SZ*SXYZ))
def Compute_CMI_Gaussian(self,X):
"""An implementation of the Gaussian conditional mutual information from
the paper by Sun, Taylor and Bollt entitled:
Causal network inference by optimal causation entropy"""
TupleX = X.shape
TupleY = self.Y.shape
if len(TupleX)==1:
SX = [[1]]
else:
if TupleX[1] == 1:
SX = [[1]]
else:
SX = np.corrcoef(X.T)
if len(TupleY) ==1:
SY = [[1]]
else:
if TupleY[1] == 1:
SY = [[1]]
else:
SY = np.corrcoef(self.Y.T)
if self.Z is None:
SX = sp.linalg.det(SX)
SY = sp.linalg.det(SY)
#SXY = np.linalg.det(np.corrcoef(X.T,self.Y.T))
SXY = sp.linalg.det(np.corrcoef(X.T,self.Y.T))
return 0.5*np.log((SX*SY)/SXY)
else:
TupleZ = self.Z.shape
if len(TupleZ)==1:
SZ = [[1]]
else:
if TupleZ[1]==1:
SZ = [[1]]
else:
SZ = np.corrcoef(self.Z.T)
#SZ = np.linalg.det(SZ)
SZ = sp.linalg.det(SZ)
#T1 = time.time()
XZ = np.concatenate((X,self.Z),axis=1)
YZ = np.concatenate((self.Y,self.Z),axis=1)
XYZ = np.concatenate((X,self.Y,self.Z),axis=1)
#T2 = time.time()-T1
#print("This is concatenation time: ", T2)
#SXZ = np.linalg.det(np.corrcoef(XZ.T))
#SYZ = np.linalg.det(np.corrcoef(YZ.T))
#SXYZ = np.linalg.det(np.corrcoef(XYZ.T))
SXZ = sp.linalg.det(np.corrcoef(XZ.T))
SYZ = sp.linalg.det(np.corrcoef(YZ.T))
SXYZ = sp.linalg.det(np.corrcoef(XYZ.T))
Value = 0.5*np.log((SXZ*SYZ)/(SZ*SXYZ))
return Value
def Compute_CMI_Hawkes(self,X):
Blah = 1
def Compute_CMI_VonMises(self,X):
Blah = 1
def Compute_CMI_Laplace(self,X):
Blah = 1
def Compute_CMI_Histogram(self,X):
Blah = 1
def Compute_Entropy_KernelDensity(self,X):
if self.KernelBandWidth is None:
#This is approximately the optimal bandwidth according to Silverman