-
Notifications
You must be signed in to change notification settings - Fork 2
/
GNN_particles_PlotFigure.py
executable file
·6449 lines (5505 loc) · 313 KB
/
GNN_particles_PlotFigure.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
from pysr import PySRRegressor
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from torch_geometric.nn import MessagePassing
import torch_geometric.utils as pyg_utils
import imageio
from matplotlib import rc
from ParticleGraph.utils import set_size
from scipy.ndimage import median_filter
# os.environ["PATH"] += os.pathsep + '/usr/local/texlive/2023/bin/x86_64-linux'
# from data_loaders import *
from GNN_particles_Ntype import *
from ParticleGraph.fitting_models import *
from ParticleGraph.sparsify import *
from ParticleGraph.models.utils import *
from ParticleGraph.models.MLP import *
from ParticleGraph.utils import to_numpy, CustomColorMap
import matplotlib as mpl
from io import StringIO
import sys
from scipy.stats import pearsonr
from scipy.spatial import Voronoi, voronoi_plot_2d
from sklearn.mixture import GaussianMixture
# matplotlib.use("Qt5Agg")
class Interaction_Particle_extract(MessagePassing):
"""Interaction Network as proposed in this paper:
https://proceedings.neurips.cc/paper/2016/hash/3147da8ab4a0437c15ef51a5cc7f2dc4-Abstract.html"""
def __init__(self, config, device, aggr_type=None, bc_dpos=None):
super(Interaction_Particle_extract, self).__init__(aggr=aggr_type) # "Add" aggregation.
config.simulation = config.simulation
config.graph_model = config.graph_model
config.training = config.training
self.device = device
self.input_size = config.graph_model.input_size
self.output_size = config.graph_model.output_size
self.hidden_dim = config.graph_model.hidden_dim
self.n_layers = config.graph_model.n_mp_layers
self.n_particles = config.simulation.n_particles
self.max_radius = config.simulation.max_radius
self.rotation_augmentation = config.training.rotation_augmentation
self.noise_level = config.training.noise_level
self.embedding_dim = config.graph_model.embedding_dim
self.n_dataset = config.training.n_runs
self.prediction = config.graph_model.prediction
self.update_type = config.graph_model.update_type
self.n_layers_update = config.graph_model.n_layers_update
self.hidden_dim_update = config.graph_model.hidden_dim_update
self.sigma = config.simulation.sigma
self.model = config.graph_model.particle_model_name
self.bc_dpos = bc_dpos
self.n_ghosts = int(config.training.n_ghosts)
self.n_particles_max = config.simulation.n_particles_max
self.lin_edge = MLP(input_size=self.input_size, output_size=self.output_size, nlayers=self.n_layers,
hidden_size=self.hidden_dim, device=self.device)
if config.simulation.has_cell_division:
self.a = nn.Parameter(
torch.tensor(np.ones((self.n_dataset, self.n_particles_max, 2)), device=self.device,
requires_grad=True, dtype=torch.float32))
else:
self.a = nn.Parameter(
torch.tensor(np.ones((self.n_dataset, int(self.n_particles) + self.n_ghosts, self.embedding_dim)),
device=self.device,
requires_grad=True, dtype=torch.float32))
if self.update_type != 'none':
self.lin_update = MLP(input_size=self.output_size + self.embedding_dim + 2, output_size=self.output_size,
nlayers=self.n_layers_update, hidden_size=self.hidden_dim_update, device=self.device)
def forward(self, data=[], data_id=[], training=[], vnorm=[], phi=[], has_field=False):
self.data_id = data_id
self.vnorm = vnorm
self.cos_phi = torch.cos(phi)
self.sin_phi = torch.sin(phi)
self.training = training
self.has_field = has_field
x, edge_index = data.x, data.edge_index
edge_index, _ = pyg_utils.remove_self_loops(edge_index)
pos = x[:, 1:3]
d_pos = x[:, 3:5]
particle_id = x[:, 0:1]
if has_field:
field = x[:, 6:7]
else:
field = torch.ones_like(x[:, 6:7])
pred = self.propagate(edge_index, pos=pos, d_pos=d_pos, particle_id=particle_id, field=field)
return pred, self.in_features, self.lin_edge_out
def message(self, pos_i, pos_j, d_pos_i, d_pos_j, particle_id_i, particle_id_j, field_j):
# squared distance
r = torch.sqrt(torch.sum(self.bc_dpos(pos_j - pos_i) ** 2, dim=1)) / self.max_radius
delta_pos = self.bc_dpos(pos_j - pos_i) / self.max_radius
dpos_x_i = d_pos_i[:, 0] / self.vnorm
dpos_y_i = d_pos_i[:, 1] / self.vnorm
dpos_x_j = d_pos_j[:, 0] / self.vnorm
dpos_y_j = d_pos_j[:, 1] / self.vnorm
if self.rotation_augmentation & (self.training == True):
new_delta_pos_x = self.cos_phi * delta_pos[:, 0] + self.sin_phi * delta_pos[:, 1]
new_delta_pos_y = -self.sin_phi * delta_pos[:, 0] + self.cos_phi * delta_pos[:, 1]
delta_pos[:, 0] = new_delta_pos_x
delta_pos[:, 1] = new_delta_pos_y
new_dpos_x_i = self.cos_phi * dpos_x_i + self.sin_phi * dpos_y_i
new_dpos_y_i = -self.sin_phi * dpos_x_i + self.cos_phi * dpos_y_i
dpos_x_i = new_dpos_x_i
dpos_y_i = new_dpos_y_i
new_dpos_x_j = self.cos_phi * dpos_x_j + self.sin_phi * dpos_y_j
new_dpos_y_j = -self.sin_phi * dpos_x_j + self.cos_phi * dpos_y_j
dpos_x_j = new_dpos_x_j
dpos_y_j = new_dpos_y_j
embedding_i = self.a[self.data_id, to_numpy(particle_id_i), :].squeeze()
embedding_j = self.a[self.data_id, to_numpy(particle_id_j), :].squeeze()
match self.model:
case 'PDE_A':
in_features = torch.cat((delta_pos, r[:, None], embedding_i), dim=-1)
case 'PDE_B' | 'PDE_B_bis' | 'PDE_Cell_B':
in_features = torch.cat((delta_pos, r[:, None], dpos_x_i[:, None], dpos_y_i[:, None], dpos_x_j[:, None],
dpos_y_j[:, None], embedding_i), dim=-1)
case 'PDE_G':
in_features = torch.cat((delta_pos, r[:, None], dpos_x_i[:, None], dpos_y_i[:, None],
dpos_x_j[:, None], dpos_y_j[:, None], embedding_j), dim=-1)
case 'PDE_GS':
in_features = torch.cat((r[:, None], embedding_j), dim=-1)
case 'PDE_E':
in_features = torch.cat(
(delta_pos, r[:, None], embedding_i, embedding_j), dim=-1)
out = self.lin_edge(in_features) * field_j
self.in_features = in_features
self.lin_edge_out = out
return out
def update(self, aggr_out):
return aggr_out # self.lin_node(aggr_out)
def psi(self, r, p):
if (len(p) == 3): # PDE_B
cohesion = p[0] * 0.5E-5 * r
separation = -p[2] * 1E-8 / r
return (cohesion + separation) * p[1] / 500 #
else: # PDE_A
return r * (p[0] * torch.exp(-r ** (2 * p[1]) / (2 * self.sigma ** 2)) - p[2] * torch.exp(
-r ** (2 * p[3]) / (2 * self.sigma ** 2)))
class model_qiqj(nn.Module):
def __init__(self, size=None, device=None):
super(model_qiqj, self).__init__()
self.device = device
self.size = size
self.qiqj = nn.Parameter(torch.randn((int(self.size), 1), device=self.device,requires_grad=True, dtype=torch.float32))
def forward(self):
x = []
for l in range(self.size):
for m in range(l,self.size,1):
x.append(self.qiqj[l] * self.qiqj[m])
return torch.stack(x)
class PDE_B_extract(MessagePassing):
"""Interaction Network as proposed in this paper:
https://proceedings.neurips.cc/paper/2016/hash/3147da8ab4a0437c15ef51a5cc7f2dc4-Abstract.html"""
def __init__(self, aggr_type=None, p=None, bc_dpos=None):
super(PDE_B_extract, self).__init__(aggr=aggr_type) # "mean" aggregation.
self.p = p
self.bc_dpos = bc_dpos
self.a1 = 0.5E-5
self.a2 = 5E-4
self.a3 = 1E-8
def forward(self, data):
x, edge_index = data.x, data.edge_index
edge_index, _ = pyg_utils.remove_self_loops(edge_index)
acc = self.propagate(edge_index, x=x)
sum = self.cohesion + self.alignment + self.separation
return acc, sum, self.cohesion, self.alignment, self.separation, self.diffx, self.diffv, self.r, self.type
def message(self, x_i, x_j):
r = torch.sum(self.bc_dpos(x_j[:, 1:3] - x_i[:, 1:3]) ** 2, dim=1) # distance squared
pp = self.p[to_numpy(x_i[:, 5]), :]
cohesion = pp[:, 0:1].repeat(1, 2) * self.a1 * self.bc_dpos(x_j[:, 1:3] - x_i[:, 1:3])
alignment = pp[:, 1:2].repeat(1, 2) * self.a2 * self.bc_dpos(x_j[:, 3:5] - x_i[:, 3:5])
separation = pp[:, 2:3].repeat(1, 2) * self.a3 * self.bc_dpos(x_i[:, 1:3] - x_j[:, 1:3]) / (
r[:, None].repeat(1, 2))
self.cohesion = cohesion
self.alignment = alignment
self.separation = separation
self.r = r
self.diffx = self.bc_dpos(x_j[:, 1:3] - x_i[:, 1:3])
self.diffv = self.bc_dpos(x_j[:, 3:5] - x_i[:, 3:5])
self.type = x_i[:, 5]
return (separation + alignment + cohesion)
def psi(self, r, p):
cohesion = p[0] * self.a1 * r
separation = -p[2] * self.a3 / r
return (cohesion + separation)
class Mesh_RPS_extract(MessagePassing):
"""Interaction Network as proposed in this paper:
https://proceedings.neurips.cc/paper/2016/hash/3147da8ab4a0437c15ef51a5cc7f2dc4-Abstract.html"""
def __init__(self, aggr_type=None, config=None, device=None, bc_dpos=None):
super(Mesh_RPS_extract, self).__init__(aggr=aggr_type)
config.simulation = config.simulation
config.graph_model = config.graph_model
self.device = device
self.input_size = config.graph_model.input_size
self.output_size = config.graph_model.output_size
self.hidden_size = config.graph_model.hidden_dim
self.nlayers = config.graph_model.n_mp_layers
self.embedding_dim = config.graph_model.embedding_dim
self.nparticles = config.simulation.n_particles
self.ndataset = config.training.n_runs
self.bc_dpos = bc_dpos
self.lin_phi = MLP(input_size=self.input_size, output_size=self.output_size, nlayers=self.nlayers,
hidden_size=self.hidden_size, device=self.device)
self.a = nn.Parameter(
torch.tensor(np.ones((int(self.ndataset), int(self.nparticles), self.embedding_dim)), device=self.device,
requires_grad=True, dtype=torch.float32))
def forward(self, data, data_id):
self.data_id = data_id
x, edge_index, edge_attr = data.x, data.edge_index, data.edge_attr
uvw = data.x[:, 6:9]
laplacian_uvw = self.propagate(edge_index, uvw=uvw, discrete_laplacian=edge_attr)
particle_id = to_numpy(x[:, 0])
embedding = self.a[self.data_id, particle_id, :]
input_phi = torch.cat((laplacian_uvw, uvw, embedding), dim=-1)
pred = self.lin_phi(input_phi)
return pred, input_phi, embedding
def message(self, uvw_j, discrete_laplacian):
return discrete_laplacian[:, None] * uvw_j
def update(self, aggr_out):
return aggr_out # self.lin_node(aggr_out)
def psi(self, r, p):
return p * r
def load_training_data(dataset_name, n_runs, log_dir, device):
x_list = []
y_list = []
print('Load data ...')
time.sleep(0.5)
for run in trange(n_runs):
# check if path exists
if os.path.exists(f'graphs_data/graphs_{dataset_name}/x_list_{run}.pt'):
x = torch.load(f'graphs_data/graphs_{dataset_name}/x_list_{run}.pt', map_location=device)
y = torch.load(f'graphs_data/graphs_{dataset_name}/y_list_{run}.pt', map_location=device)
else:
x = np.load(f'graphs_data/graphs_{dataset_name}/x_list_{run}.npy')
x = torch.tensor(x, dtype=torch.float32, device=device)
y = np.load(f'graphs_data/graphs_{dataset_name}/y_list_{run}.npy')
y = torch.tensor(y, dtype=torch.float32, device=device)
x_list.append(x)
y_list.append(y)
vnorm = torch.load(os.path.join(log_dir, 'vnorm.pt'), map_location=device).squeeze()
ynorm = torch.load(os.path.join(log_dir, 'ynorm.pt'), map_location=device).squeeze()
print("vnorm:{:.2e}, ynorm:{:.2e}".format(to_numpy(vnorm), to_numpy(ynorm)))
x = []
y = []
return x_list, y_list, vnorm, ynorm
def plot_embedding_func_cluster_tracking(model, config, config_file, embedding_cluster, cmap, index_particles, indexes, type_list,
n_particle_types, n_particles, ynorm, epoch, log_dir, embedding_type, bLatex, device):
if embedding_type == 1:
embedding = to_numpy(model.a.clone().detach())
embedding = embedding[indexes.astype(int)]
fig, ax = fig_init()
for n in range(n_particle_types):
pos = np.argwhere(type_list == n).squeeze().astype(int)
plt.scatter(embedding[pos, 0], embedding[pos, 1], s=1, alpha=0.25)
if bLatex:
plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
else:
plt.xlabel(r'$a_{i0}$', fontsize=78)
plt.ylabel(r'$a_{i1}$', fontsize=78)
plt.xlim(config.plotting.embedding_lim)
plt.ylim(config.plotting.embedding_lim)
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/all_embedding_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
else:
fig, ax = fig_init()
for k in trange(0, config.simulation.n_frames - 2):
embedding = to_numpy(model.a[k * n_particles:(k + 1) * n_particles, :].clone().detach())
for n in range(n_particle_types):
plt.scatter(embedding[index_particles[n], 0], embedding[index_particles[n], 1], s=1,
color=cmap.color(n), alpha=0.025)
if bLatex:
plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
else:
plt.xlabel(r'$a_{i0}$', fontsize=78)
plt.ylabel(r'$a_{i1}$', fontsize=78)
plt.xlim(config.plotting.embedding_lim)
plt.ylim(config.plotting.embedding_lim)
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/all_embedding_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
func_list, proj_interaction = analyze_edge_function_tracking(rr=[], vizualize=False, config=config,
model_MLP=model.lin_edge, model_a=model.a,
n_particles=n_particles, ynorm=ynorm,
indexes=indexes, type_list = type_list,
cmap=cmap, embedding_type = embedding_type, device=device)
fig, ax = fig_init()
proj_interaction = (proj_interaction - np.min(proj_interaction)) / (np.max(proj_interaction) - np.min(proj_interaction) + 1e-10)
if embedding_type == 1:
for n in range(n_particle_types):
pos = np.argwhere(type_list == n).squeeze().astype(int)
plt.scatter(proj_interaction[pos, 0], proj_interaction[pos, 1], s=1, alpha=0.25)
else:
for n in range(n_particle_types):
plt.scatter(proj_interaction[index_particles[n], 0],
proj_interaction[index_particles[n], 1], color=cmap.color(n), s=1, alpha=0.25)
plt.xlabel(r'UMAP 0', fontsize=78)
plt.ylabel(r'UMAP 1', fontsize=78)
plt.xlim([-0.2, 1.2])
plt.ylim([-0.2, 1.2])
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/UMAP_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
embedding = to_numpy(model.a.clone().detach())
if embedding_type == 1:
embedding = embedding[indexes.astype(int)]
else:
embedding = embedding[0:n_particles]
labels, n_clusters, new_labels = sparsify_cluster(config.training.cluster_method, proj_interaction, embedding,
config.training.cluster_distance_threshold, type_list,
n_particle_types, embedding_cluster)
accuracy = metrics.accuracy_score(type_list, new_labels)
fig, ax = fig_init()
for n in np.unique(labels):
pos = np.argwhere(labels == n).squeeze().astype(int)
plt.scatter(proj_interaction[pos, 0], proj_interaction[pos, 1], s=1, alpha=0.25)
return accuracy, n_clusters, new_labels
def plot_embedding_func_cluster_state(model, config, config_file, embedding_cluster, cmap, type_list, type_stack, id_list,
n_particle_types, ynorm, epoch, log_dir, bLatex, device):
fig, ax = fig_init()
for n in range(n_particle_types):
pos = torch.argwhere(type_stack == n).squeeze()
plt.scatter(to_numpy(model.a[pos, 0]), to_numpy(model.a[pos, 1]), s=1, color=cmap.color(n), alpha=0.25)
if bLatex:
plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
else:
plt.xlabel(r'$a_{i0}$', fontsize=78)
plt.ylabel(r'$a_{i1}$', fontsize=78)
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/embedding_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
fig, ax = fig_init()
func_list, true_type_list, short_model_a_list, proj_interaction = analyze_edge_function_state(rr=[], config=config,
model=model,
id_list=id_list, type_list=type_list, ynorm=ynorm,
cmap=cmap, visualize=True, device=device)
plt.savefig(f"./{log_dir}/results/function_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
fig, ax = fig_init()
for n in range(n_particle_types):
pos = np.argwhere(true_type_list == n).squeeze().astype(int)
if len(pos)>0:
plt.scatter(proj_interaction[pos, 0], proj_interaction[pos, 1], color=cmap.color(n), s=100, alpha=0.25, edgecolors='none')
plt.xlabel(r'UMAP 0', fontsize=78)
plt.ylabel(r'UMAP 1', fontsize=78)
plt.xlim([-0.2, 1.2])
plt.ylim([-0.2, 1.2])
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/UMAP_{config_file}_{epoch}.tif", dpi=170.7)
plt.close()
embedding = proj_interaction
labels, n_clusters, new_labels = sparsify_cluster_state(config.training.cluster_method, proj_interaction, embedding,
config.training.cluster_distance_threshold, true_type_list,
n_particle_types, embedding_cluster)
fig, ax = fig_init()
for n in range(n_particle_types):
pos = np.argwhere(new_labels == n).squeeze().astype(int)
if len(pos)>0:
plt.scatter(proj_interaction[pos, 0], proj_interaction[pos, 1], color=cmap.color(n), s=10, alpha=0.25)
plt.xlim([-0.2, 1.2])
plt.ylim([-0.2, 1.2])
plt.tight_layout()
plt.close()
accuracy = metrics.accuracy_score(true_type_list, new_labels)
# calculate type for all nodes
fig, ax = fig_init()
median_center_list = []
for n in range(n_clusters):
pos = np.argwhere(new_labels == n).squeeze().astype(int)
pos = np.array(pos)
if pos.size > 0:
median_center = short_model_a_list[pos, :]
plt.scatter(to_numpy(short_model_a_list[pos,0]),to_numpy(short_model_a_list[pos,1]))
median_center = torch.mean(median_center, dim=0)
plt.scatter(to_numpy(median_center[0]), to_numpy(median_center[1]), s=100, color='black')
median_center_list.append(median_center)
median_center_list = torch.stack(median_center_list)
median_center_list = median_center_list.to(dtype=torch.float32)
plt.close()
distance = torch.sum((model.a[:, None, :] - median_center_list[None, :, :]) ** 2, dim=2)
result = distance.min(dim=1)
min_index = result.indices
new_labels = to_numpy(min_index).astype(int)
accuracy = metrics.accuracy_score(to_numpy(type_stack.squeeze()), new_labels)
return accuracy, n_clusters, new_labels
def plot_embedding_func_cluster(model, config, config_file, embedding_cluster, cmap, index_particles, type_list,
n_particle_types, n_particles, ynorm, epoch, log_dir, alpha, bLatex, device):
fig, ax = fig_init()
if config.training.do_tracking:
embedding = to_numpy(model.a[0:n_particles])
else:
embedding = get_embedding(model.a, 1)
if config.training.particle_dropout > 0:
embedding = embedding[0:n_particles]
if n_particle_types > 1000:
plt.scatter(embedding[:, 0], embedding[:, 1], c=to_numpy(x[:, 5]) / n_particles, s=10,
cmap=cc)
else:
for n in range(n_particle_types):
pos = torch.argwhere(type_list == n)
pos = to_numpy(pos)
if len(pos) > 0:
plt.scatter(embedding[pos, 0], embedding[pos, 1], color=cmap.color(n), s=10)
if bLatex:
plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
else:
plt.xlabel(r'$a_{i0}$', fontsize=78)
plt.ylabel(r'$a_{i1}$', fontsize=78)
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/embedding_{epoch}.tif", dpi=170.7)
plt.close()
fig, ax = fig_init()
if 'PDE_N' in config.graph_model.signal_model_name:
model_MLP_ = model.lin_phi
else:
model_MLP_ = model.lin_edge
func_list, proj_interaction = analyze_edge_function(rr=[], vizualize=True, config=config, model_MLP=model_MLP_, model_a=model.a, type_list=to_numpy(type_list), n_particles=n_particles, dataset_number=1, ynorm=ynorm, cmap=cmap, device=device)
plt.close()
# trans = umap.UMAP(n_neighbors=100, n_components=2, init='spectral').fit(func_list_)
# proj_interaction = trans.transform(func_list_)
# tsne = TSNE(n_components=2, random_state=0)
# proj_interaction = tsne.fit_transform(func_list_)
fig, ax = fig_init()
proj_interaction = (proj_interaction - np.min(proj_interaction)) / (
np.max(proj_interaction) - np.min(proj_interaction) + 1e-10)
for n in range(n_particle_types):
pos = torch.argwhere(type_list == n)
pos = to_numpy(pos)
if len(pos) > 0:
plt.scatter(proj_interaction[pos, 0],
proj_interaction[pos, 1], color=cmap.color(n), s=200, alpha=0.1)
plt.xlabel(r'UMAP 0', fontsize=78)
plt.ylabel(r'UMAP 1', fontsize=78)
plt.xlim([-0.2, 1.2])
plt.ylim([-0.2, 1.2])
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/UMAP_functions_{epoch}.tif", dpi=170.7)
plt.close()
config.training.cluster_distance_threshold = 0.01
labels, n_clusters, new_labels = sparsify_cluster(config.training.cluster_method, proj_interaction, embedding,
config.training.cluster_distance_threshold, type_list,
n_particle_types, embedding_cluster)
accuracy = metrics.accuracy_score(to_numpy(type_list), new_labels)
fig, ax = fig_init()
for n in range(n_clusters):
pos = np.argwhere(labels == n)
if pos.size > 0:
plt.scatter(embedding[pos, 0], embedding[pos, 1], s=10)
if bLatex:
plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
else:
plt.xlabel(r'$a_{i0}$', fontsize=78)
plt.ylabel(r'$a_{i1}$', fontsize=78)
plt.tight_layout()
plt.savefig(f"./{log_dir}/results/clustered_embedding_{epoch}.tif", dpi=170.7)
plt.close()
# model_a_ = model.a[1].clone().detach()
# for n in range(n_clusters):
# pos = np.argwhere(labels == n).squeeze().astype(int)
# pos = np.array(pos)
# if pos.size > 0:
# median_center = model_a_[pos, :]
# median_center = torch.median(median_center, dim=0).values
# model_a_[pos, :] = median_center
#
# embedding = to_numpy(model_a_)
# fig, ax = fig_init()
# for n in range(n_clusters):
# pos = np.argwhere(labels == n)
# if pos.size > 0:
# plt.scatter(embedding[pos, 0], embedding[pos, 1],s=10)
# plt.xlabel(r'$\ensuremath{\mathbf{a}}_{i0}$', fontsize=78)
# plt.ylabel(r'$\ensuremath{\mathbf{a}}_{i1}$', fontsize=78)
# plt.tight_layout()
# plt.savefig(f"./{log_dir}/results/UMAP_clustered_embedding_{epoch}.tif", dpi=170.7)
# plt.close()
return accuracy, n_clusters, new_labels
def plot_focused_on_cell(config, run, style, step, cell_id, bLatex, device):
dataset_name = config.dataset
simulation_config = config.simulation
model_config = config.graph_model
training_config = config.training
has_adjacency_matrix = (simulation_config.connectivity_file != '')
has_mesh = (config.graph_model.mesh_model_name != '')
only_mesh = (config.graph_model.particle_model_name == '') & has_mesh
has_ghost = config.training.n_ghosts > 0
max_radius = simulation_config.max_radius
min_radius = simulation_config.min_radius
n_particle_types = simulation_config.n_particle_types
n_particles = simulation_config.n_particles
n_nodes = simulation_config.n_nodes
n_runs = training_config.n_runs
n_frames = simulation_config.n_frames
delta_t = simulation_config.delta_t
cmap = CustomColorMap(config=config) # create colormap for given model_config
dimension = simulation_config.dimension
has_siren = 'siren' in model_config.field_type
has_siren_time = 'siren_with_time' in model_config.field_type
has_field = ('PDE_ParticleField' in config.graph_model.particle_model_name)
l_dir = os.path.join('.', 'log')
log_dir = os.path.join(l_dir, 'try_{}'.format(config_file))
files = glob.glob(f"./{log_dir}/tmp_recons/*")
for f in files:
os.remove(f)
print('Load data ...')
x_list = torch.load(f'graphs_data/graphs_{dataset_name}/x_list_{run}.pt', map_location=device)
mass_time_series = get_time_series(x_list, cell_id, feature='mass')
vx_time_series = get_time_series(x_list, cell_id, feature='velocity_x')
vy_time_series = get_time_series(x_list, cell_id, feature='velocity_y')
v_time_series = np.sqrt(vx_time_series ** 2 + vy_time_series ** 2)
stage_time_series = get_time_series(x_list, cell_id, feature="stage")
stage_time_series_color = ["blue" if i == 0 else "orange" if i == 1 else "green" if i == 2 else "pink" for i in stage_time_series]
for it in trange(0,n_frames,step):
x = x_list[it].clone().detach()
T1 = x[:, 5:6].clone().detach()
H1 = x[:, 6:8].clone().detach()
X1 = x[:, 1:3].clone().detach()
index_particles = get_index_particles(x, n_particle_types, dimension)
pos_cell = torch.argwhere(x[:,0] == cell_id)
if len(pos_cell)>0:
if 'latex' in style:
plt.rcParams['text.usetex'] = True
rc('font', **{'family': 'serif', 'serif': ['Palatino']})
if 'color' in style:
# matplotlib.use("Qt5Agg")
matplotlib.rcParams['savefig.pad_inches'] = 0
fig = plt.figure(figsize=(24, 12))
ax = fig.add_subplot(1, 2, 1)
ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
ax.yaxis.set_major_locator(plt.MaxNLocator(3))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
index_particles = []
for n in range(n_particle_types):
pos = torch.argwhere((T1.squeeze() == n) & (H1[:, 0].squeeze() == 1))
pos = to_numpy(pos[:, 0].squeeze()).astype(int)
index_particles.append(pos)
# plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
# s=marker_size, color=cmap.color(n))
size = set_size(x, index_particles[n], 10)
plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
s=size, color=cmap.color(n))
dead_cell = np.argwhere(to_numpy(H1[:, 0]) == 0)
if len(dead_cell) > 0:
plt.scatter(to_numpy(X1[dead_cell[:, 0].squeeze(), 0]), to_numpy(X1[dead_cell[:, 0].squeeze(), 1]),
s=2, color='k', alpha=0.5)
if 'latex' in style:
plt.xlabel(r'$x$', fontsize=78)
plt.ylabel(r'$y$', fontsize=78)
plt.xticks(fontsize=48.0)
plt.yticks(fontsize=48.0)
elif 'frame' in style:
plt.xlabel('x', fontsize=13)
plt.ylabel('y', fontsize=16)
plt.xticks(fontsize=16.0)
plt.yticks(fontsize=16.0)
ax.tick_params(axis='both', which='major', pad=15)
plt.text(0, 1.05,
f'frame {it}, {int(n_particles_alive)} alive particles ({int(n_particles_dead)} dead), {edge_index.shape[1]} edges ',
ha='left', va='top', transform=ax.transAxes, fontsize=16)
plt.xticks([])
plt.yticks([])
center_x = to_numpy(x[pos_cell, 1])
center_y = to_numpy(x[pos_cell, 2])
plt.xlim([center_x - 0.1, center_x + 0.1])
plt.ylim([center_y - 0.1, center_y + 0.1])
ax = fig.add_subplot(2, 2, 2)
plt.plot(mass_time_series, color='k', ls="--")
plt.scatter([i for i in range(it)], mass_time_series[0:it], color=stage_time_series_color[0:it], s=15)
# plt.plot(mass_time_series[0:it], color = color,linewidth=3)
plt.ylim(0, max(mass_time_series) + 50)
ax = fig.add_subplot(2, 2, 4)
plt.plot(v_time_series, color='k', ls="--")
plt.plot(v_time_series[0:it], color = 'red',linewidth=4)
num = f"{it:06}"
plt.tight_layout()
plt.savefig(f"./{log_dir}/tmp_recons/cell_{cell_id}_frame_{num}.tif", dpi=80)
plt.close()
def plot_generated(config, run, style, step, bLatex, device):
dataset_name = config.dataset
simulation_config = config.simulation
model_config = config.graph_model
training_config = config.training
has_adjacency_matrix = (simulation_config.connectivity_file != '')
has_mesh = (config.graph_model.mesh_model_name != '')
only_mesh = (config.graph_model.particle_model_name == '') & has_mesh
has_ghost = config.training.n_ghosts > 0
max_radius = simulation_config.max_radius
min_radius = simulation_config.min_radius
n_particle_types = simulation_config.n_particle_types
n_particles = simulation_config.n_particles
n_nodes = simulation_config.n_nodes
n_runs = training_config.n_runs
n_frames = simulation_config.n_frames
delta_t = simulation_config.delta_t
cmap = CustomColorMap(config=config) # create colormap for given model_config
dimension = simulation_config.dimension
has_siren = 'siren' in model_config.field_type
has_siren_time = 'siren_with_time' in model_config.field_type
has_field = ('PDE_ParticleField' in config.graph_model.particle_model_name)
l_dir = os.path.join('.', 'log')
log_dir = os.path.join(l_dir, 'try_{}'.format(config_file))
files = glob.glob(f"./{log_dir}/tmp_recons/*")
for f in files:
os.remove(f)
os.makedirs(os.path.join(log_dir, 'generated_bw'), exist_ok=True)
os.makedirs(os.path.join(log_dir, 'generated_color'), exist_ok=True)
files = glob.glob(f"./{log_dir}/generated_bw/*")
for f in files:
os.remove(f)
files = glob.glob(f"./{log_dir}/generated_color/*")
for f in files:
os.remove(f)
print('Load data ...')
x_list = torch.load(f'graphs_data/graphs_{dataset_name}/x_list_{run}.pt', map_location=device)
for it in trange(0,n_frames,step):
x = x_list[it].clone().detach()
T1 = x[:, 5:6].clone().detach()
H1 = x[:, 6:8].clone().detach()
X1 = x[:, 1:3].clone().detach()
if 'latex' in style:
plt.rcParams['text.usetex'] = True
rc('font', **{'family': 'serif', 'serif': ['Palatino']})
if 'voronoi' in style:
matplotlib.use("Qt5Agg")
matplotlib.rcParams['savefig.pad_inches'] = 0
vor, vertices_pos, vertices_per_cell, all_points = get_vertices(points=X1, device=device)
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(1, 1, 1)
plt.xticks([])
plt.yticks([])
index_particles = []
voronoi_plot_2d(vor, ax=ax, show_vertices=False, line_colors='black', line_width=1, line_alpha=0.5, point_size=0)
if 'color' in style:
for n in range(n_particle_types):
pos = torch.argwhere((T1.squeeze() == n) & (H1[:, 0].squeeze() == 1))
pos = to_numpy(pos[:, 0].squeeze()).astype(int)
index_particles.append(pos)
size = set_size(x, index_particles[n], 10) / 10
patches = []
for i in index_particles[n]:
cell = vertices_per_cell[i]
vertices = to_numpy(vertices_pos[cell, :])
patches.append(Polygon(vertices, closed=True))
pc = PatchCollection(patches, alpha=0.4, facecolors=cmap.color(n))
ax.add_collection(pc)
if 'center' in style:
plt.scatter(to_numpy(X1[index_particles[n], 0]), to_numpy(X1[index_particles[n], 1]), s=size,
color=cmap.color(n))
if 'vertices' in style:
plt.scatter(to_numpy(vertices_pos[:, 0]), to_numpy(vertices_pos[:, 1]), s=5, color='k')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.tight_layout()
num = f"{it:06}"
if 'color' in style:
plt.savefig(f"./{log_dir}/generated_color/frame_{num}.tif", dpi=85.35)
else:
plt.savefig(f"./{log_dir}/generated_bw/frame_{num}.tif", dpi=85.35)
plt.close()
else:
matplotlib.rcParams['savefig.pad_inches'] = 0
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(1, 1, 1)
ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
ax.yaxis.set_major_locator(plt.MaxNLocator(3))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
index_particles = []
for n in range(n_particle_types):
pos = torch.argwhere((T1.squeeze() == n) & (H1[:, 0].squeeze() == 1))
pos = to_numpy(pos[:, 0].squeeze()).astype(int)
index_particles.append(pos)
# plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
# s=marker_size, color=cmap.color(n))
size = set_size(x, index_particles[n], 10) / 10
plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
s=40, color=cmap.color(n))
dead_cell = np.argwhere(to_numpy(H1[:, 0]) == 0)
if len(dead_cell) > 0:
plt.scatter(to_numpy(X1[dead_cell[:, 0].squeeze(), 0]), to_numpy(X1[dead_cell[:, 0].squeeze(), 1]),
s=2, color='k', alpha=0.5)
if 'latex' in style:
plt.xlabel(r'$x$', fontsize=78)
plt.ylabel(r'$y$', fontsize=78)
plt.xticks(fontsize=48.0)
plt.yticks(fontsize=48.0)
elif 'frame' in style:
plt.xlabel('x', fontsize=13)
plt.ylabel('y', fontsize=16)
plt.xticks(fontsize=16.0)
plt.yticks(fontsize=16.0)
ax.tick_params(axis='both', which='major', pad=15)
plt.text(0, 1.05,
f'frame {it}, {int(n_particles_alive)} alive particles ({int(n_particles_dead)} dead), {edge_index.shape[1]} edges ',
ha='left', va='top', transform=ax.transAxes, fontsize=16)
plt.xticks([])
plt.yticks([])
plt.xlim([0,1])
plt.ylim([0,1])
plt.tight_layout()
num = f"{it:06}"
plt.savefig(f"./{log_dir}/generated_color/frame_{num}.tif", dpi=80)
plt.close()
matplotlib.rcParams['savefig.pad_inches'] = 0
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(1, 1, 1)
ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
ax.yaxis.set_major_locator(plt.MaxNLocator(3))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
index_particles = []
for n in range(n_particle_types):
pos = torch.argwhere((T1.squeeze() == n) & (H1[:, 0].squeeze() == 1))
pos = to_numpy(pos[:, 0].squeeze()).astype(int)
index_particles.append(pos)
# plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
# s=marker_size, color=cmap.color(n))
size = set_size(x, index_particles[n], 10)
plt.scatter(to_numpy(x[index_particles[n], 1]), to_numpy(x[index_particles[n], 2]),
s=size/10, color='k')
dead_cell = np.argwhere(to_numpy(H1[:, 0]) == 0)
if len(dead_cell) > 0:
plt.scatter(to_numpy(X1[dead_cell[:, 0].squeeze(), 0]), to_numpy(X1[dead_cell[:, 0].squeeze(), 1]),
s=2, color='k', alpha=0.5)
if 'latex' in style:
plt.xlabel(r'$x$', fontsize=78)
plt.ylabel(r'$y$', fontsize=78)
plt.xticks(fontsize=48.0)
plt.yticks(fontsize=48.0)
elif 'frame' in style:
plt.xlabel('x', fontsize=13)
plt.ylabel('y', fontsize=16)
plt.xticks(fontsize=16.0)
plt.yticks(fontsize=16.0)
ax.tick_params(axis='both', which='major', pad=15)
plt.text(0, 1.05,
f'frame {it}, {int(n_particles_alive)} alive particles ({int(n_particles_dead)} dead), {edge_index.shape[1]} edges ',
ha='left', va='top', transform=ax.transAxes, fontsize=16)
plt.xticks([])
plt.yticks([])
plt.xlim([0,1])
plt.ylim([0,1])
plt.tight_layout()
num = f"{it:06}"
plt.savefig(f"./{log_dir}/generated_bw/frame_{num}.tif", dpi=80)
plt.close()
def plot_confusion_matrix(index, true_labels, new_labels, n_particle_types, epoch, it, fig, ax, bLatex):
# print(f'plot confusion matrix epoch:{epoch} it: {it}')
plt.text(-0.25, 1.1, f'{index}', ha='left', va='top', transform=ax.transAxes, fontsize=12)
confusion_matrix = metrics.confusion_matrix(true_labels, new_labels) # , normalize='true')
cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix=confusion_matrix)
if n_particle_types > 8:
cm_display.plot(ax=fig.gca(), cmap='Blues', include_values=False, colorbar=False)
else:
cm_display.plot(ax=fig.gca(), cmap='Blues', include_values=True, values_format='d', colorbar=False)
accuracy = metrics.accuracy_score(true_labels, new_labels)
plt.title(f'accuracy: {np.round(accuracy, 2)}', fontsize=12)
# print(f'accuracy: {np.round(accuracy,3)}')
plt.xticks(fontsize=10.0)
plt.yticks(fontsize=10.0)
plt.xlabel(r'Predicted label', fontsize=12)
plt.ylabel(r'True label', fontsize=12)
return accuracy
def plot_cell_rates(config, device, log_dir, n_particle_types, type_list, x_list, new_labels, cmap, logger, bLatex):
n_frames = config.simulation.n_frames
delta_t = config.simulation.delta_t
cell_cycle_length = np.array(config.simulation.cell_cycle_length)
if len(cell_cycle_length) == 1:
cell_cycle_length = to_numpy(torch.load(f'graphs_data/graphs_{config.dataset}/cycle_length.pt', map_location=device))
print('plot cell rates ...')
N_cells_alive = np.zeros((n_frames, n_particle_types))
N_cells_dead = np.zeros((n_frames, n_particle_types))
if os.path.exists(f"./{log_dir}/results/x_.npy"):
x_ = np.load(f"./{log_dir}/results/x_.npy")
N_cells_alive = np.load(f"./{log_dir}/results/cell_alive.npy")
N_cells_dead = np.load(f"./{log_dir}/results/cell_dead.npy")
else:
for it in trange(n_frames):
x = x_list[0][it].clone().detach()
particle_index = to_numpy(x[:, 0:1]).astype(int)
x[:, 5:6] = torch.tensor(new_labels[particle_index], device=device)
if it == 0:
x_=x_list[0][it].clone().detach()
else:
x_=torch.concatenate((x_,x),axis=0)
for k in range(n_particle_types):
pos = torch.argwhere((x[:, 5:6] == k) & (x[:, 6:7] == 1))
N_cells_alive[it, k] = pos.shape[0]
pos = torch.argwhere((x[:, 5:6] == k) & (x[:, 6:7] == 0))
N_cells_dead[it, k] = pos.shape[0]
x_list=[]
x_ = to_numpy(x_)
print('save data ...')
np.save(f"./{log_dir}/results/cell_alive.npy", N_cells_alive)
np.save(f"./{log_dir}/results/cell_dead.npy", N_cells_dead)
np.save(f"./{log_dir}/results/x_.npy", x_)
print('plot results ...')
last_frame_growth = np.argwhere(np.diff(N_cells_alive[:, 0], axis=0))