Example #1
0
def test_cost_function(plot=False):
    # Create parameters
    p = create_params()

    obstacle_map = SBPDMap(p.obstacle_map_params)
    obstacle_occupancy_grid = obstacle_map.create_occupancy_grid_for_map()
    map_size_2 = obstacle_occupancy_grid.shape[::-1]

    # Define a goal position and compute the corresponding fmm map
    goal_pos_n2 = np.array([[20., 16.5]])
    fmm_map = FmmMap.create_fmm_map_based_on_goal_position(goal_positions_n2=goal_pos_n2,
                                                           map_size_2=map_size_2,
                                                           dx=0.05,
                                                           map_origin_2=[0., 0.],
                                                           mask_grid_mn=obstacle_occupancy_grid)

    # Define the cost function
    objective_function = ObjectiveFunction(p.objective_fn_params)
    objective_function.add_objective(ObstacleAvoidance(params=p.avoid_obstacle_objective, obstacle_map=obstacle_map))
    objective_function.add_objective(GoalDistance(params=p.goal_distance_objective, fmm_map=fmm_map))
    objective_function.add_objective(AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map))

    # Define each objective separately
    objective1 = ObstacleAvoidance(params=p.avoid_obstacle_objective, obstacle_map=obstacle_map)
    objective2 = GoalDistance(params=p.goal_distance_objective, fmm_map=fmm_map)
    objective3 = AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map)

    # Define a set of positions and evaluate objective
    pos_nk2 = tf.constant([[[8., 16.], [8., 12.5], [18., 16.5]]], dtype=tf.float32)
    trajectory = Trajectory(dt=0.1, n=1, k=3, position_nk2=pos_nk2)

    # Compute the objective function
    values_by_objective = objective_function.evaluate_function_by_objective(trajectory)
    overall_objective = objective_function.evaluate_function(trajectory)

    # Expected objective values
    expected_objective1 = objective1.evaluate_objective(trajectory)
    expected_objective2 = objective2.evaluate_objective(trajectory)
    expected_objective3 = objective3.evaluate_objective(trajectory)
    expected_overall_objective = tf.reduce_mean(expected_objective1 + expected_objective2 + expected_objective3, axis=1)

    # assert len(values_by_objective) == 3
    # assert values_by_objective[0][1].shape == (1, 3)
    # assert overall_objective.shape == (1,)
    # assert np.allclose(overall_objective.numpy(), expected_overall_objective.numpy(), atol=1e-2)


    # Optionally visualize the traversable and the points on which
    # we compute the objective function
    if plot:
        import matplotlib.pyplot as plt

        fig = plt.figure()
        ax = fig.add_subplot(111)
        obstacle_map.render(ax)
        ax.plot(pos_nk2[0, :, 0].numpy(), pos_nk2[0, :, 1].numpy(), 'r.')
        ax.plot(goal_pos_n2[0, 0], goal_pos_n2[0, 1], 'k*')
        fig.savefig('./tmp/test_cost_function.png', bbox_inches='tight', pad_inches=0)
Example #2
0
def test_avoid_obstacle():
    # Create parameters
    p = create_params()

    # Create an SBPD Map
    obstacle_map = SBPDMap(p.obstacle_map_params)

    # Define the objective
    objective = ObstacleAvoidance(params=p.avoid_obstacle_objective,
                                  obstacle_map=obstacle_map)

    # Define a set of positions and evaluate objective
    pos_nk2 = tf.constant([[[8., 16.], [8., 12.5], [18., 16.5]]],
                          dtype=tf.float32)
    trajectory = Trajectory(dt=0.1, n=1, k=3, position_nk2=pos_nk2)

    # Compute the objective
    objective_values_13 = objective.evaluate_objective(trajectory)
    assert objective_values_13.shape == (1, 3)

    # Expected objective values
    distance_map = obstacle_map.fmm_map.fmm_distance_map.voxel_function_mn
    idxs_xy_n2 = pos_nk2[0] / .05
    idxs_yx_n2 = idxs_xy_n2[:, ::-1].numpy().astype(np.int32)
    expected_min_dist_to_obs = np.array([
        distance_map[idxs_yx_n2[0][0], idxs_yx_n2[0][1]],
        distance_map[idxs_yx_n2[1][0], idxs_yx_n2[1][1]],
        distance_map[idxs_yx_n2[2][0], idxs_yx_n2[2][1]]
    ],
                                        dtype=np.float32)

    m0 = p.avoid_obstacle_objective.obstacle_margin0
    m1 = p.avoid_obstacle_objective.obstacle_margin1
    expected_infringement = m1 - expected_min_dist_to_obs
    expected_infringement = np.clip(expected_infringement, a_min=0,
                                    a_max=None)  # ReLU
    expected_infringement /= (m1 - m0)
    expected_objective = 25. * expected_infringement * expected_infringement

    assert np.allclose(objective_values_13.numpy()[0],
                       expected_objective,
                       atol=1e-4)
    assert np.allclose(objective_values_13.numpy()[0], [0., 0., 0.54201907],
                       atol=1e-4)
Example #3
0
 def _init_obj_fn(self, params=None):
     """
     Initialize the objective function given sim params
     """
     if params is None:
         params = self.params
     obstacle_map = self.obstacle_map
     obj_fn = ObjectiveFunction(params.objective_fn_params)
     if not params.avoid_obstacle_objective.empty():
         obj_fn.add_objective(
             ObstacleAvoidance(params=params.avoid_obstacle_objective,
                               obstacle_map=obstacle_map))
     if not params.goal_distance_objective.empty():
         obj_fn.add_objective(
             GoalDistance(params=params.goal_distance_objective,
                          fmm_map=obstacle_map.fmm_map))
     if not params.goal_angle_objective.empty():
         obj_fn.add_objective(
             AngleDistance(params=params.goal_angle_objective,
                           fmm_map=obstacle_map.fmm_map))
     return obj_fn
Example #4
0
    def _init_obj_fn(self):
        """
        Initialize the objective function.
        Use fmm_map = None as this is undefined
        until a goal configuration is specified.
        """
        p = self.params

        obj_fn = ObjectiveFunction(p.objective_fn_params)
        if not p.avoid_obstacle_objective.empty():
            obj_fn.add_objective(ObstacleAvoidance(
                params=p.avoid_obstacle_objective,
                obstacle_map=self.obstacle_map))
        if not p.goal_distance_objective.empty():
            obj_fn.add_objective(GoalDistance(
                params=p.goal_distance_objective,
                fmm_map=None))
        if not p.goal_angle_objective.empty():
            obj_fn.add_objective(AngleDistance(
                params=p.goal_angle_objective,
                fmm_map=None))
        return obj_fn
Example #5
0
    def _init_obj_fn(self):
        """
        Initialize the objective function.
        Use fmm_map = None as this is undefined
        until a goal configuration is specified.
        """
        p = self.params

        obj_fn = ObjectiveFunction(p.objective_fn_params)
        if self.params.cost == 'heuristics':
            if not p.avoid_obstacle_objective.empty():
                obj_fn.add_objective(ObstacleAvoidance(
                    params=p.avoid_obstacle_objective,
                    obstacle_map=self.obstacle_map))
            if not p.goal_angle_objective.empty():
                obj_fn.add_objective(AngleDistance(
                    params=p.goal_angle_objective,
                    fmm_map=None))
            if not p.goal_distance_objective.empty():
                obj_fn.add_objective(GoalDistance(
                    params=p.goal_distance_objective,
                    fmm_map=None))
        elif self.params.cost == 'reachability':
            if not p.avoid_4d_objective.empty():
                obj_fn.add_objective(Avoid4d(
                    params=p.avoid_4d_objective,
                    reachability_map=None))
            if not p.goal_distance_objective.empty():
                obj_fn.add_objective(GoalDistance(
                    params=p.goal_distance_objective,
                    fmm_map=None))
            if not p.reach_avoid_4d_objective.empty():
                obj_fn.add_objective(ReachAvoid4d(
                    params=p.reach_avoid_4d_objective,
                    reachability_map=None))
        return obj_fn
Example #6
0
def test_avoid_obstacle(visualize=False):
    """
    Run a test on handpicked waypoint values that build a trajectory and are used
    to evaluate the computed distance_map and angle_map from the fmm_*_map.voxel_function_mn
    """
    # Create parameters
    p = create_params()

    # Create an SBPD Map
    r, dx_cm, traversible = load_building(p)

    obstacle_map = SBPDMap(p.obstacle_map_params,
                           renderer=0,
                           res=dx_cm,
                           map_trav=traversible)

    # Define the objective
    objective = ObstacleAvoidance(params=p.avoid_obstacle_objective,
                                  obstacle_map=obstacle_map)

    # Define a set of positions and evaluate objective
    pos_nk2 = p.pos_nk2
    trajectory = Trajectory(dt=0.1, n=1, k=3, position_nk2=pos_nk2)

    # Compute the objective
    objective_values_13 = objective.evaluate_objective(trajectory)
    assert objective_values_13.shape == (1, 3)

    # Expected objective values
    distance_map = obstacle_map.fmm_map.fmm_distance_map.voxel_function_mn
    angle_map = obstacle_map.fmm_map.fmm_angle_map.voxel_function_mn

    idxs_xy_n2 = pos_nk2[0] / .05
    idxs_yx_n2 = idxs_xy_n2[:, ::-1].astype(np.int32)
    expected_min_dist_to_obs = np.array([
        distance_map[idxs_yx_n2[0][0], idxs_yx_n2[0][1]],
        distance_map[idxs_yx_n2[1][0], idxs_yx_n2[1][1]],
        distance_map[idxs_yx_n2[2][0], idxs_yx_n2[2][1]]
    ],
                                        dtype=np.float32)

    m0 = p.avoid_obstacle_objective.obstacle_margin0
    m1 = p.avoid_obstacle_objective.obstacle_margin1
    expected_infringement = m1 - expected_min_dist_to_obs
    expected_infringement = np.clip(expected_infringement, a_min=0,
                                    a_max=None)  # ReLU
    expected_infringement /= (m1 - m0)
    expected_objective = 25. * expected_infringement * expected_infringement

    assert np.allclose(objective_values_13[0], expected_objective, atol=1e-4)
    assert np.allclose(objective_values_13[0], p.test_obs_obj_ans, atol=1e-4)
    if visualize:
        """
        create a 1 x 3 (or 1 x 4) image of the obstacle map itself (as a traversible plot), 
        next to its corresponding angle_map, and distance_map. Optionally plotting the trajectory
        """
        fig = plt.figure()
        ax = fig.add_subplot(1, 3, 1)
        obstacle_map.render(ax)
        ax.plot(pos_nk2[0, :, 0], pos_nk2[0, :, 1], 'r.')
        # ax.plot(objective[0, 0], objective[0, 1], 'k*')
        ax.set_title('obstacle map')

        # Plotting the "angle map"
        ax = fig.add_subplot(1, 3, 2)
        ax.imshow(angle_map, origin='lower')
        ax.set_title('angle map')

        # Plotting the "distance map"
        ax = fig.add_subplot(1, 3, 3)
        ax.imshow(distance_map, origin='lower')
        ax.set_title('distance map')

        # Plotting the trajectory
        #ax = fig.add_subplot(1,4,4)
        # trajectory.render(ax)
        # ax.set_title('trajectory')

        fig.savefig('./tests/obstacles/test_obstacle_objective.png',
                    bbox_inches='tight',
                    pad_inches=0)
def test_cost_function(plot=False):
    """
    Creating objective points maually, plotting them in the ObjectiveFunction
    class, and then asserting that combined, their sum adds up to the same
    objective cost as the sum of the individual trajectories
    """
    # Create parameters
    p = create_params()
    r, dx_cm, traversible = load_building(p)

    obstacle_map = SBPDMap(p.obstacle_map_params,
                           renderer=0,
                           res=dx_cm,
                           map_trav=traversible)
    # obstacle_map = SBPDMap(p.obstacle_map_params)
    obstacle_occupancy_grid = obstacle_map.create_occupancy_grid_for_map()
    map_size_2 = obstacle_occupancy_grid.shape[::-1]

    # Define a goal position and compute the corresponding fmm map
    goal_pos_n2 = p.goal_pos_n2
    fmm_map = FmmMap.create_fmm_map_based_on_goal_position(
        goal_positions_n2=goal_pos_n2,
        map_size_2=map_size_2,
        dx=0.05,
        map_origin_2=[0., 0.],
        mask_grid_mn=obstacle_occupancy_grid)
    # Define the cost function
    objective_function = ObjectiveFunction(p.objective_fn_params)
    objective_function.add_objective(
        ObstacleAvoidance(params=p.avoid_obstacle_objective,
                          obstacle_map=obstacle_map))
    objective_function.add_objective(
        GoalDistance(params=p.goal_distance_objective, fmm_map=fmm_map))
    objective_function.add_objective(
        AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map))

    # Define each objective separately
    objective1 = ObstacleAvoidance(params=p.avoid_obstacle_objective,
                                   obstacle_map=obstacle_map)
    objective2 = GoalDistance(params=p.goal_distance_objective,
                              fmm_map=fmm_map)
    objective3 = AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map)

    # Define a set of positions and evaluate objective
    pos_nk2 = p.pos_nk2
    heading_nk2 = np.array([[[np.pi / 2.0], [0.1], [0.1]]], dtype=np.float32)
    trajectory = Trajectory(dt=0.1,
                            n=1,
                            k=3,
                            position_nk2=pos_nk2,
                            heading_nk1=heading_nk2)

    # Compute the objective function
    values_by_objective = objective_function.evaluate_function_by_objective(
        trajectory)
    overall_objective = objective_function.evaluate_function(trajectory)

    # Expected objective values
    expected_objective1 = objective1.evaluate_objective(trajectory)
    expected_objective2 = objective2.evaluate_objective(trajectory)
    expected_objective3 = objective3.evaluate_objective(trajectory)
    # expected_overall_objective = tf.reduce_mean(
    #     expected_objective1 + expected_objective2 + expected_objective3, axis=1)
    expected_overall_objective = np.mean(
        expected_objective1 + expected_objective2 + expected_objective3,
        axis=1)
    assert len(values_by_objective) == 3
    assert values_by_objective[0][1].shape == (1, 3)
    assert overall_objective.shape == (1, )
    # assert np.allclose(overall_objective.numpy(), expected_overall_objective.numpy(), atol=1e-2)
    assert np.allclose(overall_objective,
                       expected_overall_objective,
                       atol=1e-2)

    # Optionally visualize the traversable and the points on which
    # we compute the objective function
    if plot:
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        obstacle_map.render(ax)
        ax.plot(pos_nk2[0, :, 0].numpy(), pos_nk2[0, :, 1].numpy(), 'r.')
        ax.plot(goal_pos_n2[0, 0], goal_pos_n2[0, 1], 'k*')
        fig.savefig('./tests/cost/test_cost_function.png',
                    bbox_inches='tight',
                    pad_inches=0)
def test_personal_cost_function(sim_state: SimState,
                                plot=False,
                                verbose=False):
    """
    Creating objective points maually, plotting them in the ObjectiveFunction
    class, and then asserting that combined, their sum adds up to the same
    objective cost as the sum of the individual trajectories
    """
    # Create parameters
    p = create_params()
    r, dx_cm, traversible = load_building(p)

    obstacle_map = SBPDMap(p.obstacle_map_params,
                           renderer=0,
                           res=dx_cm,
                           map_trav=traversible)
    # obstacle_map = SBPDMap(p.obstacle_map_params)
    obstacle_occupancy_grid = obstacle_map.create_occupancy_grid_for_map()
    map_size_2 = obstacle_occupancy_grid.shape[::-1]

    # Define a goal position and compute the corresponding fmm map
    goal_pos_n2 = np.array([[9., 10]])
    fmm_map = FmmMap.create_fmm_map_based_on_goal_position(
        goal_positions_n2=goal_pos_n2,
        map_size_2=map_size_2,
        dx=0.05,
        map_origin_2=[0., 0.],
        mask_grid_mn=obstacle_occupancy_grid)
    # Define the cost function
    objective_function = ObjectiveFunction(p.objective_fn_params)
    objective_function.add_objective(
        ObstacleAvoidance(params=p.avoid_obstacle_objective,
                          obstacle_map=obstacle_map))
    objective_function.add_objective(
        GoalDistance(params=p.goal_distance_objective, fmm_map=fmm_map))
    objective_function.add_objective(
        AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map))

    # Define each objective separately
    objective1 = ObstacleAvoidance(params=p.avoid_obstacle_objective,
                                   obstacle_map=obstacle_map)
    objective2 = GoalDistance(params=p.goal_distance_objective,
                              fmm_map=fmm_map)
    objective3 = AngleDistance(params=p.goal_angle_objective, fmm_map=fmm_map)

    # Define cost function for personal state
    objectiveP = PersonalSpaceCost(params=p.personal_space_params)

    # Define a set of positions and evaluate objective
    pos_nk2 = np.array([[[8., 12.5], [8., 16.], [18., 16.5]]],
                       dtype=np.float32)
    heading_nk2 = np.array([[[np.pi / 2.0], [0.1], [0.1]]], dtype=np.float32)
    trajectory = Trajectory(dt=0.1,
                            n=1,
                            k=3,
                            position_nk2=pos_nk2,
                            heading_nk1=heading_nk2)

    # Compute the objective function
    values_by_objective = objective_function.evaluate_function_by_objective(
        trajectory)
    overall_objective = objective_function.evaluate_function(trajectory)

    # Expected objective values
    expected_objective1 = objective1.evaluate_objective(trajectory)
    expected_objective2 = objective2.evaluate_objective(trajectory)
    expected_objective3 = objective3.evaluate_objective(trajectory)
    expected_overall_objective = np.mean(
        expected_objective1 + expected_objective2 + expected_objective3,
        axis=1)
    assert len(values_by_objective) == 3
    assert values_by_objective[0][1].shape == (1, 3)
    assert overall_objective.shape == (1, )
    # assert np.allclose(overall_objective.numpy(), expected_overall_objective.numpy(), atol=1e-2)
    assert np.allclose(overall_objective,
                       expected_overall_objective,
                       atol=1e-2)

    # Use sim_state from main
    sim_state_hist = {}
    sim_state_hist[0] = sim_state
    ps_cost = objectiveP.evaluate_objective(trajectory, sim_state_hist)
    if verbose:
        print("Personal space cost ", ps_cost)
        print("Obstacle avoidance cost", expected_objective1)
        print("Goal distance cost", expected_objective2)
        print("Angle distance cost", expected_objective3)

    # Optionally visualize the traversable and the points on which
    # we compute the objective function
    if plot:
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        obstacle_map.render(ax)

        # plot agent start
        ax.plot(pos_nk2[0, :, 0], pos_nk2[0, :, 1], 'r.')
        # plot agent goal
        ax.plot(goal_pos_n2[0, 0], goal_pos_n2[0, 1], 'k*')

        agents = sim_state.get_all_agents()

        for agent_name, agent_vals in agents.items():
            agent_pos3 = agent_vals.get_pos3()  # (x,y,th)
            theta = agent_pos3[2]
            ax.plot(agent_pos3[0], agent_pos3[1], 'g.')

        # plot non ego agents
        fig.savefig('../test_psc_function.png',
                    bbox_inches='tight',
                    pad_inches=0)