dots-causal 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dots_causal/__init__.py +21 -0
- dots_causal/_compat.py +12 -0
- dots_causal/dots.py +283 -0
- dots_causal/eval_utils.py +256 -0
- dots_causal/gaussian_diffusion.py +1133 -0
- dots_causal/nn.py +59 -0
- dots_causal/pruning.py +82 -0
- dots_causal/r_scripts/cam_pruning.R +13 -0
- dots_causal/r_scripts/pruning.R +27 -0
- dots_causal/r_scripts/selGam.R +25 -0
- dots_causal/r_scripts/train_gam.R +57 -0
- dots_causal/utils.py +93 -0
- dots_causal-0.1.0.dist-info/METADATA +127 -0
- dots_causal-0.1.0.dist-info/RECORD +17 -0
- dots_causal-0.1.0.dist-info/WHEEL +5 -0
- dots_causal-0.1.0.dist-info/licenses/LICENSE +21 -0
- dots_causal-0.1.0.dist-info/top_level.txt +1 -0
dots_causal/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""DOTS: Diffusion Ordered Temporal Structure.
|
|
2
|
+
|
|
3
|
+
Causal structure learning from time series, as described in
|
|
4
|
+
"Causal Ordering for Structure Learning from Time Series" (TMLR 2025).
|
|
5
|
+
"""
|
|
6
|
+
from .dots import DOTS, DiffBase
|
|
7
|
+
from .eval_utils import perform_eval, read_json
|
|
8
|
+
from .pruning import RNotFoundError
|
|
9
|
+
from .utils import apply_temporal_constraint
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DOTS",
|
|
15
|
+
"DiffBase",
|
|
16
|
+
"perform_eval",
|
|
17
|
+
"read_json",
|
|
18
|
+
"apply_temporal_constraint",
|
|
19
|
+
"RNotFoundError",
|
|
20
|
+
"__version__",
|
|
21
|
+
]
|
dots_causal/_compat.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Compatibility shims.
|
|
2
|
+
|
|
3
|
+
`functorch` was merged into PyTorch as `torch.func` (PyTorch >= 2.0).
|
|
4
|
+
Prefer `torch.func` and fall back to the standalone `functorch` package
|
|
5
|
+
for older PyTorch installs.
|
|
6
|
+
"""
|
|
7
|
+
try:
|
|
8
|
+
from torch.func import vmap, jacrev, jacfwd
|
|
9
|
+
except ImportError: # pragma: no cover - PyTorch < 2.0
|
|
10
|
+
from functorch import vmap, jacrev, jacfwd
|
|
11
|
+
|
|
12
|
+
__all__ = ["vmap", "jacrev", "jacfwd"]
|
dots_causal/dots.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from ._compat import vmap, jacrev, jacfwd
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
from itertools import permutations
|
|
9
|
+
from sklearn.mixture import GaussianMixture
|
|
10
|
+
|
|
11
|
+
from .gaussian_diffusion import GaussianDiffusion, UniformSampler, get_named_beta_schedule, \
|
|
12
|
+
LossType, ModelMeanType, ModelVarType
|
|
13
|
+
from .nn import DiffMLP
|
|
14
|
+
from .pruning import cam_pruning
|
|
15
|
+
from .utils import full_DAG, get_soft_transitive_closure_from_orderings, apply_temporal_constraint
|
|
16
|
+
|
|
17
|
+
class DiffBase():
|
|
18
|
+
def __init__(self, n_nodes, masking = True, residue= True,
|
|
19
|
+
epochs: int = int(3e3), batch_size : int = 1024, learning_rate : float = 0.001, nn_depth_mul=3, steps=1e2, esw=300):
|
|
20
|
+
self.n_nodes = n_nodes
|
|
21
|
+
assert self.n_nodes > 1, "Not enough nodes, make sure the dataset contain at least 2 variables (columns)."
|
|
22
|
+
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
|
23
|
+
|
|
24
|
+
## Diffusion parameters
|
|
25
|
+
self.n_steps = int(steps)
|
|
26
|
+
betas = get_named_beta_schedule(schedule_name = "linear",
|
|
27
|
+
num_diffusion_timesteps = self.n_steps, scale = 1,
|
|
28
|
+
beta_start = 0.0001, beta_end = 0.02)
|
|
29
|
+
self.gaussian_diffusion = GaussianDiffusion(betas = betas,
|
|
30
|
+
loss_type = LossType.MSE,
|
|
31
|
+
model_mean_type= ModelMeanType.EPSILON,#START_X,EPSILON
|
|
32
|
+
model_var_type= ModelVarType.FIXED_LARGE,
|
|
33
|
+
rescale_timesteps = True,
|
|
34
|
+
)
|
|
35
|
+
self.schedule_sampler = UniformSampler(self.gaussian_diffusion)
|
|
36
|
+
|
|
37
|
+
## Diffusion training
|
|
38
|
+
self.epochs = epochs
|
|
39
|
+
self.batch_size = int(batch_size)
|
|
40
|
+
self.model = DiffMLP(n_nodes, depth_mul= nn_depth_mul).to(self.device)
|
|
41
|
+
n_trainable_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
|
|
42
|
+
print(f'MLP number of parameters {n_trainable_params}')
|
|
43
|
+
self.model.float()
|
|
44
|
+
self.opt = torch.optim.Adam(self.model.parameters(), float(learning_rate))
|
|
45
|
+
self.val_diffusion_loss = []
|
|
46
|
+
self.best_loss = float("inf")
|
|
47
|
+
self.early_stopping_wait = esw
|
|
48
|
+
|
|
49
|
+
## Topological Ordering
|
|
50
|
+
self.n_votes = 3
|
|
51
|
+
self.masking = masking
|
|
52
|
+
self.residue = residue
|
|
53
|
+
self.sorting = (not masking) and (not residue)
|
|
54
|
+
## Pruning
|
|
55
|
+
self.cutoff = 0.001
|
|
56
|
+
|
|
57
|
+
def fit(self, X, constraint=False, inst_const=True, nb_timesteps=-1, nb_variables=-1, nb_orderings=10):
|
|
58
|
+
X = self.normalize_data(X)
|
|
59
|
+
self.train_score(X)
|
|
60
|
+
order = self.topological_ordering(X)
|
|
61
|
+
adj = self.pruning(order, X.detach().cpu().numpy())
|
|
62
|
+
if constraint:
|
|
63
|
+
adj = apply_temporal_constraint(adj, nb_timesteps, nb_variables, inst_const)
|
|
64
|
+
return adj
|
|
65
|
+
|
|
66
|
+
def normalize_data(self, X):
|
|
67
|
+
X = (X - X.mean(0, keepdims = True)) / X.std(0, keepdims = True)
|
|
68
|
+
X = torch.FloatTensor(X).to(self.device)
|
|
69
|
+
return X
|
|
70
|
+
|
|
71
|
+
def pruning(self, order, X):
|
|
72
|
+
return cam_pruning(full_DAG(order), X, self.cutoff)
|
|
73
|
+
|
|
74
|
+
def pruning_adj(self, adj, X):
|
|
75
|
+
return cam_pruning(adj, X, self.cutoff)
|
|
76
|
+
|
|
77
|
+
def train_score(self, X, fixed = None):
|
|
78
|
+
if fixed is not None:
|
|
79
|
+
self.epochs = fixed
|
|
80
|
+
best_model_state_epoch = 300
|
|
81
|
+
self.model.train()
|
|
82
|
+
n_samples = X.shape[0]
|
|
83
|
+
self.batch_size = min(n_samples, self.batch_size)
|
|
84
|
+
val_ratio = 0.2
|
|
85
|
+
val_size = int(n_samples * val_ratio)
|
|
86
|
+
train_size = n_samples - val_size
|
|
87
|
+
X = X.to(self.device)
|
|
88
|
+
X_train, X_val = X[:train_size],X[train_size:]
|
|
89
|
+
data_loader_val = torch.utils.data.DataLoader(X_val, min(val_size, self.batch_size))
|
|
90
|
+
data_loader = torch.utils.data.DataLoader(X_train, min(train_size, self.batch_size), drop_last= True)
|
|
91
|
+
pbar = tqdm(range(self.epochs), desc = "Training Epoch")
|
|
92
|
+
for epoch in pbar:
|
|
93
|
+
loss_per_step = []
|
|
94
|
+
for steps, x_start in enumerate(data_loader):
|
|
95
|
+
# apply noising and masking
|
|
96
|
+
x_start = x_start.float().to(self.device)
|
|
97
|
+
t, weights = self.schedule_sampler.sample(x_start.shape[0], self.device)
|
|
98
|
+
noise = torch.randn_like(x_start).to(self.device)
|
|
99
|
+
x_t = self.gaussian_diffusion.q_sample(x_start, t, noise=noise)
|
|
100
|
+
# get loss function
|
|
101
|
+
model_output = self.model(x_t, self.gaussian_diffusion._scale_timesteps(t))
|
|
102
|
+
diffusion_losses = (noise - model_output) ** 2
|
|
103
|
+
diffusion_loss = (diffusion_losses.mean(dim=list(range(1, len(diffusion_losses.shape)))) * weights).mean()
|
|
104
|
+
loss_per_step.append(diffusion_loss.item())
|
|
105
|
+
self.opt.zero_grad()
|
|
106
|
+
diffusion_loss.backward()
|
|
107
|
+
self.opt.step()
|
|
108
|
+
if fixed is None:
|
|
109
|
+
if epoch % 10 == 0 and epoch > best_model_state_epoch:
|
|
110
|
+
with torch.no_grad():
|
|
111
|
+
loss_per_step_val = []
|
|
112
|
+
for steps, x_start in enumerate(data_loader_val):
|
|
113
|
+
t, weights = self.schedule_sampler.sample(x_start.shape[0], self.device)
|
|
114
|
+
noise = torch.randn_like(x_start).to(self.device)
|
|
115
|
+
x_t = self.gaussian_diffusion.q_sample(x_start, t, noise=noise)
|
|
116
|
+
model_output = self.model(x_t, self.gaussian_diffusion._scale_timesteps(t))
|
|
117
|
+
diffusion_losses = (noise - model_output) ** 2
|
|
118
|
+
diffusion_loss = (diffusion_losses.mean(dim=list(range(1, len(diffusion_losses.shape)))) * weights).mean()
|
|
119
|
+
loss_per_step_val.append(diffusion_loss.item())
|
|
120
|
+
epoch_val_loss = np.mean(loss_per_step_val)
|
|
121
|
+
|
|
122
|
+
if self.best_loss > epoch_val_loss:
|
|
123
|
+
self.best_loss = epoch_val_loss
|
|
124
|
+
best_model_state = deepcopy(self.model.state_dict())
|
|
125
|
+
best_model_state_epoch = epoch
|
|
126
|
+
pbar.set_postfix({'Epoch Loss': epoch_val_loss})
|
|
127
|
+
|
|
128
|
+
if epoch - best_model_state_epoch > self.early_stopping_wait: # Early stopping
|
|
129
|
+
break
|
|
130
|
+
if fixed is None:
|
|
131
|
+
print(f"Early stoping at epoch {epoch}")
|
|
132
|
+
print(f"Best model at epoch {best_model_state_epoch} with loss {self.best_loss}")
|
|
133
|
+
self.model.load_state_dict(best_model_state)
|
|
134
|
+
|
|
135
|
+
def compute_hessian_get_leaves(self, X, steps_list, eval_batch_size, order, active_nodes):
|
|
136
|
+
leaves_per_step = list()
|
|
137
|
+
for step in steps_list:
|
|
138
|
+
model_fn_functorch = self.get_model_function_with_residue(step, active_nodes, order)
|
|
139
|
+
data_loader = torch.utils.data.DataLoader(X, eval_batch_size, drop_last=True, shuffle=False)
|
|
140
|
+
hessian_diag_var = self.compute_hessian_diagonal(data_loader, active_nodes, model_fn_functorch)
|
|
141
|
+
leaves = self.get_leaves(hessian_diag_var)
|
|
142
|
+
leaves_per_step.append(leaves)
|
|
143
|
+
# get intersection of leaves in leaves_per_step which is a list of lists
|
|
144
|
+
all_leaves = [item for sublist in leaves_per_step for item in sublist]
|
|
145
|
+
leaves_count = Counter(all_leaves)
|
|
146
|
+
sorted_leaves = sorted(leaves_count, key=leaves_count.get, reverse=True)
|
|
147
|
+
unique_leaves = sorted_leaves[:2] if len(sorted_leaves) > 2 else sorted_leaves
|
|
148
|
+
print(f'Unique leaves: {unique_leaves}')
|
|
149
|
+
# get numbers that appear more than once
|
|
150
|
+
# leaves_appearing_more_than_once = [item for item, count in Counter(all_leaves).items() if count > 1]
|
|
151
|
+
inner_order = [active_nodes[n] for n in unique_leaves]
|
|
152
|
+
return unique_leaves, inner_order
|
|
153
|
+
|
|
154
|
+
def topological_ordering(self, X, step = None, eval_batch_size = None):
|
|
155
|
+
|
|
156
|
+
if eval_batch_size is None:
|
|
157
|
+
eval_batch_size = self.batch_size
|
|
158
|
+
eval_batch_size = min(eval_batch_size, X.shape[0])
|
|
159
|
+
|
|
160
|
+
X = X[:self.batch_size]
|
|
161
|
+
|
|
162
|
+
self.model.eval()
|
|
163
|
+
order = []
|
|
164
|
+
active_nodes = list(range(self.n_nodes))
|
|
165
|
+
|
|
166
|
+
steps_list = [step] if step is not None else range(0, self.n_steps+1, self.n_steps//self.n_votes)
|
|
167
|
+
if self.sorting:
|
|
168
|
+
steps_list = [self.n_steps//2]
|
|
169
|
+
pbar = tqdm(range(self.n_nodes-1), desc = "Nodes ordered ")
|
|
170
|
+
leaf = None
|
|
171
|
+
for jac_step in pbar:
|
|
172
|
+
leaves = []
|
|
173
|
+
for i, steps in enumerate(steps_list):
|
|
174
|
+
data_loader = torch.utils.data.DataLoader(X, eval_batch_size, drop_last = True)
|
|
175
|
+
model_fn_functorch = self.get_model_function_with_residue(steps, active_nodes, order)
|
|
176
|
+
hessian_diag_var = self.compute_hessian_diagonal(data_loader, active_nodes, model_fn_functorch)
|
|
177
|
+
leaf_ = self.get_leaf(hessian_diag_var)
|
|
178
|
+
if self.sorting:
|
|
179
|
+
order = leaf_.tolist()
|
|
180
|
+
order.reverse()
|
|
181
|
+
return order
|
|
182
|
+
leaves.append(leaf_)
|
|
183
|
+
|
|
184
|
+
leaf = Counter(leaves).most_common(1)[0][0]
|
|
185
|
+
leaf_global = active_nodes[leaf]
|
|
186
|
+
order.append(leaf_global)
|
|
187
|
+
active_nodes.pop(leaf)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
order.append(active_nodes[0])
|
|
191
|
+
order.reverse()
|
|
192
|
+
|
|
193
|
+
return order
|
|
194
|
+
|
|
195
|
+
def get_model_function_with_residue(self, step, active_nodes, order):
|
|
196
|
+
t_functorch = (torch.ones(1)*step).long().to(self.device) # test if other ts or random ts are better, self.n_steps
|
|
197
|
+
get_score_active = lambda x: self.model(x, self.gaussian_diffusion._scale_timesteps(t_functorch))[:,active_nodes]
|
|
198
|
+
get_score_previous_leaves = lambda x: self.model(x, self.gaussian_diffusion._scale_timesteps(t_functorch))[:,order]
|
|
199
|
+
def model_fn_functorch(X):
|
|
200
|
+
score_active = get_score_active(X).squeeze()
|
|
201
|
+
if self.residue and len(order) > 0:
|
|
202
|
+
score_previous_leaves = get_score_previous_leaves(X).squeeze()
|
|
203
|
+
hessian_ = jacfwd(get_score_previous_leaves)(X).squeeze()
|
|
204
|
+
if len(order) == 1:
|
|
205
|
+
hessian_, score_previous_leaves = hessian_.unsqueeze(0), score_previous_leaves.unsqueeze(0)
|
|
206
|
+
score_active += torch.einsum("i,ij -> j", score_previous_leaves/ hessian_[:, order].diag(),hessian_[:, active_nodes])
|
|
207
|
+
return score_active
|
|
208
|
+
return model_fn_functorch
|
|
209
|
+
|
|
210
|
+
def get_masked(self, x, active_nodes):
|
|
211
|
+
dropout_mask = torch.zeros_like(x).to(self.device)
|
|
212
|
+
dropout_mask[:, active_nodes] = 1
|
|
213
|
+
return (x * dropout_mask).float()
|
|
214
|
+
|
|
215
|
+
def compute_hessian_diagonal(self, data_loader, active_nodes, model_fn_functorch):
|
|
216
|
+
hessian = []
|
|
217
|
+
for x_batch in data_loader:
|
|
218
|
+
x_batch_dropped = self.get_masked(x_batch, active_nodes) if self.masking else x_batch
|
|
219
|
+
hessian_ = vmap(jacrev(model_fn_functorch),randomness='same')(x_batch_dropped.unsqueeze(1)).squeeze()
|
|
220
|
+
hessian.append(hessian_[...,active_nodes].detach().cpu().numpy())
|
|
221
|
+
hessian = np.concatenate(hessian, 0)
|
|
222
|
+
hessian_var = hessian.var(0)
|
|
223
|
+
hessian_var_diag = hessian_var.diagonal()
|
|
224
|
+
return hessian_var_diag
|
|
225
|
+
|
|
226
|
+
def get_leaf(self, hess_var):
|
|
227
|
+
var_sorted_nodes = np.argsort(hess_var)
|
|
228
|
+
if self.sorting:
|
|
229
|
+
return var_sorted_nodes
|
|
230
|
+
leaf_current = var_sorted_nodes[0]
|
|
231
|
+
return leaf_current
|
|
232
|
+
|
|
233
|
+
def get_leaves(self, hess_var):
|
|
234
|
+
# Assuming 'data' is your numpy array of non-negative floats
|
|
235
|
+
data = hess_var.reshape(-1, 1) # Reshape data for sklearn (if necessary)
|
|
236
|
+
# Range of components to try
|
|
237
|
+
n_components_range = range(2, max(data.shape[0]//2,3))
|
|
238
|
+
|
|
239
|
+
lowest_bic = np.inf
|
|
240
|
+
best_gmm = None
|
|
241
|
+
|
|
242
|
+
# Fit GMMs with different numbers of components and select the best one
|
|
243
|
+
for n_components in n_components_range:
|
|
244
|
+
gmm = GaussianMixture(n_components=n_components, random_state=0)
|
|
245
|
+
gmm.fit(data)
|
|
246
|
+
bic = gmm.bic(data)
|
|
247
|
+
if bic < lowest_bic:
|
|
248
|
+
lowest_bic = bic
|
|
249
|
+
best_gmm = gmm
|
|
250
|
+
|
|
251
|
+
# Extract the means of the components
|
|
252
|
+
component_means = best_gmm.means_.flatten()
|
|
253
|
+
|
|
254
|
+
# Identify the component with the lowest mean
|
|
255
|
+
min_mean_component = np.argmin(component_means)
|
|
256
|
+
|
|
257
|
+
# Predict component assignments for each data point
|
|
258
|
+
component_assignments = best_gmm.predict(data)
|
|
259
|
+
|
|
260
|
+
# Select data points assigned to the component with the lowest mean
|
|
261
|
+
selected_indices = np.where(component_assignments == min_mean_component)[0]
|
|
262
|
+
# select the 2 smallest data components with selected_indices
|
|
263
|
+
selected_indices = np.argsort(data[selected_indices].flatten())[:2]
|
|
264
|
+
return selected_indices
|
|
265
|
+
|
|
266
|
+
class DOTS(DiffBase):
|
|
267
|
+
def __init__(self, n_nodes, masking = True, residue= True,
|
|
268
|
+
epochs: int = int(3e3), batch_size : int = 1024, learning_rate : float = 0.001, nn_depth_mul=3, steps=1e2, esw=300):
|
|
269
|
+
super().__init__(n_nodes, masking, residue, epochs, batch_size, learning_rate, nn_depth_mul, steps, esw)
|
|
270
|
+
|
|
271
|
+
def fit(self, X, constraint=True, inst_const=True, nb_timesteps=-1, nb_variables=-1, nb_orderings=10):
|
|
272
|
+
X = self.normalize_data(X)
|
|
273
|
+
self.train_score(X)
|
|
274
|
+
steps_list = list(range(0, self.n_steps+1, self.n_steps//nb_orderings))
|
|
275
|
+
orders = list()
|
|
276
|
+
for step in steps_list:
|
|
277
|
+
order = self.topological_ordering(X, step=step)
|
|
278
|
+
orders.append(order)
|
|
279
|
+
adj_matrix = get_soft_transitive_closure_from_orderings(orders)
|
|
280
|
+
adj = self.pruning_adj(adj_matrix.astype(int), X.detach().cpu().numpy())
|
|
281
|
+
if constraint:
|
|
282
|
+
adj = apply_temporal_constraint(adj, nb_timesteps, nb_variables, inst_const)
|
|
283
|
+
return adj
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import networkx as nx
|
|
4
|
+
from networkx.readwrite import json_graph
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
|
|
7
|
+
# Temporal graph to summary graph
|
|
8
|
+
def tgraph_to_graph(tg):
|
|
9
|
+
g = nx.DiGraph()
|
|
10
|
+
g.add_nodes_from(tg.nodes)
|
|
11
|
+
for cause, effects in tg.adj.items():
|
|
12
|
+
for effect, _ in effects.items():
|
|
13
|
+
g.add_edges_from([(cause, effect)])
|
|
14
|
+
return g
|
|
15
|
+
|
|
16
|
+
# Temporal graph to a list representation
|
|
17
|
+
# (for evaluation purposes)
|
|
18
|
+
def tgraph_to_list(tg):
|
|
19
|
+
list_tg = []
|
|
20
|
+
for cause, effects in tg.adj.items():
|
|
21
|
+
for effect, eattr in effects.items():
|
|
22
|
+
t_list = eattr['time']
|
|
23
|
+
for t in t_list:
|
|
24
|
+
list_tg.append((cause, effect, t))
|
|
25
|
+
return list_tg
|
|
26
|
+
|
|
27
|
+
def process_parents(parents):
|
|
28
|
+
pa_t = defaultdict(list)
|
|
29
|
+
for p in parents:
|
|
30
|
+
# X1_lag0
|
|
31
|
+
p_split = p.split('_')
|
|
32
|
+
name = p_split[0]
|
|
33
|
+
# 'lag' is always 3 chars, followed by a number
|
|
34
|
+
lag = int(p_split[1][3:])
|
|
35
|
+
pa_t[name].append(lag)
|
|
36
|
+
return pa_t
|
|
37
|
+
|
|
38
|
+
def tadjmat_to_tgraph(adjmat, nodes):
|
|
39
|
+
g_conv = nx.DiGraph()
|
|
40
|
+
# use non-lagged names
|
|
41
|
+
g_conv.add_nodes_from(nodes)
|
|
42
|
+
n_features = len(nodes)
|
|
43
|
+
|
|
44
|
+
# check only parents of non-lagged nodes
|
|
45
|
+
for child in adjmat.columns[:n_features]:
|
|
46
|
+
child_name = child.split('_')[0]
|
|
47
|
+
pa = adjmat.loc[adjmat[child] > 0, child].index.to_list()
|
|
48
|
+
pa_d = process_parents(pa)
|
|
49
|
+
for pa_key in pa_d:
|
|
50
|
+
g_conv.add_edges_from([(pa_key, child_name)])
|
|
51
|
+
g_conv.edges[pa_key, child_name]['time'] = pa_d[pa_key]
|
|
52
|
+
return g_conv
|
|
53
|
+
|
|
54
|
+
def graph_to_dict(g):
|
|
55
|
+
return json_graph.adjacency_data(g)
|
|
56
|
+
|
|
57
|
+
def dict_to_graph(d):
|
|
58
|
+
return json_graph.adjacency_graph(d)
|
|
59
|
+
|
|
60
|
+
def read_json(filepath):
|
|
61
|
+
with open(filepath, 'r') as f:
|
|
62
|
+
data = json.load(f)
|
|
63
|
+
return data
|
|
64
|
+
|
|
65
|
+
def get_result_adjmat(adjmat, nodes):
|
|
66
|
+
# convert adjmat to (temporal) DiGraph (window graph)
|
|
67
|
+
tghat = tadjmat_to_tgraph(adjmat, nodes)
|
|
68
|
+
|
|
69
|
+
# summary graph
|
|
70
|
+
ghat = tgraph_to_graph(tghat)
|
|
71
|
+
tg_d = graph_to_dict(tghat)
|
|
72
|
+
g_d = graph_to_dict(ghat)
|
|
73
|
+
|
|
74
|
+
d = {}
|
|
75
|
+
d['tgraph'] = tg_d
|
|
76
|
+
d['graph'] = g_d
|
|
77
|
+
|
|
78
|
+
return d
|
|
79
|
+
|
|
80
|
+
def perform_eval(g_true, adj_hat, cols):
|
|
81
|
+
g_hat = get_result_adjmat(adj_hat, cols)
|
|
82
|
+
|
|
83
|
+
me = ModelEvaluation(dict_to_graph(g_hat['graph']))
|
|
84
|
+
g_results = me.evaluation(dict_to_graph(g_true['graph']))
|
|
85
|
+
|
|
86
|
+
tme = TemporalModelEvaluation(dict_to_graph(g_hat['tgraph']))
|
|
87
|
+
tg_results = tme.evaluation(dict_to_graph(g_true['tgraph']))
|
|
88
|
+
|
|
89
|
+
cols = []
|
|
90
|
+
vals = []
|
|
91
|
+
|
|
92
|
+
for key, value in g_results.items():
|
|
93
|
+
# 's_' for summary graph
|
|
94
|
+
cols.append(f's_{key}')
|
|
95
|
+
vals.append(value)
|
|
96
|
+
|
|
97
|
+
for key, value in tg_results.items():
|
|
98
|
+
# 'w_' for window graph
|
|
99
|
+
cols.append(f'w_{key}')
|
|
100
|
+
vals.append(value)
|
|
101
|
+
|
|
102
|
+
df = pd.DataFrame([vals], columns=cols)
|
|
103
|
+
|
|
104
|
+
return df
|
|
105
|
+
|
|
106
|
+
class ModelEvaluation:
|
|
107
|
+
def __init__(self, ghat):
|
|
108
|
+
super(ModelEvaluation, self).__init__()
|
|
109
|
+
self.ghat = ghat
|
|
110
|
+
|
|
111
|
+
# [all_oriented, all_adjacent]
|
|
112
|
+
def evaluation(self, gtrue, mode="all_oriented"):
|
|
113
|
+
all_results = {}
|
|
114
|
+
|
|
115
|
+
all_results['precision'] = self._precision(gtrue, method=mode)
|
|
116
|
+
all_results['recall'] = self._recall(gtrue, method=mode)
|
|
117
|
+
all_results['f1'] = self._f1(gtrue, method=mode)
|
|
118
|
+
|
|
119
|
+
return all_results
|
|
120
|
+
|
|
121
|
+
def _hamming_distance(self, gtrue):
|
|
122
|
+
# todo: check if it's correct (maybe it's not truely hamming distance)
|
|
123
|
+
res = nx.graph_edit_distance(self.ghat, gtrue)
|
|
124
|
+
return 1 - res/max(self.ghat.number_of_edges(), gtrue.number_of_edges())
|
|
125
|
+
|
|
126
|
+
def _tp(self, gtrue, method="all_oriented"): # oriented or adjacent
|
|
127
|
+
if method == "all_oriented":
|
|
128
|
+
tp = nx.intersection(gtrue, self.ghat)
|
|
129
|
+
elif method == "all_adjacent":
|
|
130
|
+
undirected_true = gtrue.to_undirected()
|
|
131
|
+
undirected_hat = self.ghat.to_undirected()
|
|
132
|
+
tp = nx.intersection(undirected_true, undirected_hat)
|
|
133
|
+
else:
|
|
134
|
+
raise AttributeError(method)
|
|
135
|
+
return len(tp.edges)
|
|
136
|
+
|
|
137
|
+
def _fp(self, gtrue, method="all_oriented"): # oriented or adjacent
|
|
138
|
+
if method == "all_oriented":
|
|
139
|
+
fp = nx.difference(self.ghat, gtrue)
|
|
140
|
+
elif method == "all_adjacent":
|
|
141
|
+
undirected_true = gtrue.to_undirected()
|
|
142
|
+
undirected_hat = self.ghat.to_undirected()
|
|
143
|
+
fp = nx.difference(undirected_hat, undirected_true)
|
|
144
|
+
else:
|
|
145
|
+
raise AttributeError(method)
|
|
146
|
+
return len(fp.edges)
|
|
147
|
+
|
|
148
|
+
def _fn(self, gtrue, method="all_oriented"): # oriented or adjacent
|
|
149
|
+
if method == "all_oriented":
|
|
150
|
+
fn = nx.difference(gtrue, self.ghat)
|
|
151
|
+
elif method == "all_adjacent":
|
|
152
|
+
undirected_true = gtrue.to_undirected()
|
|
153
|
+
undirected_hat = self.ghat.to_undirected()
|
|
154
|
+
fn = nx.difference(undirected_true, undirected_hat)
|
|
155
|
+
else:
|
|
156
|
+
raise AttributeError(method)
|
|
157
|
+
return len(fn.edges)
|
|
158
|
+
|
|
159
|
+
def _topology(self, gtrue, method="all_oriented"):
|
|
160
|
+
correct = self._tp(gtrue, method)
|
|
161
|
+
added = self._fp(gtrue, method)
|
|
162
|
+
missing = self._fn(gtrue, method)
|
|
163
|
+
return correct/(correct + missing + added)
|
|
164
|
+
|
|
165
|
+
def _false_positive_rate(self, gtrue, method="all_oriented"):
|
|
166
|
+
true_pos = self._tp(gtrue, method)
|
|
167
|
+
false_pos = self._fp(gtrue, method)
|
|
168
|
+
if false_pos == 0:
|
|
169
|
+
return 0
|
|
170
|
+
else:
|
|
171
|
+
return false_pos / (true_pos + false_pos)
|
|
172
|
+
|
|
173
|
+
def _precision(self, gtrue, method="all_oriented"):
|
|
174
|
+
true_pos = self._tp(gtrue, method)
|
|
175
|
+
false_pos = self._fp(gtrue, method)
|
|
176
|
+
if true_pos == 0:
|
|
177
|
+
return 0
|
|
178
|
+
else:
|
|
179
|
+
return true_pos / (true_pos + false_pos)
|
|
180
|
+
|
|
181
|
+
def _recall(self, gtrue, method="all_oriented"):
|
|
182
|
+
true_pos = self._tp(gtrue, method)
|
|
183
|
+
false_neg = self._fn(gtrue, method)
|
|
184
|
+
if true_pos == 0:
|
|
185
|
+
return 0
|
|
186
|
+
else:
|
|
187
|
+
return true_pos / (true_pos + false_neg)
|
|
188
|
+
|
|
189
|
+
def _f1(self, gtrue, method="all_oriented"):
|
|
190
|
+
p = self._precision(gtrue, method)
|
|
191
|
+
r = self._recall(gtrue, method)
|
|
192
|
+
if (p == 0) and (r == 0):
|
|
193
|
+
return 0
|
|
194
|
+
else:
|
|
195
|
+
return 2 * p * r / (p + r)
|
|
196
|
+
|
|
197
|
+
class TemporalModelEvaluation():
|
|
198
|
+
def __init__(self, tghat):
|
|
199
|
+
super(TemporalModelEvaluation, self).__init__()
|
|
200
|
+
self.tghat = tghat
|
|
201
|
+
|
|
202
|
+
def evaluation(self, tgtrue):
|
|
203
|
+
all_results = {}
|
|
204
|
+
|
|
205
|
+
all_results['precision'] = self._temporal_precision(tgtrue)
|
|
206
|
+
all_results['recall'] = self._temporal_recall(tgtrue)
|
|
207
|
+
all_results['f1'] = self._temporal_f1(tgtrue)
|
|
208
|
+
|
|
209
|
+
return all_results
|
|
210
|
+
|
|
211
|
+
def _temporal_tp(self, tgtrue):
|
|
212
|
+
list_tg_true = tgraph_to_list(tgtrue)
|
|
213
|
+
list_tg_hat = tgraph_to_list(self.tghat)
|
|
214
|
+
tp = set(list_tg_true).intersection(list_tg_hat)
|
|
215
|
+
return len(tp)
|
|
216
|
+
|
|
217
|
+
def _temporal_fp(self, tgtrue):
|
|
218
|
+
list_tg_true = tgraph_to_list(tgtrue)
|
|
219
|
+
list_tg_hat = tgraph_to_list(self.tghat)
|
|
220
|
+
fp = set(list_tg_hat).difference(list_tg_true)
|
|
221
|
+
return len(fp)
|
|
222
|
+
|
|
223
|
+
def _temporal_fn(self, tgtrue):
|
|
224
|
+
list_tg_true = tgraph_to_list(tgtrue)
|
|
225
|
+
list_tg_hat = tgraph_to_list(self.tghat)
|
|
226
|
+
fn = set(list_tg_true).difference(list_tg_hat)
|
|
227
|
+
return len(fn)
|
|
228
|
+
|
|
229
|
+
def _temporal_false_positive_rate(self, tgtrue):
|
|
230
|
+
true_pos = self._temporal_tp(tgtrue)
|
|
231
|
+
false_pos = self._temporal_fp(tgtrue)
|
|
232
|
+
return false_pos / (true_pos + false_pos)
|
|
233
|
+
|
|
234
|
+
def _temporal_precision(self, tgtrue):
|
|
235
|
+
true_pos = self._temporal_tp(tgtrue)
|
|
236
|
+
false_pos = self._temporal_fp(tgtrue)
|
|
237
|
+
if true_pos == 0:
|
|
238
|
+
return 0
|
|
239
|
+
else:
|
|
240
|
+
return true_pos / (true_pos + false_pos)
|
|
241
|
+
|
|
242
|
+
def _temporal_recall(self, tgtrue):
|
|
243
|
+
true_pos = self._temporal_tp(tgtrue)
|
|
244
|
+
false_neg = self._temporal_fn(tgtrue)
|
|
245
|
+
if true_pos == 0:
|
|
246
|
+
return 0
|
|
247
|
+
else:
|
|
248
|
+
return true_pos / (true_pos + false_neg)
|
|
249
|
+
|
|
250
|
+
def _temporal_f1(self, tgtrue):
|
|
251
|
+
p = self._temporal_precision(tgtrue)
|
|
252
|
+
r = self._temporal_recall(tgtrue)
|
|
253
|
+
if (p == 0) and (r == 0):
|
|
254
|
+
return 0
|
|
255
|
+
else:
|
|
256
|
+
return 2 * p * r / (p + r)
|