-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloop_demo.py
executable file
·273 lines (232 loc) · 13.4 KB
/
loop_demo.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
from xml.etree.ElementTree import PI
from cv2 import log
import torch
from torch.utils.data import DataLoader
import yaml
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# os.environ['CUDA_LAUNCH_BLOCKING']="1"
os.environ["KITTI360_DATASET"] = "/home/yx/Data/yx/dataset/KITTI-360"
from render.render_helper import * #_loop
# from torch.utils.tensorboard import SummaryWriter
import time
from dataset.kitti360.init_kitti360_pose import init_all_poses
from tools.draw_line import plot_traj
import utils.qury_pose
from utils.scannet_data_tools.write_evo_data import record_evo_data
from models.multi_cubes_orb import Cubes
from minisam import *
from utils.loop.PoseGraphManager import *
from scipy.spatial.transform import Rotation as R_scipy
cube_num = 39 #65
def graph_optim(F_all_init, cubes, cfg, vec_es_data, loop_transform=None):
# loop_transform = (F_all_init[9].inv() * cubes.F[0]).matrix().detach().cpu().numpy().astype(np.float64)
# loop_transform = (cubes.F[0].inv() * F_all_init[9]).matrix().detach().cpu().numpy().astype(np.float64)
# np.save("loop_T.npy",loop_transform)
if loop_transform.any().item():
loop_transform = loop_transform.astype(np.float64)
else:
loop_transform = np.load("loop_T.npy").astype(np.float64)
u,s,vt = np.linalg.svd(loop_transform[:3,:3])
loop_transform[:3,:3] = np.dot(vt.T, u.T)
# Pose Graph Manager (for back-end optimization) initialization
PGM = PoseGraphManager()
PGM.curr_se3 = F_all_init[0].inv().matrix().cpu().numpy()
PGM.addPriorFactor()
# Result saver
save_dir = cfg["path"]['proj_dir']+ "/loop_orb"
os.makedirs(save_dir, exist_ok=True)
ResultSaver = PoseGraphResultSaver(init_pose=PGM.curr_se3,
save_gap=1,#args.save_gap,
num_frames=cube_num,#num_frames,
seq_idx="00",#args.sequence_idx,
save_dir=save_dir)
# add the odometry factor to the graph
for idx in range(1,cube_num):
PGM.curr_node_idx = idx
PGM.prev_node_idx = idx-1
odom_transform = (F_all_init[idx].inv() * F_all_init[idx-1]).matrix().cpu().numpy()
# update the current (moved) pose
PGM.curr_se3 = np.matmul(PGM.curr_se3, odom_transform)
PGM.addOdometryFactor(odom_transform)
# save the ICP odometry pose result (no loop closure)
ResultSaver.saveUnoptimizedPoseGraphResult(PGM.curr_se3, PGM.curr_node_idx)
PGM.curr_node_idx = cube_num-1
loop_idx = 4 #9
# print("loop----")
PGM.addLoopFactor(loop_transform, loop_idx)
# 2-2/ graph optimization
PGM.optimizePoseGraph()
# 2-2/ save optimized poses
w2g_init = SE3.exp(F_all_init.log().cuda()).inv().vec()
ResultSaver.saveOptimizedPoseGraphResult(cube_num, PGM.graph_optimized) #PGM.curr_node_idx
t = torch.FloatTensor(ResultSaver.pose_list[:,[3,7,11]])
R_m = ResultSaver.pose_list[:,[0,1,2,4,5,6,8,9,10]].reshape(-1,3,3)
q = torch.FloatTensor((R_scipy.from_matrix(R_m)).as_quat())
pose_vec = torch.hstack((t,q)).to(cubes.device)
F_new = SE3(pose_vec).inv()
cubes.global_update(vec_es_data, F_new)
# # cubes.pose_update()
# # plot_traj(cubes.w2gs[0,:3], traj_gt, traj_loam, -cubes.w2gs[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
# R = SE3.exp(cubes.R.log().cuda())
# T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
# plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, 3, 0+1, 1, 'b')
ResultSaver.vizCurrentTrajectory(w2g_init[:,:3].cpu().numpy(), R.vec()[:,:3].cpu().numpy(), 1, cfg["path"]['proj_dir']+"/loop_result")
if __name__ == '__main__':
start_cube_idx = 0
torch.manual_seed(0)
np.random.seed(250)
torch.set_printoptions(precision=20)
np.set_printoptions(precision=20)
# writer = SummaryWriter()
writer = None
tensorboard_flag = False if writer == None else True
# yaml_path = "config/kitti360.yaml"
yaml_path = "config/render_loop.yaml"
with open(yaml_path, "r") as f:
cfg = yaml.safe_load(f)
# data_dir = cfg['path']['proj_dir']
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cuda:0")
savedir = cfg['path']['proj_dir']
cfg['loss_term']['semantic3d'] = False
# Get grid
grid_model_name = cfg['model']['model_name']
print(f"Grid Model = {grid_model_name}")
assert( grid_model_name in GRIDMODEL )
batch_size = int(cfg['params']['ray_chunk'])
batch_size_2 = int(cfg['params']['ray_chunk_mode2'])
loss_occ = 0
frame_step = cfg['frame']['step']
# init pose
all_pose_list = range(cfg['train']['all_pose'][0], cfg['train']['all_pose'][-1])
with torch.no_grad():
seq = int(cfg['path']['dataset_dir'].split("/")[-3][-6])
_, _, vec_gt, traj_gt, traj_loam, odom, vec_loam = init_all_poses(cfg['path']['proj_dir']+"/init", seq, all_pose_list, device)
# traj_gt =
from lietorch import SE3
# set train rays
# files = os.listdir(os.path.join(cfg['path']['proj_dir'], "grid"))
cubes_num = cube_num #9# len(files)-3
train_list_key_frame = list(range(cfg['train']['all_pose'][0],
cfg['train']['all_pose'][0]+((cubes_num+1)*int(cfg['frame']['num']/2)-1)*frame_step+1,frame_step)) #cfg['train']['all_pose'][0]+((cubes_num+1)*8-1)*frame_step+1,frame_step))
# load lidar odometry pose
vec_es = {}
# vec_es_data = np.loadtxt("/home/yx/myProject/occuSLAM3D_indoor_KITTI/out/2_pose_es.txt")[:,1:]
vec_es_data = np.loadtxt(os.path.join(savedir, "pose/2_pose_es.txt"))[:,1:]
num = 0 #+9*8
for i in train_list_key_frame:
vec_es[f"{i}"] = torch.FloatTensor(vec_es_data[num,:]).to(device)
num = num + 1
# set cubes
step = 1
cubes = Cubes(cfg, cubes_num, train_list_key_frame, vec_es, step, device, cube_num)
pose_lr = 0.03 #0.01 0.005
s_lr = 0.1 #10
gamma = 0.9 #0.95
cubes.set_optimer(pose_lr, s_lr)
print(f"pose_lr={pose_lr}, s_lr={s_lr}, gamma={gamma}")
OCCExpLR = torch.optim.lr_scheduler.ExponentialLR(cubes.optimer, gamma=gamma) #0.9
# lamudas['overlap_lamuda'] = train_info['overlap_lamuda']
with torch.no_grad():
cubes.pose_update()
# plot_traj(cubes.w2gs[0,:3], traj_gt, traj_loam, -cubes.w2gs[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
R = SE3.exp(cubes.R.log().cuda())
T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, 0, 0+1, 0, 'g')
F_all_init = cubes.F_all
batch_size_cubes = 1024 #2048
# train_now = train_list_key_frame[5*40:7*40]
if cfg['path']['dataset_type'] == 'kitti-360':
from dataset.kitti360.kitti360_dataset import Kitti360Dataset
dataset_train = Kitti360Dataset(cfg, train_list_key_frame, device, vec_gt, vec_es, None, "train", optim_flag=cfg["loss_term"])
train_sampler = SimpleSampler(train_list_key_frame, dataset_train.camera, total=dataset_train.get_every_img_batch(), batch=batch_size_cubes)
##01: cal T matrix
'''
This is an example of computing a loop transformation matrix using rendering loss between nearby volumes.
The location identification in the example is manually specified.
SOTA location identification is used in the application.
Loop detection and pose estimation can also be replaced by related SOTA methods at the same time.
'''
for e in range(0):
losses = []
print(f"Start Epoch {e} : ")
# if e==2:
# train_sampler = SimpleSampler(train_list_key_frame, dataset_train.camera, total=dataset_train.get_every_img_batch(), batch=2**13)
with tqdm(total=train_sampler.epoch_iter) as t:
for i in range(train_sampler.epoch_iter):
idx = train_sampler.nextids(len(dataset_train.imgs))
loss_cubes = cubes.get_rays_loss(dataset_train[idx],e,i)
losses.append(loss_cubes)
t.set_postfix(loss=loss_cubes, s=cubes.s.data.item())
t.update(1)
loss_mean = np.stack(losses).mean()
print(f"loss={loss_mean}")
OCCExpLR.step()
with torch.no_grad():
# plot_traj(cubes.w2gs[0,:3], traj_gt, traj_loam, -cubes.w2gs[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
R = SE3.exp(cubes.R.log().cuda())
T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
# T = SE3.exp(cubes.F.log().cuda()).inv().vec()
plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
for i in range(cubes_num):
np.savetxt(os.path.join(savedir, f"loop_result/pointcloud_trans_{i+1}.txt"), (cubes.scale_matrix@cubes.F_all[i].matrix()).cpu().numpy(), fmt='%.5f',delimiter='\t')
# ours_init
cubes.pose_update()
cubes.record_pose()
record_evo_data(train_list_key_frame, \
vec_es,vec_gt, os.path.join(cfg['path']['proj_dir'], "init/timestamps.txt"), savedir, device, 5)
##02: graph optimize
# loop_transform = (cubes.F_all[4].matrix()@cubes.F_all[-1].inv().matrix()).cpu().numpy() #T38->T5
loop_transform = np.load("loop_demo/T38_2_T5.npy")
graph_optim(F_all_init, cubes, cfg, vec_es_data, loop_transform)
#03: all together
cubes.reset_F()
with torch.no_grad():
# plot_traj(cubes.w2gs[0,:3], traj_gt, traj_loam, -cubes.w2gs[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
R = SE3.exp(cubes.R.log().cuda())
T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
# T = SE3.exp(cubes.F.log().cuda()).inv().vec()
plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, 1, 0+1, 0, 'b')
pose_lr = 0.005
s_lr = 0 #0.1
gamma = 0.5
cubes.set_optimer(pose_lr, s_lr)
print(f"pose_lr={pose_lr}, s_lr={s_lr}, gamma={gamma}")
OCCExpLR = torch.optim.lr_scheduler.ExponentialLR(cubes.optimer, gamma=gamma)
batch_size_cubes = 200
train_sampler = SimpleSampler(train_list_key_frame, dataset_train.camera, total=dataset_train.get_every_img_batch(), batch=batch_size_cubes)
for e in range(2):
losses = []
print(f"Start Epoch {e} : ")
# with tqdm(total=train_sampler.epoch_iter) as t:
# for i in range(train_sampler.epoch_iter):
with tqdm(total=100) as t:
for i in range(100):
idx = train_sampler.nextids(len(dataset_train.imgs))
loss_cubes = cubes.get_rays_loss(dataset_train[idx],e,i,flag=1) #train all
losses.append(loss_cubes)
t.set_postfix(loss=loss_cubes, s=cubes.s.data.item())
t.update(1)
if i%10==0:
with torch.no_grad():
R = SE3.exp(cubes.R.log().cuda())
T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, e+1, 0+1, i, 'b')
loss_mean = np.stack(losses).mean()
print(f"loss={loss_mean}")
OCCExpLR.step()
# with torch.no_grad():
# # plot_traj(cubes.w2gs[0,:3], traj_gt, traj_loam, -cubes.w2gs[:,:3].cpu().numpy(), None, 0, 0+1, e+1, 'b')
# R = SE3.exp(cubes.R.log().cuda())
# T = SE3.exp(cubes.F_all.log().cuda()).inv().vec()
# # T = SE3.exp(cubes.F.log().cuda()).inv().vec()
# plot_traj(savedir, None, T[:,:3], traj_gt, traj_loam, R.vec()[:,:3].cpu().numpy(), None, 1, 0+1, e+1, 'b')
# for i in range(cubes_num):
# np.savetxt(os.path.join(savedir, f"loop_result/pointcloud_trans_{i+1}_hole.txt"), (cubes.scale_matrix@cubes.F_all[i].matrix()).cpu().numpy(), fmt='%.5f',delimiter='\t')
# ours_init
cubes.pose_update()
cubes.record_pose()
record_evo_data(train_list_key_frame, \
vec_es,vec_gt, os.path.join(cfg['path']['proj_dir'], "init/timestamps.txt"), savedir, device, 10)