Exemplo n.º 1
0
def main():
    """Visualizes three cars in a merging scenario."""
    from experiments.merging import ThreeLaneTestCar

    from driver.car import FixedVelocityCar
    from driver.world import ThreeLaneCarWorld

    world = ThreeLaneCarWorld()
    our_car = ThreeLaneTestCar(
        world,
        np.array([0, -0.5, 0.8, np.pi / 2]),
        horizon=5,
        weights=np.array([0.1, 0.0, 0.0, -10.0, -1.0, -10, -10]),
        debug=True,
    )
    other_car_1 = FixedVelocityCar(
        world,
        np.array([0.1, -0.7, 0.8, np.pi / 2]),
        horizon=5,
        color="gray",
        opacity=1.0,
        debug=True,
    )
    other_car_2 = FixedVelocityCar(
        world,
        np.array([0.1, -0.2, 0.8, np.pi / 2]),
        horizon=5,
        color="gray",
        opacity=1.0,
        debug=True,
    )
    world.add_cars([our_car, other_car_1, other_car_2])
    world.reset()

    # vis.render(heatmap_show=False)
    for i in range(5):
        world.step()
        print(i)
        # vis.render(heatmap_show=False)
    print([our_car.past_traj, other_car_1.past_traj, other_car_2.past_traj])
    frames = [world.render(mode="rgb_array")]

    import contextlib

    with contextlib.redirect_stdout(None):  # disable the pygame import print
        from moviepy.editor import ImageSequenceClip

    clip = ImageSequenceClip(frames, fps=int(1 / world.dt))
    clip.speedx(0.5).write_gif("test_traj.gif", program="ffmpeg")
Exemplo n.º 2
0
def execute_experiment(exp_name,
                       world,
                       time_steps,
                       experiment_args,
                       seed=None,
                       ms_car_index=0):
    '''
    Runs experiment.

    Tracks reward per time step, which models are being used,
    and the computational time for planning.

    Displays and saves relevant time series information at end.

    Saves GIF of experiment if requested.

    Args:
        world: Car World Object 
        time_steps: number of time steps to execute experiment for.
        ms_car_index: index of model switching car (default 0)
        save_gif: True iff you would like to save the simulation as a GIF.
    '''

    #Initialize planners if not yet done
    for car in world.cars:
        if (isinstance(car, PlannerCar) and car.planner is None):
            car.initialize_planner()

    if (world.verbose):
        print(f"Executing {exp_name} for {time_steps} time steps...")

    #Model Switching Car
    ms_car = world.cars[ms_car_index]

    world.reset(seed)
    if (world.verbose):
        world.render()

    if (experiment_args.save_gif):
        frames = []
        frames.append(world.render("rgb_array"))

    #Reward accrued at each time step.
    reward_ts = []

    for t in range(time_steps):
        '''
        Step world and get controls all cars
        took and the new state of the world.
        '''
        _, control, new_state = world.step()
        if (world.verbose):
            world.render()

        if (experiment_args.save_gif):
            frames.append(world.render("rgb_array"))

        ms_control = control[ms_car_index]
        #Reward for the model switching car.
        rew = ms_car.reward_fn(tf.stack(new_state), ms_control).numpy()
        reward_ts.append(rew)

        #Computational Time Breakdown
        if (world.verbose):
            ct_breakdown = ms_car.planner.avg_comp_time_breakdown()
            print(f"T: {t + 1}; R: {rew:.2f}; CT: {ct_breakdown}")

    if (experiment_args.num_run == 1):
        model_ts = ms_car.planner.models_used

        #Average Computational Time Time Series
        avg_step_times = ms_car.planner.get_avg_comp_times()

        print()
        #Gather reward and computation time information
        #Single Computational Time Time Series
        step_times = ms_car.planner.get_comp_times()

        #Display reward and computation time graphs
        display_rewards(reward_ts, model_ts)
        display_computational_times(step_times['overall'],
                                    avg_step_times['overall'])

    if (experiment_args.save_gif):
        clip = ImageSequenceClip(frames, fps=int(1 / world.dt))
        clip.speedx(0.5).write_gif(f"{exp_name}.gif", program="ffmpeg")

    #return np.mean(reward_ts), avg_step_times['overall'][-1], model_usage
    return reward_ts
Exemplo n.º 3
0
def createGif(filename):
    """Create a gif using initial and edited images"""
    clip = ImageSequenceClip([filename, 'images/editedImage.png'], fps=1350)
    clip.speedx(0.5).write_gif('images/editedImage.gif')