├── calc_f_stat.py
├── normalize_0_mean_1_std.py
├── brier_loss.py
├── recovery_performance_mod.py
├── multivariate_split.py
├── run_all
├── cao_min_embedding_dimension.py
├── utils_mod.py
├── causal_ccm.py
├── README.md
├── make_all_multi_plots.py
├── LICENSE
└── run_all_models.py
/calc_f_stat.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Input: RSS_R,RSS_U,n,pu,pr
5 | Output: f_GC as values of f-statistic
6 |
7 | - "RSS_R" and unrestricted "RSS_U" models.
8 | - "pu" and "pr" are the number of parameters to be estimated for the unrestricted and restricted model, respectively.
9 | - "n" is the number of time-delayed vectors.
10 |
11 | @Reference:
12 | Wismüller, A., Dsouza, A.M., Vosoughi, M.A., and Abidin, Anas.
13 | Large-scale nonlinear Granger causality for inferring directed dependence from short multivariate time-series data. Sci Rep 11, 7817 (2021).
14 |
15 | """
16 |
17 |
18 |
19 | def calc_f_stat(RSS_R,RSS_U,n,pu,pr):
20 | f_GC = ((RSS_R-RSS_U)/(RSS_U))*((n-pu-1)/(pu-pr));
21 | return f_GC
22 |
--------------------------------------------------------------------------------
/normalize_0_mean_1_std.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 |
5 |
6 | @Reference:
7 | Wismüller, A., Dsouza, A.M., Vosoughi, M.A. et al.
8 | Large-scale nonlinear Granger causality for inferring directed dependence from short multivariate time-series data. Sci Rep 11, 7817 (2021).
9 | """
10 | import numpy as np
11 |
12 | def normalize_0_mean_1_std(inp_series):
13 | inp_series=inp_series.copy()
14 | mean_ts=np.array([inp_series.mean(axis=1)]).transpose()
15 | mean_ts_mtrx = mean_ts*np.ones((1,inp_series.shape[1]));
16 | unb_data_mtrx = inp_series - mean_ts_mtrx
17 | p = np.power(unb_data_mtrx,2)
18 | s=np.array([p.sum(axis=1)]).transpose()
19 | sc=np.sqrt(s/p.shape[1])
20 | sc2=sc*(np.ones((1,p.shape[1])))
21 | nrm= np.divide(unb_data_mtrx,sc2)
22 | return nrm
23 |
--------------------------------------------------------------------------------
/brier_loss.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from sklearn import metrics
3 | from copy import deepcopy
4 |
5 |
6 | def brier_loss_func(proba, label):
7 | proba = proba.copy()
8 | label = label.copy()
9 | N = len(proba)
10 | brier_all = np.zeros((N), dtype=np.float32)
11 | for i in range(N):
12 | label_matrix = deepcopy(label[i]).astype(np.float32)
13 | np.fill_diagonal(label_matrix, np.nan)
14 | label_matrix = label_matrix.flatten()
15 | label_matrix = label_matrix[~np.isnan(label_matrix)]
16 | label_matrix = label_matrix.astype(int)
17 | proba_matrix = deepcopy(proba[i])
18 | proba_matrix = np.round(proba_matrix, 16)
19 | proba_matrix = proba_matrix.astype(np.float32)
20 | np.fill_diagonal(proba_matrix, np.nan)
21 | proba_matrix = proba_matrix.flatten()
22 | proba_matrix = proba_matrix[~np.isnan(proba_matrix)]
23 | proba_matrix = np.clip(proba_matrix, a_min=0, a_max=1)
24 | brier_all[i] = metrics.brier_score_loss(label_matrix, proba_matrix, pos_label=0)
25 | return brier_all
26 |
--------------------------------------------------------------------------------
/recovery_performance_mod.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | The code returns performance measures (in terms of AUROC) given a list of
5 | "Adjs": data matrices and
6 | "label": label matrices.
7 |
8 | @Reference:
9 |
10 | Originally created by:
11 | Wismüller, A., Dsouza, A.M., Vosoughi, M.A. et al.
12 | Large-scale nonlinear Granger causality for inferring directed dependence from short multivariate time-series data. Sci Rep 11, 7817 (2021).
13 |
14 | Modified by Wojciech (Victor) Fulmyk to account for the diagonal which is always labelled correctly.
15 | """
16 | import numpy as np
17 | from sklearn import metrics
18 | from copy import deepcopy
19 |
20 |
21 | def recovery_performance(Adjs,label):
22 | Adjs=Adjs.copy()
23 | label=label.copy()
24 | N=len(Adjs)
25 | auc_all = np.zeros((N), dtype=np.float32)
26 | for i in range(N):
27 | label_matrix = deepcopy(label[i]).astype(float)
28 | np.fill_diagonal(label_matrix, np.nan)
29 | label_matrix = label_matrix.flatten()
30 | label_matrix = label_matrix[~np.isnan(label_matrix)]
31 | Adj_matrix = deepcopy(Adjs[i]).astype(float)
32 | np.fill_diagonal(Adj_matrix, np.nan)
33 | Adj_matrix = Adj_matrix.flatten()
34 | Adj_matrix = Adj_matrix[~np.isnan(Adj_matrix)]
35 | auc_all[i] = metrics.roc_auc_score(label_matrix, Adj_matrix)
36 | return auc_all
37 |
38 |
--------------------------------------------------------------------------------
/multivariate_split.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | The function separates input time-series data into pieces of data, based on Taken's theorem to represent system dynamics within the state-space.
5 |
6 | @Reference:
7 | Wismüller, A., Dsouza, A.M., Vosoughi, M.A. et al.
8 | Large-scale nonlinear Granger causality for inferring directed dependence from short multivariate time-series data. Sci Rep 11, 7817 (2021).
9 | """
10 | import torch
11 | import numpy as np
12 |
13 |
14 | def multivariate_split(X,ar_order, valid_percent=0):
15 | X=X.copy()
16 | TS=np.shape(X)[1]
17 | n_vars=np.shape(X)[0]
18 | val_num=int(valid_percent*TS)
19 | my_data_train=torch.zeros((TS-ar_order-val_num,ar_order,n_vars))
20 | my_data_y_train=torch.zeros((TS-ar_order-val_num,1,n_vars))
21 | my_data_val=torch.zeros((val_num,ar_order,n_vars))
22 | my_data_y_val=torch.zeros((val_num,1,n_vars))
23 | for i in range(TS-ar_order-val_num):
24 | my_data_train[i]=torch.from_numpy(X.transpose()[i:i+ar_order,:])
25 | my_data_y_train[i]=torch.from_numpy(X.transpose()[i+ar_order,:])
26 |
27 | for i in range(TS-ar_order-val_num, TS-ar_order,1):
28 | my_data_val[i-(TS-ar_order-val_num)]=torch.from_numpy(X.transpose()[i:i+ar_order,:])
29 | my_data_y_val[i-(TS-ar_order-val_num)]=torch.from_numpy(X.transpose()[i+ar_order,:])
30 | return my_data_train, my_data_y_train, my_data_val, my_data_y_val
31 |
--------------------------------------------------------------------------------
/run_all:
--------------------------------------------------------------------------------
1 | python run_all_models.py '5_linear' '500' '100'
2 | python run_all_models.py '5_linear' '1000' '200'
3 | python run_all_models.py '5_linear' '1500' '300'
4 | python run_all_models.py '5_linear' '2000' '400'
5 |
6 | python run_all_models.py '5_nonlinear' '500' '500'
7 | python run_all_models.py '5_nonlinear' '1000' '600'
8 | python run_all_models.py '5_nonlinear' '1500' '700'
9 | python run_all_models.py '5_nonlinear' '2000' '800'
10 |
11 | python run_all_models.py '7_nonlinear' '500' '900'
12 | python run_all_models.py '7_nonlinear' '1000' '1000'
13 | python run_all_models.py '7_nonlinear' '1500' '1100'
14 | python run_all_models.py '7_nonlinear' '2000' '1200'
15 |
16 | python run_all_models.py '9_nonlinear' '500' '1300'
17 | python run_all_models.py '9_nonlinear' '1000' '1400'
18 | python run_all_models.py '9_nonlinear' '1500' '1500'
19 | python run_all_models.py '9_nonlinear' '2000' '1600'
20 |
21 | python run_all_models.py '11_nonlinear' '500' '1700'
22 | python run_all_models.py '11_nonlinear' '1000' '1800'
23 | python run_all_models.py '11_nonlinear' '1500' '1900'
24 | python run_all_models.py '11_nonlinear' '2000' '2000'
25 |
26 | python run_all_models.py '34_zachary1' '500' '2100'
27 | python run_all_models.py '34_zachary1' '1000' '2200'
28 | python run_all_models.py '34_zachary1' '1500' '2300'
29 | python run_all_models.py '34_zachary1' '2000' '2400'
30 |
31 | python run_all_models.py '34_zachary2' '500' '2500'
32 | python run_all_models.py '34_zachary2' '1000' '2600'
33 | python run_all_models.py '34_zachary2' '1500' '2700'
34 | python run_all_models.py '34_zachary2' '2000' '2800'
35 |
36 |
37 | python make_all_multi_plots.py 'auc'
38 | python make_all_multi_plots.py 'brier'
39 | python make_all_multi_plots.py 'accuracy'
40 | python make_all_multi_plots.py 'balanced_accuracy'
41 | python make_all_multi_plots.py 'f1wgt'
42 | python make_all_multi_plots.py 'sensitivity'
43 | python make_all_multi_plots.py 'specificity'
44 | python make_all_multi_plots.py 'gmean'
45 | python make_all_multi_plots.py 'accuracy2'
46 | python make_all_multi_plots.py 'balanced_accuracy2'
47 | python make_all_multi_plots.py 'f1wgt2'
48 | python make_all_multi_plots.py 'sensitivity2'
49 | python make_all_multi_plots.py 'specificity2'
50 | python make_all_multi_plots.py 'gmean2'
51 |
--------------------------------------------------------------------------------
/cao_min_embedding_dimension.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import numba
3 |
4 |
5 | # Liangyue Cao's method for finding the minimum embedding dimension
6 | # https://doi.org/10.1016/S0167-2789(97)00118-8
7 | # Python implementation by Wojciech Fulmyk, 2023
8 | # Returns d (a list of embedding dimensions), E1, and E2
9 | @numba.jit(nopython=True)
10 | def cao_min_embedding_dimension(
11 | x, maxd=10, tau=1, threshold=0.95, max_relative_change=0.1
12 | ):
13 | if maxd < 3:
14 | raise ValueError("maxd must be greater than or equal to 3")
15 | v = np.zeros(maxd)
16 | a = np.zeros(maxd)
17 | ya = np.zeros(maxd)
18 | E1 = np.zeros(maxd - 1)
19 | E2 = np.zeros(maxd - 1)
20 | ndp = x.flatten().shape[0]
21 | for d in range(1, maxd + 1):
22 | a[d - 1] = 0.0
23 | ya[d - 1] = 0.0
24 | ng = ndp - d * tau
25 | for i in range(ng):
26 | v0 = 1.0e30
27 | for j in range(ng):
28 | if j == i:
29 | continue
30 | for k in range(d):
31 | v[k] = abs(x[i + k * tau] - x[j + k * tau])
32 | if d != 1:
33 | for k in range(d - 1):
34 | v[k + 1] = max(v[k], v[k + 1])
35 | vij = v[d - 1]
36 | if vij < v0 and vij != 0.0:
37 | n0 = j
38 | v0 = vij
39 | a[d - 1] += max(v0, abs(x[i + d * tau] - x[n0 + d * tau])) / v0
40 | ya[d - 1] += abs(x[i + d * tau] - x[n0 + d * tau])
41 | a[d - 1] /= float(ng)
42 | ya[d - 1] /= float(ng)
43 | if d >= 2:
44 | E1[d - 2] = a[d - 1] / a[d - 2]
45 | E2[d - 2] = ya[d - 1] / ya[d - 2]
46 | d = np.array(list(range(1, maxd)))
47 | embedding_dim = np.nan
48 | for dimension in range(3, maxd + 1):
49 | relative_error = abs(E1[dimension - 2] - E1[dimension - 3]) / E1[dimension - 3]
50 | if (
51 | np.isnan(embedding_dim)
52 | and not np.isnan(E1[dimension - 2])
53 | and E1[dimension - 2] >= threshold
54 | and relative_error < max_relative_change
55 | ):
56 | embedding_dim = dimension - 2
57 | break
58 | return d, E1, E2, embedding_dim
59 |
60 |
61 | # Confirm implementation works by reconstructing Fig 1
62 | # from Cao's paper, which plots E1 and E2 for the
63 | # Hénon attractor
64 | # Note that some small discrepancies in Fig 1 of
65 | # Cao's paper and the implementation here are normal
66 | # because the points used here may not be the
67 | # exact same ones used by Cao. Nonetheless,
68 | # the conclusion is the same: the minimum
69 | # embedding dimension is 2 and the figures
70 | # are very similar, which confirms that the
71 | # python implementation is valid.
72 | def cao_plot_henon():
73 | import matplotlib.pyplot as plt
74 |
75 | def henon_map(xn, yn, a, b):
76 | return yn + 1 - (a * xn**2), b * xn
77 |
78 | xt = []
79 | # Initial x and y for henon_map
80 | x = 0
81 | y = 0
82 | for i in range(10000):
83 | xn, yn = henon_map(x, y, 1.4, 0.3)
84 | xt.append(x)
85 | x, y = xn, yn
86 | xt_10t = np.array(xt)
87 | xt_1t = xt_10t[-1000:]
88 | result_1t = cao_min_embedding_dimension(xt_1t, maxd=10, tau=1)
89 | result_10t = cao_min_embedding_dimension(xt_10t, maxd=10, tau=1)
90 | plt.plot(result_1t[0], result_1t[1], "D-", color="green", label="E1-1T")
91 | plt.plot(result_10t[0], result_10t[1], "+:", color="red", label="E1-10T")
92 | plt.plot(result_1t[0], result_1t[2], "s--", color="blue", label="E2-1T")
93 | plt.plot(result_10t[0], result_10t[2], "x-.", color="black", label="E2-10T")
94 | plt.legend(loc="lower left")
95 | print("result_1t embedding dimension: " + str(result_1t[3]))
96 | print("result_10t embedding dimension: " + str(result_10t[3]))
97 | plt.show(block=False)
98 | plt.pause(0.001)
99 |
--------------------------------------------------------------------------------
/utils_mod.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from scipy import stats, io, signal, linalg
3 | import matplotlib.pyplot as plt
4 | from scipy.spatial.distance import squareform, pdist
5 | from sklearn.model_selection import StratifiedShuffleSplit
6 | from sklearn.svm import SVC
7 | from sklearn import metrics
8 | from scipy.stats import f as scipyf
9 | import warnings
10 | from os.path import join
11 | import os
12 | import math
13 | from sklearn.cluster import KMeans
14 | import torch
15 | from normalize_0_mean_1_std import normalize_0_mean_1_std
16 | from calc_f_stat import calc_f_stat
17 | from multivariate_split import multivariate_split
18 |
19 | """
20 | This code includes the main functionality of the proposed method.
21 | """
22 |
23 | """
24 | The file includes the primary function which calculates Granger causality using lsNGC.
25 | """
26 |
27 | def lsNGC(inp_series, ar_order=1, k_f=3, k_g=2, normalize=1):
28 | if normalize:
29 | X_normalized=normalize_0_mean_1_std(inp_series)
30 | else:
31 | X_normalized=inp_series.copy()
32 |
33 | X_train, Y_train , X_test, Y_test=multivariate_split(X=X_normalized,ar_order=ar_order)
34 |
35 | X_train=torch.flatten(X_train, start_dim=1)
36 |
37 | km= KMeans(n_clusters= k_f, max_iter= 100, random_state=123)
38 | km.fit(X_train)
39 | cent= km.cluster_centers_
40 |
41 |
42 | max=0
43 |
44 | for i in range(k_f):
45 | for j in range(k_f):
46 | d= np.linalg.norm(cent[i]-cent[j])
47 | if(d> max):
48 | max= d
49 | d= max
50 |
51 | sigma= d/math.sqrt(2*k_f)
52 |
53 | sig_d=np.zeros((np.shape(X_normalized)[0],np.shape(X_normalized)[0]));
54 | sig=np.zeros((np.shape(X_normalized)[0],np.shape(X_normalized)[0]));
55 |
56 | # Z_train_label=Y_train
57 | for i in range(X_normalized.shape[0]):
58 | Z_temp=X_normalized.copy()
59 | Z_train, Z_train_label , _ , _=multivariate_split(X=Z_temp,ar_order=ar_order)
60 | Z_train=torch.flatten(Z_train, start_dim=1)
61 | Z_train_label=torch.flatten(Z_train_label, start_dim=1)
62 |
63 | # Obtain phase space Z_s by exclusing time series of of x_s
64 | Z_s_train, Z_s_train_label , _ , _=multivariate_split(X=np.delete(Z_temp,[i],axis=0),ar_order=ar_order)
65 | # Obtain phase space reconstruction of x_s
66 | W_s_train, W_s_train_label , _ , _=multivariate_split(X=np.array([Z_temp[i]]),ar_order=ar_order)
67 |
68 | # Flatten data
69 | Z_s_train=torch.flatten(Z_s_train, start_dim=1)
70 | Z_s_train_label=torch.flatten(Z_s_train_label, start_dim=1)
71 |
72 | W_s_train=torch.flatten(W_s_train, start_dim=1)
73 | W_s_train_label=torch.flatten(W_s_train_label, start_dim=1)
74 | # Obtain k_g number of cluster centers in the phase space W_s with k-means clustering, will have dim=(k_g * d)
75 | kmg= KMeans(n_clusters= k_g, max_iter= 100, random_state=123)
76 | kmg.fit(W_s_train)
77 | cent_W_s= kmg.cluster_centers_
78 | # Calculate activations for each of the k_g neurons
79 | shape= W_s_train.shape
80 | row= shape[0]
81 | column= k_g
82 | G= np.empty((row,column), dtype= float)
83 | maxg=0
84 |
85 | for ii in range(k_g):
86 | for jj in range(k_g):
87 | dg= np.linalg.norm(cent_W_s[ii]-cent_W_s[jj])
88 | if(dg> maxg):
89 | maxg= dg
90 | dg= maxg
91 |
92 | sigmag= dg/math.sqrt(2*k_g)
93 | if sigmag==0:
94 | sigmag=1
95 | for ii in range(row):
96 | for jj in range(column):
97 | dist= np.linalg.norm(W_s_train[ii]-cent_W_s[jj])
98 | G[ii][jj]= math.exp(-math.pow(dist,2)/math.pow(2*sigmag,2))
99 | # Generalized radial basis function
100 | g_ws=np.array([G[ii]/sum(G[ii]) for ii in range(len(G))])
101 | # Calculate activations for each of the k_f neurons
102 | shape= Z_s_train.shape
103 | row= shape[0]
104 | column= k_f
105 | F= np.empty((row,column), dtype= float)
106 | for ii in range(row):
107 | for jj in range(column):
108 | cent_temp=cent.copy()
109 | cent_temp=np.delete(cent_temp,np.arange(jj,jj+ar_order),axis=1)
110 | dist= np.linalg.norm(Z_s_train[ii]-cent_temp)
111 | F[ii][jj]= math.exp(-math.pow(dist,2)/math.pow(2*sigma,2))
112 | # Generalized radial basis function
113 | f_zs=np.array([F[ii]/sum(F[ii]) for ii in range(len(F))])
114 |
115 | # Prediction in the presence of x_s
116 | num_samples=f_zs.shape[0]
117 |
118 | f_new=np.concatenate((0.5*f_zs,0.5*g_ws),axis=1)
119 | GTG= np.dot(f_new.T,f_new)
120 | GTG_inv= np.linalg.pinv(GTG)
121 | fac= np.dot(GTG_inv,f_new.T)
122 | W_presence= np.dot(fac,Z_train_label)
123 |
124 | prediction_presence= np.dot(f_new,W_presence)
125 | error_presence=prediction_presence-np.array(Z_train_label)
126 | sig[i,:]=np.diag(np.cov(error_presence.T))
127 |
128 | # Prediction without x_s
129 | GTG= np.dot(f_zs.T,f_zs)
130 | GTG_inv= np.linalg.pinv(GTG)
131 | fac= np.dot(GTG_inv,f_zs.T)
132 | W_absence= np.dot(fac,Z_train_label)
133 |
134 | prediction_absence= np.dot(f_zs,W_absence)
135 | error_absence=prediction_absence-np.array(Z_train_label)
136 | sig_d[i,:]=np.diag(np.cov(error_absence.T))
137 | # Comupte the Granger causality index
138 |
139 | Aff=np.log(np.divide(sig_d,sig))
140 | Aff=(Aff>0)*Aff
141 | np.fill_diagonal(Aff,0)
142 | f_stat=calc_f_stat(sig_d, sig, n=num_samples+1, pu=k_f+k_g, pr=k_f)
143 | np.fill_diagonal(f_stat,0)
144 | n=num_samples+1
145 | pu=k_f+k_g
146 | pr=k_f
147 | f_dfn = pu-pr
148 | f_dfd = n-pu-1
149 | pvalue = np.empty_like(f_stat)
150 | for i in range(f_stat.shape[0]):
151 | for j in range(f_stat.shape[1]):
152 | pvalue[i,j] = scipyf.sf(f_stat[i,j], f_dfn, f_dfd)
153 |
154 | return Aff, f_stat, pvalue
155 |
--------------------------------------------------------------------------------
/causal_ccm.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | import matplotlib.pyplot as plt
4 | import seaborn as sns
5 | from scipy.spatial import distance
6 | from scipy.stats import pearsonr
7 |
8 | import itertools
9 |
10 | class ccm:
11 | """
12 | We're checking causality X -> Y
13 | Args
14 | X: timeseries for variable X that could cause Y
15 | Y: timeseries for variable Y that could be caused by X
16 | tau: time lag. default = 1
17 | E: shadow manifold embedding dimension. default = 2
18 | L: time period/duration to consider (longer = more data). default = length of X
19 | """
20 | def __init__(self, X, Y, tau=1, E=2, L=None):
21 | '''
22 | X: timeseries for variable X that could cause Y
23 | Y: timeseries for variable Y that could be caused by X
24 | tau: time lag
25 | E: shadow manifold embedding dimension
26 | L: time period/duration to consider (longer = more data)
27 | We're checking for X -> Y
28 | '''
29 | self.X = X
30 | self.Y = Y
31 | self.tau = tau
32 | self.E = E
33 | if L == None:
34 | self.L = len(X)
35 | else:
36 | self.L = L
37 | self.My = self.shadow_manifold(Y) # shadow manifold for Y (we want to know if info from X is in Y)
38 | self.t_steps, self.dists = self.get_distances(self.My) # for distances between points in manifold
39 |
40 | def shadow_manifold(self, V):
41 | """
42 | Given
43 | V: some time series vector
44 | tau: lag step
45 | E: shadow manifold embedding dimension
46 | L: max time step to consider - 1 (starts from 0)
47 | Returns
48 | {t:[t, t-tau, t-2*tau ... t-(E-1)*tau]} = Shadow attractor manifold, dictionary of vectors
49 | """
50 | V = V[:self.L] # make sure we cut at L
51 | M = {t:[] for t in range((self.E-1) * self.tau, self.L)} # shadow manifold
52 | for t in range((self.E-1) * self.tau, self.L):
53 | v_lag = [] # lagged values
54 | for t2 in range(0, self.E-1 + 1): # get lags, we add 1 to E-1 because we want to include E
55 | v_lag.append(V[t-t2*self.tau])
56 | M[t] = v_lag
57 | return M
58 |
59 | # get pairwise distances between vectors in the time series
60 | def get_distances(self, M):
61 | """
62 | Args
63 | M: The shadow manifold from the time series
64 | Returns
65 | t_steps: timesteps
66 | dists: n x n matrix showing distances of each vector at t_step (rows) from other vectors (columns)
67 | """
68 |
69 | # we extract the time indices and vectors from the manifold M
70 | # we just want to be safe and convert the dictionary to a tuple (time, vector)
71 | # to preserve the time inds when we separate them
72 | t_vec = [(k, v) for k,v in M.items()]
73 | t_steps = np.array([i[0] for i in t_vec])
74 | vecs = np.array([i[1] for i in t_vec])
75 | dists = distance.cdist(vecs, vecs)
76 | return t_steps, dists
77 |
78 | def get_nearest_distances(self, t, t_steps, dists):
79 | """
80 | Args:
81 | t: timestep of vector whose nearest neighbors we want to compute
82 | t_teps: time steps of all vectors in the manifold M, output of get_distances()
83 | dists: distance matrix showing distance of each vector (row) from other vectors (columns). output of get_distances()
84 | E: embedding dimension of shadow manifold M
85 | Returns:
86 | nearest_timesteps: array of timesteps of E+1 vectors that are nearest to vector at time t
87 | nearest_distances: array of distances corresponding to vectors closest to vector at time t
88 | """
89 | t_ind = np.where(t_steps == t) # get the index of time t
90 | dist_t = dists[t_ind].squeeze() # distances from vector at time t (this is one row)
91 |
92 | # get top closest vectors
93 | nearest_inds = np.argsort(dist_t)[1:self.E+1 + 1] # get indices sorted, we exclude 0 which is distance from itself
94 | nearest_timesteps = t_steps[nearest_inds] # index column-wise, t_steps are same column and row-wise
95 | nearest_distances = dist_t[nearest_inds]
96 |
97 | return nearest_timesteps, nearest_distances
98 |
99 | def predict(self, t):
100 | """
101 | Args
102 | t: timestep at manifold of y, My, to predict X at same time step
103 | Returns
104 | X_true: the true value of X at time t
105 | X_hat: the predicted value of X at time t using the manifold My
106 | """
107 | eps = 0.000001 # epsilon minimum distance possible
108 | t_ind = np.where(self.t_steps == t) # get the index of time t
109 | dist_t = self.dists[t_ind].squeeze() # distances from vector at time t (this is one row)
110 | nearest_timesteps, nearest_distances = self.get_nearest_distances(t, self.t_steps, self.dists)
111 |
112 | # get weights
113 | #u = np.exp(-nearest_distances/np.max([eps, nearest_distances[0]])) # we divide by the closest distance to scale
114 | # Fix FloatingPointError: underflow encountered in exp
115 | u = np.exp(np.clip( -nearest_distances/np.max([eps, nearest_distances[0]]), -500, 500 )) # we divide by the closest distance to scale
116 | w = u / np.sum(u)
117 |
118 | # get prediction of X
119 | X_true = self.X[t] # get corresponding true X
120 | X_cor = np.array(self.X)[nearest_timesteps] # get corresponding Y to cluster in Mx
121 | X_hat = (w * X_cor).sum() # get X_hat
122 |
123 | # DEBUGGING
124 | # will need to check why nearest_distances become nan
125 | # if np.isnan(X_hat):
126 | # print(nearest_timesteps)
127 | # print(nearest_distances)
128 |
129 | return X_true, X_hat
130 |
131 |
132 | def causality(self):
133 | '''
134 | Args:
135 | None
136 | Returns:
137 | (r, p): how much X causes Y. as a correlation between predicted X and true X and the p-value (significance)
138 | '''
139 |
140 | # run over all timesteps in M
141 | # X causes Y, we can predict X using My
142 | # X puts some info into Y that we can use to reverse engineer X from Y via My
143 | X_true_list = []
144 | X_hat_list = []
145 |
146 | for t in list(self.My.keys()): # for each time step in My
147 | X_true, X_hat = self.predict(t) # predict X from My
148 | X_true_list.append(X_true)
149 | X_hat_list.append(X_hat)
150 |
151 | x, y = X_true_list, X_hat_list
152 | r, p = pearsonr(x, y)
153 |
154 | return r, p
155 |
156 | def visualize_cross_mapping(self):
157 | """
158 | Visualize the shadow manifolds and some cross mappings
159 | """
160 | # we want to check cross mapping from Mx to My and My to Mx
161 |
162 | f, axs = plt.subplots(1, 2, figsize=(12, 6))
163 |
164 | for i, ax in zip((0, 1), axs): # i will be used in switching Mx and My in Cross Mapping visualization
165 | #===============================================
166 | # Shadow Manifolds Visualization
167 |
168 | X_lag, Y_lag = [], []
169 | for t in range(1, len(self.X)):
170 | X_lag.append(self.X[t-self.tau])
171 | Y_lag.append(self.Y[t-self.tau])
172 | X_t, Y_t = self.X[1:], self.Y[1:] # remove first value
173 |
174 | ax.scatter(X_t, X_lag, s=5, label='$M_x$')
175 | ax.scatter(Y_t, Y_lag, s=5, label='$M_y$', c='y')
176 |
177 | #===============================================
178 | # Cross Mapping Visualization
179 |
180 | A, B = [(self.Y, self.X), (self.X, self.Y)][i]
181 | cm_direction = ['Mx to My', 'My to Mx'][i]
182 |
183 | Ma = self.shadow_manifold(A)
184 | Mb = self.shadow_manifold(B)
185 |
186 | t_steps_A, dists_A = self.get_distances(Ma) # for distances between points in manifold
187 | t_steps_B, dists_B = self.get_distances(Mb) # for distances between points in manifold
188 |
189 | # Plot cross mapping for different time steps
190 | timesteps = list(Ma.keys())
191 | for t in np.random.choice(timesteps, size=3, replace=False):
192 | Ma_t = Ma[t]
193 | near_t_A, near_d_A = self.get_nearest_distances(t, t_steps_A, dists_A)
194 |
195 | for i in range(self.E+1):
196 | # points on Ma
197 | A_t = Ma[near_t_A[i]][0]
198 | A_lag = Ma[near_t_A[i]][1]
199 | ax.scatter(A_t, A_lag, c='b', marker='s')
200 |
201 | # corresponding points on Mb
202 | B_t = Mb[near_t_A[i]][0]
203 | B_lag = Mb[near_t_A[i]][1]
204 | ax.scatter(B_t, B_lag, c='r', marker='*', s=50)
205 |
206 | # connections
207 | ax.plot([A_t, B_t], [A_lag, B_lag], c='r', linestyle=':')
208 |
209 | ax.set_title(f'{cm_direction} cross mapping. time lag, tau = {self.tau}, E = 2')
210 | ax.legend(prop={'size': 14})
211 |
212 | ax.set_xlabel('$X_t$, $Y_t$', size=15)
213 | ax.set_ylabel('$X_{t-1}$, $Y_{t-1}$', size=15)
214 | plt.show()
215 |
216 | def plot_ccm_correls(self):
217 | """
218 | Args
219 | X: X time series
220 | Y: Y time series
221 | tau: time lag
222 | E: shadow manifold embedding dimension
223 | L: time duration
224 | Returns
225 | None. Just correlation plots between predicted X|M_y and true X
226 | """
227 | X_My_true, X_My_pred = [], []
228 | for t in range((self.E-1) * self.tau, self.L):
229 | true, pred = self.predict(t)
230 | X_My_true.append(true)
231 | X_My_pred.append(pred)
232 |
233 | # predicting X from My
234 | r, p = np.round(pearsonr(X_My_true, X_My_pred), 4)
235 |
236 | plt.scatter(X_My_true, X_My_pred, s=10)
237 | plt.xlabel('$X(t)$ (observed)', size=15)
238 | plt.ylabel('$\hat{X}(t)|M_y$ (estimated)', size=15)
239 | plt.title(f'tau={self.tau}, E={self.E}, L={self.L}, Correlation coeff = {r}')
240 |
241 | plt.show()
242 |
243 |
244 | def loop_causal_cmm(data, tau=1, E=2, L=None):
245 | results_list = []
246 | permute_list = list(itertools.permutations(range(data.shape[1]),2))
247 | for X_idx, y_idx in permute_list:
248 | ccm1 = ccm(X=data[:,X_idx], Y=data[:,y_idx], tau=tau, E=E, L=L)
249 | score, pval = ccm1.causality()
250 | results_list.append([X_idx,y_idx,score,pval])
251 | out_df = pd.DataFrame(results_list, columns=['X','y','score','pvalue'])
252 | return out_df
253 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
18 |
19 |
20 |
21 |
22 |
29 |
30 |
mlcausality-krr-paper-replication
31 |
32 |
33 | Replication code for the paper "Nonlinear Granger Causality using Kernel Ridge Regression"
34 |
35 | Report Bug
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | Table of Contents
44 |
45 | -
46 | About The Project
47 |
48 | -
49 | Getting Started
50 |
55 |
56 | - File Descriptions
57 |
63 |
64 |
65 |
72 |
73 |
74 | ## About The Project
75 |
76 |
77 |
78 | This repository stores replication code for the paper "Nonlinear Granger Causality using Kernel Ridge Regression" that introduces and highlights the use of the mlcausality package.
79 |
80 | The replication files contained herein use functions from the following projects:
81 |
82 | - spectral-connectivity
83 |
84 | - Denovellis, E., Myroshnychenko, M., Sarmashghi, M., & Stephen, E. (2022). Eden-Kramer-Lab/spectral_connectivity (Version v1.1.0) [Computer software]. https://doi.org/10.5281/zenodo.1011052
85 |
86 | - lsNGC
87 |
88 | - Wismüller, A., Dsouza, A.M., Vosoughi, M.A. et al. Large-scale nonlinear Granger causality for inferring directed dependence from short multivariate time-series data. Sci Rep 11, 7817 (2021). https://doi.org/10.1038/s41598-021-87316-6
89 | - The public access to the paper is available here: https://www.nature.com/articles/s41598-021-87316-6
90 |
91 | - causal_ccm
92 |
93 | - Javier, P. J. E. (2021). causal-ccm a Python implementation of Convergent Cross Mapping (0.3.3) [Computer software].
94 |
95 |
96 |
97 |
98 | (back to top)
99 |
100 |
101 | ## Getting Started
102 | ### Prerequisites
103 |
104 | Replication requires the installation of the following Python libraries:
105 | * [NumPy](https://numpy.org)
106 | * [SciPy](https://scipy.org)
107 | * [pandas](https://pandas.pydata.org)
108 | * [statsmodels](https://www.statsmodels.org)
109 | * [scikit-learn](https://scikit-learn.org)
110 | * [tqdm](https://github.com/tqdm/tqdm)
111 | * [matplotlib](https://matplotlib.org/)
112 | * [networkx](https://networkx.org/)
113 | * [psutil](https://github.com/giampaolo/psutil)
114 | * [tigramite](https://github.com/jakobrunge/tigramite)
115 | * [mlcausality](https://github.com/WojtekFulmyk/mlcausality)
116 |
117 | Please install these libraries into your Python system before proceeding.
118 |
119 | ### Downloading the Replication Files
120 |
121 | In order to replicate the results of the paper, you must download all of the files in this repository onto your local computer. You can do so, for instance, using the following command:
122 |
123 | git clone --depth 1 https://github.com/WojtekFulmyk/mlcausality-krr-paper-replication.git
124 |
125 | ### Replicate results
126 |
127 | You can replicate results by running all the codes in the `run_all` file on a terminal on your local machine.
128 |
129 | (back to top)
130 |
131 |
132 |
133 |
134 | ## File Descriptions
135 |
136 | ### Files from the lsNGC project
137 | The following repository files are taken from the lsNGC project. Note that these files were forked from the originals in order to perform some modifications. In particular, the `utils_mod.py` was modified to calculate p-values, and the `recovery_performance_mod.py` file was modified to ignore the diagonal of the adjacency matrix.
138 |
139 | * `utils_mod.py`
140 | * `recovery_performance_mod.py`
141 | * `normalize_0_mean_1_std.py`
142 | * `multivariate_split.py`
143 | * `calc_f_stat.py`
144 |
145 | ### Files from the causal_ccm project
146 | The following file was taken and modified from the causal_ccm project. In particular, an error involving underflow in exp was fixed.
147 |
148 | * `causal_cmm.py`
149 |
150 | ### Files written by myself with the help of some code from the spectral-connectivity library
151 | The following files were largely written by myself (Wojciech "Victor" Fulmyk) with the help of some code from the spectral-connectivity project. In particular, spectral-connectivity was used to generate the 5_linear network; see the `run_all_models.py` file for details. The relevant functions from the spectral-connectivity package were forked herein as opposed to using the original package in order to ensure that the seed was set correctly for replication.
152 |
153 | * `run_all_models.py`
154 | * `make_all_multi_plots.py`
155 | * `cao_min_embedding_dimension.py`
156 | * `brier_loss.py`
157 | * `run_all`
158 | * `Readme.md` (this file)
159 |
160 |
161 | ## License
162 |
163 | Distributed under the GPLv3 License because the spectral-connectivity library, whose functions are used in this repository, are also released under GPLv3. See [LICENSE](https://github.com/WojtekFulmyk/mlcausality-krr-paper-replication/blob/master/LICENSE) for more information.
164 |
165 | (back to top)
166 |
167 |
168 |
169 |
170 |
179 |
180 |
181 |
182 |
191 |
192 |
193 |
194 |
195 | [contributors-shield]: https://img.shields.io/github/contributors/WojtekFulmyk/mlcausality.svg?style=for-the-badge
196 | [contributors-url]: https://github.com/WojtekFulmyk/mlcausality/graphs/contributors
197 | [forks-shield]: https://img.shields.io/github/forks/WojtekFulmyk/mlcausality.svg?style=for-the-badge
198 | [forks-url]: https://github.com/WojtekFulmyk/mlcausality/network/members
199 | [stars-shield]: https://img.shields.io/github/stars/WojtekFulmyk/mlcausality.svg?style=for-the-badge
200 | [stars-url]: https://github.com/WojtekFulmyk/mlcausality/stargazers
201 | [issues-shield]: https://img.shields.io/github/issues/WojtekFulmyk/mlcausality.svg?style=for-the-badge
202 | [issues-url]: https://github.com/WojtekFulmyk/mlcausality/issues
203 | [license-shield]: https://img.shields.io/github/license/WojtekFulmyk/mlcausality.svg?style=for-the-badge
204 | [license-url]: https://github.com/WojtekFulmyk/mlcausality/blob/master/LICENSE
205 | [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
206 | [linkedin-url]: https://linkedin.com/in/linkedin_username
207 | [product-screenshot]: images/screenshot.png
208 | [Next.js]: https://img.shields.io/badge/next.js-000000?style=for-the-badge&logo=nextdotjs&logoColor=white
209 | [Next-url]: https://nextjs.org/
210 | [React.js]: https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB
211 | [React-url]: https://reactjs.org/
212 | [Vue.js]: https://img.shields.io/badge/Vue.js-35495E?style=for-the-badge&logo=vuedotjs&logoColor=4FC08D
213 | [Vue-url]: https://vuejs.org/
214 | [Angular.io]: https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white
215 | [Angular-url]: https://angular.io/
216 | [Svelte.dev]: https://img.shields.io/badge/Svelte-4A4A55?style=for-the-badge&logo=svelte&logoColor=FF3E00
217 | [Svelte-url]: https://svelte.dev/
218 | [Laravel.com]: https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white
219 | [Laravel-url]: https://laravel.com
220 | [Bootstrap.com]: https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white
221 | [Bootstrap-url]: https://getbootstrap.com
222 | [JQuery.com]: https://img.shields.io/badge/jQuery-0769AD?style=for-the-badge&logo=jquery&logoColor=white
223 | [JQuery-url]: https://jquery.com
224 |
225 | [NumPy-url]: https://numpy.org
226 | [SciPy-url]: https://scipy.org
227 | [pandas-url]: https://pandas.pydata.org
228 | [statsmodels-url]: https://www.statsmodels.org
229 | [scikit-learn-url]: https://scikit-learn.org
230 | [XGBoost-url]: https://xgboost.readthedocs.io
231 | [LightGBM-url]: https://lightgbm.readthedocs.io
232 | [CatBoost-url]: https://catboost.ai
233 | [cuML-url]: https://github.com/rapidsai/cuml
234 |
235 |
236 | [NumPy-sheild]: https://img.shields.io/badge/numpy-%23013243.svg?style=for-the-badge&logo=numpy&logoColor=white
237 | [SciPy-sheild]: https://img.shields.io/badge/SciPy-%230C55A5.svg?style=for-the-badge&logo=scipy&logoColor=%white
238 | [Pandas-sheild]: https://img.shields.io/badge/pandas-%23150458.svg?style=for-the-badge&logo=pandas&logoColor=white
239 | [scikit-learn-shield]: https://img.shields.io/badge/scikit--learn-%23F7931E.svg?style=for-the-badge&logo=scikit-learn&logoColor=white
240 |
241 |
--------------------------------------------------------------------------------
/make_all_multi_plots.py:
--------------------------------------------------------------------------------
1 | # Get plot type to make
2 | import sys
3 |
4 | plot_type = sys.argv[1]
5 | if plot_type.lower() == "brier":
6 | plot_type_cap = "Brier Score"
7 | elif plot_type.lower() == "auc":
8 | plot_type_cap = "AUC"
9 | elif plot_type.lower() == "accuracy":
10 | plot_type_cap = "Accuracy (thresh = 0.05)"
11 | elif plot_type.lower() == "balanced_accuracy":
12 | plot_type_cap = "Bal.Accuracy (thresh = 0.05)"
13 | elif plot_type.lower() == "f1wgt":
14 | plot_type_cap = "Weighted F1 (thresh = 0.05)"
15 | elif plot_type.lower() == "sensitivity":
16 | plot_type_cap = "Sensitivity (thresh = 0.05)"
17 | elif plot_type.lower() == "specificity":
18 | plot_type_cap = "Specificity (thresh = 0.05)"
19 | elif plot_type.lower() == "gmean":
20 | plot_type_cap = "G-mean (thresh = 0.05)"
21 | elif plot_type.lower() == "accuracy2":
22 | plot_type_cap = "Accuracy (max G-mean thresh)"
23 | elif plot_type.lower() == "balanced_accuracy2":
24 | plot_type_cap = "Bal. Accuracy (max G-mean thresh)"
25 | elif plot_type.lower() == "f1wgt2":
26 | plot_type_cap = "Weighted F1 (max G-mean thresh)"
27 | elif plot_type.lower() == "sensitivity2":
28 | plot_type_cap = "Sensitivity (max G-mean thresh)"
29 | elif plot_type.lower() == "specificity2":
30 | plot_type_cap = "Specificity (max G-mean thresh)"
31 | elif plot_type.lower() == "gmean2":
32 | plot_type_cap = "G-mean (max G-mean thresh)"
33 |
34 | import numpy as np
35 | import pandas as pd
36 | import matplotlib.pyplot as plt
37 | import matplotlib.ticker as ticker
38 | import seaborn as sns
39 | import pickle
40 |
41 | from copy import deepcopy
42 | from decimal import Decimal, localcontext, ROUND_DOWN
43 |
44 |
45 | # This truncate function is based on:
46 | # https://stackoverflow.com/a/28323804
47 | def truncate(number, places):
48 | if not isinstance(places, int):
49 | raise ValueError("Decimal places must be an integer.")
50 | if places < 1:
51 | raise ValueError("Decimal places must be at least 1.")
52 | # If you want to truncate to 0 decimal places, just do int(number).
53 | with localcontext() as context:
54 | context.rounding = ROUND_DOWN
55 | exponent = Decimal(str(10**-places))
56 | return Decimal(str(number)).quantize(exponent)
57 |
58 |
59 | with open(r"pickled_data/5_linear_" + plot_type + "_500.pickle", "rb") as input_file:
60 | df_init1 = pickle.load(input_file)
61 |
62 | df_init1["Length of time-series"] = 500
63 |
64 |
65 | with open(r"pickled_data/5_linear_" + plot_type + "_1000.pickle", "rb") as input_file:
66 | df_init2 = pickle.load(input_file)
67 |
68 | df_init2["Length of time-series"] = 1000
69 |
70 | with open(r"pickled_data/5_linear_" + plot_type + "_1500.pickle", "rb") as input_file:
71 | df_init3 = pickle.load(input_file)
72 |
73 | df_init3["Length of time-series"] = 1500
74 |
75 | with open(r"pickled_data/5_linear_" + plot_type + "_2000.pickle", "rb") as input_file:
76 | df_init4 = pickle.load(input_file)
77 |
78 | df_init4["Length of time-series"] = 2000
79 | df1 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
80 | df1 = df1.melt("Length of time-series", var_name="Model", value_name="Val")
81 |
82 | with open(r"pickled_data/5_nonlinear_" + plot_type + "_500.pickle", "rb") as input_file:
83 | df_init1 = pickle.load(input_file)
84 |
85 | df_init1["Length of time-series"] = 500
86 |
87 |
88 | with open(
89 | r"pickled_data/5_nonlinear_" + plot_type + "_1000.pickle", "rb"
90 | ) as input_file:
91 | df_init2 = pickle.load(input_file)
92 |
93 | df_init2["Length of time-series"] = 1000
94 |
95 | with open(
96 | r"pickled_data/5_nonlinear_" + plot_type + "_1500.pickle", "rb"
97 | ) as input_file:
98 | df_init3 = pickle.load(input_file)
99 |
100 | df_init3["Length of time-series"] = 1500
101 |
102 | with open(
103 | r"pickled_data/5_nonlinear_" + plot_type + "_2000.pickle", "rb"
104 | ) as input_file:
105 | df_init4 = pickle.load(input_file)
106 |
107 | df_init4["Length of time-series"] = 2000
108 | df2 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
109 | df2 = df2.melt("Length of time-series", var_name="Model", value_name="Val")
110 |
111 | with open(r"pickled_data/7_nonlinear_" + plot_type + "_500.pickle", "rb") as input_file:
112 | df_init1 = pickle.load(input_file)
113 |
114 | df_init1["Length of time-series"] = 500
115 |
116 |
117 | with open(
118 | r"pickled_data/7_nonlinear_" + plot_type + "_1000.pickle", "rb"
119 | ) as input_file:
120 | df_init2 = pickle.load(input_file)
121 |
122 | df_init2["Length of time-series"] = 1000
123 |
124 | with open(
125 | r"pickled_data/7_nonlinear_" + plot_type + "_1500.pickle", "rb"
126 | ) as input_file:
127 | df_init3 = pickle.load(input_file)
128 |
129 | df_init3["Length of time-series"] = 1500
130 |
131 | with open(
132 | r"pickled_data/7_nonlinear_" + plot_type + "_2000.pickle", "rb"
133 | ) as input_file:
134 | df_init4 = pickle.load(input_file)
135 |
136 | df_init4["Length of time-series"] = 2000
137 | df3 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
138 | df3 = df3.melt("Length of time-series", var_name="Model", value_name="Val")
139 |
140 | with open(r"pickled_data/9_nonlinear_" + plot_type + "_500.pickle", "rb") as input_file:
141 | df_init1 = pickle.load(input_file)
142 |
143 | df_init1["Length of time-series"] = 500
144 |
145 |
146 | with open(
147 | r"pickled_data/9_nonlinear_" + plot_type + "_1000.pickle", "rb"
148 | ) as input_file:
149 | df_init2 = pickle.load(input_file)
150 |
151 | df_init2["Length of time-series"] = 1000
152 |
153 | with open(
154 | r"pickled_data/9_nonlinear_" + plot_type + "_1500.pickle", "rb"
155 | ) as input_file:
156 | df_init3 = pickle.load(input_file)
157 |
158 | df_init3["Length of time-series"] = 1500
159 |
160 | with open(
161 | r"pickled_data/9_nonlinear_" + plot_type + "_2000.pickle", "rb"
162 | ) as input_file:
163 | df_init4 = pickle.load(input_file)
164 |
165 | df_init4["Length of time-series"] = 2000
166 | df4 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
167 | df4 = df4.melt("Length of time-series", var_name="Model", value_name="Val")
168 |
169 | with open(
170 | r"pickled_data/11_nonlinear_" + plot_type + "_500.pickle", "rb"
171 | ) as input_file:
172 | df_init1 = pickle.load(input_file)
173 |
174 | df_init1["Length of time-series"] = 500
175 |
176 |
177 | with open(
178 | r"pickled_data/11_nonlinear_" + plot_type + "_1000.pickle", "rb"
179 | ) as input_file:
180 | df_init2 = pickle.load(input_file)
181 |
182 | df_init2["Length of time-series"] = 1000
183 |
184 | with open(
185 | r"pickled_data/11_nonlinear_" + plot_type + "_1500.pickle", "rb"
186 | ) as input_file:
187 | df_init3 = pickle.load(input_file)
188 |
189 | df_init3["Length of time-series"] = 1500
190 |
191 | with open(
192 | r"pickled_data/11_nonlinear_" + plot_type + "_2000.pickle", "rb"
193 | ) as input_file:
194 | df_init4 = pickle.load(input_file)
195 |
196 | df_init4["Length of time-series"] = 2000
197 | df5 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
198 | df5 = df5.melt("Length of time-series", var_name="Model", value_name="Val")
199 |
200 | with open(r"pickled_data/34_zachary1_" + plot_type + "_500.pickle", "rb") as input_file:
201 | df_init1 = pickle.load(input_file)
202 |
203 | df_init1["Length of time-series"] = 500
204 |
205 |
206 | with open(
207 | r"pickled_data/34_zachary1_" + plot_type + "_1000.pickle", "rb"
208 | ) as input_file:
209 | df_init2 = pickle.load(input_file)
210 |
211 | df_init2["Length of time-series"] = 1000
212 |
213 | with open(
214 | r"pickled_data/34_zachary1_" + plot_type + "_1500.pickle", "rb"
215 | ) as input_file:
216 | df_init3 = pickle.load(input_file)
217 |
218 | df_init3["Length of time-series"] = 1500
219 |
220 | with open(
221 | r"pickled_data/34_zachary1_" + plot_type + "_2000.pickle", "rb"
222 | ) as input_file:
223 | df_init4 = pickle.load(input_file)
224 |
225 | df_init4["Length of time-series"] = 2000
226 | df6 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
227 | df6 = df6.melt("Length of time-series", var_name="Model", value_name="Val")
228 |
229 | with open(r"pickled_data/34_zachary2_" + plot_type + "_500.pickle", "rb") as input_file:
230 | df_init1 = pickle.load(input_file)
231 |
232 | df_init1["Length of time-series"] = 500
233 |
234 |
235 | with open(
236 | r"pickled_data/34_zachary2_" + plot_type + "_1000.pickle", "rb"
237 | ) as input_file:
238 | df_init2 = pickle.load(input_file)
239 |
240 | df_init2["Length of time-series"] = 1000
241 |
242 | with open(
243 | r"pickled_data/34_zachary2_" + plot_type + "_1500.pickle", "rb"
244 | ) as input_file:
245 | df_init3 = pickle.load(input_file)
246 |
247 | df_init3["Length of time-series"] = 1500
248 |
249 | with open(
250 | r"pickled_data/34_zachary2_" + plot_type + "_2000.pickle", "rb"
251 | ) as input_file:
252 | df_init4 = pickle.load(input_file)
253 |
254 | df_init4["Length of time-series"] = 2000
255 | df7 = pd.concat([df_init1, df_init2, df_init3, df_init4]).reset_index(drop=True)
256 | df7 = df7.melt("Length of time-series", var_name="Model", value_name="Val")
257 |
258 | title_font = {
259 | "size": "32",
260 | "color": "black",
261 | "weight": "bold",
262 | "verticalalignment": "bottom",
263 | }
264 | title_font2 = {
265 | "size": "52",
266 | "color": "black",
267 | "weight": "bold",
268 | "verticalalignment": "bottom",
269 | }
270 | f, axes = plt.subplots(1, 7, sharex=False, sharey=True, figsize=(30, 14))
271 | f.text(0.5, 1.025, plot_type_cap, ha="center", va="center", **title_font2)
272 | f.text(-0.01, 0.5, plot_type_cap, ha="center", va="center", rotation=90, **title_font)
273 |
274 | sns.boxplot(
275 | x="Model",
276 | y="Val",
277 | hue="Length of time-series",
278 | data=df1,
279 | palette="Set3",
280 | ax=axes[0],
281 | linewidth=2,
282 | saturation=1,
283 | width=0.7,
284 | color="black",
285 | notch=False,
286 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
287 | whis=(0, 100),
288 | showfliers=False,
289 | bootstrap=10000,
290 | whiskerprops=dict(color="black", alpha=1),
291 | boxprops=dict(edgecolor="black", alpha=1),
292 | capprops=dict(color="black", alpha=1),
293 | )
294 | sns.boxplot(
295 | x="Model",
296 | y="Val",
297 | hue="Length of time-series",
298 | data=df2,
299 | palette="Set3",
300 | ax=axes[1],
301 | linewidth=2,
302 | saturation=1,
303 | width=0.7,
304 | color="black",
305 | notch=False,
306 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
307 | whis=(0, 100),
308 | showfliers=False,
309 | bootstrap=10000,
310 | whiskerprops=dict(color="black", alpha=1),
311 | boxprops=dict(edgecolor="black", alpha=1),
312 | capprops=dict(color="black", alpha=1),
313 | )
314 | sns.boxplot(
315 | x="Model",
316 | y="Val",
317 | hue="Length of time-series",
318 | data=df3,
319 | palette="Set3",
320 | ax=axes[2],
321 | linewidth=2,
322 | saturation=1,
323 | width=0.7,
324 | color="black",
325 | notch=False,
326 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
327 | whis=(0, 100),
328 | showfliers=False,
329 | bootstrap=10000,
330 | whiskerprops=dict(color="black", alpha=1),
331 | boxprops=dict(edgecolor="black", alpha=1),
332 | capprops=dict(color="black", alpha=1),
333 | )
334 | sns.boxplot(
335 | x="Model",
336 | y="Val",
337 | hue="Length of time-series",
338 | data=df4,
339 | palette="Set3",
340 | ax=axes[3],
341 | linewidth=2,
342 | saturation=1,
343 | width=0.7,
344 | color="black",
345 | notch=False,
346 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
347 | whis=(0, 100),
348 | showfliers=False,
349 | bootstrap=10000,
350 | whiskerprops=dict(color="black", alpha=1),
351 | boxprops=dict(edgecolor="black", alpha=1),
352 | capprops=dict(color="black", alpha=1),
353 | )
354 | sns.boxplot(
355 | x="Model",
356 | y="Val",
357 | hue="Length of time-series",
358 | data=df5,
359 | palette="Set3",
360 | ax=axes[4],
361 | linewidth=2,
362 | saturation=1,
363 | width=0.7,
364 | color="black",
365 | notch=False,
366 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
367 | whis=(0, 100),
368 | showfliers=False,
369 | bootstrap=10000,
370 | whiskerprops=dict(color="black", alpha=1),
371 | boxprops=dict(edgecolor="black", alpha=1),
372 | capprops=dict(color="black", alpha=1),
373 | )
374 | sns.boxplot(
375 | x="Model",
376 | y="Val",
377 | hue="Length of time-series",
378 | data=df6,
379 | palette="Set3",
380 | ax=axes[5],
381 | linewidth=2,
382 | saturation=1,
383 | width=0.7,
384 | color="black",
385 | notch=False,
386 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
387 | whis=(0, 100),
388 | showfliers=False,
389 | bootstrap=10000,
390 | whiskerprops=dict(color="black", alpha=1),
391 | boxprops=dict(edgecolor="black", alpha=1),
392 | capprops=dict(color="black", alpha=1),
393 | )
394 | sns.boxplot(
395 | x="Model",
396 | y="Val",
397 | hue="Length of time-series",
398 | data=df7,
399 | palette="Set3",
400 | ax=axes[6],
401 | linewidth=2,
402 | saturation=1,
403 | width=0.7,
404 | color="black",
405 | notch=False,
406 | medianprops=dict(color="black", linewidth=10, alpha=1, solid_capstyle="butt"),
407 | whis=(0, 100),
408 | showfliers=False,
409 | bootstrap=10000,
410 | whiskerprops=dict(color="black", alpha=1),
411 | boxprops=dict(edgecolor="black", alpha=1),
412 | capprops=dict(color="black", alpha=1),
413 | )
414 |
415 | axes[0].set_title("5-linear", fontweight="bold", fontsize=48)
416 | axes[1].set_title("5-nonlin", fontweight="bold", fontsize=48)
417 | axes[2].set_title("7-nonlin", fontweight="bold", fontsize=48)
418 | axes[3].set_title("9-nonlin", fontweight="bold", fontsize=48)
419 | axes[4].set_title("11-nonlin", fontweight="bold", fontsize=48)
420 | axes[5].set_title("Zachary1", fontweight="bold", fontsize=48)
421 | axes[6].set_title("Zachary2", fontweight="bold", fontsize=48)
422 |
423 | for i in range(7):
424 | if i < 6:
425 | axes[i].get_legend().remove()
426 | else:
427 | axes[i].legend(
428 | prop=dict(size=26, weight="bold"),
429 | title="$\\bf{Num. obs.}$",
430 | title_fontsize=26,
431 | )
432 | x_axis = axes[i].axes.get_xaxis()
433 | x_label = x_axis.get_label()
434 | x_label.set_visible(False)
435 | y_axis = axes[i].axes.get_yaxis()
436 | y_label = y_axis.get_label()
437 | y_label.set_visible(False)
438 | if i == 0:
439 | start, end = axes[i].get_ylim()
440 | new_start = float(truncate(deepcopy(start), 1))
441 | if plot_type.lower() == "accuracy" or plot_type.lower() == "accuracy2":
442 | new_start = abs(round(max(new_start - 0.1, 0), 1))
443 | else:
444 | new_start = abs(round(max(new_start, 0), 1))
445 | axes[i].yaxis.set_ticks(np.arange(new_start, end, 0.1))
446 | axes[i].yaxis.set_major_formatter(ticker.FormatStrFormatter("%0.1f"))
447 | if i == 0:
448 | axes[i].tick_params(width=5, size=10)
449 | else:
450 | axes[i].tick_params(
451 | top=False, bottom=True, left=False, right=False, width=5, size=10
452 | )
453 | axes[i].tick_params(axis="x", rotation=90, labelsize=48)
454 | axes[i].tick_params(axis="y", labelsize=48)
455 | [
456 | axes[i].axvline(x, color="0.3", linestyle="--", linewidth=3)
457 | for x in [0.5, 1.5, 2.5]
458 | ]
459 | axes[i].grid(visible=True, which="major", axis="y", linewidth=3)
460 | axes[i].set(axisbelow=True)
461 | for axis in ["top", "bottom", "left", "right"]:
462 | axes[i].spines[axis].set_linewidth(5) # change width
463 | if i == 0:
464 | start2, end2 = axes[i].get_ylim()
465 | for axis in ["left", "right"]:
466 | axes[i].spines[axis].set_bounds(
467 | low=start2 - (end2 - start2) * 0.21153846153846154,
468 | high=end2 + (end2 - start2) * 0.06937799043062202,
469 | ) # Extend spine bounds
470 |
471 | f.tight_layout()
472 | f.subplots_adjust(wspace=0, hspace=0)
473 | plt.rcParams["svg.fonttype"] = "none"
474 | plt.savefig(
475 | "plots/" + plot_type.replace("_", "") + "plotmulti.pdf", bbox_inches="tight"
476 | )
477 | plt.savefig(
478 | "plots/" + plot_type.replace("_", "") + "plotmulti.eps", bbox_inches="tight"
479 | )
480 | # plt.show()
481 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/run_all_models.py:
--------------------------------------------------------------------------------
1 | # Get time samples and seed from arguments passed when this script is called
2 | import sys
3 |
4 | network_to_check = sys.argv[1]
5 | n_time_samples_str = sys.argv[2]
6 | n_time_samples_int = int(n_time_samples_str)
7 | seed = int(sys.argv[3])
8 |
9 | import os
10 |
11 | # Set environment variables useful for multiprocessing.
12 | # This will only work if your BLAS is MKL or openblas.
13 | # If using other BLAS implementations, these have no effect
14 | os.environ["MKL_NUM_THREADS"] = "1"
15 | os.environ["OPENBLAS_NUM_THREADS"] = "1"
16 |
17 | os.makedirs("plots", exist_ok=True)
18 | os.makedirs("pickled_data", exist_ok=True)
19 |
20 | import warnings
21 |
22 | warnings.simplefilter(action="ignore", category=FutureWarning)
23 | warnings.simplefilter(action="ignore", category=UserWarning)
24 |
25 | import numpy as np
26 |
27 | np.seterr(all="raise")
28 |
29 | import pandas as pd
30 |
31 | import cao_min_embedding_dimension
32 | import mlcausality
33 |
34 | from utils_mod import lsNGC as granger
35 | from recovery_performance_mod import recovery_performance
36 |
37 | from brier_loss import brier_loss_func
38 |
39 | import causal_ccm
40 |
41 | from tigramite import data_processing as pcmci_data_processing
42 | from tigramite.pcmci import PCMCI
43 | from tigramite.independence_tests.parcorr import ParCorr
44 |
45 | import tqdm
46 |
47 | import matplotlib.pyplot as plt
48 |
49 | from copy import deepcopy
50 | import itertools
51 | from pprint import pprint
52 | import pickle
53 |
54 | import networkx as nx
55 |
56 | from sklearn.metrics import (
57 | confusion_matrix,
58 | accuracy_score,
59 | balanced_accuracy_score,
60 | f1_score,
61 | )
62 |
63 | # Get number of cpu cores
64 | import psutil
65 |
66 | num_cores = psutil.cpu_count(logical=True)
67 | # Import multriprocessing plugins from tqdm
68 | # These rely on concurrent.futures
69 | from tqdm.contrib.concurrent import ensure_lock, process_map
70 |
71 | # Set seed.
72 | np.random.seed(seed)
73 |
74 | if network_to_check == "5_linear":
75 | # from spectral_connectivity.simulate import simulate_MVAR
76 | def simulate_MVAR(
77 | coefficients,
78 | noise_covariance=None,
79 | n_time_samples=100,
80 | n_trials=1,
81 | n_burnin_samples=100,
82 | ):
83 | """
84 | Simulate multivariate autoregressive (MVAR) process.
85 | Parameters
86 | ----------
87 | coefficients : array, shape (n_time_samples, n_lags, n_signals, n_signals)
88 | noise_covariance : array, shape (n_signals, n_signals)
89 | Returns
90 | -------
91 | time_series : array, shape (n_time_samples - n_burnin_samples,
92 | n_trials, n_signals)
93 | """
94 | n_lags, n_signals, _ = coefficients.shape
95 | if noise_covariance is None:
96 | noise_covariance = np.eye(n_signals)
97 | time_series = np.random.multivariate_normal(
98 | np.zeros((n_signals,)),
99 | noise_covariance,
100 | size=(n_time_samples + n_burnin_samples, n_trials),
101 | )
102 |
103 | for time_ind in np.arange(n_lags, n_time_samples + n_burnin_samples):
104 | for lag_ind in np.arange(n_lags):
105 | time_series[time_ind, ...] += np.matmul(
106 | coefficients[np.newaxis, np.newaxis, lag_ind, ...],
107 | time_series[time_ind - (lag_ind + 1), ..., np.newaxis],
108 | ).squeeze()
109 | return time_series[n_burnin_samples:, ...]
110 |
111 | # Generate data using the spectral_connectivity package
112 |
113 | def baccala_example3():
114 | """Baccalá, L.A., and Sameshima, K. (2001). Partial directed coherence:
115 | a new concept in neural structure determination. Biological
116 | Cybernetics 84, 463–474.
117 | """
118 | np.random.seed(seed)
119 | n_time_samples, n_lags, n_signals = n_time_samples_int, 3, 5
120 | coefficients = np.zeros((n_lags, n_signals, n_signals))
121 |
122 | coefficients[0, 0, 0] = 0.95 * np.sqrt(2)
123 | coefficients[1, 0, 0] = -0.9025
124 |
125 | coefficients[1, 1, 0] = 0.50
126 | coefficients[2, 2, 0] = -0.40
127 |
128 | coefficients[1, 3, 0] = -0.5
129 | coefficients[0, 3, 3] = 0.5 * np.sqrt(2)
130 | coefficients[0, 3, 4] = 0.25 * np.sqrt(2)
131 |
132 | coefficients[0, 4, 3] = -0.5 * np.sqrt(2)
133 | coefficients[0, 4, 4] = 0.5 * np.sqrt(2)
134 |
135 | noise_covariance = None
136 |
137 | return (
138 | simulate_MVAR(
139 | coefficients,
140 | noise_covariance=noise_covariance,
141 | n_time_samples=n_time_samples,
142 | n_trials=50,
143 | n_burnin_samples=500,
144 | ),
145 | coefficients,
146 | )
147 |
148 | data, coefficients = baccala_example3()
149 |
150 | data_list = [data[:, i, :] for i in range(data.shape[1])]
151 |
152 | # Find the adjacency matrix (which are essentially the true labels)
153 | adjacency_matrix = np.zeros((coefficients.shape[1], coefficients.shape[2]))
154 | for i in range(coefficients.shape[0]):
155 | adjacency_matrix += np.ceil(np.abs(coefficients[i]))
156 |
157 | adjacency_matrix = np.clip(adjacency_matrix, 0, 1)
158 | np.fill_diagonal(adjacency_matrix, 0)
159 | adjacency_matrix = adjacency_matrix.T.astype(int)
160 | true_labels = adjacency_matrix
161 | elif network_to_check == "5_nonlinear":
162 | # 5-node nonlinear network
163 | true_labels = np.array(
164 | [
165 | [0, 1, 1, 1, 0],
166 | [0, 0, 0, 0, 0],
167 | [0, 0, 0, 0, 0],
168 | [0, 0, 0, 0, 1],
169 | [0, 0, 0, 1, 0],
170 | ]
171 | )
172 | n_burnin_samples = 500
173 | n_trials = 50
174 | n_lags = 3
175 | data_list = []
176 | while True:
177 | np.random.seed(seed)
178 | seed += 1
179 | data = np.random.normal(0, 1, [n_lags, 5])
180 | try:
181 | for j in range(n_lags, n_time_samples_int + n_burnin_samples):
182 | x1 = (
183 | 0.95 * np.sqrt(2) * data[-1, 0]
184 | - 0.9025 * data[-2, 0]
185 | + np.random.normal(0, 1)
186 | )
187 | x2 = 0.5 * data[-2, 0] ** 2 + np.random.normal(0, 1)
188 | x3 = -0.4 * data[-3, 0] + np.random.normal(0, 1)
189 | x4 = (
190 | -0.5 * data[-2, 0] ** 2
191 | + 0.5 * np.sqrt(2) * data[-1, 3]
192 | + 0.25 * np.sqrt(2) * data[-1, 4]
193 | + np.random.normal(0, 1)
194 | )
195 | x5 = (
196 | -0.5 * np.sqrt(2) * data[-1, 3]
197 | + 0.5 * np.sqrt(2) * data[-1, 4]
198 | + np.random.normal(0, 1)
199 | )
200 | data = np.vstack([data, np.array([x1, x2, x3, x4, x5])])
201 | except Exception:
202 | continue
203 | data = np.array(data[n_burnin_samples:])
204 | data_list.append(data)
205 | if len(data_list) == n_trials:
206 | break
207 | elif network_to_check == "7_nonlinear":
208 | # 7-node nonlinear network
209 | true_labels = np.array(
210 | [
211 | [0, 1, 0, 0, 0, 1, 1],
212 | [0, 0, 1, 0, 0, 0, 0],
213 | [0, 0, 0, 1, 0, 1, 0],
214 | [0, 0, 0, 0, 0, 0, 0],
215 | [0, 0, 0, 0, 0, 0, 0],
216 | [0, 0, 0, 0, 1, 0, 1],
217 | [0, 0, 0, 1, 0, 0, 0],
218 | ]
219 | )
220 | n_burnin_samples = 500
221 | n_trials = 50
222 | n_lags = 3
223 | data_list = []
224 | while True:
225 | np.random.seed(seed)
226 | seed += 1
227 | data = np.random.normal(0, 1, [n_lags, 7])
228 | try:
229 | for j in range(n_lags, n_time_samples_int + n_burnin_samples):
230 | x1 = (
231 | 0.95 * np.sqrt(2) * data[-1, 0]
232 | - 0.9025 * data[-2, 0]
233 | + np.random.normal(0, 1)
234 | )
235 | x2 = (
236 | -0.04 * data[-3, 0] ** 3
237 | + 0.04 * data[-1, 0] ** 3
238 | + np.random.normal(0, 1)
239 | )
240 | x3 = (
241 | -0.04 * np.sqrt(2) * data[-1, 1] ** 3
242 | + 0.04 * np.sqrt(2) * data[-2, 1] ** 3
243 | + np.random.normal(0, 1)
244 | )
245 | x4 = (
246 | np.log1p(np.abs(data[-1, 2])) * np.sign(data[-1, 2])
247 | + 0.001 * data[-2, 6] ** 3
248 | - 0.001 * data[-3, 6] ** 3
249 | + np.random.normal(0, 1)
250 | )
251 | x5 = np.clip(np.random.normal(0, 1), -1, 1) * 0.04 * data[
252 | -2, 5
253 | ] ** 5 + np.random.normal(0, 1)
254 | x6 = (
255 | 0.04 * data[-2, 0] ** 3
256 | + 0.04 * data[-1, 2] ** 3
257 | + np.random.normal(0, 1)
258 | )
259 | x7 = np.clip(np.random.normal(0, 1), -0.5, 0.5) * (
260 | 0.04 * data[-2, 0] ** 3
261 | + 0.1 * data[-1, 5] ** 2
262 | - 0.1 * data[-2, 5] ** 2
263 | ) + np.random.normal(0, 1)
264 | data = np.vstack([data, np.array([x1, x2, x3, x4, x5, x6, x7])])
265 | except Exception:
266 | continue
267 | data = np.array(data[n_burnin_samples:])
268 | data_list.append(data)
269 | if len(data_list) == n_trials:
270 | break
271 | elif network_to_check == "9_nonlinear":
272 | # 9-node nonlinear network
273 | true_labels = np.array(
274 | [
275 | [0, 1, 1, 1, 0, 0, 0, 1, 1],
276 | [0, 0, 0, 0, 0, 0, 0, 0, 0],
277 | [0, 0, 0, 0, 0, 0, 0, 1, 0],
278 | [0, 0, 0, 0, 1, 1, 0, 0, 0],
279 | [0, 0, 0, 1, 0, 0, 0, 0, 0],
280 | [0, 0, 0, 0, 0, 0, 1, 0, 0],
281 | [0, 0, 0, 0, 0, 0, 0, 0, 0],
282 | [0, 0, 0, 0, 0, 0, 0, 0, 1],
283 | [0, 0, 0, 0, 0, 0, 0, 0, 0],
284 | ]
285 | )
286 | n_burnin_samples = 500
287 | n_trials = 50
288 | n_lags = 3
289 | data_list = []
290 | while True:
291 | np.random.seed(seed)
292 | seed += 1
293 | data = np.random.normal(0, 1, [n_lags, 9])
294 | try:
295 | for j in range(n_lags, n_time_samples_int + n_burnin_samples):
296 | x1 = (
297 | 0.95 * np.sqrt(2) * data[-1, 0]
298 | - 0.9025 * data[-2, 0]
299 | + np.random.normal(0, 1)
300 | )
301 | x2 = (
302 | 0.5 * data[-2, 0] ** 2
303 | + 0.5 * data[-1, 1]
304 | - 0.4 * data[-2, 1]
305 | + np.random.normal(0, 1)
306 | )
307 | x3 = (
308 | -0.4 * data[-3, 0]
309 | + 0.5 * data[-1, 2]
310 | - 0.4 * data[-2, 2]
311 | + np.random.normal(0, 1)
312 | )
313 | x4 = (
314 | -0.5 * data[-2, 0] ** 2
315 | + 0.5 * data[-1, 3]
316 | - 0.4 * data[-2, 3]
317 | + 0.5 * np.sqrt(2) * data[-1, 3]
318 | + 0.25 * np.sqrt(2) * data[-1, 4]
319 | + np.random.normal(0, 1)
320 | )
321 | x5 = (
322 | -0.5 * np.sqrt(2) * data[-1, 3]
323 | + 0.5 * np.sqrt(2) * data[-1, 4]
324 | + np.random.normal(0, 1)
325 | )
326 | x6 = (
327 | np.log1p(np.abs(data[-1, 3])) * np.sign(data[-1, 3])
328 | + 0.5 * data[-1, 5]
329 | - 0.4 * data[-2, 5]
330 | + np.random.normal(0, 1)
331 | )
332 | x7 = (
333 | np.clip(np.random.normal(0, 1), -1, 1) * 0.04 * data[-2, 5] ** 5
334 | + 0.5 * data[-1, 6]
335 | - 0.4 * data[-2, 6]
336 | + np.random.normal(0, 1)
337 | )
338 | x8 = (
339 | 0.4 * data[-2, 0]
340 | + 0.25 * data[-1, 2] ** 3
341 | + 0.5 * data[-1, 7]
342 | - 0.4 * data[-2, 7]
343 | + np.random.normal(0, 1)
344 | )
345 | x9 = (
346 | np.clip(np.random.normal(0, 1), -0.5, 0.5)
347 | * (
348 | 0.2 * data[-2, 0]
349 | + 0.1 * data[-1, 7] ** 2
350 | - 0.1 * data[-2, 7] ** 2
351 | )
352 | + 0.5 * data[-1, 8]
353 | - 0.4 * data[-2, 8]
354 | + np.random.normal(0, 1)
355 | )
356 | data = np.vstack([data, np.array([x1, x2, x3, x4, x5, x6, x7, x8, x9])])
357 | except Exception:
358 | continue
359 | data = np.array(data[n_burnin_samples:])
360 | data_list.append(data)
361 | if len(data_list) == n_trials:
362 | break
363 | elif network_to_check == "11_nonlinear":
364 | # 11-node nonlinear network
365 | true_labels = np.array(
366 | [
367 | [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0],
368 | [0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1],
369 | [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
370 | [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
371 | [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
372 | [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
373 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
374 | [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
375 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
376 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
377 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
378 | ]
379 | )
380 | n_burnin_samples = 500
381 | n_trials = 50
382 | n_lags = 3
383 | data_list = []
384 | while True:
385 | np.random.seed(seed)
386 | seed += 1
387 | data = np.random.normal(0, 1, [n_lags, 11])
388 | try:
389 | for j in range(n_lags, n_time_samples_int + n_burnin_samples):
390 | x1 = (
391 | 0.25 * data[-1, 0] ** 2
392 | - 0.25 * data[-2, 0] ** 2
393 | + np.random.normal(0, 1)
394 | )
395 | x2 = np.log1p(np.abs(data[-2, 0])) * np.sign(
396 | data[-2, 0]
397 | ) + np.random.normal(0, 1)
398 | x3 = -0.1 * data[-3, 1] ** 3 + np.random.normal(0, 1)
399 | x4 = (
400 | -0.5 * data[-2, 1] ** 2
401 | + 0.5 * np.sqrt(2) * data[-1, 3]
402 | + 0.25 * np.sqrt(2) * data[-1, 4]
403 | + np.random.normal(0, 1)
404 | )
405 | x5 = (
406 | -0.5 * np.sqrt(2) * data[-1, 3]
407 | + 0.5 * np.sqrt(2) * data[-1, 4]
408 | + np.random.normal(0, 1)
409 | )
410 | x6 = np.log1p(np.abs(data[-1, 3])) * np.sign(
411 | data[-1, 3]
412 | ) + np.random.normal(0, 1)
413 | x7 = np.clip(np.random.normal(0, 1), -1, 1) * 0.04 * data[
414 | -2, 5
415 | ] ** 5 + np.random.normal(0, 1)
416 | x8 = (
417 | 0.4 * data[-2, 0] + 0.25 * data[-1, 2] ** 3 + np.random.normal(0, 1)
418 | )
419 | x9 = np.clip(np.random.normal(0, 1), -0.5, 0.5) * (
420 | 0.2 * data[-2, 0] + 0.1 * data[-1, 7] ** 2 - 0.1 * data[-2, 7] ** 2
421 | ) + np.random.normal(0, 1)
422 | x10 = (
423 | 0.25 * data[-3, 0] ** 2
424 | - 0.01 * data[-3, 1] ** 2
425 | + 0.15 * data[-3, 2] ** 3
426 | + np.random.normal(0, 1)
427 | )
428 | x11 = (
429 | 0.1 * data[-1, 1] ** 4
430 | - 0.1 * data[-2, 1] ** 4
431 | + 0.1 * data[-3, 5] ** 3
432 | + np.random.normal(0, 1)
433 | )
434 | data = np.vstack(
435 | [data, np.array([x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11])]
436 | )
437 | except Exception:
438 | continue
439 | data = np.array(data[n_burnin_samples:])
440 | data_list.append(data)
441 | if len(data_list) == n_trials:
442 | break
443 | elif network_to_check == "34_zachary1":
444 | # Generate data
445 | n_burnin_samples = 500
446 | n_trials = 50
447 | n_lags = 1
448 | true_labels_list = []
449 | data_list = []
450 | while True:
451 | np.random.seed(seed)
452 | seed += 1
453 | # Load the Zachary karate club dataset
454 | G_orig = nx.karate_club_graph()
455 | adjacency_matrix = nx.adjacency_matrix(G_orig).todense()
456 |
457 | true_labels = np.clip(adjacency_matrix, 0, 1).astype(int)
458 | true_labels_list.append(true_labels)
459 |
460 | data = 0.01 * np.random.normal(0, 1, [n_lags, true_labels.shape[0]])
461 | try:
462 | for t in range(n_lags, n_time_samples_int + n_burnin_samples):
463 | data_new = np.zeros_like(data[[-1]])
464 | for i in range(data_new.shape[1]):
465 | data_new[0, i] = (
466 | (1 - 0.025 * true_labels[:, i].sum())
467 | * (1 - 1.8 * data[-1, i] ** 2)
468 | + np.matmul(
469 | 0.025 * true_labels[:, i], (1 - 1.8 * np.square(data[-1]))
470 | )
471 | + 0.01 * np.random.normal(0, 1)
472 | )
473 | data = np.vstack([data, data_new])
474 | except Exception:
475 | continue
476 | data = np.array(data[n_burnin_samples:])
477 | data_list.append(data)
478 | if len(data_list) == n_trials:
479 | break
480 | elif network_to_check == "34_zachary2":
481 | # Generate data
482 | n_burnin_samples = 500
483 | n_trials = 50
484 | n_lags = 1
485 | true_labels_list = []
486 | data_list = []
487 | while True:
488 | np.random.seed(seed)
489 | seed += 1
490 | # Load the Zachary karate club dataset
491 | G_orig = nx.karate_club_graph()
492 | adjacency_matrix = nx.adjacency_matrix(G_orig).todense()
493 | comb_list = deepcopy(
494 | list(itertools.combinations(range(adjacency_matrix.shape[0]), 2))
495 | )
496 | list_of_edges = [(i, j) for (i, j) in comb_list if adjacency_matrix[i, j] != 0]
497 | # Randomly select 5 edges to keep as bidirectional
498 | idx_bidirectional = np.random.choice(range(len(list_of_edges)), 5)
499 | edges_nonbidirectional = [
500 | list_of_edges[i]
501 | for i in range(len(list_of_edges))
502 | if i not in idx_bidirectional
503 | ]
504 | # Randomly assign a direction
505 | for a, b in edges_nonbidirectional:
506 | if np.random.random() < 0.5:
507 | adjacency_matrix[a, b] = 0
508 | else:
509 | adjacency_matrix[b, a] = 0
510 |
511 | true_labels = np.clip(adjacency_matrix, 0, 1).astype(int)
512 | true_labels_list.append(true_labels)
513 |
514 | data = 0.01 * np.random.normal(0, 1, [n_lags, true_labels.shape[0]])
515 | try:
516 | for t in range(n_lags, n_time_samples_int + n_burnin_samples):
517 | data_new = np.zeros_like(data[[-1]])
518 | for i in range(data_new.shape[1]):
519 | data_new[0, i] = (
520 | (1 - 0.05 * true_labels[:, i].sum())
521 | * (1 - 1.8 * data[-1, i] ** 2)
522 | + np.matmul(
523 | 0.05 * true_labels[:, i], (1 - 1.8 * np.square(data[-1]))
524 | )
525 | + 0.01 * np.random.normal(0, 1)
526 | )
527 | data = np.vstack([data, data_new])
528 | except Exception as e:
529 | print(e)
530 | continue
531 | data = np.array(data[n_burnin_samples:])
532 | data_list.append(data)
533 | if len(data_list) == n_trials:
534 | break
535 |
536 |
537 | if network_to_check != "34_zachary1" and network_to_check != "34_zachary2":
538 | true_labels_list = [true_labels for i in range(len(data_list))]
539 |
540 |
541 | G = nx.from_numpy_array(true_labels_list[0], create_using=nx.DiGraph)
542 | if network_to_check != "34_zachary1" and network_to_check != "34_zachary2":
543 | G_pos = nx.kamada_kawai_layout(G)
544 | else:
545 | G_pos = nx.circular_layout(G)
546 |
547 | G_d = dict(G.degree)
548 | G_labels = {node: str(node + 1) for node in G_d.keys()}
549 | nx.draw(
550 | G,
551 | G_pos,
552 | labels=G_labels,
553 | with_labels=True,
554 | node_color="white",
555 | node_size=750,
556 | edgecolors="black",
557 | linewidths=2,
558 | arrows=True,
559 | arrowstyle="->",
560 | connectionstyle="arc3, rad = 0.2",
561 | )
562 | plt.rcParams["svg.fonttype"] = "none"
563 | if n_time_samples_str == "500":
564 | if network_to_check == "5_linear":
565 | plt.savefig("plots/5_linear_nonlinear_network.pdf", bbox_inches="tight")
566 | plt.savefig("plots/5_linear_nonlinear_network.eps", bbox_inches="tight")
567 | elif network_to_check == "5_nonlinear":
568 | pass
569 | else:
570 | plt.savefig("plots/" + network_to_check + "_network.pdf", bbox_inches="tight")
571 | plt.savefig("plots/" + network_to_check + "_network.eps", bbox_inches="tight")
572 | # plt.show(block=False)
573 | # plt.pause(0.001)
574 |
575 |
576 | # Cao's minimum embedding dimension
577 | pprint("### Find Cao's minimum embedding dimension ###")
578 |
579 |
580 | def caoloop(d):
581 | d_list = [[] for i in range(d.shape[1])]
582 | E1_list = [[] for i in range(d.shape[1])]
583 | E2_list = [[] for i in range(d.shape[1])]
584 | embedding_dim_list = [[] for i in range(d.shape[1])]
585 | for c in range(d.shape[1]):
586 | (
587 | cur_d,
588 | cur_E1,
589 | cur_E2,
590 | embedding_dim,
591 | ) = cao_min_embedding_dimension.cao_min_embedding_dimension(
592 | d[:, c], maxd=20, tau=1, threshold=0.8, max_relative_change=0.3
593 | )
594 | d_list[c].append(cur_d)
595 | E1_list[c].append(cur_E1)
596 | E2_list[c].append(cur_E2)
597 | embedding_dim_list[c].append(embedding_dim)
598 | return [d_list, E1_list, E2_list, embedding_dim_list]
599 |
600 |
601 | cao_loop_output = process_map(caoloop, data_list, max_workers=num_cores)
602 | # Ensure process_map finished before continuing:
603 | # the following will not pass until the lock can be acquired
604 | with ensure_lock(tqdm.auto.tqdm, lock_name="mp_lock") as lk:
605 | pass
606 |
607 | # Extract output into lists of lists for easier processing downstream
608 | d_list = [[] for i in range(data_list[0].shape[1])]
609 | E1_list = [[] for i in range(data_list[0].shape[1])]
610 | E2_list = [[] for i in range(data_list[0].shape[1])]
611 | embedding_dim_list = [[] for i in range(data_list[0].shape[1])]
612 | for o in range(len(cao_loop_output)):
613 | for v in range(len(cao_loop_output[0][0])):
614 | d_list[v].append(cao_loop_output[o][0][v][0])
615 | E1_list[v].append(cao_loop_output[o][1][v][0])
616 | E2_list[v].append(cao_loop_output[o][2][v][0])
617 | embedding_dim_list[v].append(cao_loop_output[o][3][v][0])
618 |
619 |
620 | min_embed_dim = round(np.nanmax(np.array(embedding_dim_list).flatten()))
621 |
622 | pprint("Minimum embedding dimension: " + str(min_embed_dim))
623 |
624 |
625 | # Function to calculate metrics
626 | def calc_metrics(pvalue_matricies, thresh):
627 | # Check sensitivity and specificity
628 | sensitivities = []
629 | specificities = []
630 | accuracies = []
631 | balanced_accuracies = []
632 | f1wgt = []
633 | listlen = deepcopy(len(pvalue_matricies))
634 | for i in range(listlen):
635 | preds = deepcopy(np.array(pvalue_matricies[i])).astype(float)
636 | np.fill_diagonal(preds, np.nan)
637 | preds = preds.flatten()
638 | preds = preds[~np.isnan(preds)]
639 | preds = (preds < thresh).astype(int)
640 | true_labels_curr = deepcopy(true_labels_list[i]).astype(float)
641 | np.fill_diagonal(true_labels_curr, np.nan)
642 | true_labels_curr = true_labels_curr.flatten()
643 | true_labels_curr = true_labels_curr[~np.isnan(true_labels_curr)]
644 | true_labels_curr = true_labels_curr.astype(int)
645 | tn, fp, fn, tp = confusion_matrix(
646 | true_labels_curr.flatten(), preds.flatten()
647 | ).ravel()
648 | sensitivity = tp / (tp + fn)
649 | sensitivities.append(sensitivity)
650 | specificity = tn / (tn + fp)
651 | specificities.append(specificity)
652 | accuracy = accuracy_score(true_labels_curr.flatten(), preds.flatten())
653 | accuracies.append(accuracy)
654 | balanced_accuracy = balanced_accuracy_score(
655 | true_labels_curr.flatten(), preds.flatten()
656 | )
657 | balanced_accuracies.append(balanced_accuracy)
658 | f1 = f1_score(true_labels_curr.flatten(), preds.flatten(), average="weighted")
659 | f1wgt.append(f1)
660 | return sensitivities, specificities, accuracies, balanced_accuracies, f1wgt
661 |
662 |
663 | # Run mlcausality:
664 | pprint("### Run mlcausality ###")
665 | # Note: use minimum embedding dimension - 1 for lag if no logdiff is used and
666 | # dimension - 2 for lag if logdiff is used
667 | lag = max(min_embed_dim - 1, 1)
668 |
669 |
670 | def locoloop(d):
671 | mlcausality_output = mlcausality.multiloco_mlcausality(
672 | d, lags=[lag], scaler_init_1="quantile", return_pvalue_matrix_only=True
673 | )
674 | return mlcausality_output
675 |
676 |
677 | all_mlcausality_output = process_map(locoloop, data_list, max_workers=num_cores)
678 | # Ensure process_map finished before continuing:
679 | # the following will not pass until the lock can be acquired
680 | with ensure_lock(tqdm.auto.tqdm, lock_name="mp_lock") as lk:
681 | pass
682 |
683 | mlcausality_pvalue_matricies = all_mlcausality_output
684 | mlcausality_adjacency_matricies = [1 - i for i in mlcausality_pvalue_matricies]
685 |
686 | mlcausality_recovery_performance = recovery_performance(
687 | mlcausality_adjacency_matricies, true_labels_list
688 | )
689 | pprint("mlcausality recovery performance:")
690 | pprint("Mean: " + str(mlcausality_recovery_performance.mean()))
691 | pprint(
692 | pd.DataFrame(mlcausality_recovery_performance).quantile([0, 0.25, 0.5, 0.75, 1]).T
693 | )
694 |
695 | mlcausality_brier_score_loss = brier_loss_func(
696 | mlcausality_pvalue_matricies, true_labels_list
697 | )
698 | pprint("mlcausality brier score:")
699 | pprint("Mean: " + str(mlcausality_brier_score_loss.mean()))
700 | pprint(pd.DataFrame(mlcausality_brier_score_loss).quantile([0, 0.25, 0.5, 0.75, 1]).T)
701 |
702 | # Check sensitivity and specificity for the mlcausality model
703 | mlc_sens, mlc_spec, mlc_acc, mlc_bal_acc, mlc_f1wgt = calc_metrics(
704 | mlcausality_pvalue_matricies, 0.05
705 | )
706 |
707 |
708 | pprint("mlcausality sensitivities:")
709 | pprint(pd.DataFrame(mlc_sens).quantile([0, 0.25, 0.5, 0.75, 1]).T)
710 | pprint("mlcausality specificities:")
711 | pprint(pd.DataFrame(mlc_spec).quantile([0, 0.25, 0.5, 0.75, 1]).T)
712 | pprint("mlcausality (sensitivities*specificities)**0.5:")
713 | pprint(
714 | pd.DataFrame((np.array(mlc_sens) * np.array(mlc_spec)) ** 0.5)
715 | .quantile([0, 0.25, 0.5, 0.75, 1])
716 | .T
717 | )
718 | pprint("mlcausality accuracies:")
719 | pprint(pd.DataFrame(mlc_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
720 | pprint("mlcausality balanced accuracies:")
721 | pprint(pd.DataFrame(mlc_bal_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
722 | pprint("mlcausality f1 scores:")
723 | pprint(pd.DataFrame(mlc_f1wgt).quantile([0, 0.25, 0.5, 0.75, 1]).T)
724 |
725 | optimal_j = 0
726 | best_score = 0
727 | for j in [round(r * 0.01, 2) for r in range(1, 100)]:
728 | mlc_sens2, mlc_spec2, mlc_acc2, mlc_bal_acc2, mlc_f1wgt2 = calc_metrics(
729 | mlcausality_pvalue_matricies, j
730 | )
731 | best_score_new = np.median((np.array(mlc_sens2) * np.array(mlc_spec2)) ** 0.5)
732 | if best_score_new > best_score:
733 | best_score = deepcopy(best_score_new)
734 | optimal_j = deepcopy(j)
735 |
736 |
737 | mlc_sens2, mlc_spec2, mlc_acc2, mlc_bal_acc2, mlc_f1wgt2 = calc_metrics(
738 | mlcausality_pvalue_matricies, optimal_j
739 | )
740 |
741 |
742 | pprint("Optimal cutoff: " + str(optimal_j))
743 | pprint("Optimal mlcausality sensitivities:")
744 | pprint(pd.DataFrame(mlc_sens2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
745 | pprint("Optimal mlcausality specificities:")
746 | pprint(pd.DataFrame(mlc_spec2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
747 | pprint("Optimal mlcausality (sensitivities*specificities)**0.5:")
748 | pprint(
749 | pd.DataFrame((np.array(mlc_sens2) * np.array(mlc_spec2)) ** 0.5)
750 | .quantile([0, 0.25, 0.5, 0.75, 1])
751 | .T
752 | )
753 | pprint("Optimal mlcausality accuracies:")
754 | pprint(pd.DataFrame(mlc_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
755 | pprint("Optimal mlcausality balanced accuracies:")
756 | pprint(pd.DataFrame(mlc_bal_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
757 | pprint("Optimal mlcausality f1 scores:")
758 | pprint(pd.DataFrame(mlc_f1wgt2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
759 |
760 |
761 | # Run lsNGC
762 | pprint("### Run lsNGC ###")
763 |
764 | k_f = 25
765 | k_g = 5
766 | ar_order = max(min_embed_dim - 1, 1)
767 | while k_f >= 2:
768 | try:
769 | _ = granger(data_list[0].T, k_f=k_f, k_g=k_g, ar_order=ar_order, normalize=1)
770 | break
771 | except Exception:
772 | k_f -= 1
773 |
774 | pprint(
775 | "lsNGC parameters: k_f="
776 | + str(k_f)
777 | + ", k_g="
778 | + str(k_g)
779 | + ", ar_order="
780 | + str(ar_order)
781 | )
782 |
783 |
784 | def lsNGCloop(d):
785 | lsNGC_output = granger(d.T, k_f=k_f, k_g=k_g, ar_order=ar_order, normalize=1)
786 | return lsNGC_output
787 |
788 |
789 | all_lsNGC_output = process_map(lsNGCloop, data_list, max_workers=num_cores)
790 | # Ensure process_map finished before continuing:
791 | # the following will not pass until the lock can be acquired
792 | with ensure_lock(tqdm.auto.tqdm, lock_name="mp_lock") as lk:
793 | pass
794 |
795 | lsgc_adjacency_matricies = []
796 | lsgc_fstat_matricies = []
797 | lsgc_pvalue_matricies = []
798 | for out in all_lsNGC_output:
799 | lsgc_adjacency_matricies.append(out[0])
800 | lsgc_fstat_matricies.append(out[1])
801 | pvalues_lsgc = out[2]
802 | np.fill_diagonal(pvalues_lsgc, 1)
803 | # lsgc_adjacency_matricies.append(1 - pvalues_lsgc)
804 | lsgc_pvalue_matricies.append(pvalues_lsgc)
805 |
806 | lsgc_recovery_performance = recovery_performance(lsgc_fstat_matricies, true_labels_list)
807 | # lsgc_recovery_performance = recovery_performance(lsgc_adjacency_matricies,true_labels_list)
808 | pprint("lsNGC recovery performance:")
809 | pprint("Mean: " + str(lsgc_recovery_performance.mean()))
810 | pprint(pd.DataFrame(lsgc_recovery_performance).quantile([0, 0.25, 0.5, 0.75, 1]).T)
811 |
812 | lsgc_brier_score_loss = brier_loss_func(lsgc_pvalue_matricies, true_labels_list)
813 | pprint("lsgc brier score:")
814 | pprint("Mean: " + str(lsgc_brier_score_loss.mean()))
815 | pprint(pd.DataFrame(lsgc_brier_score_loss).quantile([0, 0.25, 0.5, 0.75, 1]).T)
816 |
817 | # Check sensitivity and specificity for the lsNGC model
818 | lsgc_sens, lsgc_spec, lsgc_acc, lsgc_bal_acc, lsgc_f1wgt = calc_metrics(
819 | lsgc_pvalue_matricies, 0.05
820 | )
821 |
822 |
823 | pprint("lsgc sensitivities:")
824 | pprint(pd.DataFrame(lsgc_sens).quantile([0, 0.25, 0.5, 0.75, 1]).T)
825 | pprint("lsgc specificities:")
826 | pprint(pd.DataFrame(lsgc_spec).quantile([0, 0.25, 0.5, 0.75, 1]).T)
827 | pprint("lsgc (sensitivities*specificities)**0.5:")
828 | pprint(
829 | pd.DataFrame((np.array(lsgc_sens) * np.array(lsgc_spec)) ** 0.5)
830 | .quantile([0, 0.25, 0.5, 0.75, 1])
831 | .T
832 | )
833 | pprint("lsgc accuracies:")
834 | pprint(pd.DataFrame(lsgc_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
835 | pprint("lsgc balanced accuracies:")
836 | pprint(pd.DataFrame(lsgc_bal_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
837 | pprint("lsgc f1 scores:")
838 | pprint(pd.DataFrame(lsgc_f1wgt).quantile([0, 0.25, 0.5, 0.75, 1]).T)
839 |
840 | optimal_j = 0
841 | best_score = 0
842 | for j in [round(r * 0.01, 2) for r in range(1, 100)]:
843 | lsgc_sens2, lsgc_spec2, lsgc_acc2, lsgc_bal_acc2, lsgc_f1wgt2 = calc_metrics(
844 | lsgc_pvalue_matricies, j
845 | )
846 | best_score_new = np.median((np.array(lsgc_sens2) * np.array(lsgc_spec2)) ** 0.5)
847 | if best_score_new > best_score:
848 | best_score = deepcopy(best_score_new)
849 | optimal_j = deepcopy(j)
850 |
851 |
852 | lsgc_sens2, lsgc_spec2, lsgc_acc2, lsgc_bal_acc2, lsgc_f1wgt2 = calc_metrics(
853 | lsgc_pvalue_matricies, optimal_j
854 | )
855 |
856 |
857 | pprint("Optimal cutoff: " + str(optimal_j))
858 | pprint("Optimal lsgc sensitivities:")
859 | pprint(pd.DataFrame(lsgc_sens2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
860 | pprint("Optimal lsgc specificities:")
861 | pprint(pd.DataFrame(lsgc_spec2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
862 | pprint("Optimal lsgc (sensitivities*specificities)**0.5:")
863 | pprint(
864 | pd.DataFrame((np.array(lsgc_sens2) * np.array(lsgc_spec2)) ** 0.5)
865 | .quantile([0, 0.25, 0.5, 0.75, 1])
866 | .T
867 | )
868 | pprint("Optimal lsgc accuracies:")
869 | pprint(pd.DataFrame(lsgc_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
870 | pprint("Optimal lsgc balanced accuracies:")
871 | pprint(pd.DataFrame(lsgc_bal_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
872 | pprint("Optimal lsgc f1 scores:")
873 | pprint(pd.DataFrame(lsgc_f1wgt2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
874 |
875 |
876 | # Run causal_ccm
877 | pprint("### Run causal_ccm ###")
878 |
879 |
880 | def causal_ccm_loop(d):
881 | causal_ccm_output = causal_ccm.loop_causal_cmm(d.astype(np.float64), tau=1, E=2)
882 | return causal_ccm_output
883 |
884 |
885 | all_causal_ccm_output = process_map(causal_ccm_loop, data_list, max_workers=num_cores)
886 | # Ensure process_map finished before continuing:
887 | # the following will not pass until the lock can be acquired
888 | with ensure_lock(tqdm.auto.tqdm, lock_name="mp_lock") as lk:
889 | pass
890 |
891 |
892 | # Generate pvalue adjacency matricies
893 | permute_lists = list(itertools.permutations(range(data_list[0].shape[1]), 2))
894 | causal_ccm_pvalue_matricies = []
895 | for mlout in all_causal_ccm_output:
896 | cur_pvalue_matrix = np.ones([data_list[0].shape[1], data_list[0].shape[1]])
897 | for X_idx, y_idx in permute_lists:
898 | cur_pvalue_matrix[X_idx, y_idx] = mlout.loc[
899 | ((mlout.X == X_idx) & (mlout.y == y_idx)), "pvalue"
900 | ].iloc[0]
901 | np.fill_diagonal(cur_pvalue_matrix, 1)
902 | causal_ccm_pvalue_matricies.append(cur_pvalue_matrix)
903 |
904 |
905 | # Generate adjacency matricies and check recovery performance
906 | permute_lists = list(itertools.permutations(range(data_list[0].shape[1]), 2))
907 | causal_ccm_adjacency_matricies = []
908 | for mlout in all_causal_ccm_output:
909 | cur_pvalue_adjacency_matrix = np.zeros(
910 | [data_list[0].shape[1], data_list[0].shape[1]]
911 | )
912 | for X_idx, y_idx in permute_lists:
913 | cur_pvalue_adjacency_matrix[X_idx, y_idx] = mlout.loc[
914 | ((mlout.X == X_idx) & (mlout.y == y_idx)), "score"
915 | ].iloc[0]
916 | causal_ccm_adjacency_matricies.append(cur_pvalue_adjacency_matrix)
917 |
918 | causal_ccm_recovery_performance = recovery_performance(
919 | causal_ccm_adjacency_matricies, true_labels_list
920 | )
921 | pprint("causal_ccm recovery performance:")
922 | pprint("Mean: " + str(causal_ccm_recovery_performance.mean()))
923 | pprint(
924 | pd.DataFrame(causal_ccm_recovery_performance).quantile([0, 0.25, 0.5, 0.75, 1]).T
925 | )
926 |
927 | causal_ccm_brier_score_loss = brier_loss_func(
928 | causal_ccm_pvalue_matricies, true_labels_list
929 | )
930 | pprint("causal_ccm brier score:")
931 | pprint("Mean: " + str(causal_ccm_brier_score_loss.mean()))
932 | pprint(pd.DataFrame(causal_ccm_brier_score_loss).quantile([0, 0.25, 0.5, 0.75, 1]).T)
933 |
934 | # Check sensitivity and specificity for the causal_ccm model
935 | (
936 | causal_ccm_sens,
937 | causal_ccm_spec,
938 | causal_ccm_acc,
939 | causal_ccm_bal_acc,
940 | causal_ccm_f1wgt,
941 | ) = calc_metrics(causal_ccm_pvalue_matricies, 0.05)
942 |
943 |
944 | pprint("causal_ccm sensitivities:")
945 | pprint(pd.DataFrame(causal_ccm_sens).quantile([0, 0.25, 0.5, 0.75, 1]).T)
946 | pprint("causal_ccm specificities:")
947 | pprint(pd.DataFrame(causal_ccm_spec).quantile([0, 0.25, 0.5, 0.75, 1]).T)
948 | pprint("causal_ccm (sensitivities*specificities)**0.5:")
949 | pprint(
950 | pd.DataFrame((np.array(causal_ccm_sens) * np.array(causal_ccm_spec)) ** 0.5)
951 | .quantile([0, 0.25, 0.5, 0.75, 1])
952 | .T
953 | )
954 | pprint("causal_ccm accuracies:")
955 | pprint(pd.DataFrame(causal_ccm_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
956 | pprint("causal_ccm balanced accuracies:")
957 | pprint(pd.DataFrame(causal_ccm_bal_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
958 | pprint("causal_ccm f1 scores:")
959 | pprint(pd.DataFrame(causal_ccm_f1wgt).quantile([0, 0.25, 0.5, 0.75, 1]).T)
960 |
961 | optimal_j = 0
962 | best_score = 0
963 | for j in [round(r * 0.01, 2) for r in range(1, 100)]:
964 | (
965 | causal_ccm_sens2,
966 | causal_ccm_spec2,
967 | causal_ccm_acc2,
968 | causal_ccm_bal_acc2,
969 | causal_ccm_f1wgt2,
970 | ) = calc_metrics(causal_ccm_pvalue_matricies, j)
971 | best_score_new = np.median(
972 | (np.array(causal_ccm_sens2) * np.array(causal_ccm_spec2)) ** 0.5
973 | )
974 | if best_score_new > best_score:
975 | best_score = deepcopy(best_score_new)
976 | optimal_j = deepcopy(j)
977 |
978 |
979 | (
980 | causal_ccm_sens2,
981 | causal_ccm_spec2,
982 | causal_ccm_acc2,
983 | causal_ccm_bal_acc2,
984 | causal_ccm_f1wgt2,
985 | ) = calc_metrics(causal_ccm_pvalue_matricies, optimal_j)
986 |
987 |
988 | pprint("Optimal cutoff: " + str(optimal_j))
989 | pprint("Optimal causal_ccm sensitivities:")
990 | pprint(pd.DataFrame(causal_ccm_sens2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
991 | pprint("Optimal causal_ccm specificities:")
992 | pprint(pd.DataFrame(causal_ccm_spec2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
993 | pprint("Optimal causal_ccm (sensitivities*specificities)**0.5:")
994 | pprint(
995 | pd.DataFrame((np.array(causal_ccm_sens2) * np.array(causal_ccm_spec2)) ** 0.5)
996 | .quantile([0, 0.25, 0.5, 0.75, 1])
997 | .T
998 | )
999 | pprint("Optimal causal_ccm accuracies:")
1000 | pprint(pd.DataFrame(causal_ccm_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1001 | pprint("Optimal causal_ccm balanced accuracies:")
1002 | pprint(pd.DataFrame(causal_ccm_bal_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1003 | pprint("Optimal causal_ccm f1 scores:")
1004 | pprint(pd.DataFrame(causal_ccm_f1wgt2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1005 |
1006 |
1007 | # Run pcmci
1008 | pprint("### Run pcmci ###")
1009 |
1010 |
1011 | def pmciloop(d):
1012 | dataframe = pcmci_data_processing.DataFrame(d)
1013 | parcorr = ParCorr()
1014 | pcmci = PCMCI(dataframe=dataframe, cond_ind_test=parcorr, verbosity=0)
1015 | results = pcmci.run_pcmci(
1016 | tau_min=1, tau_max=min_embed_dim - 1, pc_alpha=None, alpha_level=0.05
1017 | )
1018 | pcmci_pvalues_matrix = results["p_matrix"].min(axis=2)
1019 | np.fill_diagonal(pcmci_pvalues_matrix, 1)
1020 | return pcmci_pvalues_matrix
1021 |
1022 |
1023 | pcmci_pvalue_matricies = process_map(pmciloop, data_list, max_workers=num_cores)
1024 | # Ensure process_map finished before continuing:
1025 | # the following will not pass until the lock can be acquired
1026 | with ensure_lock(tqdm.auto.tqdm, lock_name="mp_lock") as lk:
1027 | pass
1028 |
1029 | pcmci_adjacency_matricies = []
1030 | for i in range(len(pcmci_pvalue_matricies)):
1031 | pcmci_pvalues_matrix_oneminus = 1 - pcmci_pvalue_matricies[i]
1032 | np.fill_diagonal(pcmci_pvalues_matrix_oneminus, 0)
1033 | pcmci_adjacency_matricies.append(pcmci_pvalues_matrix_oneminus)
1034 |
1035 | pcmci_recovery_performance = recovery_performance(
1036 | pcmci_adjacency_matricies, true_labels_list
1037 | )
1038 | pprint("pcmci recovery performance:")
1039 | pprint("Mean: " + str(pcmci_recovery_performance.mean()))
1040 | pprint(pd.DataFrame(pcmci_recovery_performance).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1041 |
1042 | pcmci_brier_score_loss = brier_loss_func(pcmci_pvalue_matricies, true_labels_list)
1043 | pprint("pcmci brier score:")
1044 | pprint("Mean: " + str(pcmci_brier_score_loss.mean()))
1045 | pprint(pd.DataFrame(pcmci_brier_score_loss).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1046 |
1047 | # Check sensitivity and specificity for the pcmci model
1048 | pcmci_sens, pcmci_spec, pcmci_acc, pcmci_bal_acc, pcmci_f1wgt = calc_metrics(
1049 | pcmci_pvalue_matricies, 0.05
1050 | )
1051 |
1052 |
1053 | pprint("pcmci sensitivities:")
1054 | pprint(pd.DataFrame(pcmci_sens).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1055 | pprint("pcmci specificities:")
1056 | pprint(pd.DataFrame(pcmci_spec).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1057 | pprint("pcmci (sensitivities*specificities)**0.5:")
1058 | pprint(
1059 | pd.DataFrame((np.array(pcmci_sens) * np.array(pcmci_spec)) ** 0.5)
1060 | .quantile([0, 0.25, 0.5, 0.75, 1])
1061 | .T
1062 | )
1063 | pprint("pcmci accuracies:")
1064 | pprint(pd.DataFrame(pcmci_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1065 | pprint("pcmci balanced accuracies:")
1066 | pprint(pd.DataFrame(pcmci_bal_acc).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1067 | pprint("pcmci f1 scores:")
1068 | pprint(pd.DataFrame(pcmci_f1wgt).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1069 |
1070 | optimal_j = 0
1071 | best_score = 0
1072 | for j in [round(r * 0.01, 2) for r in range(1, 100)]:
1073 | pcmci_sens2, pcmci_spec2, pcmci_acc2, pcmci_bal_acc2, pcmci_f1wgt2 = calc_metrics(
1074 | pcmci_pvalue_matricies, j
1075 | )
1076 | best_score_new = np.median((np.array(pcmci_sens2) * np.array(pcmci_spec2)) ** 0.5)
1077 | if best_score_new > best_score:
1078 | best_score = deepcopy(best_score_new)
1079 | optimal_j = deepcopy(j)
1080 |
1081 |
1082 | pcmci_sens2, pcmci_spec2, pcmci_acc2, pcmci_bal_acc2, pcmci_f1wgt2 = calc_metrics(
1083 | pcmci_pvalue_matricies, optimal_j
1084 | )
1085 |
1086 |
1087 | pprint("Optimal cutoff: " + str(optimal_j))
1088 | pprint("Optimal pcmci sensitivities:")
1089 | pprint(pd.DataFrame(pcmci_sens2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1090 | pprint("Optimal pcmci specificities:")
1091 | pprint(pd.DataFrame(pcmci_spec2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1092 | pprint("Optimal pcmci (sensitivities*specificities)**0.5:")
1093 | pprint(
1094 | pd.DataFrame((np.array(pcmci_sens2) * np.array(pcmci_spec2)) ** 0.5)
1095 | .quantile([0, 0.25, 0.5, 0.75, 1])
1096 | .T
1097 | )
1098 | pprint("Optimal pcmci accuracies:")
1099 | pprint(pd.DataFrame(pcmci_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1100 | pprint("Optimal pcmci balanced accuracies:")
1101 | pprint(pd.DataFrame(pcmci_bal_acc2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1102 | pprint("Optimal pcmci f1 scores:")
1103 | pprint(pd.DataFrame(pcmci_f1wgt2).quantile([0, 0.25, 0.5, 0.75, 1]).T)
1104 |
1105 |
1106 | df_all_recovery_performance = pd.DataFrame(
1107 | np.array(
1108 | [
1109 | mlcausality_recovery_performance,
1110 | lsgc_recovery_performance,
1111 | causal_ccm_recovery_performance,
1112 | pcmci_recovery_performance,
1113 | ]
1114 | ).T,
1115 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1116 | )
1117 | with open(
1118 | "pickled_data/" + network_to_check + "_auc_" + n_time_samples_str + ".pickle", "wb"
1119 | ) as f: # should be 'wb' rather than 'w'
1120 | pickle.dump(df_all_recovery_performance, f)
1121 |
1122 |
1123 | df_all_brier_score_loss = pd.DataFrame(
1124 | np.array(
1125 | [
1126 | mlcausality_brier_score_loss,
1127 | lsgc_brier_score_loss,
1128 | causal_ccm_brier_score_loss,
1129 | pcmci_brier_score_loss,
1130 | ]
1131 | ).T,
1132 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1133 | )
1134 | with open(
1135 | "pickled_data/" + network_to_check + "_brier_" + n_time_samples_str + ".pickle",
1136 | "wb",
1137 | ) as f: # should be 'wb' rather than 'w'
1138 | pickle.dump(df_all_brier_score_loss, f)
1139 |
1140 |
1141 | df_all_sensitivities = pd.DataFrame(
1142 | np.array(
1143 | [
1144 | mlc_sens,
1145 | lsgc_sens,
1146 | causal_ccm_sens,
1147 | pcmci_sens,
1148 | ]
1149 | ).T,
1150 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1151 | )
1152 | with open(
1153 | "pickled_data/"
1154 | + network_to_check
1155 | + "_sensitivity_"
1156 | + n_time_samples_str
1157 | + ".pickle",
1158 | "wb",
1159 | ) as f: # should be 'wb' rather than 'w'
1160 | pickle.dump(df_all_sensitivities, f)
1161 |
1162 |
1163 | df_all_specificities = pd.DataFrame(
1164 | np.array(
1165 | [
1166 | mlc_spec,
1167 | lsgc_spec,
1168 | causal_ccm_spec,
1169 | pcmci_spec,
1170 | ]
1171 | ).T,
1172 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1173 | )
1174 | with open(
1175 | "pickled_data/"
1176 | + network_to_check
1177 | + "_specificity_"
1178 | + n_time_samples_str
1179 | + ".pickle",
1180 | "wb",
1181 | ) as f: # should be 'wb' rather than 'w'
1182 | pickle.dump(df_all_specificities, f)
1183 |
1184 |
1185 | df_all_gmean = pd.DataFrame(
1186 | np.array(
1187 | [
1188 | list((np.array(mlc_sens) * np.array(mlc_spec)) ** (1 / 2)),
1189 | list((np.array(lsgc_sens) * np.array(lsgc_spec)) ** (1 / 2)),
1190 | list((np.array(causal_ccm_sens) * np.array(causal_ccm_spec)) ** (1 / 2)),
1191 | list((np.array(pcmci_sens) * np.array(pcmci_spec)) ** (1 / 2)),
1192 | ]
1193 | ).T,
1194 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1195 | )
1196 | with open(
1197 | "pickled_data/" + network_to_check + "_gmean_" + n_time_samples_str + ".pickle",
1198 | "wb",
1199 | ) as f: # should be 'wb' rather than 'w'
1200 | pickle.dump(df_all_gmean, f)
1201 |
1202 |
1203 | df_all_accuracies = pd.DataFrame(
1204 | np.array([mlc_acc, lsgc_acc, causal_ccm_acc, pcmci_acc]).T,
1205 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1206 | )
1207 | with open(
1208 | "pickled_data/" + network_to_check + "_accuracy_" + n_time_samples_str + ".pickle",
1209 | "wb",
1210 | ) as f: # should be 'wb' rather than 'w'
1211 | pickle.dump(df_all_accuracies, f)
1212 |
1213 |
1214 | df_all_balanced_accuracies = pd.DataFrame(
1215 | np.array(
1216 | [
1217 | mlc_bal_acc,
1218 | lsgc_bal_acc,
1219 | causal_ccm_bal_acc,
1220 | pcmci_bal_acc,
1221 | ]
1222 | ).T,
1223 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1224 | )
1225 | with open(
1226 | "pickled_data/"
1227 | + network_to_check
1228 | + "_balanced_accuracy_"
1229 | + n_time_samples_str
1230 | + ".pickle",
1231 | "wb",
1232 | ) as f: # should be 'wb' rather than 'w'
1233 | pickle.dump(df_all_balanced_accuracies, f)
1234 |
1235 |
1236 | df_all_f1wgt = pd.DataFrame(
1237 | np.array([mlc_f1wgt, lsgc_f1wgt, causal_ccm_f1wgt, pcmci_f1wgt]).T,
1238 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1239 | )
1240 | with open(
1241 | "pickled_data/" + network_to_check + "_f1wgt_" + n_time_samples_str + ".pickle",
1242 | "wb",
1243 | ) as f: # should be 'wb' rather than 'w'
1244 | pickle.dump(df_all_f1wgt, f)
1245 |
1246 |
1247 | df_all_sensitivities2 = pd.DataFrame(
1248 | np.array(
1249 | [
1250 | mlc_sens2,
1251 | lsgc_sens2,
1252 | causal_ccm_sens2,
1253 | pcmci_sens2,
1254 | ]
1255 | ).T,
1256 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1257 | )
1258 | with open(
1259 | "pickled_data/"
1260 | + network_to_check
1261 | + "_sensitivity2_"
1262 | + n_time_samples_str
1263 | + ".pickle",
1264 | "wb",
1265 | ) as f: # should be 'wb' rather than 'w'
1266 | pickle.dump(df_all_sensitivities2, f)
1267 |
1268 |
1269 | df_all_specificities2 = pd.DataFrame(
1270 | np.array(
1271 | [
1272 | mlc_spec2,
1273 | lsgc_spec2,
1274 | causal_ccm_spec2,
1275 | pcmci_spec2,
1276 | ]
1277 | ).T,
1278 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1279 | )
1280 | with open(
1281 | "pickled_data/"
1282 | + network_to_check
1283 | + "_specificity2_"
1284 | + n_time_samples_str
1285 | + ".pickle",
1286 | "wb",
1287 | ) as f: # should be 'wb' rather than 'w'
1288 | pickle.dump(df_all_specificities2, f)
1289 |
1290 |
1291 | df_all_gmean2 = pd.DataFrame(
1292 | np.array(
1293 | [
1294 | list((np.array(mlc_sens2) * np.array(mlc_spec2)) ** (1 / 2)),
1295 | list((np.array(lsgc_sens2) * np.array(lsgc_spec2)) ** (1 / 2)),
1296 | list((np.array(causal_ccm_sens2) * np.array(causal_ccm_spec2)) ** (1 / 2)),
1297 | list((np.array(pcmci_sens2) * np.array(pcmci_spec2)) ** (1 / 2)),
1298 | ]
1299 | ).T,
1300 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1301 | )
1302 | with open(
1303 | "pickled_data/" + network_to_check + "_gmean2_" + n_time_samples_str + ".pickle",
1304 | "wb",
1305 | ) as f: # should be 'wb' rather than 'w'
1306 | pickle.dump(df_all_gmean2, f)
1307 |
1308 |
1309 | df_all_accuracies2 = pd.DataFrame(
1310 | np.array([mlc_acc2, lsgc_acc2, causal_ccm_acc2, pcmci_acc2]).T,
1311 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1312 | )
1313 | with open(
1314 | "pickled_data/" + network_to_check + "_accuracy2_" + n_time_samples_str + ".pickle",
1315 | "wb",
1316 | ) as f: # should be 'wb' rather than 'w'
1317 | pickle.dump(df_all_accuracies2, f)
1318 |
1319 |
1320 | df_all_balanced_accuracies2 = pd.DataFrame(
1321 | np.array(
1322 | [
1323 | mlc_bal_acc2,
1324 | lsgc_bal_acc2,
1325 | causal_ccm_bal_acc2,
1326 | pcmci_bal_acc2,
1327 | ]
1328 | ).T,
1329 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1330 | )
1331 | with open(
1332 | "pickled_data/"
1333 | + network_to_check
1334 | + "_balanced_accuracy2_"
1335 | + n_time_samples_str
1336 | + ".pickle",
1337 | "wb",
1338 | ) as f: # should be 'wb' rather than 'w'
1339 | pickle.dump(df_all_balanced_accuracies2, f)
1340 |
1341 |
1342 | df_all_f1wgt2 = pd.DataFrame(
1343 | np.array([mlc_f1wgt2, lsgc_f1wgt2, causal_ccm_f1wgt2, pcmci_f1wgt2]).T,
1344 | columns=["MLC", "lsNGC", "LM", "PCMCI"],
1345 | )
1346 | with open(
1347 | "pickled_data/" + network_to_check + "_f1wgt2_" + n_time_samples_str + ".pickle",
1348 | "wb",
1349 | ) as f: # should be 'wb' rather than 'w'
1350 | pickle.dump(df_all_f1wgt2, f)
1351 |
1352 |
1353 | pprint("Program finished running!")
1354 |
--------------------------------------------------------------------------------