-
Notifications
You must be signed in to change notification settings - Fork 3
/
exp_runner_stage_1.py
8732 lines (6454 loc) · 458 KB
/
exp_runner_stage_1.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 os
import time
import logging
import argparse
import numpy as np
# import cv2 as cv
import trimesh
import torch
import torch.nn.functional as F
try:
from torch.utils.tensorboard import SummaryWriter
except:
SummaryWriter = None
pass
from shutil import copyfile
# from icecream import ic
from tqdm import tqdm
from pyhocon import ConfigFactory
from models.fields import RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF, BendingNetwork
import models.data_utils_torch as data_utils
# import models.dyn_model_utils as dyn_utils
import torch.nn as nn
# import models.renderer_def_multi_objs as render_utils
import models.fields as fields
from torch.distributions.categorical import Categorical
try:
import redmax_py as redmax
except:
pass
import open3d as o3d
import models.dyn_model_act as dyn_model_act
import models.dyn_model_act_v2 as dyn_model_act_mano
from scipy.spatial.transform import Rotation as R
import traceback
import pickle as pkl
class Runner:
def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False):
self.device = torch.device('cuda')
self.conf_path = conf_path
f = open(self.conf_path)
conf_text = f.read()
conf_text = conf_text.replace('CASE_NAME', case)
f.close()
self.conf = ConfigFactory.parse_string(conf_text)
self.base_exp_dir = self.conf['general.base_exp_dir']
# local_exp_dir = "/data2/xueyi/quasisim/exp/"
local_exp_dir = "/data/xueyi/quasisim/exp"
if os.path.exists(local_exp_dir):
self.base_exp_dir = local_exp_dir
print(f"self.base_exp_dir:", self.base_exp_dir)
self.base_exp_dir = self.base_exp_dir + f"_reverse_value_totviews_tag_{self.conf['general.tag']}"
os.makedirs(self.base_exp_dir, exist_ok=True)
# self.dataset = Dataset(self.conf['dataset'])
self.n_timesteps = self.conf['model.n_timesteps']
self.iter_step = 0
self.end_iter = self.conf.get_int('train.end_iter')
self.save_freq = self.conf.get_int('train.save_freq')
self.report_freq = self.conf.get_int('train.report_freq')
self.val_freq = self.conf.get_int('train.val_freq')
self.val_mesh_freq = self.conf.get_int('train.val_mesh_freq')
self.batch_size = self.conf.get_int('train.batch_size')
self.validate_resolution_level = self.conf.get_int('train.validate_resolution_level')
self.learning_rate = self.conf.get_float('train.learning_rate')
self.learning_rate_alpha = self.conf.get_float('train.learning_rate_alpha')
self.use_white_bkgd = self.conf.get_bool('train.use_white_bkgd')
self.warm_up_end = self.conf.get_float('train.warm_up_end', default=0.0)
self.anneal_end = self.conf.get_float('train.anneal_end', default=0.0)
self.use_bending_network = True
# use_split_network
self.use_selector = True
# Weights #
self.igr_weight = self.conf.get_float('train.igr_weight')
self.mask_weight = self.conf.get_float('train.mask_weight')
self.is_continue = is_continue #
self.mode = mode
self.model_list = []
self.writer = None
self.bending_latent_size = self.conf['model.bending_network']['bending_latent_size']
params_to_train = []
self.nerf_outside = NeRF(**self.conf['model.nerf']).to(self.device)
self.sdf_network = SDFNetwork(**self.conf['model.sdf_network']).to(self.device)
self.deviation_network = SingleVarianceNetwork(**self.conf['model.variance_network']).to(self.device)
self.color_network = RenderingNetwork(**self.conf['model.rendering_network']).to(self.device)
# self.use_bending_network = self.conf['model.use_bending_network']
# # bending network size #
# if self.use_bending_network: # add the bendingnetwork #
self.bending_network = BendingNetwork(**self.conf['model.bending_network']).to(self.device)
self.use_split_network = self.conf.get_bool('model.use_split_network', False)
if self.use_split_network:
self.bending_network.set_split_bending_network()
self.bending_network.n_timesteps = self.n_timesteps
self.extract_delta_mesh = self.conf['model.extract_delta_mesh']
# self.use_passive_nets = self.conf['model.use_passive_nets']
if 'model.bending_net_type' in self.conf:
self.bending_net_type = self.conf['model.bending_net_type']
else:
self.bending_net_type = "pts_def"
if 'model.train_multi_seqs' in self.conf and self.conf['model.train_multi_seqs']:
self.rhand_verts, self.hand_faces, self.obj_faces, self.obj_normals, self.ts_to_contact_pts, self.hand_verts = self.load_active_passive_timestep_to_mesh_multi_seqs()
self.train_multi_seqs = True
self.nn_instances = len(self.rhand_verts)
else:
self.train_multi_seqs = False
self.nn_instances = 1
if 'model.minn_dist_threshold' in self.conf:
self.minn_dist_threshold = self.conf['model.minn_dist_threshold']
else:
self.minn_dist_threshold = 0.05
if 'model.optimize_with_intermediates' in self.conf:
self.optimize_with_intermediates = self.conf['model.optimize_with_intermediates']
else:
self.optimize_with_intermediates = False
if 'model.no_friction_constraint' in self.conf:
self.no_friction_constraint = self.conf['model.no_friction_constraint']
else:
self.no_friction_constraint = False
if 'model.optimize_active_object' in self.conf:
self.optimize_active_object = self.conf['model.optimize_active_object']
else:
self.optimize_active_object = False
if 'model.optimize_glb_transformations' in self.conf:
self.optimize_glb_transformations = self.conf['model.optimize_glb_transformations']
else:
self.optimize_glb_transformations = False
if 'model.with_finger_tracking_loss' in self.conf:
self.with_finger_tracking_loss = self.conf['model.with_finger_tracking_loss']
else:
self.with_finger_tracking_loss = True
if 'model.finger_cd_loss' in self.conf:
self.finger_cd_loss_coef = self.conf['model.finger_cd_loss']
else:
self.finger_cd_loss_coef = 0.
if 'model.finger_tracking_loss' in self.conf:
self.finger_tracking_loss_coef = self.conf['model.finger_tracking_loss']
else:
self.finger_tracking_loss_coef = 0.
if 'model.tracking_loss' in self.conf:
self.tracking_loss_coef = self.conf['model.tracking_loss']
else:
self.tracking_loss_coef = 0.
if 'model.penetrating_depth_penalty' in self.conf:
self.penetrating_depth_penalty_coef = self.conf['model.penetrating_depth_penalty']
else:
self.penetrating_depth_penalty_coef = 0.
if 'model.ragged_dist' in self.conf:
self.ragged_dist_coef = self.conf['model.ragged_dist']
else:
self.ragged_dist_coef = 1.
if 'mode.load_only_glb' in self.conf:
self.load_only_glb = self.conf['model.load_only_glb']
else:
self.load_only_glb = False
# optimize_rules; optimize_robot #
if 'model.optimize_robot' in self.conf:
self.optimize_robot = self.conf['model.optimize_robot']
else:
self.optimize_robot = True
if 'model.optimize_rules' in self.conf:
self.optimize_rules = self.conf['model.optimize_rules']
else:
self.optimize_rules = False
if 'model.optimize_expanded_pts' in self.conf:
self.optimize_expanded_pts = self.conf['model.optimize_expanded_pts']
else:
self.optimize_expanded_pts = True
if 'model.optimize_expanded_ragged_pts' in self.conf:
self.optimize_expanded_ragged_pts = self.conf['model.optimize_expanded_ragged_pts']
else:
self.optimize_expanded_ragged_pts = False
if 'model.add_delta_state_constraints' in self.conf:
self.add_delta_state_constraints = self.conf['model.add_delta_state_constraints']
else:
self.add_delta_state_constraints = True
#
if 'model.train_actions_with_states' in self.conf:
self.train_actions_with_states = self.conf['model.train_actions_with_states']
else:
self.train_actions_with_states = False
if 'model.train_with_forces_to_active' in self.conf:
self.train_with_forces_to_active = self.conf['model.train_with_forces_to_active']
else:
self.train_with_forces_to_active = False
if 'model.loss_weight_diff_states' in self.conf:
self.loss_weight_diff_states = self.conf['model.loss_weight_diff_states']
else:
self.loss_weight_diff_states = 1.
if 'model.loss_tangential_diff_coef' in self.conf:
self.loss_tangential_diff_coef = float(self.conf['model.loss_tangential_diff_coef'])
else:
self.loss_tangential_diff_coef = 1.
if 'model.use_penalty_based_friction' in self.conf:
self.use_penalty_based_friction = self.conf['model.use_penalty_based_friction']
else:
self.use_penalty_based_friction = False
if 'model.use_disp_based_friction' in self.conf:
self.use_disp_based_friction = self.conf['model.use_disp_based_friction']
else:
self.use_disp_based_friction = False
if 'model.use_sqrt_dist' in self.conf:
self.use_sqrt_dist = self.conf['model.use_sqrt_dist']
else:
self.use_sqrt_dist = False
if 'model.reg_loss_coef' in self.conf:
self.reg_loss_coef = float(self.conf['model.reg_loss_coef'])
else:
self.reg_loss_coef = 0.
if 'model.contact_maintaining_dist_thres' in self.conf:
self.contact_maintaining_dist_thres = float(self.conf['model.contact_maintaining_dist_thres'])
else:
self.contact_maintaining_dist_thres = 0.1
if 'model.penetration_proj_k_to_robot' in self.conf:
self.penetration_proj_k_to_robot = float(self.conf['model.penetration_proj_k_to_robot'])
else:
self.penetration_proj_k_to_robot = 0.0
if 'model.use_mano_inputs' in self.conf:
self.use_mano_inputs = self.conf['model.use_mano_inputs']
else:
self.use_mano_inputs = False
if 'model.use_split_params' in self.conf:
self.use_split_params = self.conf['model.use_split_params']
else:
self.use_split_params = False
if 'model.use_split_params' in self.conf:
self.use_split_params = self.conf['model.use_split_params']
else:
self.use_split_params = False
if 'model.use_sqr_spring_stiffness' in self.conf:
self.use_sqr_spring_stiffness = self.conf['model.use_sqr_spring_stiffness']
else:
self.use_sqr_spring_stiffness = False
if 'model.use_pre_proj_frictions' in self.conf:
self.use_pre_proj_frictions = self.conf['model.use_pre_proj_frictions']
else:
self.use_pre_proj_frictions = False
if 'model.use_static_mus' in self.conf:
self.use_static_mus = self.conf['model.use_static_mus']
else:
self.use_static_mus = False
if 'model.contact_friction_static_mu' in self.conf:
self.contact_friction_static_mu = self.conf['model.contact_friction_static_mu']
else:
self.contact_friction_static_mu = 1.0
if 'model.debug' in self.conf:
self.debug = self.conf['model.debug']
else:
self.debug = False
if 'model.robot_actions_diff_coef' in self.conf:
self.robot_actions_diff_coef = self.conf['model.robot_actions_diff_coef']
else:
self.robot_actions_diff_coef = 0.1
if 'model.use_sdf_as_contact_dist' in self.conf:
self.use_sdf_as_contact_dist = self.conf['model.use_sdf_as_contact_dist']
else:
self.use_sdf_as_contact_dist = False
if 'model.use_contact_dist_as_sdf' in self.conf:
self.use_contact_dist_as_sdf = self.conf['model.use_contact_dist_as_sdf']
else:
self.use_contact_dist_as_sdf = False
if 'model.use_same_contact_spring_k' in self.conf:
self.use_same_contact_spring_k = self.conf['model.use_same_contact_spring_k']
else:
self.use_same_contact_spring_k = False
if 'model.minn_dist_threshold_robot_to_obj' in self.conf:
self.minn_dist_threshold_robot_to_obj = float(self.conf['model.minn_dist_threshold_robot_to_obj'])
else:
self.minn_dist_threshold_robot_to_obj = 0.0
if 'model.obj_mass' in self.conf:
self.obj_mass = float(self.conf['model.obj_mass'])
else:
self.obj_mass = 100.0
if 'model.diff_hand_tracking_coef' in self.conf:
self.diff_hand_tracking_coef = float(self.conf['model.diff_hand_tracking_coef'])
else: #
self.diff_hand_tracking_coef = 0.0
if 'model.use_mano_hand_for_test' in self.conf:
self.use_mano_hand_for_test = self.conf['model.use_mano_hand_for_test']
else:
self.use_mano_hand_for_test = False
if 'model.train_residual_friction' in self.conf:
self.train_residual_friction = self.conf['model.train_residual_friction']
else:
self.train_residual_friction = False
if 'model.use_LBFGS' in self.conf:
self.use_LBFGS = self.conf['model.use_LBFGS']
else:
self.use_LBFGS = False
if 'model.use_optimizable_params' in self.conf:
self.use_optimizable_params = self.conf['model.use_optimizable_params']
else:
self.use_optimizable_params = False
if 'model.penetration_determining' in self.conf:
self.penetration_determining = self.conf['model.penetration_determining']
else:
self.penetration_determining = "sdf_of_canon"
if 'model.sdf_sv_fn' in self.conf:
self.sdf_sv_fn = self.conf['model.sdf_sv_fn']
else:
self.sdf_sv_fn = None
if 'model.loss_scale_coef' in self.conf:
self.loss_scale_coef = float(self.conf['model.loss_scale_coef'])
else:
self.loss_scale_coef = 1.0
if 'model.penetration_proj_k_to_robot_friction' in self.conf:
self.penetration_proj_k_to_robot_friction = float(self.conf['model.penetration_proj_k_to_robot_friction'])
else:
self.penetration_proj_k_to_robot_friction = self.penetration_proj_k_to_robot
if 'model.retar_only_glb' in self.conf:
self.retar_only_glb = self.conf['model.retar_only_glb']
else:
self.retar_only_glb = False
if 'model.optim_sim_model_params_from_mano' in self.conf:
self.optim_sim_model_params_from_mano = self.conf['model.optim_sim_model_params_from_mano']
else:
self.optim_sim_model_params_from_mano = False
# opt_robo_states, opt_robo_glb_trans, opt_robo_glb_rot #
if 'model.opt_robo_states' in self.conf:
self.opt_robo_states = self.conf['model.opt_robo_states']
else:
self.opt_robo_states = True
if 'model.opt_robo_glb_trans' in self.conf:
self.opt_robo_glb_trans = self.conf['model.opt_robo_glb_trans']
else:
self.opt_robo_glb_trans = False
if 'model.opt_robo_glb_rot' in self.conf:
self.opt_robo_glb_rot = self.conf['model.opt_robo_glb_rot']
else:
self.opt_robo_glb_rot = False
# motion_reg_loss_coef
if 'model.motion_reg_loss_coef' in self.conf:
self.motion_reg_loss_coef = self.conf['model.motion_reg_loss_coef']
else:
self.motion_reg_loss_coef = 1.0
if 'model.drive_robot' in self.conf:
self.drive_robot = self.conf['model.drive_robot']
else:
self.drive_robot = 'states'
if 'model.use_scaled_urdf' in self.conf:
self.use_scaled_urdf =self.conf['model.use_scaled_urdf']
else:
self.use_scaled_urdf = False
if 'model.window_size' in self.conf:
self.window_size = self.conf['model.window_size']
else:
self.window_size = 60
if 'model.use_taco' in self.conf:
self.use_taco = self.conf['model.use_taco']
else:
self.use_taco = False
if 'model.ang_vel_damping' in self.conf:
self.ang_vel_damping = float(self.conf['model.ang_vel_damping'])
else:
self.ang_vel_damping = 0.0
if 'model.drive_glb_delta' in self.conf:
self.drive_glb_delta = self.conf['model.drive_glb_delta']
else:
self.drive_glb_delta = False
if 'model.fix_obj' in self.conf:
self.fix_obj = self.conf['model.fix_obj']
else:
self.fix_obj = False
if 'model.diff_reg_coef' in self.conf:
self.diff_reg_coef = self.conf['model.diff_reg_coef']
else:
self.diff_reg_coef = 0.01
if 'model.use_damping_params_vel' in self.conf:
self.use_damping_params_vel = self.conf['model.use_damping_params_vel']
else:
self.use_damping_params_vel = False
if 'train.ckpt_sv_freq' in self.conf:
self.ckpt_sv_freq = int(self.conf['train.ckpt_sv_freq'])
else:
self.ckpt_sv_freq = 100
if 'model.optm_alltime_ks' in self.conf:
self.optm_alltime_ks = self.conf['model.optm_alltime_ks']
else:
self.optm_alltime_ks = False
if 'model.retar_dense_corres' in self.conf:
self.retar_dense_corres = self.conf['model.retar_dense_corres']
else:
self.retar_dense_corres = False
if 'model.retar_delta_glb_trans' in self.conf:
self.retar_delta_glb_trans = self.conf['model.retar_delta_glb_trans']
else:
self.retar_delta_glb_trans = False
if 'model.use_multi_stages' in self.conf:
self.use_multi_stages = self.conf['model.use_multi_stages']
else:
self.use_multi_stages = False
if 'model.seq_start_idx' in self.conf:
self.seq_start_idx = self.conf['model.seq_start_idx']
else:
self.seq_start_idx = 40
if 'model.obj_sdf_fn' in self.conf:
self.obj_sdf_fn = self.conf['model.obj_sdf_fn']
else:
self.obj_sdf_fn = ""
if 'model.kinematic_mano_gt_sv_fn' in self.conf:
self.kinematic_mano_gt_sv_fn = self.conf['model.kinematic_mano_gt_sv_fn']
else:
self.kinematic_mano_gt_sv_fn = ""
if 'model.scaled_obj_mesh_fn' in self.conf:
self.scaled_obj_mesh_fn = self.conf['model.scaled_obj_mesh_fn']
else:
self.scaled_obj_mesh_fn = ""
if 'model.ckpt_fn' in self.conf:
self.ckpt_fn = self.conf['model.ckpt_fn']
else:
self.ckpt_fn = ""
if 'model.load_optimized_init_transformations' in self.conf:
self.load_optimized_init_transformations = self.conf['model.load_optimized_init_transformations']
else:
self.load_optimized_init_transformations = ""
if 'model.optimize_dyn_actions' in self.conf:
self.optimize_dyn_actions = self.conf['model.optimize_dyn_actions']
else:
self.optimize_dyn_actions = False
if 'model.load_optimized_obj_transformations' in self.conf:
self.load_optimized_obj_transformations = self.conf['model.load_optimized_obj_transformations']
else:
self.load_optimized_obj_transformations = None
if 'model.train_pointset_acts_via_deltas' in self.conf:
self.train_pointset_acts_via_deltas = self.conf['model.train_pointset_acts_via_deltas']
else:
self.train_pointset_acts_via_deltas = False
if 'model.drive_pointset' in self.conf:
self.drive_pointset = self.conf['model.drive_pointset']
else:
self.drive_pointset = "states"
if 'model.optimize_anchored_pts' in self.conf:
self.optimize_anchored_pts = self.conf['model.optimize_anchored_pts']
else:
self.optimize_anchored_pts = True
if 'model.optimize_pointset_motion_only' in self.conf:
self.optimize_pointset_motion_only = self.conf['model.optimize_pointset_motion_only']
else:
self.optimize_pointset_motion_only = True
# print(f"optimize_dyn_actions: {self.optimize_dyn_actions}")
#### get pointset parameters ###
if 'model.pointset_expand_factor' in self.conf:
self.pointset_expand_factor = self.conf['model.pointset_expand_factor']
else:
self.pointset_expand_factor = 0.1
if 'model.pointset_nn_expand_pts' in self.conf:
self.pointset_nn_expand_pts = self.conf['model.pointset_nn_expand_pts']
else:
self.pointset_nn_expand_pts = 10
print(f"[Settings] Setting pointset_expand_factor to {self.pointset_expand_factor}, pointset_nn_expand_pts to {self.pointset_nn_expand_pts}")
if 'dataset.obj_idx' in self.conf:
print(f"dataset.obj_idx:", self.conf['dataset.obj_idx'])
self.obj_idx = self.conf['dataset.obj_idx']
# ###### only for the grab dataset only currently ########
# GRAB_data_root = "/data1/xueyi/GRAB_extracted_test/train"
# # /data/xueyi/GRAB/GRAB_extracted_test/train/102_obj.npy
# if not os.path.exists(GRAB_data_root):
# GRAB_data_root = "/data/xueyi/GRAB/GRAB_extracted_test/train"
GRAB_data_root = "data/grab"
GRAB_data_root = os.path.join(GRAB_data_root, f"{self.obj_idx}")
if not os.path.exists(GRAB_data_root):
GRAB_data_root = "/data1/xueyi/GRAB_extracted_test/train"
self.obj_sdf_fn = os.path.join(GRAB_data_root, f"{self.obj_idx}_obj.npy")
self.kinematic_mano_gt_sv_fn = os.path.join(GRAB_data_root, f"{self.obj_idx}_sv_dict.npy")
self.scaled_obj_mesh_fn = os.path.join(GRAB_data_root, f"{self.obj_idx}_obj.obj")
# self.ckpt_fn = self.conf['model.ckpt_fn']
# self.load_optimized_init_transformations = self.conf['model.load_optimized_init_transformations']
print(f"obj_sdf_fn:", self.obj_sdf_fn)
print(f"kinematic_mano_gt_sv_fn:", self.kinematic_mano_gt_sv_fn)
print(f"scaled_obj_mesh_fn:", self.scaled_obj_mesh_fn)
self.minn_init_passive_mesh = None
self.maxx_init_passive_mesh = None
self.mano_nn_substeps = 1
self.canon_passive_obj_verts = None
self.canon_passive_obj_normals = None
if self.bending_net_type == "active_force_field_v18":
self.other_bending_network = fields.BendingNetworkActiveForceFieldForwardLagV18(**self.conf['model.bending_network'], nn_instances=self.nn_instances, minn_dist_threshold=self.minn_dist_threshold).to(self.device)
if mode in ["train_real_robot_actions_from_mano_model_rules_v5_manohand_fortest_states_grab", "train_point_set", "train_sparse_retar", "train_real_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_grab", "train_point_set_retar", "train_point_set_retar_pts", "train_finger_kinematics_retargeting_arctic_twohands", "train_real_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_arctic_twohands", "train_real_robot_actions_from_mano_model_rules_shadowhand", "train_redmax_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_grab", "train_dyn_mano_model", "train_dyn_mano_model_wreact"]:
if mode in ['train_finger_kinematics_retargeting_arctic_twohands', 'train_real_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_arctic_twohands']:
self.timestep_to_passive_mesh, self.timestep_to_active_mesh, self.timestep_to_passive_mesh_normals = self.load_active_passive_timestep_to_mesh_twohands_arctic()
else:
if self.use_taco:
self.timestep_to_passive_mesh, self.timestep_to_active_mesh, self.timestep_to_passive_mesh_normals = self.load_active_passive_timestep_to_mesh_v3_taco()
else:
self.timestep_to_passive_mesh, self.timestep_to_active_mesh, self.timestep_to_passive_mesh_normals = self.load_active_passive_timestep_to_mesh_v3()
if self.conf['model.penetration_determining'] == "ball_primitives":
self.center_verts, self.ball_r = self.get_ball_primitives()
self.other_bending_network.canon_passive_obj_verts = self.obj_verts
self.other_bending_network.canon_passive_obj_normals = self.obj_normals
self.canon_passive_obj_verts = self.obj_verts
self.canon_passive_obj_normals = self.obj_normals
# tot_obj_quat, tot_reversed_obj_rot_mtx #
''' Load passive object's SDF '''
self.obj_sdf_fn = self.obj_sdf_fn ## load passive object's sdf
self.other_bending_network.sdf_space_center = self.sdf_space_center
self.other_bending_network.sdf_space_scale = self.sdf_space_scale
self.obj_sdf = np.load(self.obj_sdf_fn, allow_pickle=True)
self.sdf_res = self.obj_sdf.shape[0]
self.other_bending_network.obj_sdf = self.obj_sdf
self.other_bending_network.sdf_res = self.sdf_res
if self.conf['model.penetration_determining'] == "sdf_of_canon":
print(f"Setting the penetration determining method to sdf_of_canon")
self.other_bending_network.penetration_determining = "sdf_of_canon"
elif self.conf['model.penetration_determining'] == 'plane_primitives':
print(f"setting the penetration determining method to plane_primitives with maxx_xyz: {self.maxx_init_passive_mesh}, minn_xyz: {self.minn_init_passive_mesh}")
self.other_bending_network.penetration_determining = "plane_primitives" #
elif self.conf['model.penetration_determining'] == 'ball_primitives':
print(f"Setting the penetration determining method to ball_primitives with ball_r: {self.ball_r}, center: {self.center_verts}")
self.other_bending_network.penetration_determining = "ball_primitives" #
self.other_bending_network.center_verts = self.center_verts
self.other_bending_network.ball_r = self.ball_r ## get the ball primitives here? ##
else:
raise NotImplementedError(f"penetration determining method {self.conf['model.penetration_determining']} not implemented")
elif mode in ["train_dyn_mano_model", "train_dyn_mano_model_wreact"]:
self.load_active_passive_timestep_to_mesh()
self.timestep_to_passive_mesh, self.timestep_to_active_mesh, self.timestep_to_passive_mesh_normals = self.load_active_passive_timestep_to_mesh_v3()
self.obj_sdf_grad = None
else:
if not self.train_multi_seqs:
self.timestep_to_passive_mesh, self.timestep_to_active_mesh, self.timestep_to_passive_mesh_normals = self.load_active_passive_timestep_to_mesh()
self.other_bending_network.sdf_space_center = self.sdf_space_center
self.other_bending_network.sdf_space_scale = self.sdf_space_scale
self.other_bending_network.obj_sdf = self.obj_sdf #
self.other_bending_network.sdf_res = self.sdf_res #
else:
raise ValueError(f"Unrecognized bending net type: {self.bending_net_type}")
if self.maxx_init_passive_mesh is None and self.minn_init_passive_mesh is None:
self.calculate_collision_geometry_bounding_boxes()
###### initialize the dyn model ######
for i_time_idx in range(self.n_timesteps):
self.other_bending_network.timestep_to_vel[i_time_idx] = torch.zeros((3,), dtype=torch.float32).cuda()
self.other_bending_network.timestep_to_point_accs[i_time_idx] = torch.zeros((3,), dtype=torch.float32).cuda()
self.other_bending_network.timestep_to_total_def[i_time_idx] = torch.zeros((3,), dtype=torch.float32).cuda()
self.other_bending_network.timestep_to_angular_vel[i_time_idx] = torch.zeros((3,), dtype=torch.float32).cuda()
self.other_bending_network.timestep_to_quaternion[i_time_idx] = torch.tensor([1., 0., 0., 0.], dtype=torch.float32).cuda()
self.other_bending_network.timestep_to_torque[i_time_idx] = torch.zeros((3,), dtype=torch.float32).cuda()
### set initial transformations ###
if mode in ["train_real_robot_actions_from_mano_model_rules_v5_manohand_fortest_states_grab", "train_point_set", "train_point_set_retar", "train_point_set_retar_pts", "train_real_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_grab", "train_finger_kinematics_retargeting_arctic_twohands", "train_real_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_arctic_twohands", "train_real_robot_actions_from_mano_model_rules_shadowhand", "train_redmax_robot_actions_from_mano_model_rules_v5_shadowhand_fortest_states_grab", "train_dyn_mano_model_wreact"] and self.bending_net_type == "active_force_field_v18":
self.other_bending_network.timestep_to_total_def[0] = self.object_transl[0]
self.other_bending_network.timestep_to_quaternion[0] = self.tot_obj_quat[0]
self.other_bending_network.timestep_to_optimizable_offset[0] = self.object_transl[0].detach()
self.other_bending_network.timestep_to_optimizable_quaternion[0] = self.tot_obj_quat[0].detach()
self.other_bending_network.timestep_to_optimizable_rot_mtx[0] = self.tot_reversed_obj_rot_mtx[0].detach()
self.other_bending_network.timestep_to_optimizable_total_def[0] = self.object_transl[0].detach()
if self.fix_obj:
print(f"fix_obj = True")
for i_fr in range(self.object_transl.size(0)):
self.other_bending_network.timestep_to_total_def[i_fr] = self.object_transl[i_fr]
self.other_bending_network.timestep_to_quaternion[i_fr] = self.tot_obj_quat[i_fr]
self.other_bending_network.timestep_to_optimizable_offset[i_fr] = self.object_transl[i_fr].detach()
self.other_bending_network.timestep_to_optimizable_quaternion[i_fr] = self.tot_obj_quat[i_fr].detach()
self.other_bending_network.timestep_to_optimizable_rot_mtx[i_fr] = self.tot_reversed_obj_rot_mtx[i_fr].detach()
self.other_bending_network.timestep_to_optimizable_total_def[i_fr] = self.object_transl[i_fr].detach()
self.calculate_obj_inertia()
self.other_bending_network.use_penalty_based_friction = self.use_penalty_based_friction
self.other_bending_network.use_disp_based_friction = self.use_disp_based_friction
self.other_bending_network.use_sqrt_dist = self.use_sqrt_dist
self.other_bending_network.contact_maintaining_dist_thres = self.contact_maintaining_dist_thres
self.other_bending_network.penetration_proj_k_to_robot = self.penetration_proj_k_to_robot
self.other_bending_network.use_split_params = self.use_split_params
# self.other_bending_network.use_split_params = self.use_split_params
self.other_bending_network.use_sqr_spring_stiffness = self.use_sqr_spring_stiffness
self.other_bending_network.use_pre_proj_frictions = self.use_pre_proj_frictions
self.other_bending_network.use_static_mus = self.use_static_mus
self.other_bending_network.contact_friction_static_mu = self.contact_friction_static_mu
self.other_bending_network.debug = self.debug
self.obj_sdf_grad = None
self.other_bending_network.obj_sdf_grad = self.obj_sdf_grad ## set obj_sdf #
self.other_bending_network.use_sdf_as_contact_dist = self.use_sdf_as_contact_dist
self.other_bending_network.use_contact_dist_as_sdf = self.use_contact_dist_as_sdf
self.other_bending_network.minn_dist_threshold_robot_to_obj = self.minn_dist_threshold_robot_to_obj
self.other_bending_network.use_same_contact_spring_k = self.use_same_contact_spring_k
self.other_bending_network.I_ref = self.I_ref
self.other_bending_network.I_inv_ref = self.I_inv_ref
self.other_bending_network.obj_mass = self.obj_mass
# self.maxx_init_passive_mesh, self.minn_init_passive_mesh
self.other_bending_network.maxx_init_passive_mesh = self.maxx_init_passive_mesh
self.other_bending_network.minn_init_passive_mesh = self.minn_init_passive_mesh # ### init maximum passive meshe #
self.other_bending_network.train_residual_friction = self.train_residual_friction
### use optimizable params ###
self.other_bending_network.use_optimizable_params = self.use_optimizable_params
self.other_bending_network.penetration_proj_k_to_robot_friction = self.penetration_proj_k_to_robot_friction
self.other_bending_network.ang_vel_damping = self.ang_vel_damping
self.other_bending_network.use_damping_params_vel = self.use_damping_params_vel ## use_damping_params
self.other_bending_network.optm_alltime_ks = self.optm_alltime_ks
# self.ts_to_mesh_offset = self.load_calcu_timestep_to_passive_mesh_offset()
# self.ts_to_mesh_offset_for_opt = self.load_calcu_timestep_to_passive_mesh_offset()
params_to_train += list(self.other_bending_network.parameters()) #
self.optimizer = torch.optim.Adam(params_to_train, lr=self.learning_rate)
if len(self.ckpt_fn) > 0:
cur_ckpt_fn = self.ckpt_fn
self.load_checkpoint_via_fn(cur_ckpt_fn)
# if self.train_multi_seqs:
# damping_coefs = self.other_bending_network.damping_constant[0].weight.data
# spring_ks_values = self.other_bending_network.spring_ks_values[0].weight.data
# else:
damping_coefs = self.other_bending_network.damping_constant.weight.data
spring_ks_values = self.other_bending_network.spring_ks_values.weight.data
print(f"loaded ckpt has damping_coefs: {damping_coefs}, and spring ks values: {spring_ks_values}")
try:
friction_spring_ks = self.other_bending_network.spring_friction_ks_values.weight.data
print(f"friction_spring_ks:")
print(friction_spring_ks)
obj_inertia_val = self.other_bending_network.obj_inertia.weight.data
optimizable_obj_mass = self.other_bending_network.optimizable_obj_mass.weight.data
print(f"obj_inertia_val: {obj_inertia_val ** 2}, optimizable_obj_mass: {optimizable_obj_mass ** 2}")
except:
pass
time_constant = self.other_bending_network.time_constant.weight.data
print(f"time_constant: {time_constant}")
''' set gravity '''
### gravity ### #
self.gravity_acc = 9.8
self.gravity_dir = torch.tensor([0., 0., -1]).float().cuda()
self.passive_obj_mass = 1.
if not self.bending_net_type == "active_force_field_v13":
#### init passive mesh center and I_ref # #
self.init_passive_mesh_center, self.I_ref = self.calculate_passive_mesh_center_intertia()
self.inv_I_ref = torch.linalg.inv(self.I_ref)
self.other_bending_network.passive_obj_inertia = self.I_ref
self.other_bending_network.passive_obj_inertia_inv = self.inv_I_ref
def get_robohand_type_from_conf_fn(self, conf_model_fn):
if "redmax" in conf_model_fn:
hand_type = "redmax_hand"
elif "shadow" in conf_model_fn:
hand_type = "shadow_hand"
else:
raise ValueError(f"Cannot identify robot hand type from the conf_model file: {conf_model_fn}")
return hand_type
def calculate_passive_mesh_center_intertia(self, ): # passive
# self.timestep_to_passive_mesh # ## passvie mesh center ###
init_passive_mesh = self.timestep_to_passive_mesh[0] ### nn_mesh_pts x 3 ###
init_passive_mesh_center = torch.mean(init_passive_mesh, dim=0) ### init_center ###
per_vert_mass = self.passive_obj_mass / float(init_passive_mesh.size(0))
# (center to the vertex)
# assume the mass is uniformly distributed across all vertices ##
I_ref = torch.zeros((3, 3), dtype=torch.float32).cuda()
for i_v in range(init_passive_mesh.size(0)):
cur_vert = init_passive_mesh[i_v]
cur_r = cur_vert - init_passive_mesh_center
dot_r_r = torch.sum(cur_r * cur_r)
cur_eye_mtx = torch.eye(3, dtype=torch.float32).cuda()
r_mult_rT = torch.matmul(cur_r.unsqueeze(-1), cur_r.unsqueeze(0))
I_ref += (dot_r_r * cur_eye_mtx - r_mult_rT) * per_vert_mass
return init_passive_mesh_center, I_ref
def calculate_obj_inertia(self, ):
if self.canon_passive_obj_verts is None:
cur_init_passive_mesh_verts = self.timestep_to_passive_mesh[0].clone()
else:
cur_init_passive_mesh_verts = self.canon_passive_obj_verts.clone()
cur_init_passive_mesh_center = torch.mean(cur_init_passive_mesh_verts, dim=0)
cur_init_passive_mesh_verts = cur_init_passive_mesh_verts - cur_init_passive_mesh_center
# per_vert_mass= cur_init_passive_mesh_verts.size(0) / self.obj_mass
per_vert_mass = self.obj_mass / cur_init_passive_mesh_verts.size(0)
##
print(f"[Calculating obj inertia] per_vert_mass: {per_vert_mass}")
I_ref = torch.zeros((3, 3), dtype=torch.float32).cuda() ## caclulate I_ref; I_inv_ref; ##
for i_v in range(cur_init_passive_mesh_verts.size(0)):
cur_vert = cur_init_passive_mesh_verts[i_v]
cur_r = cur_vert # - cur_init_passive_mesh_center
cur_v_inertia = per_vert_mass * (torch.sum(cur_r * cur_r) - torch.matmul(cur_r.unsqueeze(-1), cur_r.unsqueeze(0)))
# cur_v_inertia = torch.cross(cur_r, cur_r) * per_vert_mass3 # #
I_ref += cur_v_inertia
print(f"In calculating inertia")
print(I_ref)
self.I_inv_ref = torch.linalg.inv(I_ref)
self.I_ref = I_ref
# the collison geometry should be able to locate the contact points #
def calculate_collision_geometry_bounding_boxes(self, ):
# #
# nearest ppont ?
init_passive_mesh = self.timestep_to_passive_mesh[0]
maxx_init_passive_mesh, _ = torch.max(init_passive_mesh, dim=0)
minn_init_passive_mesh, _ = torch.min(init_passive_mesh, dim=0)
# maxx init passive mesh; minn init passvie mesh ##
# contact passive mesh #
self.maxx_init_passive_mesh = maxx_init_passive_mesh
self.minn_init_passive_mesh = minn_init_passive_mesh
pass
def load_active_passive_timestep_to_mesh_v3(self, ):
sv_fn = self.kinematic_mano_gt_sv_fn
print(f'Loading from {sv_fn}')
''' Loading mano template '''
mano_hand_template_fn = 'assets/mano_hand_template.obj'
mano_hand_temp = trimesh.load(mano_hand_template_fn, force='mesh')
hand_faces = mano_hand_temp.faces
self.hand_faces = torch.from_numpy(hand_faces).long().to(self.device)
print(f"Loading data from {sv_fn}")
sv_dict = np.load(sv_fn, allow_pickle=True).item()
print(f"sv_dict: {sv_dict.keys()}")
obj_pcs = sv_dict['object_pc']
obj_pcs = torch.from_numpy(obj_pcs).float().cuda()
# self.obj_pcs = obj_pcs
obj_vertex_normals = sv_dict['obj_vertex_normals']
obj_vertex_normals = torch.from_numpy(obj_vertex_normals).float().cuda()
self.obj_normals = obj_vertex_normals
object_global_orient = sv_dict['object_global_orient'] # glboal orient
object_transl = sv_dict['object_transl']
obj_faces = sv_dict['obj_faces']
obj_faces = torch.from_numpy(obj_faces).long().cuda()
self.obj_faces = obj_faces
obj_verts = sv_dict['obj_verts']
minn_verts = np.min(obj_verts, axis=0)
maxx_verts = np.max(obj_verts, axis=0)
extent = maxx_verts - minn_verts
center_ori = (maxx_verts + minn_verts) / 2
scale_ori = np.sqrt(np.sum(extent ** 2))
obj_verts = torch.from_numpy(obj_verts).float().cuda()
self.obj_verts = obj_verts
mesh_scale = 0.8
bbmin, _ = obj_verts.min(0) #
bbmax, _ = obj_verts.max(0) #
center = (bbmin + bbmax) * 0.5
scale = 2.0 * mesh_scale / (bbmax - bbmin).max() # bounding box's max #
# vertices = (vertices - center) * scale # (vertices - center) * scale # #
self.sdf_space_center = center
self.sdf_space_scale = scale
# sdf_sv_fn = self.sdf_sv_fn
# self.obj_sdf = np.load(sdf_sv_fn, allow_pickle=True)
# self.sdf_res = self.obj_sdf.shape[0]
tot_reversed_obj_rot_mtx = []
tot_obj_quat = [] ## rotation matrix
transformed_obj_verts = []
print(f"object_global_orient: {object_global_orient.shape}")
for i_fr in range(object_global_orient.shape[0]):
cur_glb_rot = object_global_orient[i_fr]
cur_transl = object_transl[i_fr]
cur_transl = torch.from_numpy(cur_transl).float().cuda()
cur_glb_rot_struct = R.from_rotvec(cur_glb_rot)
cur_glb_rot_mtx = cur_glb_rot_struct.as_matrix()
cur_glb_rot_mtx = torch.from_numpy(cur_glb_rot_mtx).float().cuda()
cur_transformed_verts = torch.matmul(
self.obj_verts, cur_glb_rot_mtx
) + cur_transl.unsqueeze(0)
cur_glb_rot_mtx_reversed = cur_glb_rot_mtx.contiguous().transpose(1, 0).contiguous()
tot_reversed_obj_rot_mtx.append(cur_glb_rot_mtx_reversed)
cur_glb_rot_struct = R.from_matrix(cur_glb_rot_mtx_reversed.cpu().numpy())
cur_obj_quat = cur_glb_rot_struct.as_quat()
cur_obj_quat = cur_obj_quat[[3, 0, 1, 2]]
cur_obj_quat = torch.from_numpy(cur_obj_quat).float().cuda()
tot_obj_quat.append(cur_obj_quat)
# center_obj_verts = torch.mean(self.obj_verts, dim=0, keepdim=True)
# cur_transformed_verts = torch.matmul(
# (self.obj_verts - center_obj_verts), cur_glb_rot_mtx
# ) + cur_transl.unsqueeze(0) + center_obj_verts
# cur_transformed_verts = torch.matmul(
# cur_glb_rot_mtx, self.obj_verts.transpose(1, 0)
# ).contiguous().transpose(1, 0).contiguous() + cur_transl.unsqueeze(0)
transformed_obj_verts.append(cur_transformed_verts)
transformed_obj_verts = torch.stack(transformed_obj_verts, dim=0)
self.obj_pcs = transformed_obj_verts
rhand_verts = sv_dict['rhand_verts']
rhand_verts = torch.from_numpy(rhand_verts).float().cuda()
self.rhand_verts = rhand_verts ## rhand verts ##
if '30_sv_dict' in sv_fn:
bbox_selected_verts_idxes = torch.tensor([1511, 1847, 2190, 2097, 2006, 2108, 1604], dtype=torch.long).cuda()
obj_selected_verts = self.obj_verts[bbox_selected_verts_idxes]
else:
obj_selected_verts = self.obj_verts.clone()