-
Notifications
You must be signed in to change notification settings - Fork 1
/
plots.py
2894 lines (2385 loc) · 148 KB
/
plots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import torch
import scipy
import seaborn as sns
import pickle
import pandas as pd
from matplotlib import pyplot as plt
color_list = [(0.5, 0.5, 0.5),
(0.3, 0.3, 0.7),
#(0.55, 0.55, 1.0),
#(1.0, 0.55, 0.55),
(0.3, 0.7, 0.3),
(0.7, 0.3, 0.3)]
def compute_metric(gt, pre_mean, pre_std=None):
T, N, D = gt.shape
metric = {}
pearsonr_net = 0
spearmanr_net = 0
kendalltau_net = 0
nl1_net = 0
mse_net = 0
negative_loglikelihood_net = 0
for nn in range(N):
pearsonr_per_node = 0
spearmanr_per_node = 0
kendalltau_per_node = 0
nl1_per_node = 0
mse_per_node = 0
negative_loglikelihood_per_node = 0
for dd in range(D):
gt_ = gt[:, nn, dd]
pre_mean_ = pre_mean[:, nn, dd]
pearsonr = scipy.stats.pearsonr(gt_, pre_mean_)[0]
spearmanr = scipy.stats.spearmanr(gt_, pre_mean_)[0]
kendalltau = scipy.stats.kendalltau(gt_, pre_mean_)[0]
if np.isnan(pearsonr):
pearsonr = 0
if np.isnan(spearmanr):
spearmanr = 0
if np.isnan(kendalltau):
kendalltau = 0
pearsonr_per_node += pearsonr
spearmanr_per_node += spearmanr
kendalltau_per_node += kendalltau
nl1_per_node += np.mean(np.abs(pre_mean_ - gt_))
mse_per_node += np.mean((pre_mean_ - gt_) ** 2)
if pre_std is not None:
pre_std_ = pre_std[:, nn, dd]
pre_dist = torch.distributions.Normal(torch.from_numpy(pre_mean_), torch.from_numpy(pre_std_))
negative_loglikelihood_per_node += torch.mean(-pre_dist.log_prob(torch.from_numpy(gt_))).item()
pearsonr_net += pearsonr_per_node / D
spearmanr_net += spearmanr_per_node / D
kendalltau_net += kendalltau_per_node / D
nl1_net += nl1_per_node / D
mse_net += mse_per_node / D
negative_loglikelihood_net += negative_loglikelihood_per_node / D
pearsonr_net = pearsonr_net / N
spearmanr_net = spearmanr_net / N
kendalltau_net = kendalltau_net / N
nl1_net = nl1_net / N
mse_net = mse_net / N
negative_loglikelihood_net = negative_loglikelihood_net / N
metric['pearsonr'] = pearsonr_net
metric['spearmanr'] = spearmanr_net
metric['Kendalltau'] = kendalltau_net
metric['negative_loglikelihood'] = negative_loglikelihood_net
metric['MAE'] = nl1_net
metric['mse'] = mse_net
# print(kendalltau_net)
return metric
def plot_functions(ax, target_x, target_y, context_x, context_y, pred_y, std, is_2D=False):
"""Plots the predicted mean and variance and the context points.
Args:
target_x: An array of shape [B,num_targets,1] that contains the
x values of the target points.
target_y: An array of shape [B,num_targets,1] that contains the
y values of the target points.
context_x: An array of shape [B,num_contexts,1] that contains
the x values of the context points.
context_y: An array of shape [B,num_contexts,1] that contains
the y values of the context points.
pred_y: An array of shape [B,num_targets,1] that contains the
predicted means of the y values at the target points in target_x.
std: An array of shape [B,num_targets,1] that contains the
predicted std dev of the y values at the target points in target_x.
"""
# Plot everything
if not is_2D:
if len(target_y.size()) == 3:
draw_target_x_sorted, draw_target_sorted_index = torch.sort(target_x[0], dim=0)
draw_context_x_sorted, draw_context_sorted_index = torch.sort(context_x[0], dim=0)
# groundtruth
ax.plot(draw_target_x_sorted, target_y[0][draw_target_sorted_index.view(-1), :], 'k:', linewidth=1)
# observations
ax.plot(draw_context_x_sorted, context_y[0][draw_context_sorted_index.view(-1), :], 'kx', markersize=10)
# predictions
for i in range(pred_y.size(0)):
ax.plot(draw_target_x_sorted, pred_y[i, 0, draw_target_sorted_index.view(-1), :], 'b', linewidth=1,
alpha=0.1)
ax.fill_between(
draw_target_x_sorted[:, 0],
pred_y[i, 0, draw_target_sorted_index.view(-1), 0] - std[
i, 0, draw_target_sorted_index.view(-1), 0],
pred_y[i, 0, draw_target_sorted_index.view(-1), 0] + std[
i, 0, draw_target_sorted_index.view(-1), 0],
# alpha=0.05,
alpha=0.05,
facecolor='b',
interpolate=True)
elif len(target_y.size()) == 4:
for j in range(target_x.size(0)):
draw_target_x_sorted, draw_target_sorted_index = torch.sort(target_x[j][0], dim=0)
draw_context_x_sorted, draw_context_sorted_index = torch.sort(context_x[j][0], dim=0)
# groundtruth
ax.plot(draw_target_x_sorted, target_y[j][0][draw_target_sorted_index.view(-1), :], 'k:', linewidth=1,
alpha=0.2)
# observations
# ax.plot(draw_context_x_sorted, context_y[j][0][draw_context_sorted_index.view(-1), :], 'kx', markersize=10)
# predictions
i = j
ax.plot(draw_target_x_sorted, pred_y[i, 0, draw_target_sorted_index.view(-1), :], 'b', linewidth=1,
alpha=0.2)
ax.fill_between(
draw_target_x_sorted[:, 0],
pred_y[i, 0, draw_target_sorted_index.view(-1), 0] - std[
i, 0, draw_target_sorted_index.view(-1), 0],
pred_y[i, 0, draw_target_sorted_index.view(-1), 0] + std[
i, 0, draw_target_sorted_index.view(-1), 0],
# alpha=0.05,
alpha=0.05,
facecolor='b',
interpolate=True)
else:
print('wrong dim for target_y!!!')
exit(1)
else:
# 2D draw
# groundtruth
draw_target_x = target_x[0]
draw_target_y = target_y[0]
draw_context_x = context_x[0]
draw_context_y = context_y[0]
n = int(torch.sqrt(torch.tensor(draw_target_x.size(0))).item())
X = draw_target_x[:, 0].view(n, n)
Y = draw_target_x[:, 1].view(n, n)
Z = draw_target_y.view(n, n)
ax0 = ax[0].contourf(X, Y, Z, 25, cmap='jet', vmin=-2, vmax=2)
# ax[0].contour(X, Y, Z)
# predictions
Z = pred_y[0, 0, :, :].view(n, n)
ax1 = ax[1].contourf(X, Y, Z, 25, cmap='jet', vmin=-2, vmax=2)
Z = std[0, 0, :, :].view(n, n)
ax2 = ax[2].contourf(X, Y, Z, 25, cmap='jet', vmin=0, vmax=3)
# observations
ax[0].plot(draw_context_x[:, 0], draw_context_x[:, 1], 'kx', markersize=10)
ax[1].plot(draw_context_x[:, 0], draw_context_x[:, 1], 'kx', markersize=10)
ax[2].plot(draw_context_x[:, 0], draw_context_x[:, 1], 'kx', markersize=10)
return [ax0, ax1, ax2]
# Make the plot pretty
# plt.yticks([-6, 0, 6], fontsize=16)
# plt.xticks([-6, 0, 6], fontsize=16)
# plt.ylim([-6, 6])
ax.grid(False)
# ax = plt.gca()
def plot_violinplot(save_fig=True, add_str='', plot_type='violin', dynamics_list=[], topo_list=[],
bound_t_context_list=[], test_N=-1, test_num_trials=10,
exp_type='3dynamics5topo_onedynamics_onetopo', ndcn_flag=False,
x_dim=1,
train_topo=''):
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import pickle
figsize = (6, 5.2)
# sns.set_theme(style="whitegrid", palette="pastel")
sns.set(context='notebook', style='whitegrid', font_scale=2, palette="pastel")
data_ndcn_all_dynamics = []
data_all_dynamics = []
for dynamics in dynamics_list:
data_ndcn = []
data = []
for topo in topo_list:
if ndcn_flag:
#### load ndcn results
fname = 'compared_methods/ndcn_all_%s_on_%s_ndcn_norm_adj.pickle'%(dynamics, topo)
with open(fname, 'rb') as f:
ndcn_results_data = pickle.load(f)
ndcn_results_data_dict = {}
for dd in ndcn_results_data:
ndcn_results_data_dict[list(dd.keys())[0]] = list(dd.values())[0]
for bound_t_context in bound_t_context_list:
if exp_type == '3dynamics5topo_onedynamics_onetopo':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, topo, bound_t_context, test_N)
elif exp_type == '3dynamics5topo_onedynamics_alltopo':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_all%s_x1_numgraph1000_timestep100_epoch20_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, topo, bound_t_context, test_N)
elif exp_type == '3dynamics5topo_alldynamics_alltopo':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_all%s_all%s_x1_numgraph1000_timestep100_epoch20_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, topo, bound_t_context, test_N)
elif exp_type == '3dynamics5topo_onedynamics_onetopo_difftopo':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s%s_x1_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, train_topo, topo, bound_t_context, test_N)
elif exp_type == '5dynamics1topo_onedynamics_onetopo_all_epidemic':
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_all_epidemic%s_%s_x4_numgraph1000_timestep100_epoch20_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics, topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_all_epidemic%s_%s_x4_numgraph1000_timestep100_epoch40_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics, topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_all_epidemic%s_%s_x4_numgraph1000_timestep100_epoch60_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics, topo, bound_t_context, test_N)
if 'SI_' in dynamics or 'SIS_' in dynamics:
x_dim_ = 2
elif 'SIR_' in dynamics or 'SEIS_' in dynamics:
x_dim_ = 3
else:
x_dim_ = 4
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, topo, x_dim_,bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_all_epidemic%s_%s_x4_numgraph1000_timestep100_epoch40_bound_t_context%s_seed1_num_nodes%s_True.pkl' % (
# dynamics, topo, bound_t_context, test_N)
else:
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics + dynamics, topo + topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph1000_timestep100_epoch50_bound_t_context%s_seed1_num_nodes-1.pkl' % (
# dynamics + dynamics, topo + topo, bound_t_context)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph1000_timestep100_epoch50_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics + dynamics, topo + topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph400_timestep100_epoch20_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics + dynamics, topo + topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_GNDP_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph5000_timestep100_epoch20_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# dynamics + dynamics, topo + topo, bound_t_context, test_N)
# fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch60_bound_t_context%s_seed1_num_nodes%s.pkl' % (
# model_name, dynamics, topo, x_dim, bound_t_context, test_N)
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s_with_2nd_phase.pkl' % (
model_name, dynamics, topo, x_dim, bound_t_context, test_N)
with open(fname, 'rb') as f:
saved_results_data = pickle.load(f)
print('hhah')
groundtruth_saved = []
for idx in range(len(saved_results_data['test_id']) - test_num_trials,
len(saved_results_data['test_id'])):
test_id = saved_results_data['test_id'][idx]
observations = saved_results_data['observations'][idx]
groundtruth = saved_results_data['groundtruth'][idx]
# groundtruth_sum = saved_results_data['groundtruth_sum'][idx].view(-1)
predictions = saved_results_data['predictions'][idx]
# predictions_sum = saved_results_data['predictions_sum'][idx].view(-1, len(groundtruth_sum))
# nl1_error = saved_results_data['nl1_error'][idx]
# l2_error = saved_results_data['l2_error'][idx]
groundtruth = torch.transpose(groundtruth, 0, 1)
predictions['mean'] = torch.transpose(predictions['mean'], 1, 2)
predictions['std'] = torch.transpose(predictions['std'], 1, 2)
groundtruth_saved.append(groundtruth)
metric = compute_metric(groundtruth.numpy(), torch.mean(predictions['mean'], dim=0).numpy(),
pre_std=None)
data.append([metric['MAE'], metric['Kendalltau'], 'GMNND', bound_t_context, dynamics, topo])
data_all_dynamics.append(
[metric['MAE'], metric['Kendalltau'], 'GMNND', bound_t_context, dynamics.split('_')[0],
topo])
if idx in [0, 1, 2, 3, 4]:
print("************run_idx=%s, Ours (%s-%s-%s), MAE=%s, Kendalltau=%s" % (
idx, dynamics, topo, bound_t_context, metric['MAE'], metric['Kendalltau']))
if ndcn_flag:
# get ndcn results data
for idx in range(test_num_trials):
ndcn_results_data_one = ndcn_results_data_dict[(dynamics, topo, bound_t_context, idx)]
predictions = ndcn_results_data_one['pred_y']
predictions_sum = torch.sum(ndcn_results_data_one['pred_y'], dim=1)
#nl1_error = ndcn_results_data_one['normalized_l1'].item()
#l2_error = ndcn_results_data_one['mse'].item()
groundtruth = groundtruth_saved[idx]
# predictions [100,225]
if len(predictions.shape) == 2:
predictions = predictions.unsqueeze(-1)
metric = compute_metric(groundtruth.cpu().numpy(), predictions.cpu().numpy(), pre_std=None)
data_ndcn.append(
[metric['MAE'], metric['Kendalltau'], 'NDCN', bound_t_context, dynamics.split('_')[0],
topo])
data_ndcn_all_dynamics.append(
[metric['MAE'], metric['Kendalltau'], 'NDCN', bound_t_context, dynamics.split('_')[0],
topo])
if idx in [0, 1, 2, 3, 4]:
print("************run_idx=%s, NDCN (%s-%s-%s), MAE=%s, Kendalltau=%s" % (
idx, dynamics, topo, bound_t_context, metric['MAE'], metric['Kendalltau']))
df_ndcn_all_dynamics = pd.DataFrame(data_ndcn_all_dynamics,
columns=['MAE', 'Kendalltau', 'Methods', 'bound_t_context',
'Dynamics types', 'Topology types'],
dtype=float)
df_all_dynamics = pd.DataFrame(data_all_dynamics,
columns=['MAE', 'Kendalltau', 'Methods', 'bound_t_context', 'Dynamics types',
'Topology types'],
dtype=float)
df_all_all_dynamics = pd.concat([df_all_dynamics, df_ndcn_all_dynamics], axis=0)
if dynamics == 'opinion_dynamics_Baumann2021_2topic':
exp_name = 'EXP2_opinion_dynamics'
elif dynamics == 'SI_Individual_dynamics' or \
dynamics == 'SIS_Individual_dynamics' or \
dynamics == 'SIR_Individual_dynamics' or \
dynamics == 'SEIS_Individual_dynamics' or dynamics == 'SEIR_Individual_dynamics' or dynamics == 'Coupled_Epidemic_dynamics':
exp_name = 'EXP3_all_epidemic'
elif dynamics == 'SIR_meta_pop_dynamics':
exp_name = 'EXP4_real_epidemic'
else:
print('unknown dynamics [%s]' % dynamics)
for key_metric in ['MAE', 'Kendalltau']:
# Draw
plt.figure(figsize=figsize)
if plot_type == 'box':
color_palette = sns.color_palette(
sns.color_palette('pastel')[2:3] + sns.color_palette('pastel')[3:4])
sns.boxplot(x="Methods", y=key_metric, showfliers=False,
# hue="Methods",
data=df_all_all_dynamics,
palette=color_palette
)
sns.stripplot(x="Methods", y=key_metric,
data=df_all_all_dynamics,
size=5, linewidth=0, alpha=0.5,
# color=".3",
hue='bound_t_context',
legend=False,
palette=sns.color_palette(color_list)
)
else:
sns.violinplot(x="Methods", y=key_metric,
# hue="Methods",
data=df_all_all_dynamics)
# add mid line for each context_t_bound
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
else:
idx_t += 1
sns.boxplot(x="Methods", y=key_metric, showfliers=False, showcaps=False,
whiskerprops={'color': 'w', 'alpha': 0},
# hue="Methods",
linewidth=2,
data=df_all_all_dynamics[df_all_all_dynamics['bound_t_context'] == bound_t_context],
boxprops={"facecolor": (1, 1, 1, 1), 'alpha': 0},
medianprops={'marker': '>', 'markevery': 2, 'markersize': 10, 'markeredgecolor': 'w',
'linestyle': 'none', "color": color_list[idx_t], 'alpha': 0.9},
)
if dynamics == 'heat_diffusion_dynamics':
plt.ylim(0, 60)
elif dynamics == 'mutualistic_interaction_dynamics':
plt.ylim(0, 100)
elif dynamics == 'gene_regulatory_dynamics':
plt.ylim(0, 200)
elif dynamics == 'opinion_dynamics':
plt.ylim(0, 10)
elif dynamics == 'opinion_dynamics_Baumann2021':
plt.ylim(0, 100)
elif dynamics == 'opinion_dynamics_Baumann2021_2topic':
plt.ylim(0, 3)
if key_metric == 'MAE':
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f'))
elif dynamics == 'SI_Individual_dynamics' or \
dynamics == 'SIS_Individual_dynamics' or \
dynamics == 'SIR_Individual_dynamics' or \
dynamics == 'SEIS_Individual_dynamics' or dynamics == 'SEIR_Individual_dynamics':
plt.ylim(0, 5)
if key_metric == 'MAE':
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f'))
else:
plt.ylim(0, 10)
if key_metric == 'Kendalltau':
plt.ylim(-1, 1)
xticks = plt.gca().get_xticklabels()
plt.gca().set_xticklabels(xticks, rotation=0)
plt.tight_layout()
#
if save_fig:
plt.savefig(
'results/%s_%s_%s_all_topo_together.png' % (exp_name, key_metric, add_str))
plt.close()
else:
plt.show()
###
###
for key_metric in ['Kendalltau', 'MAE']:
for dynamics_name in dynamics_list:
df_i = df_all_all_dynamics[df_all_all_dynamics['Dynamics types'] == dynamics_name.split('_')[0]]
plt.figure(figsize=figsize)
if plot_type == 'box':
color_palette = sns.color_palette(
sns.color_palette('pastel')[2:3] + sns.color_palette('pastel')[3:4])
sns.boxplot(x="Methods", y=key_metric, showfliers=False,
# hue="Methods",
data=df_i,
palette=color_palette)
sns.stripplot(x="Methods", y=key_metric,
data=df_i,
size=5, linewidth=0, alpha=0.6,
# color='0.3',
hue='bound_t_context',
edgecolor='w',
legend=False,
# palette="rainbow")
palette=sns.color_palette(color_list))
else:
sns.violinplot(x="Methods", y=key_metric,
# hue="Methods",
data=df_i)
# add mid line for each context_t_bound
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
else:
idx_t += 1
sns.boxplot(x="Methods", y=key_metric, showfliers=False, showcaps=False,
whiskerprops={'color': 'w', 'alpha': 0},
# hue="Methods",
linewidth=2,
data=df_i[df_i['bound_t_context'] == bound_t_context],
boxprops={"facecolor": (1, 1, 1, 1), 'alpha': 0},
medianprops={'marker': '>', 'markevery': 2, 'markersize': 10, 'markeredgecolor': 'w',
'linestyle': 'none', "color": color_list[idx_t], 'alpha': 0.9},
)
if dynamics == 'heat_diffusion_dynamics':
plt.ylim(0, 60)
elif dynamics == 'mutualistic_interaction_dynamics':
plt.ylim(0, 100)
elif dynamics == 'gene_regulatory_dynamics':
plt.ylim(0, 200)
elif dynamics == 'opinion_dynamics':
plt.ylim(0, 10)
elif dynamics == 'opinion_dynamics_Baumann2021':
plt.ylim(0, 100)
elif dynamics == 'opinion_dynamics_Baumann2021_2topic':
plt.ylim(0, 3)
if key_metric == 'MAE':
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f'))
elif dynamics == 'SI_Individual_dynamics' or \
dynamics == 'SIS_Individual_dynamics' or \
dynamics == 'SIR_Individual_dynamics' or \
dynamics == 'SEIS_Individual_dynamics' or dynamics == 'SEIR_Individual_dynamics':
plt.ylim(0, 5)
if key_metric == 'MAE':
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f'))
else:
plt.ylim(0, 10)
if key_metric == 'Kendalltau':
plt.ylim(-1, 1.1)
xticks = plt.gca().get_xticklabels()
plt.gca().set_xticklabels(xticks, rotation=0)
plt.tight_layout()
#
if save_fig:
plt.savefig(
'results/%s_%s_%s_for_each_%s_all_topo_together.png' % (
exp_name, key_metric, dynamics_name, add_str))
plt.close()
else:
plt.show()
def plot_violinplot_new(save_fig=True, add_str='', plot_type='violin', dynamics_topo_list=[],
bound_t_context_list=[], test_N=-1, test_num_trials=10, ndcn_flag=False,
x_dim=1,
train_topo=''):
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import pickle
# figsize = (14, 10)
#figsize = (6, 6)
figsize = (5, 6)
# sns.set_theme(style="whitegrid", palette="pastel")
sns.set(context='notebook', style='whitegrid', font_scale=2, palette="pastel")
data = []
for dynamics, topo in dynamics_topo_list:
#### load ndcn results
if ndcn_flag:
fname = 'compared_methods/ndcn_all_%s_on_%s_ndcn_norm_adj.pickle'%(dynamics, topo)
ndcn_results_data_dict = {}
with open(fname, 'rb') as f:
ndcn_results_data = pickle.load(f)
for dd in ndcn_results_data:
ndcn_results_data_dict[list(dd.keys())[0]] = list(dd.values())[0]
test_num_trials = 100
add_str_topo = ''
if 'SI_' in dynamics or 'SIS_' in dynamics or 'opinion_' in dynamics:
test_N = 200
x_dim = 2
elif 'SEIS_' in dynamics or 'SIR_' in dynamics:
test_N = 200
x_dim = 3
elif 'SEIR_' in dynamics:
test_N = 200
x_dim = 4
else:
test_N = 225
x_dim = 1
test_num_trials = 20
add_str_topo = 'all'
for bound_t_context in bound_t_context_list:
#for exp_type in [ 'GMNND', 'GraphNDP',]:
for exp_type in [ 'GNND',]:
if exp_type == 'GraphNDP':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s.pkl' % (
model_name, dynamics, add_str_topo+topo, x_dim, bound_t_context, test_N)
elif exp_type == 'GNND':
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s_with_2nd_phase.pkl' % (
model_name, dynamics, add_str_topo+topo, x_dim, bound_t_context, test_N)
else:
print("Unknown [%s]"%exp_type)
exit(1)
with open(fname, 'rb') as f:
saved_results_data = pickle.load(f)
print('loading ...', dynamics, topo, bound_t_context, exp_type)
groundtruth_saved = []
for idx in range(len(saved_results_data['test_id']) - test_num_trials,
len(saved_results_data['test_id'])):
test_id = saved_results_data['test_id'][idx]
# observations = saved_results_data['observations'][idx]
groundtruth = saved_results_data['groundtruth'][idx]
# groundtruth_sum = saved_results_data['groundtruth_sum'][idx].view(-1)
predictions = saved_results_data['predictions'][idx]
# predictions_sum = saved_results_data['predictions_sum'][idx].view(-1, len(groundtruth_sum))
# nl1_error = saved_results_data['nl1_error'][idx]
# l2_error = saved_results_data['l2_error'][idx]
# groundtruth [225, 100, 1]; predictions['mean'] [20, 225, 100, 1]; predictions['std'] [20, 225, 100, 1]
# |
# v using transpose
# v
# groundtruth [100, 225, 1]; predictions['mean'] [20, 100, 225, 1]; predictions['std'] [20, 100, 225, 1]
groundtruth = torch.transpose(groundtruth, 0, 1)
predictions['mean'] = torch.transpose(predictions['mean'], 1, 2)
predictions['std'] = torch.transpose(predictions['std'], 1, 2)
groundtruth_saved.append(groundtruth)
metric = compute_metric(groundtruth.numpy(),
torch.mean(predictions['mean'], dim=0).numpy(),
(torch.mean(
torch.pow(predictions['std'], 2) + torch.pow(predictions['mean'],
2),
dim=0) \
- torch.pow(torch.mean(predictions['mean'], dim=0), 2)).numpy())
if bound_t_context == 0:
bound_t_context_str = '$=0$'
else:
bound_t_context_str = '$(0,%s]$' % bound_t_context
data.append(
list(metric.values()) + [exp_type, bound_t_context_str, dynamics[:4], topo])
#data.append(
# list(metric.values()) + ['GMNND', bound_t_context_str, dynamics[:4], topo])
if ndcn_flag:
# get ndcn results data
for idx in range(test_num_trials):
ndcn_results_data_one = ndcn_results_data_dict[(dynamics, topo, bound_t_context, idx)]
predictions = ndcn_results_data_one['pred_y'].cpu()
# predictions_sum = torch.sum(ndcn_results_data_one['pred_y'], dim=1)
# nl1_error = ndcn_results_data_one['normalized_l1'].item()
# l2_error = ndcn_results_data_one['mse'].item()
groundtruth = groundtruth_saved[idx]
# predictions [100,225] -> [100,225,1]
if predictions.dim() == 2:
predictions = predictions.unsqueeze(-1)
metric = compute_metric(groundtruth.numpy(),
predictions.numpy())
if bound_t_context == 0:
bound_t_context_str = '$=0$'
else:
bound_t_context_str = '$(0,%s]$' % bound_t_context
data.append(list(metric.values()) + ['NDCN', bound_t_context_str, dynamics[:4], topo])
df = pd.DataFrame(data,
columns=list(metric.keys()) + ['Methods', 'max $t_{obs}$',
'Dynamics types', 'Topology types'],
dtype=float)
# metric['pearsonr'] = pearsonr_net
# metric['spearmanr'] = spearmanr_net
# metric['kendalltau'] = kendalltau_net
# metric['negative_loglikelihood'] = negative_loglikelihood_net
# metric['nl1_net'] = nl1_net
# metric['mse'] = mse_net
# Draw
for key_metric in ['Kendalltau', 'negative_loglikelihood', 'MAE', 'mse']:
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
bound_t_context_str = '$=0$'
else:
idx_t += 1
bound_t_context_str = '$(0,%s]$' % bound_t_context
plt.figure(figsize=figsize)
if plot_type == 'box':
sns.boxplot(x="Methods", y=key_metric, showfliers=False,
# hue="Methods",
data=df[df['max $t_{obs}$'] == bound_t_context_str])
sns.stripplot(x="Methods", y=key_metric,
data=df[df['max $t_{obs}$'] == bound_t_context_str],
size=3, linewidth=0, alpha=0.3,
# color='0.3',
hue='max $t_{obs}$',
edgecolor='w',
legend=False,
# palette="rainbow")
palette=sns.color_palette(color_list[idx_t:idx_t+1]))
else:
sns.violinplot(x="Methods", y=key_metric,
# hue="Methods",
data=df)
"""
# add mid line for each context_t_bound
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
bound_t_context_str = '$=0$'
else:
idx_t += 1
bound_t_context_str = '$(0,%s]$' % bound_t_context
sns.boxplot(x="Methods", y=key_metric, showfliers=False, showcaps=False,
whiskerprops={'color': 'w', 'alpha': 0},
# hue="Methods",
linewidth=2,
data=df[df['max $t_{obs}$'] == bound_t_context_str],
boxprops={"facecolor": (1, 1, 1, 1), 'alpha': 0},
medianprops={'marker': '>', 'markevery': 2, 'markersize': 10, 'markeredgecolor': 'w',
'linestyle': 'none', "color": color_list[idx_t], 'alpha': 0.9},
)
"""
if key_metric == 'Kendalltau':
plt.ylim(-1, 1.1)
elif key_metric == 'negative_loglikelihood':
plt.ylim(0, 100)
elif key_metric == 'MAE':
plt.ylim(0, 10)
elif key_metric == 'mse':
plt.ylim(0, 20)
xticks = plt.gca().get_xticklabels()
plt.gca().set_xticklabels(xticks, rotation=0)
plt.tight_layout()
#
if save_fig:
plt.savefig(
'results/EXP1_%s_%s_%s.png' % (add_str, key_metric, bound_t_context))
plt.close()
else:
plt.show()
###
for key_metric in ['Kendalltau', 'negative_loglikelihood', 'MAE', 'mse']:
for dynamics_name in [dd[0] for dd in dynamics_topo_list]:
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
bound_t_context_str = '$=0$'
else:
idx_t += 1
bound_t_context_str = '$(0,%s]$' % bound_t_context
df_i = df[df['Dynamics types'] == dynamics_name[:4]]
plt.figure(figsize=figsize)
if plot_type == 'box':
sns.boxplot(x="Methods", y=key_metric, showfliers=False,
# hue="Methods",
data=df_i[df_i['max $t_{obs}$'] == bound_t_context_str])
sns.stripplot(x="Methods", y=key_metric,
data=df_i[df_i['max $t_{obs}$'] == bound_t_context_str],
size=3, linewidth=0, alpha=0.3,
# color='0.3',
hue='max $t_{obs}$',
edgecolor='w',
legend=False,
# palette="rainbow")
palette=sns.color_palette(color_list[idx_t:idx_t+1]))
else:
sns.violinplot(x="Methods", y=key_metric,
# hue="Methods",
data=df_i)
"""
# add mid line for each context_t_bound
idx_t = 0
for bound_t_context in bound_t_context_list:
if bound_t_context == 0:
idx_t = 0
bound_t_context_str = '$=0$'
else:
idx_t += 1
bound_t_context_str = '$(0,%s]$' % bound_t_context
sns.boxplot(x="Methods", y=key_metric, showfliers=False, showcaps=False,
whiskerprops={'color': 'w', 'alpha': 0},
# hue="Methods",
linewidth=2,
data=df_i[df_i['max $t_{obs}$'] == bound_t_context_str],
boxprops={"facecolor": (1, 1, 1, 1), 'alpha': 0},
medianprops={'marker': '>', 'markevery': 2, 'markersize': 10, 'markeredgecolor': 'w',
'linestyle': 'none', "color": color_list[idx_t], 'alpha': 0.9},
)
"""
if key_metric == 'Kendalltau':
plt.ylim(-1, 1.1)
elif key_metric == 'negative_loglikelihood':
plt.ylim(0, 100)
elif key_metric == 'MAE':
if 'opinion' in dynamics_name or 'SI_' in dynamics_name or 'SIS_' in dynamics_name or 'SIR_' in dynamics_name or 'SEIS_' in dynamics_name or 'SEIR_' in dynamics_name:
plt.ylim(0, 5)
else:
plt.ylim(0, 10)
elif key_metric == 'mse':
plt.ylim(0, 20)
xticks = plt.gca().get_xticklabels()
plt.gca().set_xticklabels(xticks, rotation=0)
plt.tight_layout()
#
if save_fig:
plt.savefig(
'results/EXP1_%s_%s_%s_%s.png' % (add_str, dynamics_name, key_metric, bound_t_context))
plt.close()
else:
plt.show()
# plt.close()
def plot_sum_state_compare(test_ids, save_fig=False, dynamics_topo_list=[],
show_run_no_indexs_per_dynamic_topo_dict=None):
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
figsize = (6, 3.5)
sns.set(context='notebook', style='whitegrid', font_scale=2)
color_palette = sns.color_palette("pastel")
# color_palette.insert(0,(0,0,0))
# sns.color_palette(color_palette)
for dynamics, topo in dynamics_topo_list:
#### load ndcn results
ndcn_results_data_dict = {}
fname = 'compared_methods/ndcn_all_%s_on_%s_ndcn_norm_adj.pickle'%(dynamics, topo)
with open(fname, 'rb') as f:
ndcn_results_data = pickle.load(f)
for dd in ndcn_results_data:
ndcn_results_data_dict[list(dd.keys())[0]] = list(dd.values())[0]
data = []
data_ndcn = []
for bound_t_context in [0.0, 0.25, 0.5, 0.75]:
# for bound_t_context in [0.0, 0.25, 0.5]:
test_N = 225
x_dim = 1
test_num_trials = 20
add_str_topo = 'all'
fname = 'results/saved_test_results_%s_MLlossFalse_deterTrue_uncerTrue_%s_%s_x%s_numgraph1000_timestep100_epoch30_bound_t_context%s_seed1_num_nodes%s_with_2nd_phase.pkl' % (
model_name, dynamics, add_str_topo+topo, x_dim, bound_t_context, test_N)
#fname = 'results/saved_test_results_GNDP_OneForAll_MLlossFalse_deterTrue_uncerTrue_%s_%s_x1_numgraph1000_timestep100_epoch60_bound_t_context%s_seed1_num_nodes225.pkl' % (
# dynamics, topo, bound_t_context)
with open(fname, 'rb') as f:
saved_results_data = pickle.load(f)
print('hhah')
for idx in range(len(saved_results_data['test_id']) - test_num_trials, len(saved_results_data['test_id'])):
test_id = saved_results_data['test_id'][idx]
if show_run_no_indexs_per_dynamic_topo_dict is not None:
test_ids = show_run_no_indexs_per_dynamic_topo_dict[(dynamics, topo)]['trial_no']
if test_id in test_ids:
observations = saved_results_data['observations'][idx]
groundtruth = saved_results_data['groundtruth'][idx]
#groundtruth_sum = saved_results_data['groundtruth_sum'][idx].view(-1)
predictions = saved_results_data['predictions'][idx]
#predictions_sum = saved_results_data['predictions_sum'][idx].view(-1, len(groundtruth_sum))
#nl1_error = saved_results_data['nl1_error'][idx]
#l2_error = saved_results_data['l2_error'][idx]
groundtruth_sum = torch.sum(groundtruth, dim=0).sum(-1).view(-1)
predictions_sum = torch.sum(predictions['mean'], dim=1).sum(-1)
ndcn_predictions_sum = torch.sum(
ndcn_results_data_dict[(dynamics, topo, bound_t_context, test_id)]['pred_y'].view(
len(groundtruth_sum), -1), dim=-1)
x_time = np.linspace(0, 1, len(groundtruth_sum))
for iidx in range(len(x_time)):
if bound_t_context == 0:
data.append([x_time[iidx], groundtruth_sum[iidx], 0, 'Groundtruth', dynamics, topo])
for j in range(len(predictions_sum)):
# data.append([x_time[iidx], predictions_sum[j][iidx], 'GraphNDP-%s-%s' % (bound_t_context,j), dynamics, topo])
if bound_t_context == 0:
data.append(
[x_time[iidx], predictions_sum[j][iidx], j + 1,
'GNND s.t. $t_{obs}=%s$' % (bound_t_context),
dynamics,
topo])
else:
data.append(
[x_time[iidx], predictions_sum[j][iidx], j + 1,
'GNND s.t. $t_{obs}<=%s$' % (bound_t_context),
dynamics,
topo])
if bound_t_context == 0:
data_ndcn.append([x_time[iidx], ndcn_predictions_sum[iidx], 0,
'NDCN s.t. $t_{obs}=%s$' % bound_t_context, dynamics, topo])
else:
data_ndcn.append([x_time[iidx], ndcn_predictions_sum[iidx], 0,
'NDCN s.t. $t_{obs}<=%s$' % bound_t_context, dynamics, topo])
df = pd.DataFrame(data, columns=['time', 'sum of states', 'sampled_z_i', 'Methods', 'Dynamics types',
'Topology types'], dtype=float)
df_ndcn = pd.DataFrame(data_ndcn,
columns=['time', 'sum of states', 'sampled_z_i', 'Methods', 'Dynamics types',
'Topology types'], dtype=float)
plt.figure(figsize=figsize)
#print(df)
y_min = min(df['sum of states'].to_numpy())
y_max = max(df['sum of states'].to_numpy())
idx = -1
for bound_t_context in [0.0, 0.25, 0.5, 0.75]:
idx += 1
if bound_t_context == 0:
df_i = df[df['Methods'] == 'GNND s.t. $t_{obs}=%s$' % (bound_t_context)]
else:
df_i = df[df['Methods'] == 'GNND s.t. $t_{obs}<=%s$' % (bound_t_context)]
plt.plot(np.mean(df_i['time'].to_numpy().reshape(-1, 20), axis=-1),
np.mean(df_i['sum of states'].to_numpy().reshape(-1, 20), axis=-1),
'--', c=color_list[idx],
marker='o',
markerfacecolor='w',
markersize=10, markevery=10, alpha=0.5, linewidth=2)
plt.fill_between(np.mean(df_i['time'].to_numpy().reshape(-1, 20), axis=-1),
np.mean(df_i['sum of states'].to_numpy().reshape(-1, 20), axis=-1) \
+ 1.96 * np.std(df_i['sum of states'].to_numpy().reshape(-1, 20), axis=-1),
np.mean(df_i['sum of states'].to_numpy().reshape(-1, 20), axis=-1) \
- 1.96 * np.std(df_i['sum of states'].to_numpy().reshape(-1, 20), axis=-1),
facecolor=color_list[idx], alpha=0.2)
idx = -1
for bound_t_context in [0.0, 0.25, 0.5, 0.75]:
idx += 1
if bound_t_context == 0:
df_ndcn_i = df_ndcn[df_ndcn['Methods'] == 'NDCN s.t. $t_{obs}=%s$' % (bound_t_context)]
else:
df_ndcn_i = df_ndcn[df_ndcn['Methods'] == 'NDCN s.t. $t_{obs}<=%s$' % (bound_t_context)]
plt.plot(df_ndcn_i['time'].to_numpy(),
df_ndcn_i['sum of states'].to_numpy(),
':', c=color_list[idx],
marker='s',
markerfacecolor='w',
markersize=10, markevery=10, alpha=0.5, linewidth=2)
df_gt = df[df['Methods'] == 'Groundtruth']
plt.plot(df_gt['time'].to_numpy(),
df_gt['sum of states'].to_numpy(),
'k-', markersize=10, markevery=10, alpha=1, linewidth=1)
plt.xlabel('Time')