""" Copyright (C) 2018 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import numpy as np import scipy.linalg as slin import open3d as o3d import math import transforms3d.quaternions as txq import transforms3d.euler as txe from scipy.spatial.transform import Rotation as Rot # see for formulas: # https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-801-machine-vision-fall-2004/readings/quaternions.pdf # and "Quaternion and Rotation" - Yan-Bin Jia, September 18, 2016 # from IPython.core.debugger import set_trace import argparse parser = argparse.ArgumentParser() parser.add_argument('--train', help='train number', required=True) parser.add_argument('--test', help='test_number', required=True) args = parser.parse_args() train_num = int(args.train) test_num = int(args.test) # runs pgo in batches of size base_lim until all time steps are handled. consecutive batches have an overlap base_lim = 100 # number of steps to simultaneously consider for pgo (low for faster runtime) overlapping_percent = 0.2 # percent of overlapping time steps to the previous pgo run # path to save the created values save_base_path = "..." # adds the test and train num to the save path (for better structure) save_base_path_ext = str(test_num) + "_" + str(train_num) # ------------ Rel vals ------------ # rel_vals_base_folder = "..." % train_num txt_file_exts = {1: ..., 2: ...} # One extension for every test case txt_file_ext = txt_file_exts[test_num] rel_vals_file = rel_vals_base_folder + txt_file_ext # file containing the predicted relative poses/orientation # ---------------------------------- # # ------------ GT + Abs vals ------------ # gt_abs_vals_base_folder = "..." % train_num gt_abs_txt_file_exts = {1: ..., 2: ...} # One extension for every test case gt_abs_txt_file_ext = gt_abs_txt_file_exts[test_num] # file containing the predicted absolute poses/orientation gt_abs_vals_file = gt_abs_vals_base_folder + gt_abs_txt_file_ext # ---------------------------------- # def getRelDiff(posx, posq, actualx, actualq): """ Calculates the relative difference in position and rotation. """ rel_x = posx - actualx m1 = Rot.from_quat(posq).as_matrix() m2 = Rot.from_quat(actualq).as_matrix() m_rel = m1 @ m2.T #m_rel = m2.T @ m1 rel_q = Rot.from_matrix(m_rel).as_quat() return rel_x, rel_q ## NUMPY # see: https://github.com/NVlabs/geomapnet/blob/master/common/pose_utils.py ----------------------------- # def qlog(q): """ Applies logarithm map to q :param q: (4,) :return: (3,) """ if all(q[1:] == 0): q = np.zeros(3) else: q = np.arccos(q[0]) * q[1:] / np.linalg.norm(q[1:]) return q def qexp(q): """ Applies the exponential map to q :param q: (3,) :return: (4,) """ n = np.linalg.norm(q) q = np.hstack((np.cos(n), np.sinc(n / np.pi) * q)) return q def log_quaternion_angular_error(q1, q2): return quaternion_angular_error(qexp(q1), qexp(q2)) def quaternion_angular_error(q1, q2): """ angular error between two quaternions :param q1: (4, ) :param q2: (4, ) :return: """ d = abs(np.dot(q1, q2)) d = min(1.0, max(-1.0, d)) theta = 2 * np.arccos(d) * 180 / np.pi return theta def skew(x): """ returns skew symmetric matrix from vector :param x: 3 x 1 :return: """ s = np.asarray([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]) return s def dpq_q(p): """ returns the jacobian of quaternion product pq w.r.t. q :param p: 4 x 1 :return: 4 x 4 """ J = np.zeros((4, 4)) J[0, 0] = p[0] J[0, 1:] = -p[1:].squeeze() J[1:, 0] = p[1:].squeeze() J[1:, 1:] = p[0] * np.eye(3) + skew(p[1:]) return J def dpsq_q(p): """ returns the jacobian of quaternion product (p*)q w.r.t. q :param p: 4 x 1 :return: 4 x 4 """ J = np.zeros((4, 4)) J[0, 0] = p[0] J[0, 1:] = -p[1:].squeeze() J[1:, 0] = -p[1:].squeeze() J[1:, 1:] = p[0] * np.eye(3) - skew(p[1:]) return J def dpsq_p(q): """ returns the jacobian of quaternion product (p*)q w.r.t. p :param q: 4 x 1 :return: 4 x 4 """ J = np.zeros((4, 4)) J[0, 0] = q[0] J[0, 1:] = q[1:].squeeze() J[1:, 0] = q[1:].squeeze() J[1:, 1:] = -q[0] * np.eye(3) + skew(q[1:]) return J def dqstq_q(q, t): """ jacobian of q* t q w.r.t. q :param q: 4 x 1 :param t: 3 x 1 :return: 3 x 4 """ J = np.zeros((3, 4)) J[:, :1] = q[0] * t - np.cross(q[1:], t, axis=0) J[:, 1:] = -np.dot(t, q[1:].T) + np.dot(t.T, q[1:]) * np.eye(3) + \ np.dot(q[1:], t.T) + q[0] * skew(t) J *= 2 return J def dqstq_t(q): """ jacobian of q* t q w.r.t. t :param q: 4 x 1 :return: 3 x 3 """ J = (q[0] * q[0] - np.dot(q[1:].T, q[1:])) * np.eye(3) + 2 * np.dot(q[1:], q[1:].T) - \ 2 * q[0] * skew(q[1:]) return J def m_rot(x): """ returns Jacobian of exponential map w.r.t. manifold increment :param x: part of state vector affected by increment, 4 x 1 :return: 4 x 3 """ # jacobian of full q wrt qm (quaternion update on manifold), # evaluated at qv = (0, 0, 0) # full q is derived using either the exponential map or q0 = sqrt(1-qm^2) jm = np.vstack((np.zeros((1, 3)), np.eye(3))) # 4 x 3 m = np.dot(dpq_q(p=x), jm) return m class PoseGraph: def __init__(self): """ implements pose graph optimization from "Hybrid Hessians for Optimization of Pose Graphs" - Y. LeCun et al and "A Tutorial on Graph-Based SLAM" - W. Burgard et al """ self.N = 0 self.z = np.zeros((0, 0)) def jacobian(self, L_ax, L_aq, L_rx, L_rq): J = np.zeros((0, 6 * self.N)) # 6 because updates for rotation are on manifold # unary constraints for i in np.arange(self.N): # translation constraint jt = np.zeros((3, J.shape[1])) jt[:, 6 * i: 6 * i + 3] = np.eye(3) J = np.vstack((J, np.dot(L_ax, jt))) # rotation constraint jr = np.zeros((4, J.shape[1])) jr[:, 6 * i + 3: 6 * i + 6] = m_rot(x=self.z[7 * i + 3: 7 * i + 7]) J = np.vstack((J, np.dot(L_aq, jr))) # pairwise constraints for i in np.arange(self.N - 1): # translation constraint jt = np.zeros((3, J.shape[1])) dt = dqstq_t(q=self.z[7 * i + 3: 7 * i + 7]) jt[:, 6 * i: 6 * i + 3] = -dt jt[:, 6 * (i + 1): 6 * (i + 1) + 3] = dt J = np.vstack((J, np.dot(L_rx, jt))) # rotation constraint jr = np.zeros((4, J.shape[1])) m = m_rot(x=self.z[7 * i + 3: 7 * i + 7]) a = dpsq_p(q=self.z[7 * (i + 1) + 3: 7 * (i + 1) + 7]) jr[:, 6 * i + 3: 6 * i + 6] = np.dot(a, m) m = m_rot(x=self.z[7 * (i + 1) + 3: 7 * (i + 1) + 7]) b = dpsq_q(p=self.z[7 * i + 3: 7 * i + 7]) jr[:, 6 * (i + 1) + 3: 6 * (i + 1) + 6] = np.dot(b, m) J = np.vstack((J, np.dot(L_rq, jr))) return J def residuals(self, poses, vos, L_ax, L_aq, L_rx, L_rq): """ computes the residuals :param poses: N x 7 :param vos: (N-1) x 7 :param L_ax: 3 x 3 :param L_aq: 4 x 4 :param L_rx: 3 x 3 :param L_rq: 4 x 4 :return: """ r = np.zeros((0, 1)) # unary residuals L = np.zeros((7, 7)) L[:3, :3] = L_ax L[3:, 3:] = L_aq for i in np.arange(self.N): rr = self.z[7 * i: 7 * (i + 1)] - np.reshape(poses[i], (-1, 1)) r = np.vstack((r, np.dot(L, rr))) # pairwise residuals for i in np.arange(self.N - 1): # translation residual v = self.z[7 * (i + 1):7 * (i + 1) + 3, 0] - self.z[7 * i:7 * i + 3, 0] q = txq.qinverse(self.z[7 * i + 3:7 * i + 7, 0]) rt = txq.rotate_vector(v, q) rt = rt[:, np.newaxis] - vos[i, :3].reshape((-1, 1)) r = np.vstack((r, np.dot(L_rx, rt))) # rotation residual q0 = self.z[7 * i + 3: 7 * i + 7].squeeze() q1 = self.z[7 * (i + 1) + 3: 7 * (i + 1) + 7].squeeze() qvo = txq.qmult(txq.qinverse(q0), q1).reshape((-1, 1)) rq = qvo - vos[i, 3:].reshape((-1, 1)) r = np.vstack((r, np.dot(L_rq, rq))) return r def update_on_manifold(self, x): """ Updates the state vector on manifold :param x: manifold increment, column vector :return: """ for i in np.arange(self.N): # update translation t = x[6 * i: 6 * i + 3] self.z[7 * i: 7 * i + 3] += t # update rotation qm = x[6 * i + 3: 6 * i + 6] # quaternion on the manifold dq = np.zeros(4) # method in Burgard paper # dq[1:] = qm.squeeze() # dq[0] = math.sqrt(1 - sum(np.square(qm))) # incremental quaternion # method of exponential map n = np.linalg.norm(qm) dq[0] = math.cos(n) dq[1:] = np.sinc(n / np.pi) * qm.squeeze() q = self.z[7 * i + 3: 7 * i + 7].squeeze() q = txq.qmult(q, dq).reshape((-1, 1)) self.z[7 * i + 3: 7 * i + 7] = q def optimize(self, poses, vos, sax=1, saq=1, srx=1, srq=1, n_iters=10): """ run PGO, with init = poses :param poses: :param vos: :param sax: sigma for absolute translation :param saq: sigma for absolute rotation :param srx: sigma for relative translation :param srq: sigma for relative rotation :param n_iters: :return: """ self.N = len(poses) # init state vector with the predicted poses self.z = np.reshape(poses.copy(), (-1, 1)) # construct the information matrices L_ax = np.linalg.cholesky(np.eye(3) / sax) L_aq = np.linalg.cholesky(np.eye(4) / saq) L_rx = np.linalg.cholesky(np.eye(3) / srx) L_rq = np.linalg.cholesky(np.eye(4) / srq) for n_iter in np.arange(n_iters): J = self.jacobian(L_ax.T, L_aq.T, L_rx.T, L_rq.T) r = self.residuals(poses.copy(), vos.copy(), L_ax.T, L_aq.T, L_rx.T, L_rq.T) H = np.dot(J.T, J) # hessian b = np.dot(J.T, r) # residuals # solve Hx = -b for x R = slin.cholesky(H) # H = R' R y = slin.solve_triangular(R.T, -b) x = slin.solve_triangular(R, y) self.update_on_manifold(x) return self.z.reshape((-1, 7)) def print_poses(poses): for i in np.arange(poses.shape[0]): a = txe.mat2euler(txq.quat2mat(poses[i, 3:])) print([np.rad2deg(aa) for aa in a]) # --------------------------------------------------------------------------------------------------------------- # def getError(posx, posq, actualx, actualq): """ Calculates the position error (euclidean distance) and the rotation error. """ q1 = actualq / np.linalg.norm(actualq) q2 = posq / np.linalg.norm(posq) d = abs(np.sum(np.multiply(q1, q2))) theta = 2 * np.arccos(d) * 180 / np.pi errx = np.linalg.norm(actualx - posx) return errx, theta def run_pgo(): # read in the prediction and ground truth values for the absolute position and rotation with open(gt_abs_vals_file, "r") as f: gt_abs_vals = f.readlines() pred_poses = [] position_gt = [] rotation_gt = [] gt_abs_vals_names = [] for gav in gt_abs_vals: pred_poses.append([float(x.split(",")[0]) for x in gav.split("\n")[0].split(": ")[-7:]]) position_gt.append([float(x.split(",")[0]) for x in gav.split("\n")[0].split(" Prediction: ")[0].split(": ")[-7:-4]]) rotation_gt.append([float(x.split(",")[0]) for x in gav.split("\n")[0].split(" Prediction: ")[0].split(": ")[-4:]]) gt_abs_vals_names.append(int(gav.split(" ")[1].split("/")[1].split("_")[2][:-5])) pred_poses = np.array(pred_poses) position_gt = np.array(position_gt) rotation_gt = np.array(rotation_gt) gt_abs_vals_names = np.array(gt_abs_vals_names) # for any positions outside of the area replace them with the position of the previous step for i in range(len(pred_poses)): for j in range(2): if pred_poses[i, j] < -1 or pred_poses[i, j] > 46: pred_poses[i, j] = pred_poses[i - 1, j] if pred_poses[i, 2] < -1 or pred_poses[i, 2] > 8: pred_poses[i, 2] = pred_poses[i - 1, 2] # read in the predicted relative translation/rotation with open(rel_vals_file, "r") as f: r_vals = f.readlines() r_vals_rel = [] r_vals_names = [] for rv in r_vals: r_vals_rel.append([float(x.split(",")[0]) for x in rv.split("\n")[0].split(": ")[-7:]]) r_vals_names.append(int(rv.split(" ")[1].split("/")[1].split("_")[1][:-5])) r_vals_names = np.array(r_vals_names) r_vals_rel = np.array(r_vals_rel) removed_images = [] removed_images_pt = [] cur_ind = 0 # makes sure that each absolute value has the correct corresponding relative value for xi, x in enumerate(gt_abs_vals_names): if cur_ind >= len(r_vals_names): removed_images.append(xi) continue while x > r_vals_names[cur_ind]: removed_images_pt.append(cur_ind) cur_ind += 1 if cur_ind >= len(r_vals_names): break if cur_ind >= len(r_vals_names) or (x != r_vals_names[cur_ind]): removed_images.append(xi) else: cur_ind += 1 valid_images = np.array(list(set(np.arange(len(gt_abs_vals_names))) - set(removed_images))).astype(int) valid_images_pt = np.array(list(set(np.arange(len(r_vals_names))) - set(removed_images_pt))).astype(int) print(len(position_gt), len(rotation_gt), len(pred_poses), len(valid_images), len(valid_images_pt)) position_gt = position_gt[valid_images] rotation_gt = rotation_gt[valid_images] pred_poses = pred_poses[valid_images] vos = r_vals_rel[valid_images_pt] # --- correct rel xyz --- # rotate the relative orientation back to the world coordinate system (before it is based on the previous view) for i in range(len(pred_poses)): vos[i][:3] = Rot.from_quat(pred_poses[i][-4:]).as_matrix().T @ vos[i][:3] # ------- # calculates the position/orientation error before applying pgo position_errors_base = [] rotation_errors_base = [] for i in range(len(position_gt)): pos_err, rot_err = getError(pred_poses[i, :3], pred_poses[i, 3:], position_gt[i], rotation_gt[i]) position_errors_base.append(pos_err) rotation_errors_base.append(rot_err) position_errors_base = np.array(position_errors_base) rotation_errors_base = np.array(rotation_errors_base) # -------- overlapping PGO -------- # # applies pgo on overlapping batches of a above defined size start_poses = np.arange(0, len(pred_poses), int(base_lim*(1-overlapping_percent))) all_optimized_poses = np.zeros((len(valid_images), 7)) for si, sp in enumerate(start_poses): print(si, sp) pgo = PoseGraph() optimized_poses = pgo.optimize(pred_poses[sp:sp+base_lim], vos[sp:sp+base_lim]) if si == 0: all_optimized_poses[sp:sp+base_lim] = optimized_poses elif si == len(start_poses) - 1: if len(optimized_poses) > int(base_lim * overlapping_percent): all_optimized_poses[sp + int(base_lim * overlapping_percent):sp + len(optimized_poses)] = optimized_poses[ int( base_lim * overlapping_percent):] else: all_optimized_poses[sp + int(base_lim * overlapping_percent):sp + base_lim] = optimized_poses[int( base_lim * overlapping_percent):] # --------------------------------- # # calculates the position/orientation error after applying pgo position_errors = [] rotation_errors = [] for i in range(len(all_optimized_poses)): pos_err, rot_err = getError(all_optimized_poses[i, :3], all_optimized_poses[i, 3:], position_gt[i], rotation_gt[i]) position_errors.append(pos_err) rotation_errors.append(rot_err) position_errors = np.array(position_errors) rotation_errors = np.array(rotation_errors) all_errors_arr = np.vstack([position_errors_base, rotation_errors_base, position_errors, rotation_errors]) np.save(save_base_path + save_base_path_ext + "_all_errors.npy", all_errors_arr) with open(save_base_path + save_base_path_ext + "_medians.txt", "w") as f: f.write("Before PGO: %.5f\t%.5f\n" % (np.nanmedian(position_errors_base), np.nanmedian(rotation_errors_base))) f.write("After PGO: %.5f\t%.5f\n" % (np.nanmedian(position_errors), np.nanmedian(rotation_errors))) print("Before PGO: %.5f\t%.5f" % (np.nanmedian(position_errors_base), np.nanmedian(rotation_errors_base))) print("After PGO: %.5f\t%.5f" % (np.nanmedian(position_errors), np.nanmedian(rotation_errors))) if __name__ == '__main__': run_pgo()