Пример #1
0
    def test_num_runs(self):
        # run the experiment for 1 run and collect the last position of all
        # vehicles
        env, _, flow_params = ring_road_exp_setup()
        flow_params['sim'].render = False
        flow_params['env'].horizon = 10
        exp = Experiment(flow_params)
        exp.env = env
        exp.run(num_runs=1)

        vel1 = [exp.env.k.vehicle.get_speed(exp.env.k.vehicle.get_ids())]

        # run the experiment for 2 runs and collect the last position of all
        # vehicles
        env, _, flow_params = ring_road_exp_setup()
        flow_params['sim'].render = False
        flow_params['env'].horizon = 10

        exp = Experiment(flow_params)
        exp.env = env
        exp.run(num_runs=2)

        vel2 = [exp.env.k.vehicle.get_speed(exp.env.k.vehicle.get_ids())]

        # check that the final position is the same in both instances
        np.testing.assert_array_almost_equal(vel1, vel2)
Пример #2
0
    def setUp_failsafe(self, vehicles):
        additional_env_params = {
            "target_velocity": 8,
            "max_accel": 3,
            "max_decel": 3,
            "sort_vehicles": False
        }
        env_params = EnvParams(additional_params=additional_env_params)

        additional_net_params = {
            "length": 100,
            "lanes": 1,
            "speed_limit": 30,
            "resolution": 40
        }
        net_params = NetParams(additional_params=additional_net_params)

        initial_config = InitialConfig(bunching=10)

        # create the environment and scenario classes for a ring road
        env, scenario = ring_road_exp_setup(
            vehicles=vehicles,
            env_params=env_params,
            net_params=net_params,
            initial_config=initial_config)

        # instantiate an experiment class
        self.exp = Experiment(env)
Пример #3
0
    def test_convert_to_csv(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        sim_params = SumoParams(emission_path="{}/".format(dir_path))
        env, scenario = ring_road_exp_setup(sim_params=sim_params)
        exp = Experiment(env)
        exp.run(num_runs=1, num_steps=10, convert_to_csv=True)

        time.sleep(0.1)

        # check that both the emission xml and csv files exist
        self.assertTrue(
            os.path.isfile(dir_path +
                           "/{}-emission.xml".format(scenario.name)))
        self.assertTrue(
            os.path.isfile(dir_path +
                           "/{}-emission.csv".format(scenario.name)))

        time.sleep(0.1)

        # delete the files
        os.remove(
            os.path.expanduser(dir_path +
                               "/{}-emission.xml".format(scenario.name)))
        os.remove(
            os.path.expanduser(dir_path +
                               "/{}-emission.csv".format(scenario.name)))
Пример #4
0
class TestItRuns(unittest.TestCase):
    """
    Tests the set_state function
    """

    def setUp(self):
        vehicles = Vehicles()
        vehicles.add(
            veh_id="idm",
            acceleration_controller=(IDMController, {}),
            routing_controller=(GridRouter, {}),
            sumo_car_following_params=SumoCarFollowingParams(
                min_gap=2.5, tau=1.1),
            num_vehicles=16)

        env, scenario = grid_mxn_exp_setup(
            row_num=1, col_num=3, vehicles=vehicles)

        self.exp = Experiment(env)

    def tearDown(self):
        # free data used by the class
        self.exp = None

    def test_it_runs(self):
        self.exp.run(5, 50)
Пример #5
0
class TestItRuns(unittest.TestCase):
    """
    Tests the set_state function
    """
    def setUp(self):
        vehicles = VehicleParams()
        vehicles.add(veh_id="idm",
                     acceleration_controller=(IDMController, {}),
                     routing_controller=(GridRouter, {}),
                     car_following_params=SumoCarFollowingParams(min_gap=2.5,
                                                                 tau=1.1),
                     num_vehicles=16)

        _, _, flow_params = traffic_light_grid_mxn_exp_setup(row_num=1,
                                                             col_num=3,
                                                             vehicles=vehicles)

        flow_params['env'].horizon = 50
        self.exp = Experiment(flow_params)

    def tearDown(self):
        # free data used by the class
        self.exp = None

    def test_it_runs(self):
        self.exp.run(5)
Пример #6
0
    def test_rl_actions(self):
        def rl_actions(*_):
            return [1]  # actions are always an acceleration of 1 for one veh

        # create an environment using AccelEnv with 1 RL vehicle
        vehicles = VehicleParams()
        vehicles.add(
            veh_id="rl",
            acceleration_controller=(RLController, {}),
            routing_controller=(ContinuousRouter, {}),
            car_following_params=SumoCarFollowingParams(
                speed_mode="aggressive",
            ),
            num_vehicles=1)

        env, _ = ring_road_exp_setup(vehicles=vehicles)

        exp = Experiment(env=env)

        exp.run(1, 10, rl_actions=rl_actions)

        # check that the acceleration of the RL vehicle was that specified by
        # the rl_actions method
        self.assertAlmostEqual(exp.env.k.vehicle.get_speed("rl_0"), 1,
                               places=1)
Пример #7
0
class TestLoopMerges(unittest.TestCase):
    """
    Tests the loop_merges scenario and environment.
    """
    def setUp(self):
        # create the environment and scenario classes for a ring road
        self.env, scenario = two_loops_one_merging_exp_setup()

        # instantiate an experiment class
        self.exp = Experiment(self.env)

    def tearDown(self):
        # terminate the traci instance
        try:
            self.env.terminate()
        except FileNotFoundError:
            pass

        # free up used memory
        self.env = None
        self.exp = None

    def test_it_runs(self):
        """
        Tests that the loop merges experiment runs, and vehicles do not exit
        the network.
        """
        self.exp.run(1, 10)

    def test_gen_custom_start_pos(self):
        """
        Tests that vehicle with the prefix "merge" are in the merge_in lane,
        and all other vehicles are in the ring road.
        """
        # reset the environment to ensure all vehicles are at their starting
        # positions
        self.env.reset()
        ids = self.env.k.vehicle.get_ids()

        # collect the starting edges of all vehicles
        merge_starting_edges = []
        other_starting_edges = []
        for veh_id in ids:
            if veh_id[:5] == "merge":
                merge_starting_edges.append(
                    self.env.k.vehicle.get_edge(veh_id))
            else:
                other_starting_edges.append(
                    self.env.k.vehicle.get_edge(veh_id))

        # ensure that all vehicles are starting in the edges they should be in
        expected_merge_starting_edges = ["right", "top", "bottom"]

        self.assertTrue(
            all(starting_edge in expected_merge_starting_edges
                for starting_edge in merge_starting_edges))

        self.assertTrue(
            all(starting_edge not in expected_merge_starting_edges
                for starting_edge in other_starting_edges))
Пример #8
0
    def test_collide_inflows(self):
        """Tests collisions in the presence of inflows."""
        # create the environment and network classes for a ring road
        sim_params = SumoParams(sim_step=1, render=False)
        total_vehicles = 0
        vehicles = VehicleParams()
        vehicles.add(
            veh_id="idm",
            acceleration_controller=(SimCarFollowingController, {}),
            routing_controller=(GridRouter, {}),
            car_following_params=SumoCarFollowingParams(
                tau=0.1, carFollowModel="Krauss", minGap=2.5,
                speed_mode=0b00000,
            ),
            num_vehicles=total_vehicles)
        grid_array = {
            "short_length": 100,
            "inner_length": 100,
            "long_length": 100,
            "row_num": 1,
            "col_num": 1,
            "cars_left": 0,
            "cars_right": 0,
            "cars_top": 0,
            "cars_bot": 0
        }

        additional_net_params = {
            "speed_limit": 35,
            "grid_array": grid_array,
            "horizontal_lanes": 1,
            "vertical_lanes": 1
        }

        inflows = InFlows()
        inflows.add(veh_type="idm", edge="bot0_0", vehs_per_hour=1000)
        inflows.add(veh_type="idm", edge="top0_1", vehs_per_hour=1000)
        inflows.add(veh_type="idm", edge="left1_0", vehs_per_hour=1000)
        inflows.add(veh_type="idm", edge="right0_0", vehs_per_hour=1000)

        net_params = NetParams(
            inflows=inflows,
            additional_params=additional_net_params)

        env, _ = traffic_light_grid_mxn_exp_setup(
            row_num=1,
            col_num=1,
            sim_params=sim_params,
            vehicles=vehicles,
            net_params=net_params)

        # go through the env and set all the lights to green
        for i in range(env.rows * env.cols):
            env.k.traffic_light.set_state(
                node_id='center' + str(i), state="gggggggggggg")

        # instantiate an experiment class
        exp = Experiment(env)

        exp.run(50, 50)
Пример #9
0
def merge_baseline(num_runs, render=True):
    """Run script for all merge baselines.

    Parameters
    ----------
        num_runs : int
            number of rollouts the performance of the environment is evaluated
            over
        render: bool, optional
            specifies whether to use the gui during execution

    Returns
    -------
        flow.core.experiment.Experiment
            class needed to run simulations
    """
    sim_params = flow_params['sim']
    env_params = flow_params['env']

    # modify the rendering to match what is requested
    sim_params.render = render

    # set the evaluation flag to True
    env_params.evaluate = True

    flow_params['env'].horizon = env_params.horizon
    exp = Experiment(flow_params)

    results = exp.run(num_runs)
    avg_speed = np.mean(results['mean_returns'])

    return avg_speed
Пример #10
0
 def setUp(self):
     # create the environment and network classes for a ring road
     env, _, flow_params = ring_road_exp_setup()
     flow_params['sim'].render = False
     flow_params['env'].horizon = 10
     # instantiate an experiment class
     self.exp = Experiment(flow_params)
     self.exp.env = env
Пример #11
0
class TestIndividualLights(unittest.TestCase):
    """
    Tests the functionality of the the TrafficLightParams class in allowing
    for customization of specific nodes
    """
    def setUp(self):
        tl_logic = TrafficLightParams(baseline=False)
        phases = [{
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "GrGr"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "yryr"
        }, {
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "rGrG"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "ryry"
        }]
        tl_logic.add("center0", phases=phases, programID=1)
        tl_logic.add("center1", phases=phases, programID=1, offset=1)
        tl_logic.add("center2",
                     tls_type="actuated",
                     phases=phases,
                     programID=1)
        tl_logic.add("center3",
                     tls_type="actuated",
                     phases=phases,
                     programID=1,
                     maxGap=3.0,
                     detectorGap=0.8,
                     showDetectors=True,
                     file="testindividuallights.xml",
                     freq=100)

        _, _, flow_params = traffic_light_grid_mxn_exp_setup(row_num=1,
                                                             col_num=4,
                                                             tl_logic=tl_logic)

        flow_params['env'].horizon = 50
        self.exp = Experiment(flow_params)

    def tearDown(self):
        # free data used by the class
        self.exp = None

    def test_it_runs(self):
        self.exp.run(5)
Пример #12
0
def run_experiment(parameters):

    additional_net_params = parameters["additional_net_params"]
    flow_rate = parameters["flow_rate"]
    name = parameters["name"]
    vehicle_types = parameters["vehicle_types"]
    vehicle_speeds = parameters["vehicle_speeds"]
    lane_change_modes = parameters["lane_change_modes"]
    experiment_len = parameters["experiment_len"]
    emission_path = parameters["emission_path"]

    inflow_c = Inflow(flow_rate=flow_rate, vehicle_types=vehicle_types)
    inflow = inflow_c.create_inflow()

    net_params = NetParams(additional_params=additional_net_params,
                           inflows=inflow)

    initial_config = InitialConfig(spacing="random",
                                   perturbation=1,
                                   edges_distribution=["edge4"])
    traffic_lights = TrafficLightParams()

    sim_params = SumoParams(sim_step=1,
                            render=True,
                            emission_path=emission_path,
                            restart_instance=True,
                            overtake_right=True)

    env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS)

    vehicle_c = Vehicles(vehicle_types=vehicle_types,
                         vehicle_speeds=vehicle_speeds,
                         lane_change_modes=lane_change_modes)
    vehicles = vehicle_c.create_vehicles()

    flow_params = dict(exp_tag=name,
                       env_name=AccelEnv,
                       network=HighwayNetwork,
                       simulator='traci',
                       sim=sim_params,
                       env=env_params,
                       net=net_params,
                       veh=vehicles,
                       initial=initial_config,
                       tls=traffic_lights)

    # number of time steps
    flow_params['env'].horizon = experiment_len
    exp = Experiment(flow_params)

    # run the sumo simulation
    _ = exp.run(1, convert_to_csv=True)

    emission_location = os.path.join(exp.env.sim_params.emission_path,
                                     exp.env.network.name)
    print(emission_location + '-emission.xml')
Пример #13
0
def run_scenario(render=False,
                 emissions=None,#"/home/mesto/flow/data/",
                 output=output_path,
                 step=0.1,
                 duration=1000,
                 flow_rate=2800,
                 car_following_model=IDMController,
                 speed=30
                 ):

	env_params = EnvParams()
	initial_config = InitialConfig()
	vehicles = VehicleParams()

	sim_params = SumoParams(render=render, sim_step=step, emission_path=emissions)

	vehicles = VehicleParams()
	inflow = InFlows()

        #Parameters for the network.
        #Template( net: file path for the sumo network. rou: path to the routes xml file
        #vtype: path to vehicle types xml. 
        #e1det: Requires modified traci simulation python file. Points to where detector definitions are stored
        #location that output will be saved. Also requires modified traci.py
	net_params = NetParams(inflows=inflow, template= {
	                       "net" : net_path,
                               "rou" : route_path,
                               "vtype": vtype_path,
	                       "e1Det": detector_path,
                               "output": output
	                       },
	                       no_internal_links=False)
	initial_config = InitialConfig(
	    edges_distribution=[starting_edge])

	scenario = Custom_Scenario(
	    name="template",
	    net_params=net_params,
	    initial_config=initial_config,
	    vehicles=vehicles
	)
	
	#The following determines which lanes vehicles spawn in. By default they spawn in rightmost lane
        #possibles are: int (number of lane), free (which lane is open), best, random
	for key in scenario.template_vehicles:
	    scenario.template_vehicles[key]['departLane'] = 'free'

	env = myEnv(
	    env_params=env_params,
	    sim_params=sim_params,
	    scenario=scenario
	)
	env.setSpeed(speed)

	exp = Experiment(env=env)
	_ = exp.run(1, duration)
Пример #14
0
    def run_simulation(flow_params):
        # make the horizon small and set render to False
        flow_params['sim'].render = False
        flow_params['env'].horizon = 5

        # create an experiment object
        exp = Experiment(flow_params)

        # run the experiment for one run
        exp.run(1)
Пример #15
0
def merge_baseline(num_runs, render=True):
    """Run script for all merge baselines.

    Parameters
    ----------
        num_runs : int
            number of rollouts the performance of the environment is evaluated
            over
        render: bool, optional
            specifies whether to use the gui during execution

    Returns
    -------
        flow.core.experiment.Experiment
            class needed to run simulations
    """
    exp_tag = flow_params['exp_tag']
    sim_params = flow_params['sim']
    vehicles = flow_params['veh']
    env_params = flow_params['env']
    net_params = flow_params['net']
    initial_config = flow_params.get('initial', InitialConfig())
    traffic_lights = flow_params.get('tls', TrafficLightParams())

    # modify the rendering to match what is requested
    sim_params.render = render

    # set the evaluation flag to True
    env_params.evaluate = True

    # import the scenario class
    module = __import__('flow.scenarios', fromlist=[flow_params['scenario']])
    scenario_class = getattr(module, flow_params['scenario'])

    # create the scenario object
    scenario = scenario_class(name=exp_tag,
                              vehicles=vehicles,
                              net_params=net_params,
                              initial_config=initial_config,
                              traffic_lights=traffic_lights)

    # import the environment class
    module = __import__('flow.envs', fromlist=[flow_params['env_name']])
    env_class = getattr(module, flow_params['env_name'])

    # create the environment object
    env = env_class(env_params, sim_params, scenario)

    exp = Experiment(env)

    results = exp.run(num_runs, env_params.horizon)
    avg_speed = np.mean(results['mean_returns'])

    return avg_speed
Пример #16
0
    def test_collide(self):
        """Tests collisions in the absence of inflows."""
        # create the environment and scenario classes for a ring road
        sim_params = SumoParams(sim_step=1, render=False)
        total_vehicles = 20
        vehicles = VehicleParams()
        vehicles.add(
            veh_id="idm",
            acceleration_controller=(SimCarFollowingController, {}),
            routing_controller=(GridRouter, {}),
            car_following_params=SumoCarFollowingParams(
                tau=0.1, carFollowModel="Krauss", minGap=2.5,
                speed_mode=0b00000,
            ),
            num_vehicles=total_vehicles)
        grid_array = {
            "short_length": 100,
            "inner_length": 100,
            "long_length": 100,
            "row_num": 1,
            "col_num": 1,
            "cars_left": int(total_vehicles / 4),
            "cars_right": int(total_vehicles / 4),
            "cars_top": int(total_vehicles / 4),
            "cars_bot": int(total_vehicles / 4)
        }

        additional_net_params = {
            "speed_limit": 35,
            "grid_array": grid_array,
            "horizontal_lanes": 1,
            "vertical_lanes": 1
        }

        net_params = NetParams(
            no_internal_links=False, additional_params=additional_net_params)

        self.env, self.scenario = grid_mxn_exp_setup(
            row_num=1,
            col_num=1,
            sim_params=sim_params,
            vehicles=vehicles,
            net_params=net_params)

        # go through the env and set all the lights to green
        for i in range(self.env.rows * self.env.cols):
            self.env.traci_connection.trafficlight.setRedYellowGreenState(
                'center' + str(i), "gggggggggggg")

        # instantiate an experiment class
        self.exp = Experiment(self.env)

        self.exp.run(50, 50)
Пример #17
0
def merge_baseline(num_runs):
    """Run script for all merge baselines.

    Parameters
    ----------
        num_runs : int
            number of rollouts the performance of the environment is evaluated
            over
        flow_params : dict
            the flow meta-parameters describing the structure of a benchmark.
            Must be one of the merge flow_params

    Returns
    -------
        flow.core.experiment.Experiment
            class needed to run simulations
    """
    exp_tag = flow_params['exp_tag']
    sim_params = flow_params['sim']
    vehicles = flow_params['veh']
    env_params = flow_params['env']
    net_params = flow_params['net']
    initial_config = flow_params.get('initial', InitialConfig())
    traffic_lights = flow_params.get('tls', TrafficLightParams())

    # set the evaluation flag to True
    env_params.evaluate = True

    # import the scenario class
    module = __import__('flow.scenarios', fromlist=[flow_params['scenario']])
    scenario_class = getattr(module, flow_params['scenario'])

    # create the scenario object
    scenario = scenario_class(name=exp_tag,
                              vehicles=vehicles,
                              net_params=net_params,
                              initial_config=initial_config,
                              traffic_lights=traffic_lights)

    # import the environment class
    module = __import__('flow.envs', fromlist=[flow_params['env_name']])
    env_class = getattr(module, flow_params['env_name'])

    # create the environment object
    env = env_class(env_params, sim_params, scenario)

    exp = Experiment(env)

    results = exp.run(num_runs, env_params.horizon, convert_to_csv=True)
    avg_speed = np.mean(results['mean_returns'])

    return avg_speed
Пример #18
0
def bottleneck1_baseline(num_runs, render=True):
    """Run script for the bottleneck1 baseline.

    Parameters
    ----------
        num_runs : int
            number of rollouts the performance of the environment is evaluated
            over
        render: str, optional
            specifies whether to use the gui during execution

    Returns
    -------
        flow.core.experiment.Experiment
            class needed to run simulations
    """
    sim_params = flow_params['sim']
    env_params = flow_params['env']
    net_params = flow_params['net']

    # we want no autonomous vehicles in the simulation
    vehicles = VehicleParams()
    vehicles.add(veh_id='human',
                 car_following_params=SumoCarFollowingParams(speed_mode=9, ),
                 routing_controller=(ContinuousRouter, {}),
                 lane_change_params=SumoLaneChangeParams(
                     lane_change_mode=1621, ),
                 num_vehicles=1 * SCALING)

    # only include human vehicles in inflows
    flow_rate = 2300 * SCALING
    inflow = InFlows()
    inflow.add(veh_type='human',
               edge='1',
               vehs_per_hour=flow_rate,
               departLane='random',
               departSpeed=10)
    net_params.inflows = inflow

    # modify the rendering to match what is requested
    sim_params.render = render

    # set the evaluation flag to True
    env_params.evaluate = True

    flow_params['env'].horizon = env_params.horizon
    exp = Experiment(flow_params)

    results = exp.run(num_runs)

    return np.mean(results['returns']), np.std(results['returns'])
Пример #19
0
    def setUp(self):
        vehicles = Vehicles()
        vehicles.add(
            veh_id="idm",
            acceleration_controller=(IDMController, {}),
            routing_controller=(GridRouter, {}),
            sumo_car_following_params=SumoCarFollowingParams(
                min_gap=2.5, tau=1.1),
            num_vehicles=16)

        env, scenario = grid_mxn_exp_setup(
            row_num=1, col_num=3, vehicles=vehicles)

        self.exp = Experiment(env)
Пример #20
0
    def setUp(self):
        vehicles = VehicleParams()
        vehicles.add(veh_id="idm",
                     acceleration_controller=(IDMController, {}),
                     routing_controller=(GridRouter, {}),
                     car_following_params=SumoCarFollowingParams(min_gap=2.5,
                                                                 tau=1.1),
                     num_vehicles=16)

        _, _, flow_params = traffic_light_grid_mxn_exp_setup(row_num=1,
                                                             col_num=3,
                                                             vehicles=vehicles)

        flow_params['env'].horizon = 50
        self.exp = Experiment(flow_params)
Пример #21
0
    def setUp(self):
        # create the environment and scenario classes for a grid network
        self.env, _ = grid_mxn_exp_setup(row_num=2, col_num=2)
        self.env.reset()

        # instantiate an experiment class
        self.exp = Experiment(self.env)
def cross_road_experiment(render=None):
    """ Parameters & Returns: tutorials/tutorial05_networks.ipynb """
    vehicles = get_vehicle_params(TTCController, {
        "a": 2.0,
        "ttc_threshold": 4.5
    })

    env_params = EnvParams(
        warmup_steps=150,
        additional_params=ADDITIONAL_ENV_PARAMS,
    )
    net_params = get_net_params(inflow_probability=0.3)
    sumo_params = SumoParams(render=True,
                             emission_path="./emission/",
                             summary_path="./emission/",
                             tripinfo_path="./emission/",
                             sim_step=0.1,
                             restart_instance=True)
    if render is not None:
        sumo_params.render = render
    initial_config = get_initial_config()

    network = CrossRoadNetwork(name="cross_road_network",
                               vehicles=vehicles,
                               net_params=net_params,
                               initial_config=initial_config)

    env = CrossRoadAccelEnv(env_params, sumo_params, network)
    return Experiment(env)
Пример #23
0
def figure_eight_example(render=None):
    """Perform a simulation of vehicles on a figure eight.

    Parameters
    ----------
    render: bool, optional
        specifies whether to use the gui during execution

    Returns
    -------
    exp: flow.core.experiment.Experiment
        A non-rl experiment demonstrating the performance of human-driven
        vehicles on a figure eight.
    """
    sim_params = AimsunParams(sim_step=0.5, render=False, emission_path='data')

    if render is not None:
        sim_params.render = render

    vehicles = VehicleParams()
    vehicles.add(veh_id="human",
                 acceleration_controller=(IDMController, {}),
                 num_vehicles=14)

    env_params = EnvParams()

    net_params = NetParams(additional_params=ADDITIONAL_NET_PARAMS.copy())

    scenario = Figure8Scenario(name="figure8",
                               vehicles=vehicles,
                               net_params=net_params)

    env = TestEnv(env_params, sim_params, scenario, simulator='aimsun')

    return Experiment(env)
Пример #24
0
    def setUp(self):
        # create the environment and network classes for a traffic light grid network
        self.env, _ = traffic_light_grid_mxn_exp_setup(row_num=2, col_num=2)
        self.env.reset()

        # instantiate an experiment class
        self.exp = Experiment(self.env)
Пример #25
0
    def setUp(self):
        # create the environment and scenario classes for a ring road
        self.env, self.scenario = grid_mxn_exp_setup()
        self.env.reset()

        # instantiate an experiment class
        self.exp = Experiment(self.env)
Пример #26
0
def minicity_example(render=None,
                     save_render=None,
                     sight_radius=None,
                     pxpm=None,
                     show_radius=None):
    """
    Perform a simulation of vehicles on modified minicity of University of
    Delaware.

    Parameters
    ----------
    render: bool, optional
        specifies whether to use the gui during execution

    Returns
    -------
    exp: flow.core.experiment.Experiment
        A non-rl experiment demonstrating the performance of human-driven
        vehicles on the minicity scenario.
    """
    sim_params = SumoParams(sim_step=0.25)

    # update sim_params values if provided as inputs
    sim_params.render = render or sim_params.render
    sim_params.save_render = save_render or sim_params.save_render
    sim_params.sight_radius = sight_radius or sim_params.sight_radius
    sim_params.pxpm = pxpm or sim_params.pxpm
    sim_params.show_radius = show_radius or sim_params.show_radius

    vehicles = VehicleParams()
    vehicles.add(veh_id="idm",
                 acceleration_controller=(IDMController, {}),
                 routing_controller=(MinicityRouter, {}),
                 car_following_params=SumoCarFollowingParams(speed_mode=1, ),
                 lane_change_params=SumoLaneChangeParams(
                     lane_change_mode="no_lat_collide", ),
                 initial_speed=0,
                 num_vehicles=90)
    vehicles.add(veh_id="rl",
                 acceleration_controller=(RLController, {}),
                 routing_controller=(MinicityRouter, {}),
                 car_following_params=SumoCarFollowingParams(
                     speed_mode="obey_safe_speed", ),
                 initial_speed=0,
                 num_vehicles=10)

    env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS)

    net_params = NetParams(no_internal_links=False)

    initial_config = InitialConfig(spacing="random", min_gap=5)
    scenario = MiniCityScenario(name="minicity",
                                vehicles=vehicles,
                                initial_config=initial_config,
                                net_params=net_params)

    env = AccelEnv(env_params, sim_params, scenario)

    return Experiment(env)
Пример #27
0
    def setUp(self):
        tl_logic = TrafficLightParams(baseline=False)
        phases = [{
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "GrGr"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "yryr"
        }, {
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "rGrG"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "ryry"
        }]
        tl_logic.add("center0", phases=phases, programID=1)
        tl_logic.add("center1", phases=phases, programID=1, offset=1)
        tl_logic.add("center2",
                     tls_type="actuated",
                     phases=phases,
                     programID=1)
        tl_logic.add("center3",
                     tls_type="actuated",
                     phases=phases,
                     programID=1,
                     maxGap=3.0,
                     detectorGap=0.8,
                     showDetectors=True,
                     file="testindividuallights.xml",
                     freq=100)

        _, _, flow_params = traffic_light_grid_mxn_exp_setup(row_num=1,
                                                             col_num=4,
                                                             tl_logic=tl_logic)

        flow_params['env'].horizon = 50
        self.exp = Experiment(flow_params)
Пример #28
0
def main():
    env = GetTrafficLightEnv()
    act = deepq.learn(env,
                      network='mlp',
                      total_timesteps=0,
                      load_path="tls_model.pkl")
    reward = 0
    iterations = 1
    exp = Experiment(getFlowParamsForTls())

    ## This is the RL agent that is using the trained model that we saved from train_tls file
    rl_agent = lambda state: act(state[None])[0]

    ## This is the static agent that switches the light every 20s
    static_agent = static_rl_actions

    # Passing the appropriate lambda among static and rl, you can perform the experiment
    exp.run(10, rl_agent, convert_to_csv=True)
    def setUp(self):
        tl_logic = TrafficLightParams(baseline=False)
        phases = [{
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "GGGrrrGGGrrr"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "yyyrrryyyrrr"
        }, {
            "duration": "31",
            "minDur": "8",
            "maxDur": "45",
            "state": "rrrGGGrrrGGG"
        }, {
            "duration": "6",
            "minDur": "3",
            "maxDur": "6",
            "state": "rrryyyrrryyy"
        }]
        tl_logic.add("center0", phases=phases, programID=1)
        tl_logic.add("center1", phases=phases, programID=1, offset=1)
        tl_logic.add("center2",
                     tls_type="actuated",
                     phases=phases,
                     programID=1)
        tl_logic.add("center3",
                     tls_type="actuated",
                     phases=phases,
                     programID=1,
                     maxGap=3.0,
                     detectorGap=0.8,
                     showDetectors=True,
                     file="testindividuallights.xml",
                     freq=100)

        env, scenario = grid_mxn_exp_setup(row_num=1,
                                           col_num=4,
                                           tl_logic=tl_logic)

        self.exp = Experiment(env)
Пример #30
0
def highway_example(render=None):
    """
    Perform a simulation of vehicles on a highway.

    Parameters
    ----------
    render : bool, optional
        specifies whether to use the gui during execution

    Returns
    -------
    exp: flow.core.experiment.Experiment
        A non-rl experiment demonstrating the performance of human-driven
        vehicles on a figure eight.
    """
    sim_params = SumoParams(render=True)

    if render is not None:
        sim_params.render = render

    vehicles = VehicleParams()
    vehicles.add(veh_id="human",
                 acceleration_controller=(IDMController, {}),
                 num_vehicles=20)
    vehicles.add(veh_id="human2",
                 acceleration_controller=(IDMController, {}),
                 num_vehicles=20)

    env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS)

    inflow = InFlows()
    inflow.add(veh_type="human",
               edge="highway_0",
               probability=0.25,
               departLane="free",
               departSpeed=20)
    inflow.add(veh_type="human2",
               edge="highway_0",
               probability=0.25,
               departLane="free",
               departSpeed=20)

    additional_net_params = ADDITIONAL_NET_PARAMS.copy()
    net_params = NetParams(inflows=inflow,
                           additional_params=additional_net_params)

    initial_config = InitialConfig(spacing="uniform", shuffle=True)

    network = HighwayNetwork(name="highway",
                             vehicles=vehicles,
                             net_params=net_params,
                             initial_config=initial_config)

    env = LaneChangeAccelEnv(env_params, sim_params, network)

    return Experiment(env)