-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgnns.py
5898 lines (5186 loc) · 272 KB
/
gnns.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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from copy import deepcopy
from pickle import FALSE
import torch
import torch.nn as nn
from torch_geometric.nn import MessagePassing
from torch_geometric.data import Data
from torch_scatter import scatter
import torch.nn.functional as F
import numpy as np
import torch_geometric
import torch_scatter
from random import choice
import pdb
import time
import math
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..'))
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..', '..'))
from lamp.datasets.arcsimmesh_dataset import ArcsimMesh
from lamp.datasets.mppde1d_dataset import get_data_pred, update_edge_attr_1d
from lamp.pytorch_net.util import to_np_array, init_args, to_cpu, Attr_Dict
from lamp.pytorch_net.net import fill_triangular, matrix_diag_transform
from lamp.utils_model import FCBlock
from lamp.utils import p, copy_data, sample_reward_beta, deepsnap_to_pyg, attrdict_to_pygdict, loss_op_core, parse_multi_step, to_tuple_shape, get_activation, seed_everything, edge_index_to_num, add_edge_normal_curvature, load_data
try:
import dolfin as dolfin
except:
pass
# ## Helper classes:
# In[ ]:
class processor_mean(MessagePassing):
def __init__(
self,
in_channels,
out_channels,
layer_norm=False,
act_name='relu',
edge_attr=False
):
super(processor_mean, self).__init__(aggr="mean") # "Add" aggregation.
self.edge_attr = edge_attr
if self.edge_attr:
in_features = in_channels * 3
else:
in_features = in_channels * 2
self.edge_encoder = FCBlock(in_features=in_features,
out_features=out_channels,
num_hidden_layers=2,
hidden_features=in_channels,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.node_encoder = FCBlock(in_features=in_channels*2,
out_features=out_channels,
num_hidden_layers=2,
hidden_features=in_channels,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.latent_dim = out_channels
def forward(self, graph):
# pdb.set_trace()
edge_index = graph.edge_index
# cat features together (eij,vi,ei)
x_receiver = torch.gather(graph.x, 0, edge_index[0,:].unsqueeze(-1).repeat(1, graph.x.shape[1]))
x_sender = torch.gather(graph.x, 0, edge_index[1,:].unsqueeze(-1).repeat(1,graph.x.shape[1]))
# pdb.set_trace()
if not self.edge_attr:
edge_features = torch.cat([x_receiver, x_sender], dim=-1)
else:
edge_features = torch.cat([x_receiver, x_sender, graph.edge_attr], dim=-1)
# edge processor
edge_features = self.edge_encoder(edge_features)
# aggregate edge_features
#try:
save_edges = edge_index.clone().detach().cpu()
save_x = graph.x.clone().detach().cpu()
save_edgefeat = edge_features.clone().detach().cpu()
#pdb.set_trace()
node_features = self.propagate(edge_index, x=graph.x, edge_attr=edge_features)
#except:
# pdb.set_trace()
# cat features for node processor (vi,\sum_eij)
features = torch.cat([graph.x, node_features[:,self.latent_dim:]],dim=-1)
# node processor and update graph
graph.x = self.node_encoder(features) + graph.x
if self.edge_attr:
graph.edge_attr = edge_features
return graph
def message(self, x_i, edge_attr):
z = torch.cat([x_i, edge_attr], dim=-1)
return z
class processor(MessagePassing):
def __init__(
self,
in_channels,
out_channels,
layer_norm=False,
act_name='relu',
edge_attr=False
):
super(processor, self).__init__(aggr='add') # "Add" aggregation.
self.edge_attr = edge_attr
if self.edge_attr:
in_features = in_channels * 3
else:
in_features = in_channels * 2
self.edge_encoder = FCBlock(in_features=in_features,
out_features=out_channels,
num_hidden_layers=2,
hidden_features=in_channels,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.node_encoder = FCBlock(in_features=in_channels*2,
out_features=out_channels,
num_hidden_layers=2,
hidden_features=in_channels,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.latent_dim = out_channels
def forward(self, graph):
# pdb.set_trace()
edge_index = graph.edge_index
# cat features together (eij,vi,ei)
x_receiver = torch.gather(graph.x, 0, edge_index[0,:].unsqueeze(-1).repeat(1, graph.x.shape[1]))
x_sender = torch.gather(graph.x, 0, edge_index[1,:].unsqueeze(-1).repeat(1,graph.x.shape[1]))
# pdb.set_trace()
if not self.edge_attr:
edge_features = torch.cat([x_receiver, x_sender], dim=-1)
else:
edge_features = torch.cat([x_receiver, x_sender, graph.edge_attr], dim=-1)
# edge processor
edge_features = self.edge_encoder(edge_features)
# aggregate edge_features
#try:
save_edges = edge_index.clone().detach().cpu()
save_x = graph.x.clone().detach().cpu()
save_edgefeat = edge_features.clone().detach().cpu()
#pdb.set_trace()
node_features = self.propagate(edge_index, x=graph.x, edge_attr=edge_features)
#except:
# pdb.set_trace()
# cat features for node processor (vi,\sum_eij)
features = torch.cat([graph.x, node_features[:,self.latent_dim:]],dim=-1)
# node processor and update graph
graph.x = self.node_encoder(features) + graph.x
if self.edge_attr:
graph.edge_attr = edge_features
return graph
def message(self, x_i, edge_attr):
z = torch.cat([x_i, edge_attr], dim=-1)
return z
class normalizer(nn.Module):
def __init__(self, dim, mean=0, std=1e-8, max_acc = 60*600):
super().__init__()
self.acc_sum = nn.Parameter(torch.zeros(dim, device=self.device), requires_grad=False)
self.acc_sum_squared = nn.Parameter(torch.zeros(dim, device=self.device), requires_grad=False)
self.mean = nn.Parameter(torch.zeros(dim, device=self.device), requires_grad=False)
self.std = nn.Parameter(torch.ones(dim, device=self.device), requires_grad=False)
self.total_acc = 0
self.max_acc = max_acc
def update(self, value, train):
if self.total_acc<self.max_acc*value.shape[0] and train:
self.total_acc += value.shape[0]
self.acc_sum += torch.sum(value,0).data
self.acc_sum_squared += torch.sum(value**2,0).data
safe_count = max(1,self.total_acc)
self.mean = nn.Parameter(self.acc_sum/safe_count)
self.std = nn.Parameter(torch.maximum(torch.sqrt(self.acc_sum_squared / safe_count - self.mean**2),torch.tensor(1e-5, dtype=float, device=self.device)))
return (value-self.mean.data)/self.std.data
def reverse(self,value):
return value*self.std.data+self.mean.data
def get_data_dropout(data, dropout_mode, exclude_idx=None, sample_idx=None):
"""
Randomly dropout nodes of a path graph. Only work for 1d case.
Args:
dropout_mode: "None" or f"node:{dropout_prob}" or f"node:{dropout_prob}:0.3" or "uniform:{interval}".
if startswith "uniform", the exclude_idx will be used to do uniform subsampling.
"""
if dropout_mode == "None":
return data
if len(dropout_mode.split(":")) == 2:
dropout_target, dropout_prob = dropout_mode.split(":")
is_dropout_prob = 1
elif len(dropout_mode.split(":")) == 3:
dropout_target, dropout_prob, is_dropout_prob = dropout_mode.split(":")
is_dropout_prob = float(is_dropout_prob)
if "-" in dropout_prob:
dropout_prob_min, dropout_prob_max = dropout_prob.split("-")
dropout_prob_min, dropout_prob_max = float(dropout_prob_min), float(dropout_prob_max)
else:
dropout_prob_min, dropout_prob_max = float(dropout_prob), float(dropout_prob)
if dropout_target in ["node", "uniform"]:
if np.random.rand() > is_dropout_prob:
return data
if hasattr(data, "node_feature"):
length = data.node_feature["n0"].shape[0]
device = data.node_feature["n0"].device
else:
length = data.x.shape[0]
device = data.x.device
nx = dict(to_tuple_shape(data.original_shape))["n0"][0]
batch_size = length // nx
edge_index_new_list = []
nx_new_sum = 0
idx_list = []
batch_list = []
if dropout_target == "uniform":
interval = int(dropout_mode.split(":")[1])
include_idx = np.concatenate([np.arange(0, nx, interval), np.array([nx-1])])
exclude_idx = [idx for idx in range(nx) if idx not in include_idx]
for ii in range(batch_size):
dropout_prob_chosen = dropout_prob_min + np.random.rand() * (dropout_prob_max - dropout_prob_min)
if exclude_idx is None:
nx_new = int(nx * (1 - dropout_prob_chosen))
else:
if not isinstance(exclude_idx, list):
exclude_idx = [exclude_idx]
nx_new = nx - len(exclude_idx)
if exclude_idx is None and (sample_idx is not None):
nx_new = min(nx_new, len(sample_idx))
if hasattr(data, "node_feature"):
edge_index_new = data.edge_index[("n0", "0", "n0")][:,:(nx_new-1)*2]
else:
edge_index_new = data.edge_index[:,:(nx_new-1)*2]
if exclude_idx is None:
idx = np.sort(np.random.choice(np.arange(1, nx-1), size=nx_new-2, replace=False))
idx = np.concatenate([np.array([0]), idx, np.array([nx-1])])
if sample_idx is not None:
idx = np.sort(np.random.choice(sample_idx, size=nx_new, replace=False))
else:
idx = np.array([i for i in range(nx) if i not in exclude_idx])
idx_list.append(idx + nx * ii)
edge_index_new_list.append(edge_index_new + nx_new_sum)
batch_list.append(torch.ones(nx_new, device=device)*ii)
nx_new_sum += nx_new
idx_core = np.concatenate(idx_list)
batch = torch.cat(batch_list)
edge_index_new_list = torch.cat(edge_index_new_list, -1)
if hasattr(data, "node_feature"):
data_new = Attr_Dict({
"node_feature": {"n0": data.node_feature["n0"][idx_core]},
"node_label": {"n0": data.node_label["n0"][idx_core]},
"node_pos": {"n0": data.node_pos["n0"][idx_core]},
"x_bdd": {"n0": data.x_bdd["n0"][idx_core]},
"xfaces": data.xfaces,
"edge_index": {("n0", "0", "n0"): edge_index_new_list},
"original_shape": (('n0', (nx_new,)),),
"dyn_dims": data.dyn_dims,
"compute_func": data.compute_func,
"dataset": to_tuple_shape(data.dataset),
"mask": {"n0": data.mask["n0"]},
"batch": batch,
})
if hasattr(data, "edge_attr"):
rel_pos = data_new.node_pos["n0"][data_new.edge_index[("n0", "0", "n0")][0]] - data_new.node_pos["n0"][data_new.edge_index[("n0", "0", "n0")][1]]
if data.edge_attr[("n0", "0", "n0")].shape[-1] == 1:
data_new["edge_attr"] = {("n0", "0", "n0"): rel_pos}
elif data.edge_attr[("n0", "0", "n0")].shape[-1] == 2:
data_new["edge_attr"] = {("n0", "0", "n0"): torch.cat([rel_pos, rel_pos.abs()], -1)}
else:
raise
else:
data_new = Data(
x=data.x[idx_core],
y=data.y[idx_core],
x_pos=data.x_pos[idx_core],
x_bdd=data.x_bdd[idx_core],
xfaces=data.xfaces,
edge_index=edge_index_new_list, # Assuming 1D path graph, and the specific way of edge_index.
original_shape=(('n0', (nx_new,)),),
dyn_dims=data.dyn_dims,
compute_func=data.compute_func,
dataset=to_tuple_shape(data.dataset),
mask=data.mask,
batch=batch,
)
if hasattr(data, "edge_attr"):
rel_pos = data_new.x_pos[data_new.edge_index[0]] - data_new.x_pos[data_new.edge_index[1]]
if data.edge_attr.shape[-1] == 1:
data_new.edge_attr = rel_pos
elif data.edge_attr.shape[-1] == 2:
data_new.edge_attr = torch.cat([rel_pos, rel_pos.abs()], -1)
else:
raise
if hasattr(data, "param"):
data_new.param = data.param
if hasattr(data, "dataset"):
data_new.dataset = data.dataset
else:
raise
return data_new
def get_minus_reward(loss, state, time, reward_mode="None", reward_beta=1.):
"""
Args:
reward_mode:
"None": r = loss + time
""
"""
if reward_mode in ["None", "loss+time"]:
return loss.item() + time * reward_beta
elif reward_mode == "loss+state":
return loss.item() + len(state)/1e5 * reward_beta
else:
raise
def get_reward_batch(
loss,
state,
time,
loss_alt=None,
state_alt=None,
time_alt=None,
reward_mode="None",
reward_beta=1.,
reward_loss_coef=100,
prefix="",
):
"""
Minus reward in batch.
Args:
loss: shape of [B, 1]
reward_mode:
"None": -r = loss + time * reward_beta
"loss+state": -r = loss + state_size * reward_beta
Returns:
reward: shape [B, 1]
"""
if len(reward_beta.shape)==1: reward_beta=reward_beta[:,None]
# if isinstance(reward_beta, str):
# reward_beta = sample_reward_beta(reward_beta)
if reward_mode in ["None", "loss+time"]:
loss = loss.detach()
reward = -(loss * reward_loss_coef * (1-reward_beta) + time * 10 * reward_beta)
info = {prefix+"r_loss": -loss * reward_loss_coef * (1-reward_beta),
prefix+"r_time": -time * reward_beta,
prefix+"r_beta": torch.tensor(reward_beta, dtype=torch.float32),
}
elif reward_mode == "loss+state":
batch = state.batch
state_size = torch.unique(batch, return_counts=True)[1].unsqueeze(-1).type(torch.float32)
assert loss.shape == state_size.shape
loss = loss.detach()
reward = -(loss * reward_loss_coef * (1-reward_beta) + state_size/400 * reward_beta)
info = {prefix+"r_loss": -loss * reward_loss_coef * (1-reward_beta),
prefix+"r_state": -state_size/400 * reward_beta,
prefix+"r_beta": torch.tensor(reward_beta, dtype=torch.float32),
}
elif reward_mode == "loss":
batch = state.batch
loss = loss.detach()
reward = -loss * reward_loss_coef * (1-reward_beta)
info = {prefix+"r_loss": -loss * reward_loss_coef * (1-reward_beta),
prefix+"r_beta": torch.tensor(reward_beta, dtype=torch.float32),
}
elif reward_mode == "state":
state_size = torch.unique(state.batch, return_counts=True)[1].unsqueeze(-1).type(torch.float32)
assert loss.shape == state_size.shape
reward = -state_size/400 * reward_beta
info = {prefix+"r_state": -state_size/400 * reward_beta,
prefix+"r_beta": torch.tensor(reward_beta, dtype=torch.float32),
}
elif reward_mode in ["lossdiff+statediff", "statediff", "lossdiff", "lossdiff+timediff", "timediff"]:
# assert (0 <= reward_beta).any() and (reward_beta <= 1).any()
state_size = torch.unique(state.batch, return_counts=True)[1].unsqueeze(-1).type(torch.float32)
state_size_alt = torch.unique(state_alt.batch, return_counts=True)[1].unsqueeze(-1).type(torch.float32)
loss_diff = (loss_alt - loss).detach()
state_diff = state_size_alt - state_size
time_diff = (time_alt - time)
info = {prefix+"v/lossdiff": loss_diff * reward_loss_coef,
prefix+"v/statediff": state_diff / 100,
prefix+"v/timediff": torch.tensor(time_diff) * 100,
prefix+"v/beta": reward_beta.float(),
prefix+"v/state_size": state_size,
prefix+"r/lossdiff": loss_diff * reward_loss_coef * (1-reward_beta),
prefix+"r/statediff": state_diff / 100 * reward_beta,
prefix+"r/timediff": torch.tensor(time_diff) * 100 * reward_beta,
}
if reward_mode == "statediff":
reward = state_diff / 100 * reward_beta
elif reward_mode == "lossdiff":
reward = loss_diff * reward_loss_coef * (1-reward_beta)
elif reward_mode == "lossdiff+statediff":
# print("loss_diff",loss_diff.mean())
reward = loss_diff * reward_loss_coef * (1-reward_beta) + state_diff / 100 * reward_beta
elif reward_mode == "lossdiff+timediff":
reward = loss_diff * reward_loss_coef * (1-reward_beta) + torch.tensor(time_diff)[None] * 100 * reward_beta
elif reward_mode == "timediff":
reward = torch.tensor(time_diff)[None] * 100 * reward_beta
else:
raise
else:
raise
return reward, info
def parse_rl_coefs(rl_coefs):
if rl_coefs == "None":
return {}
rl_coefs_dict = {}
for item in rl_coefs.split("+"):
key, value = item.split(":")
rl_coefs_dict[key] = float(value)
return rl_coefs_dict
class Value_Model(nn.Module):
def __init__(
self,
input_size,
output_size,
edge_dim,
latent_dim=32,
num_pool=1,
act_name="relu",
act_name_final="relu",
layer_norm=False,
batch_norm=False,
num_steps=3,
pooling_type="global_mean_pool",
edge_attr=False,
use_pos=False,
final_ratio=0.1,
final_pool="global_mean_pool",
reward_condition=False,
processors=[None],
encoder_edge=None,
encoder_nodes=None,
):
super().__init__()
"""
input_size - input feature size
edge_dim - edge dimension size
latent_dim - latent dimension size of node features
num_pool - number of pooling steps
act_name - activation function
"""
self.input_size = input_size
self.output_size = output_size
self.edge_dim = edge_dim
self.latent_dim = latent_dim
self.num_pool = num_pool
self.act_name = act_name
self.act_name_final = act_name_final
self.layer_norm = layer_norm
self.batch_norm = batch_norm
self.num_steps = num_steps
self.pooling_type = pooling_type
self.edge_attr = edge_attr
self.use_pos = use_pos
self.final_ratio = final_ratio
self.final_pool = final_pool
self.reward_condition = reward_condition
if self.edge_dim>6:
import dolfin as dolfin
self.dolfin = dolfin
# self.input_size = 8
if (processors[0]==None):
self.encoder_edge = FCBlock(in_features=edge_dim,
out_features=latent_dim,
num_hidden_layers=2,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.encoder_nodes = FCBlock(in_features=self.input_size + (5 if self.reward_condition else 0),
out_features=latent_dim,
num_hidden_layers=2,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
else:
self.encoder_edge = encoder_edge
self.encoder_nodes = encoder_nodes
if pooling_type in ["global_max_pool","global_mean_pool","global_mean_pool"]:
if (processors[0]==None):
self.processors = []
for _ in range(num_steps):
self.processors.append((processor(latent_dim,
latent_dim,
layer_norm=layer_norm,
act_name=act_name,
edge_attr=edge_attr)))
if self.batch_norm:
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors = torch.nn.Sequential(*self.processors)
else:
self.processors = processors
elif pooling_type in ["TopKPooling"]:
ratio = float(np.exp(np.log(self.final_ratio)/self.num_pool))
self.topKpoolings = []
self.processors = []
for _ in range(num_pool):
self.topKpoolings.append(torch_geometric.nn.TopKPooling(latent_dim ,ratio))
self.processors.append((processor(latent_dim,
latent_dim,
layer_norm=layer_norm,
act_name=act_name,
edge_attr=edge_attr)))
if self.batch_norm:
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors = torch.nn.Sequential(*self.processors)
self.topKpoolings = torch.nn.Sequential(*self.topKpoolings)
self.fc1 = nn.Linear(latent_dim + (5 if self.reward_condition else 0), 1)
self.fc2 = nn.Linear(latent_dim + (5 if self.reward_condition else 0), 1)
self.activation1 = get_activation(self.act_name_final)
self.activation2 = get_activation(self.act_name_final)
def encoder(self, graph):
""" Encode node and edge features.
Args:
graph: pyg data instance for graph.
"""
graph.x = self.encoder_nodes(graph.x)
# pdb.set_trace()
graph.edge_attr = self.encoder_edge(graph.edge_attr)
return graph
def get_reward(self, graph_latent,batch,reward_beta=None):
""" perform pooling and output the graph-level latent representation
"""
if self.reward_condition:
graph_latent = torch.cat([graph_latent,reward_beta[:,None].repeat([1,5])],dim=-1).float()
reward_1 = self.activation1((self.fc1(graph_latent)))
reward_2 = self.activation2((self.fc2(graph_latent)))
return reward_1, reward_2
def global_pooling(self, graph_evolved,reward_beta=None):
# message passing steps with different MLP each time
for i in range(self.num_steps):
# if self.reward_condition:
# beta_batch = torch.zeros(graph_evolved.x.shape[0]).to(graph_evolved.x.device)
# beta_batch = reward_beta[graph_evolved.batch.to(torch.int64)][:,None]
# graph_evolved.x = torch.cat([graph_evolved.x,beta_batch],dim=-1).float()
# pdb.set_trace()
if self.batch_norm:
graph_evolved = self.processors[i*3](graph_evolved)
graph_evolved.x = self.processors[i*3+1](graph_evolved.x)
graph_evolved.edge_attr = self.processors[i*3+2](graph_evolved.edge_attr)
else:
graph_evolved = self.processors[i](graph_evolved)
batch = graph_evolved.batch.long()
if self.pooling_type=="global_max_pool":
graph_latent = torch_geometric.nn.global_max_pool(graph_evolved.x, batch)
elif self.pooling_type=="global_add_pool":
graph_latent = torch_geometric.nn.global_add_pool(graph_evolved.x, batch)
elif self.pooling_type=="global_mean_pool":
graph_latent = torch_geometric.nn.global_mean_pool(graph_evolved.x, batch)
return graph_latent
def topk_pooling(self,graph_evolved,reward_beta=None):
for i in range(self.num_pool):
node_feature,edge_index,edge_attr,batch,perm,score = self.topKpoolings[i](graph_evolved.x,graph_evolved.edge_index,graph_evolved.edge_attr,graph_evolved.batch,)
graph_evolved.x = node_feature
# print("pooling layer:{},node feature shape:{}".format(i,graph_evolved.x.shape))
graph_evolved.edge_index = edge_index
graph_evolved.edge_attr = edge_attr
graph_evolved.batch = batch
graph_evolved.perm = perm
graph_evolved.score = score
if self.batch_norm:
graph_evolved = self.processors[i*3](graph_evolved)
graph_evolved.x = self.processors[i*3+1](graph_evolved.x)
graph_evolved.edge_attr = self.processors[i*3+2](graph_evolved.edge_attr)
else:
graph_evolved = self.processors[i](graph_evolved)
if self.final_pool=="global_max_pool":
graph_latent = torch_geometric.nn.global_max_pool(graph_evolved.x, graph_evolved.batch)
elif self.final_pool=="global_add_pool":
graph_latent = torch_geometric.nn.global_add_pool(graph_evolved.x, graph_evolved.batch)
elif self.final_pool=="global_mean_pool":
graph_latent = torch_geometric.nn.global_mean_pool(graph_evolved.x, graph_evolved.batch.long())
return graph_latent
def forward(self, graph, reward_beta=None,**kwargs):
"""Given the data (graph) and a reward_beta, return a value estimating the cumulative expected reward.
Args:
data: graph
reward_beta: float, nonnegative
"""
if hasattr(graph, "node_feature"):
if len(dict(to_tuple_shape(graph.original_shape))["n0"]) == 0:
batch = graph.batch
interp_index = graph.interp_index
graph = attrdict_to_pygdict(graph, is_flatten=True, use_pos=self.use_pos)
graph.batch = batch
if graph.x.shape[1]!=6:
if hasattr(graph, "onehot_list"):
onehot = graph.onehot_list[0]
assert onehot.shape[0]==graph.x.shape[0]
raw_kinems = self.compute_kinematics(graph, interp_index)
kinematics = graph.onehot_list[0][:,:1] * raw_kinems
try:
graph.x = torch.cat([graph.x, onehot, kinematics], dim=-1)
except:
pdb.set_trace()
else:
batch = graph.batch.clone()
graph = deepsnap_to_pyg(graph, is_flatten=True, use_pos=self.use_pos)
elif hasattr(graph, "x"):
batch = graph.batch.clone()
x_coords = graph.history[-1]
interp_index = graph.interp_index
if graph.x.shape[1]!=6:
if hasattr(graph, "onehot_list"):
onehot = graph.onehot_list[0]
assert onehot.shape[0]==graph.x.shape[0]
raw_kinems = self.compute_kinematics(graph, interp_index)
kinematics = graph.onehot_list[0][:,:1] * raw_kinems
graph.x = torch.cat([graph.x, onehot, kinematics], dim=-1)
if self.reward_condition:
beta_batch = torch.zeros(graph.x.shape[0]).to(graph.x.device)
beta_batch = reward_beta[batch.to(torch.int64)][:,None]
graph.x = torch.cat([graph.x,beta_batch.repeat([1,5])],dim=-1).float()
graph_evolved = self.encoder(graph)
graph_evolved.batch = batch
if self.pooling_type in ["global_max_pool","global_mean_pool","global_min_pool"]:
graph_latent = self.global_pooling(graph_evolved,reward_beta=reward_beta)
elif self.pooling_type in ["TopKPooling"]:
graph_latent = self.topk_pooling(graph_evolved,reward_beta=reward_beta)
reward_1, reward_2 = self.get_reward(graph_latent,reward_beta=reward_beta,batch=batch)
value = reward_1 + reward_beta[:,None] * reward_2
return value/10
def compute_kinematics(self, data, index):
# return
ybatch = ((data.reind_yfeatures[index][:,0] - data.yfeatures[index][:,0])/2).T
# onehot_list = data.onehot_list[index+1][:,0] #for handles
handles_index = torch.where(data.onehot_list[index+1][:,0]==1)[0]
handles_batch_info = ybatch[handles_index]
vers = data.yfeatures[index][handles_index][:,3:] #handle value at t+1
kinematic = torch.zeros_like(data.history[-1][:,3:])
handles_index_tar = torch.where(data.onehot_list[0][:,0]==1)[0]
kinematic[handles_index_tar] = (vers - data.history[-1][handles_index_tar][:,3:].clone().detach())
# assert ((data.history[-1][:,:2][handles_index_tar]-data.yfeatures[index][handles_index][:,:2]).abs()).mean()<1e-12
# try:
# assert ((ybatch[handles_index].to(torch.int64) == data.batch[handles_index_tar])*1-1).sum()==0
# except:
# pdb.set_trace()
return kinematic
def pyg_to_dolfin_mesh(self, vers, faces):
tmesh = self.dolfin.Mesh()
editor = self.dolfin.MeshEditor()
editor.open(tmesh, 'triangle', 2, 2)
editor.init_vertices(vers.shape[0])
for i in range(vers.shape[0]):
editor.add_vertex(i, vers[i,:2].cpu().numpy())
editor.init_cells(faces.shape[0])
for f in range(faces.shape[0]):
editor.add_cell(f, faces[f].cpu().numpy())
editor.close()
return tmesh
def generate_barycentric_interpolated_data_forward(self, mesh, bvhtree, outvec, tarvers):
faces, weights = self.generate_baryweight(tarvers, mesh, bvhtree)
indices = mesh.cells()[faces].astype('int64')
fweights = torch.tensor(np.array(weights), device=outvec.device, dtype=torch.float32)
return torch.matmul(fweights, outvec[indices,:]).diagonal().T
def generate_baryweight(self, tarvers, mesh, bvh_tree):
faces = []
weights = []
for query in tarvers:
face = bvh_tree.compute_first_entity_collision(self.dolfin.Point(query))
while (mesh.num_cells() <= face):
#print("query: ", query)
if query[0] < 0.5:
query[0] += 1e-15
elif query[0] >= 0.5:
query[0] -= 1e-15
if query[1] < 0.5:
query[1] += 1e-15
elif query[1] >= 0.5:
query[1] -= 1e-15
face = bvh_tree.compute_first_entity_collision(self.dolfin.Point(query))
faces.append(face)
face_coords = mesh.coordinates()[mesh.cells()[face]]
mat = face_coords.T[:,[0,1]] - face_coords.T[:,[2,2]]
const = query - face_coords[2,:]
weight = np.linalg.solve(mat, const)
final_weights = np.concatenate([weight, np.ones(1) - weight.sum()], axis=-1)
weights.append(final_weights)
return faces, weights
@property
def model_dict(self):
model_dict = {"type": "Value_Model"}
model_dict["input_size"] = self.input_size
model_dict["output_size"] = self.output_size
model_dict["edge_dim"] = self.edge_dim
model_dict["latent_dim"] = self.latent_dim
model_dict["num_pool"] = self.num_pool
model_dict["act_name_final"] = self.act_name_final
model_dict["pooling_type"] = self.pooling_type
model_dict["batch_norm"] = self.batch_norm
model_dict["layer_norm"] = self.layer_norm
model_dict["num_steps"] = self.num_steps
model_dict["act_name"] = self.act_name
model_dict["edge_attr"] = self.edge_attr
model_dict["use_pos"] = self.use_pos
model_dict["final_ratio"] = self.final_ratio
model_dict["final_pool"] = self.final_pool
model_dict["reward_condition"] = self.reward_condition
model_dict["state_dict"] = to_cpu(self.state_dict())
return model_dict
# ## GNNRemesher:
# In[ ]:
class GNNRemesher(nn.Module):
""" Perform remeshing for given mesh data.
Attributes::
nmax: maximun number to give hash for edge indices.
device: gpu device.
encoder_edge: encoder for edge features.
encoder_nodes: encoder for node features.
pdist: distance function used to detect obtuse triagnles.
num_steps: message passing step.
processors: message passing networks.
diffMLP: use different message passing networks if True.
decoder_node: decoder for node features.
samplemode: strategy to sample independent edges.
use_encoder: use encoder if True.
is_split_test: perform split function for original mesh data.
is_flip_test: perform flip function for original mesh data.
is_coarsen_test: perform coarsen function for original mesh data.
skip_split: skip split action if True.
skip_flip: skip flip action if True.
is_forward: perform forwarding by gnn before remeshing actions.
"""
def __init__(
self,
input_size,
output_size,
edge_dim,
sizing_field_dim,
nmax,
reward_dim=16,
latent_dim=32,
num_steps=3,
layer_norm=False,
act_name="relu",
var=0,
batch_norm=False,
normalize = False,
diffMLP=False,
checkpoints=None,
samplemode="random",
use_encoder=False,
edge_attr=False,
is_split_test=False,
is_flip_test=False,
is_coarsen_test=False,
skip_split=False,
skip_flip=False,
is_y_diff=False,
edge_threshold=0.,
noise_amp=0.,
correction_rate=0.,
):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.edge_dim = edge_dim
self.sizing_field_dim = sizing_field_dim
if self.sizing_field_dim == 4:
import dolfin as dolfin
self.dolfin = dolfin
self.reward_dim = reward_dim
self.nmax = nmax.type(torch.int64) if isinstance(nmax, torch.Tensor) else torch.tensor(nmax, dtype=torch.int64)
self.latent_dim = latent_dim
self.num_steps = num_steps
self.layer_norm = layer_norm
self.act_name = act_name
self.var = var
self.batch_norm = batch_norm
self.normalize = normalize
self.diffMLP = diffMLP
self.checkpoints = checkpoints
self.is_y_diff = is_y_diff
self.edge_threshold = edge_threshold
self.noise_amp = noise_amp
self.correction_rate = correction_rate
self.encoder_edge = FCBlock(in_features=edge_dim,
out_features=latent_dim,
num_hidden_layers=2,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
if self.edge_threshold > 0.:
self.world_encoder_edge = FCBlock(in_features=int(edge_dim/2),
out_features=latent_dim,
num_hidden_layers=2,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.encoder_nodes = FCBlock(in_features=input_size,
out_features=latent_dim,
num_hidden_layers=2,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=layer_norm,
)
self.pdist = torch.nn.PairwiseDistance(p=2)
if diffMLP:
# message passing with different MLP for each steps
self.processors = []
for _ in range(num_steps):
self.processors.append((processor(latent_dim, latent_dim, layer_norm=layer_norm, act_name=act_name, edge_attr=edge_attr)))
if batch_norm:
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors.append(torch.nn.BatchNorm1d(latent_dim))
self.processors = torch.nn.Sequential(*self.processors)
else:
self.processors = ((processor(latent_dim, latent_dim, layer_norm=layer_norm, act_name=act_name, edge_attr=edge_attr)))
self.decoder_node = FCBlock(in_features=latent_dim,
out_features=output_size+sizing_field_dim,
num_hidden_layers=3,
hidden_features=latent_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=False,
)
if self.reward_dim > 0:
self.reward_model = FCBlock(in_features=latent_dim+1,
out_features=2,
num_hidden_layers=3,
hidden_features=reward_dim,
outermost_linear=True,
nonlinearity=act_name,
layer_norm=False,
)
if self.normalize:
if checkpoints==None:
self.normalizer_node_feature = normalizer(input_size)
self.normalizer_edge_feature = normalizer(edge_dim)
self.normalizer_v_gt = normalizer(1)
else:
self.normalizer_node_feature = normalizer(input_size,max_acc=0)
self.normalizer_edge_feature = normalizer(edge_dim,max_acc=0)
self.normalizer_v_gt = normalizer(1,max_acc=0)
self.samplemode = samplemode
self.use_encoder = use_encoder
self.edge_attr = edge_attr
self.is_split_test = is_split_test
self.is_flip_test = is_flip_test
self.is_coarsen_test = is_coarsen_test
self.skip_split = skip_split
self.skip_flip = skip_flip
def generate_world_edge(self, graph):
total_dim = graph.node_dim[0].sum().item()
diagonal_mask = torch.zeros(total_dim, total_dim, device=graph.x.device)
sum = 0
for dim in graph.node_dim[0].reshape(graph.node_dim[0].shape[0]).tolist():
diagonal_mask[sum:sum+dim, sum:sum+dim] = 1
sum += dim
distance = torch.sqrt(torch.sum((graph.x[None] - graph.x[:,None])**2, dim=-1))
distance = distance * diagonal_mask
mask = (0 < distance) * (distance < self.edge_threshold)
x = torch.arange(graph.x.shape[0])
y = torch.arange(graph.x.shape[0])
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
candidate_edges = torch.stack([grid_x[mask], grid_y[mask]]).to(graph.x.device)
if candidate_edges.shape[1] == 0:
return candidate_edges, torch.empty([0, 2*graph.x.shape[1]], device=graph.x.device)
can_hashes = edge_index_to_num(candidate_edges, self.nmax)
edge_hashes = edge_index_to_num(graph.edge_index, self.nmax)
world_mask = torch.logical_not(torch.isin(can_hashes, edge_hashes))
world_edge_index = candidate_edges[:, world_mask]
x_receiver = torch.gather(graph.x, 0, world_edge_index[0,:].unsqueeze(-1).repeat(1,graph.x.shape[1]))
x_sender = torch.gather(graph.x, 0, world_edge_index[1,:].unsqueeze(-1).repeat(1,graph.x.shape[1]))
rel_vec = x_receiver - x_sender
new_edge_attr = torch.cat([rel_vec, rel_vec.abs()], dim=-1)
return world_edge_index, new_edge_attr
def encoder(self, graph):
""" Encode node and edge features.
Args:
graph: pyg data instance for graph.
"""
if self.var > 0:
noise = (torch.normal(0,1,size=(graph.x.shape[0],graph.x.shape[1]-1))*self.var).to(graph.x.device)
graph.x[:,:-1] = graph.x[:,:-1] + graph.x[:,[-1]]*noise
graph.noise = graph.x[:,[-1]]*noise
else:
graph.noise = torch.zeros_like(graph.x)
if self.edge_attr:
graph.edge_attr = self.encoder_edge(graph.edge_attr)
if self.edge_threshold > 0:
graph.orig_edge_shape = graph.edge_index.shape
world_edge_index, new_edge_attr = self.generate_world_edge(graph)
graph.edge_index = torch.cat([graph.edge_index, world_edge_index], dim=-1)
graph.edge_attr = torch.cat([graph.edge_attr, self.world_encoder_edge(new_edge_attr)], dim=0)
graph.x = self.encoder_nodes(graph.x)
return graph
def decoder(self, graph):
""" Decode node features.