示例#1
0
 def visualize_steering(self, encoder_list, clear=False, draw=False):
     assert self.plot_steering
     Plot3D.plot_steering_commands(encoder_list,
                                   self.rev,
                                   self.steer,
                                   style='-yx',
                                   clear=clear,
                                   draw=draw)
示例#2
0
    def visualize_poses(self, pose_list, draw=True, style='-rx'):
        if len(pose_list) == 0:
            print('pose list is empty, skipping')
            return

        se3_init = pose_list[0]
        points_to_be_graphed = np.matmul(se3_init, self.point_pair)[0:3, :]

        for i in range(1, len(pose_list)):

            se3 = pose_list[i]

            points_transformed = np.matmul(se3, self.point_pair)[0:3, :]
            # identity gets transformed twice
            points_to_be_graphed = np.append(points_to_be_graphed,
                                             points_transformed,
                                             axis=1)

        if self.plot_trajectory:
            Plot3D.plot_array_lines(points_to_be_graphed,
                                    self.se3_graph,
                                    clear=False,
                                    draw=draw)

        Plot3D.plot_translation_component(0,
                                          pose_list,
                                          self.x_graph,
                                          style=style,
                                          clear=False,
                                          draw=draw)
        Plot3D.plot_translation_component(1,
                                          pose_list,
                                          self.y_graph,
                                          style=style,
                                          clear=False,
                                          draw=draw)
        Plot3D.plot_translation_component(2,
                                          pose_list,
                                          self.z_graph,
                                          style=style,
                                          clear=False,
                                          draw=draw)
        if self.plot_rmse:
            Plot3D.plot_rmse(self.ground_truth_list,
                             pose_list,
                             self.rmse_graph,
                             clear=False,
                             draw=draw,
                             offset=1)
示例#3
0
    def visualize_ground_truth(self, clear=True, draw=False):
        if len(self.ground_truth_list) > 0:
            gt_init = self.ground_truth_list[0]
            points_gt_to_be_graphed = np.matmul(gt_init,
                                                self.point_pair)[0:3, :]

            for i in range(1, len(self.ground_truth_list)):
                se3 = self.ground_truth_list[i]
                points_transformed = np.matmul(se3, self.point_pair)[0:3, :]
                # identity gets transformed twice
                points_gt_to_be_graphed = np.append(points_gt_to_be_graphed,
                                                    points_transformed,
                                                    axis=1)

            if self.plot_trajectory:
                Plot3D.plot_array_lines(points_gt_to_be_graphed,
                                        self.se3_graph,
                                        '-go',
                                        clear=clear,
                                        draw=False)

            Plot3D.plot_translation_component(0,
                                              self.ground_truth_list,
                                              self.x_graph,
                                              style='-gx',
                                              clear=False,
                                              draw=draw)
            Plot3D.plot_translation_component(1,
                                              self.ground_truth_list,
                                              self.y_graph,
                                              style='-gx',
                                              clear=False,
                                              draw=draw)
            Plot3D.plot_translation_component(2,
                                              self.ground_truth_list,
                                              self.z_graph,
                                              style='-gx',
                                              clear=False,
                                              draw=draw)
示例#4
0
 def show(self):
     Plot3D.show()
示例#5
0
dt = 1.0
pose = Pose.Pose()
steering_command_straight = SteeringCommand.SteeringCommands(1.0, 0.0)

ackermann_motion = Ackermann.Ackermann()

new_motion_delta = ackermann_motion.ackermann_dead_reckoning_delta(steering_command_straight)
pose.apply_motion(new_motion_delta,dt)

#TODO investigate which theta to use
# this might actually be better since we are interested in the uncertainty only in this timestep
theta = new_motion_delta.delta_theta
# traditional uses accumulated theta
#theta = pose.theta

motion_cov_small = ackermann_motion.covariance_dead_reckoning(steering_command_straight,theta,dt)

se3 = SE3.generate_se3_from_motion_delta(new_motion_delta)
origin_transformed = np.matmul(se3, origin)

points = np.append(origin, origin_transformed, axis=1)
points_xyz = points[0:3,:]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Plot3D.plot_array_lines(points_xyz, ax)


示例#6
0
 def legend(self, handles, anchor):
     Plot3D.legend(handles, anchor)
示例#7
0
pose.apply_motion(new_motion_delta,dt)

#TODO investigate which theta to use
# this might actually be better since we are interested in the uncertainty only in this timestep
#theta = new_motion_delta.delta_theta
# traditional uses accumulated theta
theta = pose.theta

motion_cov_small = ackermann_motion.covariance_dead_reckoning(steering_command_straight,theta,dt)

se3 = SE3.generate_se3_from_motion_delta(new_motion_delta)
origin_transformed = np.matmul(se3, origin)

w,v = Utils.covariance_eigen_decomp(motion_cov_small)
z_factor, x_factor = Ackermann.get_standard_deviation_factors_for_projection(w)

change_of_basis = np.identity(4,dtype=Utils.matrix_data_type)
#change_of_basis = SE3.rotation_around_x(-math.pi/2)

# testing inverse
cov_inv = np.linalg.inv(motion_cov_small)
t = np.matmul(cov_inv,motion_cov_small)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Plot3D.plot_wireframe_ellipsoid(1,1,1,ax,label_axes=True, clear=True,draw=False)
Plot3D.plot_wireframe_ellipsoid(0.1, [(x_factor,z_factor)], [change_of_basis], ax, label_axes=True, clear=False,draw=True)


示例#8
0
def solve_photometric(frame_reference,
                      frame_target,
                      max_its,
                      eps,
                      alpha_step,
                      use_ndc=False,
                      debug=False):
    # init
    # array for twist values x, y, z, roll, pitch, yaw
    t_est = np.array([0, 0, 0], dtype=matrix_data_type).reshape((3, 1))
    #R_est = np.array([[0.0, -1.0, 0],
    #                  [1.0, 0.0, 0],
    #                  [0, 0, 1]], dtype=matrix_data_type)
    R_est = np.identity(3, dtype=matrix_data_type)
    I_3 = np.identity(3, dtype=matrix_data_type)

    (height, width) = frame_target.pixel_image.shape
    N = height * width
    position_vector_size = 3
    twist_size = 6
    stacked_obs_size = position_vector_size * N
    homogeneous_se3_padding = Utils.homogenous_for_SE3()
    # Step Factor
    #alpha = 0.125
    Gradient_step_manager = GradientStepManager.GradientStepManager(
        alpha_start=alpha_step,
        alpha_min=-0.7,
        alpha_step=-0.01,
        alpha_change_rate=0,
        gradient_monitoring_window_start=3,
        gradient_monitoring_window_size=0)
    v_mean = -10000
    v_mean_abs = -10000
    it = -1
    std = math.sqrt(0.4)
    image_range_offset = 10
    #depth_factor = 1.0
    #depth_factor = 1000 # 0.001 # ZR300

    SE_3_est = np.append(np.append(R_est, t_est, axis=1),
                         Utils.homogenous_for_SE3(),
                         axis=0)
    SE_3_est_orig = np.append(np.append(R_est, t_est, axis=1),
                              Utils.homogenous_for_SE3(),
                              axis=0)
    SE_3_est_last_valid = np.append(np.append(R_est, t_est, axis=1),
                                    Utils.homogenous_for_SE3(),
                                    axis=0)

    generator_x = Lie.generator_x_3_4()
    generator_y = Lie.generator_y_3_4()
    generator_z = Lie.generator_z_3_4()
    generator_roll = Lie.generator_roll_3_4()
    generator_pitch = Lie.generator_pitch_3_4()
    generator_yaw = Lie.generator_yaw_3_4()

    X_back_projection = np.ones((4, N), Utils.matrix_data_type)
    X_back_projection_last_valid = np.ones((4, N), Utils.matrix_data_type)
    valid_measurements_reference = np.full(N, False)
    valid_measurements_last = np.full(N, False)
    valid_measurements_target = np.full(N, False)
    valid_measurements = valid_measurements_reference

    # Precompute back projection of pixels
    GaussNewtonRoutines.back_project_image(width, height, image_range_offset,
                                           frame_reference.camera,
                                           frame_reference.pixel_depth,
                                           X_back_projection,
                                           valid_measurements, use_ndc)

    if debug:
        Plot3D.save_projection_of_back_projected(height, width,
                                                 frame_reference,
                                                 X_back_projection)

    # Precompute the Jacobian of SE3 around the identity
    J_lie = JacobianGenerator.get_jacobians_lie(generator_x,
                                                generator_y,
                                                generator_z,
                                                generator_yaw,
                                                generator_pitch,
                                                generator_roll,
                                                X_back_projection,
                                                N,
                                                stacked_obs_size,
                                                coefficient=2.0)

    # Precompute the Jacobian of the projection function
    J_pi = JacobianGenerator.get_jacobian_camera_model(
        frame_reference.camera.intrinsic, X_back_projection)

    # count the number of true
    #valid_measurements_total = np.logical_and(valid_measurements_reference,valid_measurements_target)

    #number_of_valid_reference = np.sum(valid_measurements_reference)
    #number_of_valid_total = np.sum(valid_measurements_total)
    #number_of_valid_measurements = number_of_valid_reference

    for it in range(0, max_its, 1):
        start = time.time()
        # accumulators
        #TODO: investigate preallocate and clear in a for loop
        J_v = np.zeros((twist_size, 1))
        normal_matrix = np.zeros((twist_size, twist_size))

        # Warp with the current SE3 estimate
        Y_est = np.matmul(SE_3_est, X_back_projection)
        v = np.zeros((N, 1), dtype=matrix_data_type, order='F')

        target_index_projections = frame_target.camera.apply_perspective_pipeline(
            Y_est)

        v_sum = GaussNewtonRoutines.compute_residual(
            width, height, target_index_projections, valid_measurements,
            frame_target.pixel_image, frame_reference.pixel_image, v,
            image_range_offset)

        number_of_valid_measurements = np.sum(valid_measurements_reference)

        Gradient_step_manager.save_previous_mean_error(v_mean_abs, it)

        v_mean = v_sum / number_of_valid_measurements
        valid_pixel_ratio = number_of_valid_measurements / N
        #v_mean_abs = np.abs(v_mean)
        #v_mean_abs = v_mean

        # TODO put this in gradient step manager
        #if valid_pixel_ratio< 0.8:
        #    print('Too many pixels are marked invalid')
        #    Gradient_step_manager.current_alpha+=0.1
        #    SE_3_est = SE_3_est_last_valid
        #    valid_measurements = valid_measurements_last
        #else:
        #    SE_3_est_last_valid = SE_3_est
        #    valid_measurements_last = valid_measurements

        Gradient_step_manager.track_gradient(v_mean_abs, it)

        if v_mean < eps:
            print('done, mean error:', v_mean)
            break

        Gradient_step_manager.analyze_gradient_history(it)
        #Gradient_step_manager.analyze_gradient_history_instantly(v_mean_abs)

        # See Kerl et al. ensures error decreases ( For pyramid levels )
        #if(v_mean > Gradient_step_manager.last_error_mean_abs):
        #continue

        GaussNewtonRoutines.gauss_newton_step(width, height,
                                              valid_measurements, J_pi, J_lie,
                                              frame_target.grad_x,
                                              frame_target.grad_y, v, J_v,
                                              normal_matrix,
                                              image_range_offset)

        # TODO: Investigate faster inversion with QR
        try:
            pseudo_inv = linalg.inv(normal_matrix)
            #(Q,R) = linalg.qr(normal_matrix)
            #Q_t = np.transpose(Q)
            #R_inv = linalg.inv(R)
            #pseudo_inv = np.multiply(R_inv,Q_t)
        except:
            print('Cant invert')
            return SE_3_est

        w = np.matmul(pseudo_inv, J_v)
        # Apply Step Factor
        w = Gradient_step_manager.current_alpha * w

        w_transpose = np.transpose(w)
        w_x = Utils.skew_symmetric(w[3], w[4], w[5])
        w_x_squared = np.matmul(w_x, w_x)

        # closed form solution for exponential map
        theta = math.sqrt(np.matmul(w_transpose, w))
        theta_sqred = math.pow(theta, 2)
        # TODO use Taylor Expansion when theta_sqred is small
        try:
            A = math.sin(theta) / theta
            B = (1 - math.cos(theta)) / theta_sqred
            C = (1 - A) / theta_sqred
        except:
            print('bad theta')
            return SE_3_est

        u = np.array([w[0], w[1], w[2]]).reshape((3, 1))

        R_new = I_3 + np.multiply(A, w_x) + np.multiply(B, w_x_squared)
        V = I_3 + np.multiply(B, w_x) + np.multiply(C, w_x_squared)

        t_est += +np.matmul(V, u)
        R_est = np.matmul(R_new, R_est)

        SE_3_est = np.append(np.append(R_est, t_est, axis=1),
                             homogeneous_se3_padding,
                             axis=0)
        end = time.time()
        print('mean error:', v_mean, 'iteration: ', it, 'valid pixel ratio: ',
              valid_pixel_ratio, 'runtime: ', end - start)

    return SE_3_est
示例#9
0
import Numerics.Generator as Generator
import Visualization.Plot3D as Plot3D
import numpy as np
import Numerics.Utils as NumUtils
import VisualOdometry.Solver as Solver
from math import pi

N = 100
(X, Y, Z) = Generator.generate_3d_plane(1, 1, -10, N, 4)
H = np.repeat(1, N)

points = np.transpose(
    np.array(list(map(lambda x: list(x), list(zip(X, Y, Z, H))))))

SE3 = Generator.generate_random_se3(-10, 10, 4, pi / 2, 0, pi / 2)

rotated_points_gt = np.matmul(SE3, points)

(X_gt, Y_gt, Z_gt) = list(NumUtils.points_into_components(rotated_points_gt))

SE3_est = Solver.solve_SE3(points, rotated_points_gt, 20000, 0.01)

rotated_points_est = np.matmul(SE3_est, points)

(X_est, Y_est,
 Z_est) = list(NumUtils.points_into_components(rotated_points_est))

Plot3D.scatter_plot([(X, Y, Z), (X_gt, Y_gt, Z_gt), (X_est, Y_est, Z_est)],
                    ['original', 'ground truth', 'estimate'])
示例#10
0
scene = Scene.Scene(image_width, image_height, spheres, camera)

scene.render()

frame_buffer_image = ImageProcessing.normalize_to_image_space(
    scene.frame_buffer)
depth_buffer_image = scene.depth_buffer

cv2.imwrite("framebuffer.png", frame_buffer_image)
cv2.imwrite("depthbuffer.png", depth_buffer_image)

###############

scene_translated = Scene.Scene(image_width, image_height, spheres,
                               camera_translated)

scene_translated.render()

frame_buffer_image = ImageProcessing.normalize_to_image_space(
    scene_translated.frame_buffer)
depth_buffer_image = scene_translated.depth_buffer

cv2.imwrite("framebuffer_translated.png", frame_buffer_image)
cv2.imwrite("depthbuffer_translated.png", depth_buffer_image)

################

Plot3D.scatter_plot_sub([(X_orig, Y_orig, Z_orig)],
                        [(X_persp, Y_persp, Z_persp)], ['original'],
                        ['projected'])
示例#11
0
import Numerics.Generator as Generator
import Visualization.Plot3D as Plot3D

(X, Y, Z) = Generator.generate_3d_plane(1, 1, 0, 20, 4)

Plot3D.scatter_plot(X, Y, Z)
import Numerics.Generator as Generator
import Visualization.Plot3D as Plot3D
import numpy as np
import Numerics.Utils as NumUtils

(X, Y, Z) = Generator.generate_3d_plane(1, 1, -30, 20, 4)
H = np.repeat(1, 20)

points = np.transpose(
    np.array(list(map(lambda x: list(x), list(zip(X, Y, Z, H))))))

SE3 = Generator.generate_random_se3(-1, 1, 4)

rotated_points = np.matmul(SE3, points)

(X_new, Y_new, Z_new) = list(NumUtils.points_into_components(rotated_points))

#Plot3D.scatter_plot(X_new,Y_new,Z_new)
Plot3D.scatter_plot([(X, Y, Z), (X_new, Y_new, Z_new)],
                    ['original', 'perturbed'])
示例#13
0
import matplotlib.pyplot as plt
from Visualization import Plot3D
import numpy as np

id = np.identity(3)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')





#Plot3D.plot_wireframe_ellipsoid(1,1,1,id,ax,label_axes=True, clear=True,draw=False)
Plot3D.plot_wireframe_ellipsoid(2,0.1,1, id,ax,label_axes=True, clear=False,draw=True)



示例#14
0
motion_delta = ackermann_motion.pose_delta_list[0]
se3 = SE3.generate_se3_from_motion_delta(motion_delta)
origin_transformed = np.matmul(se3, origin)
origin_transformed_2 = np.matmul(se3, origin_transformed)

points = np.append(np.append(origin, origin_transformed, axis=1),
                   origin_transformed_2,
                   axis=1)
points_xyz = points[0:3, :]

# testing inverse
#cov_inv = np.linalg.inv(motion_cov_small_1)
#t = np.matmul(cov_inv,motion_cov_small_1)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Plot3D.plot_wireframe_ellipsoid(1,1,1,ax,label_axes=True, clear=True,draw=False)
Plot3D.plot_array_lines(points_xyz, ax, clear=True, draw=False)
Plot3D.plot_wireframe_ellipsoid(0.1,
                                ellipse_factor_list,
                                se3_list,
                                ax,
                                label_axes=True,
                                clear=False,
                                draw=False)
ax.set_xlim(-10, 10)
ax.set_ylim(-1, 1)
ax.set_zlim(-10, 10)
Plot3D.show()
示例#15
0
def solve_photometric(frame_reference,
                      frame_target,
                      threadLock,
                      pose_estimate_list,
                      max_its,
                      eps,
                      alpha_step,
                      gradient_monitoring_window_start,
                      image_range_offset_start,
                      max_depth,
                      twist_prior=None,
                      motion_cov_inv_in=None,
                      use_ndc=False,
                      use_robust=False,
                      track_pose_estimates=False,
                      use_motion_prior=False,
                      ackermann_pose_prior=None,
                      use_ackermann=False,
                      debug=False):

    if track_pose_estimates and (threadLock == None
                                 or pose_estimate_list == None):
        raise RuntimeError(
            'Visualization Flag is set, but no list and lock are supplied')

    # init
    # array for twist values x, y, z, roll, pitch, yaw
    t_est = np.array([0, 0, 0], dtype=matrix_data_type).reshape((3, 1))
    #R_est = np.array([[0.0, -1.0, 0],
    #                  [1.0, 0.0, 0],
    #                  [0, 0, 1]], dtype=matrix_data_type)
    R_est = np.identity(3, dtype=matrix_data_type)
    I_3 = np.identity(3, dtype=matrix_data_type)
    I_4 = np.identity(4, dtype=matrix_data_type)
    I_6 = np.identity(6, dtype=matrix_data_type)
    zero_cov = np.zeros((6, 6), dtype=matrix_data_type)
    #SE3_best = np.identity(4,dtype=matrix_data_type)
    (height, width) = frame_target.pixel_image.shape
    N = height * width
    position_vector_size = 3
    twist_size = 6
    stacked_obs_size = position_vector_size * N
    homogeneous_se3_padding = Utils.homogenous_for_SE3()
    variance = -1
    v_mean = maxsize
    image_range_offset = image_range_offset_start
    degrees_of_freedom = 5.0  # empirically derived: see paper
    normal_matrix_ret = np.identity(6, dtype=Utils.matrix_data_type)
    motion_cov_inv = motion_cov_inv_in
    #motion_cov_inv = np.linalg.inv(motion_cov_inv_in)
    w = np.zeros((twist_size, 1), dtype=Utils.matrix_data_type)
    w_empty = np.zeros((twist_size, 1), dtype=Utils.matrix_data_type)
    w_prev = np.zeros((twist_size, 1), dtype=Utils.matrix_data_type)
    w_acc = np.zeros((twist_size, 1), dtype=Utils.matrix_data_type)
    v_id = np.zeros((N, 1), dtype=matrix_data_type, order='F')
    pseudo_inv = np.identity(twist_size, dtype=matrix_data_type)
    not_better = False
    valid_pixel_ratio = 1.0
    motion_cov_inv_norm = Utils.norm_covariance_row(motion_cov_inv_in)

    fx = frame_reference.camera.intrinsic.extract_fx()
    fy = frame_reference.camera.intrinsic.extract_fy()

    depth_factor = np.sign(fx)
    #depth_factor = -np.sign(fx)

    Gradient_step_manager = GradientStepManager.GradientStepManager(
        alpha_start=alpha_step,
        alpha_min=-0.7,
        alpha_step=-0.01,
        alpha_change_rate=0,
        gradient_monitoring_window_start=gradient_monitoring_window_start,
        gradient_monitoring_window_size=0)

    SE_3_est = np.append(np.append(R_est, t_est, axis=1),
                         Utils.homogenous_for_SE3(),
                         axis=0)
    SE_3_prev = np.append(np.append(R_est, t_est, axis=1),
                          Utils.homogenous_for_SE3(),
                          axis=0)
    #SE_3_est_orig = np.append(np.append(R_est, t_est, axis=1), Utils.homogenous_for_SE3(), axis=0)
    #SE_3_est_last_valid = np.append(np.append(R_est, t_est, axis=1), Utils.homogenous_for_SE3(), axis=0)

    generator_x = Lie.generator_x_3_4()
    #generator_x = Lie.generator_x_3_4_neg()
    generator_y = Lie.generator_y_3_4()
    #generator_y = Lie.generator_y_3_4_neg()
    #generator_z = Lie.generator_z_3_4()
    generator_z = Lie.generator_z_3_4_neg()

    # Depth factor of -1.0 leads to inverted roll and pitch when displaying
    # Why?: Generator defines the direction of increase (My thoughts)
    generator_roll = Lie.generator_roll_3_4()
    #generator_roll = Lie.generator_roll_3_4_neg()
    #generator_pitch = Lie.generator_pitch_3_4()
    generator_pitch = Lie.generator_pitch_3_4_neg()
    generator_yaw = Lie.generator_yaw_3_4()
    #generator_yaw = Lie.generator_yaw_3_4_neg()

    X_back_projection = depth_factor * np.ones((4, N), Utils.matrix_data_type)
    X_back_projection[3, :] = 1.0
    #X_back_projection_last_valid = np.ones((4, N), Utils.matrix_data_type)
    valid_measurements_reference = np.full(N, False)
    valid_measurements_target = np.full(N, False)
    #valid_measurements_last = np.full(N,False)
    #valid_measurements_target = np.full(N,False)
    valid_measurements = valid_measurements_reference
    number_of_valid_measurements = N
    #v = np.zeros((N, 1), dtype=matrix_data_type, order='F')

    # Precompute back projection of pixels
    GaussNewtonRoutines.back_project_image(
        width, height, image_range_offset, frame_reference.camera,
        frame_reference.pixel_depth, frame_target.pixel_depth,
        X_back_projection, valid_measurements, valid_measurements_target,
        use_ndc, depth_factor, max_depth)

    count = np.sum(valid_measurements)
    count_target = np.sum(valid_measurements_target)

    z_rot = SE3.makeS03(0, 0, math.pi)
    se3_rot = np.identity(4, dtype=matrix_data_type)
    se3_rot[0:3, 0:3] = z_rot
    #X_back_projection = np.matmul(se3_rot,X_back_projection)

    if debug:
        Plot3D.save_projection_of_back_projected(height, width,
                                                 frame_reference,
                                                 X_back_projection)

    # Precompute the Jacobian of SE3 around the identity
    J_lie = JacobianGenerator.get_jacobians_lie(generator_x,
                                                generator_y,
                                                generator_z,
                                                generator_yaw,
                                                generator_pitch,
                                                generator_roll,
                                                X_back_projection,
                                                N,
                                                stacked_obs_size,
                                                coefficient=1.0)

    # Precompute the Jacobian of the projection function
    J_pi = JacobianGenerator.get_jacobian_camera_model(
        frame_reference.camera.intrinsic, X_back_projection)

    # count the number of true
    #valid_measurements_total = np.logical_and(valid_measurements_reference,valid_measurements_target)

    #number_of_valid_reference = np.sum(valid_measurements_reference)
    #number_of_valid_total = np.sum(valid_measurements_total)
    #number_of_valid_measurements = number_of_valid_reference

    #target_index_projections_id = frame_target.camera.apply_perspective_pipeline(I_4)

    target_index_projections = frame_target.camera.apply_perspective_pipeline(
        X_back_projection, use_ndc, width, height)

    GaussNewtonRoutines.compute_residual(
        width, height, target_index_projections, valid_measurements,
        valid_measurements_target, frame_target.pixel_image,
        frame_reference.pixel_image, frame_target.pixel_depth,
        frame_reference.pixel_depth, v_id, image_range_offset)

    v = np.copy(v_id)
    W = np.ones((1, N), dtype=matrix_data_type, order='F')

    for it in range(0, max_its, 1):
        start = time.time()
        # accumulators
        #TODO: investigate preallocate and clear in a for loop
        g = np.zeros((twist_size, 1))
        normal_matrix = np.identity(twist_size, dtype=matrix_data_type)

        # TODO investigate performance impact
        if track_pose_estimates:
            threadLock.acquire()
            pose_estimate_list.append(SE_3_est)
            threadLock.release()

        #v_diff = math.fabs(Gradient_step_manager.last_error_mean_abs - v_mean)
        #v_diff = Gradient_step_manager.last_error_mean_abs - v_mean

        #Gradient_step_manager.track_gradient(v_mean,it)

        # TODO investigate absolute error threshold aswel?
        #if ((v_diff <= eps)) and Gradient_step_manager.check_iteration(it) :
        #    print('done, mean error:', v_mean, 'diff: ', v_diff, 'pixel ratio:', valid_pixel_ratio)
        #    break

        # no if statement means solver 2
        #if v_mean <= Gradient_step_manager.last_error_mean_abs:
        not_better = False
        prior_empty = False
        if twist_prior[0] == 0 and twist_prior[1] == 0 and twist_prior[2] == 0 and twist_prior[3] == 0 and \
                twist_prior[4] == 0 and twist_prior[5] == 0:
            prior_empty = True

        if use_motion_prior:
            converged = GaussNewtonRoutines.gauss_newton_step_motion_prior(
                width, height, valid_measurements, valid_measurements_target,
                W, J_pi, J_lie, frame_target.grad_x, frame_target.grad_y, v, g,
                normal_matrix, motion_cov_inv, twist_prior, w,
                image_range_offset)
        else:
            converged = GaussNewtonRoutines.gauss_newton_step(
                width, height, valid_measurements, valid_measurements_target,
                W, J_pi, J_lie, frame_target.grad_x, frame_target.grad_y, v, g,
                normal_matrix, image_range_offset)
        normal_matrix_ret = normal_matrix

        #try:
        #    pseudo_inv = linalg.inv(normal_matrix)
        #except:
        #    print('Cant invert')
        #    return SE_3_est

        #w_new = np.matmul(pseudo_inv, g)

        try:
            w_new = linalg.solve(normal_matrix, g)
        except:
            print('Cant solve')
            return SE_3_est

        # initial step with empty motion prior seems to be quite large
        #if use_motion_prior and prior_empty:
        #    w_new = np.multiply(Gradient_step_manager.current_alpha/2.0, w_new)
        #else:
        w_new = np.multiply(Gradient_step_manager.current_alpha, w_new)

        # For using ackermann motion
        if use_ackermann:
            # V1
            # inc = ackermann_pose_prior - w
            # w_new += np.matmul(motion_cov_inv,inc)
            # w_new += inc

            # V2
            #factor = 0.1*Gradient_step_manager.current_alpha
            factor = 0.1
            #factor = math.pow(Gradient_step_manager.current_alpha,it)
            # ack_prior = np.multiply(Gradient_step_manager.current_alpha,ackermann_pose_prior)
            ack_prior = ackermann_pose_prior

            w_new += Lie.lie_ackermann_correction(factor, motion_cov_inv,
                                                  ack_prior, w, twist_size)

        #else:
        #    not_better = True
        #    w_new = w_empty

        R_cur, t_cur = Lie.exp(w, twist_size)
        R_new, t_new = Lie.exp(w_new, twist_size)

        # C_new . C_cur
        #t_est = np.add(np.matmul(R_new, t_cur), t_new)
        #R_est = np.matmul(R_new, R_cur)

        # C_Cur . C_new
        t_est = np.add(np.matmul(R_cur, t_new), t_cur)
        R_est = np.matmul(R_cur, R_new)

        w = Lie.ln(R_est, t_est, twist_size)

        #SE_3_current = np.append(np.append(R_cur, t_cur, axis=1), homogeneous_se3_padding, axis=0)
        SE_3_est = np.append(np.append(R_est, t_est, axis=1),
                             homogeneous_se3_padding,
                             axis=0)

        #debug_list  = [i for i, x in enumerate(valid_measurements) if x]

        Y_est = np.matmul(SE_3_est, X_back_projection)

        target_index_projections = frame_target.camera.apply_perspective_pipeline(
            Y_est, use_ndc, width, height)
        #target_index_projections[2,:] -= depth_factor*1

        v = GaussNewtonRoutines.compute_residual(
            width, height, target_index_projections, valid_measurements,
            valid_measurements_target, frame_target.pixel_image,
            frame_reference.pixel_image, frame_target.pixel_depth,
            frame_reference.pixel_depth, v, image_range_offset)

        number_of_valid_measurements = np.sum(valid_measurements)
        valid_pixel_ratio = number_of_valid_measurements / N

        if number_of_valid_measurements <= 0 and Gradient_step_manager.check_iteration(
                it):
            print('pixel ratio break')
            print('done, mean error:', v_mean, 'diff: ', v_diff,
                  'pixel ratio:', valid_pixel_ratio)
            #SE_3_est = SE3_best
            break

        if use_robust:
            variance = GaussNewtonRoutines.compute_t_dist_variance(
                v,
                degrees_of_freedom,
                N,
                valid_measurements,
                valid_measurements_target,
                number_of_valid_measurements,
                variance_min=1000,
                eps=0.001)
            if variance > 0.0:
                # clear old weights
                for i in range(0, N):
                    W[0, i] = 1
                GaussNewtonRoutines.generate_weight_matrix(
                    W, v, variance, degrees_of_freedom, N)

        v_weighted = np.copy(v)
        GaussNewtonRoutines.multiply_v_by_diagonal_matrix(
            W, v_weighted, N, valid_measurements)

        v_sum = np.matmul(np.transpose(v), v_weighted)[0][0]

        end = time.time()

        #if v_mean < Gradient_step_manager.last_error_mean_abs:
        #    SE3_best = np.copy(SE_3_est)
        #if not not_better: # solver 6
        Gradient_step_manager.save_previous_mean_error(v_mean)

        if number_of_valid_measurements > 0:
            v_mean = v_sum / number_of_valid_measurements
        else:
            v_mean = maxsize

        v_diff = math.fabs(Gradient_step_manager.last_error_mean_abs - v_mean)
        print('mean error:', v_mean, 'error diff: ', v_diff, 'iteration: ', it,
              'valid pixel ratio: ', valid_pixel_ratio, 'runtime: ',
              end - start, 'variance: ', variance)
        #v_diff = Gradient_step_manager.last_error_mean_abs - v_mean

        #Gradient_step_manager.track_gradient(v_mean,it)

        # TODO investigate absolute error threshold aswel?
        if ((v_diff <= eps)) and Gradient_step_manager.check_iteration(it):
            print('done, mean error:', v_mean, 'diff: ', v_diff,
                  'pixel ratio:', valid_pixel_ratio)
            break

    motion_cov_inv = normal_matrix_ret

    return SE_3_est, w, motion_cov_inv