Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
161 lines (139 loc) · 5.36 KB
/
Copy pathutils.py
File metadata and controls
161 lines (139 loc) · 5.36 KB
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
import os
import torch
import io, pickle
import numpy as np
from inspect import currentframe, getframeinfo
import wandb
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
import pypose as pp
def so3_log(quat: torch.Tensor) -> torch.Tensor:
"""Quaternion (..., 4) -> so(3) log map (..., 3) as a plain tensor."""
return pp.SO3(quat).Log().tensor()
def save_state(out_states:dict, in_state:dict):
for k, v in in_state.items():
if v is None:
continue
elif isinstance(v, dict):
save_state(out_states=out_states, in_state=v)
elif k in out_states.keys():
out_states[k].append(v)
else:
out_states[k] = [v]
def Gaussian_noise(num_nodes, sigma_x=0.05 ,sigma_y=0.05, sigma_z=0.05):
std = torch.stack([torch.ones(num_nodes)*sigma_x, torch.ones(num_nodes)*sigma_y, torch.ones(num_nodes)*sigma_z], dim=-1)
return torch.normal(mean = 0, std = std)
def move_to(obj, device):
if torch.is_tensor(obj):return obj.to(device)
elif obj is None:
return None
elif isinstance(obj, dict):
res = {}
for k, v in obj.items():
res[k] = move_to(v, device)
return res
elif isinstance(obj, list):
res = []
for v in obj:
res.append(move_to(v, device))
return res
elif isinstance(obj, np.ndarray):
return torch.tensor(obj).to(device)
else:
raise TypeError("Invalid type for move_to", type(obj))
def qinterp(qs, t, t_int):
qs = R.from_quat(qs.numpy())
slerp = Slerp(t, qs)
interp_rot = slerp(t_int).as_quat()
return torch.tensor(interp_rot)
def interp_xyz(time, opt_time, xyz):
intep_x = np.interp(time, xp=opt_time, fp = xyz[:,0])
intep_y = np.interp(time, xp=opt_time, fp = xyz[:,1])
intep_z = np.interp(time, xp=opt_time, fp = xyz[:,2])
inte_xyz = np.stack([intep_x, intep_y, intep_z]).transpose()
return torch.tensor(inte_xyz)
def lookAt(dir_vec, up = torch.tensor([0.,0.,1.], dtype=torch.float64), source = torch.tensor([0.,0.,0.], dtype=torch.float64)):
'''
dir_vec: the tensor shall be (1)
return the rotation matrix of the
'''
if not isinstance(dir_vec, torch.Tensor):
dir_vec = torch.tensor(dir_vec)
def normalize(x):
length = x.norm()
if length< 0.005:
length = 1
warnings.warn('Normlization error that the norm is too small')
return x/length
zaxis = normalize(dir_vec - source)
xaxis = normalize(torch.cross(zaxis, up))
yaxis = torch.cross(xaxis, zaxis)
m = torch.tensor([
[xaxis[0], xaxis[1], xaxis[2]],
[yaxis[0], yaxis[1], yaxis[2]],
[zaxis[0], zaxis[1], zaxis[2]],
])
return m
def cat_state(in_state:dict):
pop_list = []
for k, v in in_state.items():
if len(v[0].shape) > 2:
in_state[k] = torch.cat(v, dim=-2)
else:
pop_list.append(k)
for k in pop_list:
in_state.pop(k)
class CPU_Unpickler(pickle.Unpickler):
def find_class(self, module, name):
if module == 'torch.storage' and name == '_load_from_bytes':
return lambda b: torch.load(io.BytesIO(b), map_location='cpu')
else:
return super().find_class(module, name)
def write_board(writer, objs, epoch_i, header = ''):
# writer = SummaryWriter(log_dir=conf.general.exp_dir)
if isinstance(objs, dict):
for k, v in objs.items():
if isinstance(v, float):
writer.add_scalar(os.path.join(header, k), v, epoch_i)
elif isinstance(objs, float):
writer.add_scalar(header, v, epoch_i)
def write_wandb(header, objs, epoch_i):
if isinstance(objs, dict):
for k, v in objs.items():
if isinstance(v, float):
wandb.log({os.path.join(header, k): v}, epoch_i)
else:
wandb.log({header: objs}, step = epoch_i)
def save_ckpt(network, optimizer, scheduler, epoch_i, test_loss, conf, save_best = False):
if epoch_i%conf.train.save_freq==conf.train.save_freq-1:
torch.save({
'epoch': epoch_i,
'model_state_dict': network.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict(),
'best_loss': test_loss,
}, os.path.join(conf.general.exp_dir, "ckpt/%04d.ckpt"%epoch_i))
if save_best:
print("saving the best model", test_loss)
torch.save({
'epoch': epoch_i,
'model_state_dict': network.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict(),
'best_loss': test_loss,
}, os.path.join(conf.general.exp_dir, "ckpt/best_model.ckpt"))
torch.save({
'epoch': epoch_i,
'model_state_dict': network.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict(),
'best_loss': test_loss,
}, os.path.join(conf.general.exp_dir, "ckpt/newest.ckpt"))
def report_hasNan(x):
cf = currentframe().f_back
res = torch.any(torch.isnan(x)).cpu().item()
if res: print(f"[hasnan!] {getframeinfo(cf).filename}:{cf.f_lineno}")
def report_hasNeg(x):
cf = currentframe().f_back
res = torch.any(x < 0).cpu().item()
if res: print(f"[hasneg!] {getframeinfo(cf).filename}:{cf.f_lineno}")