Exemplo n.º 1
0
    def __init__(
            self,
            name,
            vehicles,
            net_params,
            initial_config=InitialConfig(),
            traffic_lights=TrafficLightParams(),
            detector_params=DetectorParams(),
    ):
        """Initialize an n*m traffic light grid network."""
        optional = ["tl_logic"]
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params and p not in optional:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        for p in ADDITIONAL_NET_PARAMS["grid_array"].keys():
            if p not in net_params.additional_params["grid_array"]:
                raise KeyError(
                    'Grid array parameter "{}" not supplied'.format(p))

        # retrieve all additional parameters
        # refer to the ADDITIONAL_NET_PARAMS dict for more documentation
        self.vertical_lanes = net_params.additional_params["vertical_lanes"]
        self.horizontal_lanes = net_params.additional_params[
            "horizontal_lanes"]
        self.speed_limit = net_params.additional_params["speed_limit"]
        if not isinstance(self.speed_limit, dict):
            self.speed_limit = {
                "horizontal": self.speed_limit,
                "vertical": self.speed_limit
            }

        self.grid_array = net_params.additional_params["grid_array"]
        self.row_num = self.grid_array["row_num"]
        self.col_num = self.grid_array["col_num"]
        self.inner_length = self.grid_array["inner_length"]
        self.short_length = self.grid_array["short_length"]
        self.long_length = self.grid_array["long_length"]
        self.cars_heading_top = self.grid_array["cars_top"]
        self.cars_heading_bot = self.grid_array["cars_bot"]
        self.cars_heading_left = self.grid_array["cars_left"]
        self.cars_heading_right = self.grid_array["cars_right"]

        # specifies whether or not there will be traffic lights at the
        # intersections (True by default)
        self.use_traffic_lights = net_params.additional_params.get(
            "traffic_lights", True)

        # radius of the inner nodes (ie of the intersections)
        self.inner_nodes_radius = 2.9 + 3.3 * max(self.vertical_lanes,
                                                  self.horizontal_lanes)

        # total number of edges in the network
        self.num_edges = 4 * ((self.col_num + 1) * self.row_num + self.col_num)

        # name of the network (DO NOT CHANGE)
        self.name = "BobLoblawsLawBlog"

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights, detector_params)
Exemplo n.º 2
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a highway scenario.

        Requires from net_params:
        - length: length of the highway
        - lanes: number of lanes in the highway
        - speed_limit: max speed limit of the highway

        See flow/scenarios/base_scenario.py for description of params.
        """
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        self.length = net_params.additional_params["length"]
        self.lanes = net_params.additional_params["lanes"]
        self.num_edges = net_params.additional_params.get("num_edges", 1)

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 3
0
 def __init__(self,
              name,
              vehicles,
              net_params,
              initial_config=initial_config,
              traffic_lights=TrafficLightParams()):
     super(offRampGrid,self).__init__(name,vehicles,net_params,initial_config,traffic_lights)
Exemplo n.º 4
0
 def __init__(self,
              name,
              vehicles,
              net_params,
              initial_config=InitialConfig(),
              traffic_lights=TrafficLightParams()):
     """Initialize an n*m traffic light grid network."""
Exemplo n.º 5
0
    def setUp(self):
        # add a traffic light to the top node
        traffic_lights = TrafficLightParams()

        # Phase durations in seconds
        self.green = 4
        self.yellow = 1
        self.red = 4
        phases = [{
            "duration": repr(self.green),
            "state": "G"
        }, {
            "duration": repr(self.yellow),
            "state": "y"
        }, {
            "duration": repr(self.red),
            "state": "r"
        }]

        traffic_lights.add("top", phases=phases)

        # create a ring road with two lanes
        additional_net_params = {
            "length": 230,
            "lanes": 1,
            "speed_limit": 30,
            "resolution": 40
        }
        net_params = NetParams(additional_params=additional_net_params)

        # create the environment and scenario classes for a ring road
        self.env, scenario = ring_road_exp_setup(
            net_params=net_params, traffic_lights=traffic_lights)
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a figure 8 scenario."""
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        ring_radius = net_params.additional_params["radius_ring"]
        self.ring_edgelen = ring_radius * np.pi / 2.
        self.intersection_len = 2 * ring_radius
        self.junction_len = 2.9 + 3.3 * net_params.additional_params["lanes"]
        self.inner_space_len = 0.28

        # instantiate "length" in net params
        net_params.additional_params["length"] = \
            6 * self.ring_edgelen + 2 * self.intersection_len + \
            2 * self.junction_len + 10 * self.inner_space_len

        self.radius_ring = net_params.additional_params["radius_ring"]
        self.length = net_params.additional_params["length"]
        self.lanes = net_params.additional_params["lanes"]
        self.resolution = net_params.additional_params["resolution"]

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 7
0
def flow_register(flow_params, render=None, **kwargs):
    exp_tag = flow_params["exp_tag"]
    env_params = flow_params['env']
    net_params = flow_params['net']
    env_class = flow_params['env_name']
    initial_config = flow_params.get('initial', InitialConfig())
    traffic_lights = flow_params.get("tls", TrafficLightParams())
    sim_params = deepcopy(flow_params['sim'])
    vehicles = deepcopy(flow_params['veh'])

    sim_params.render = render or sim_params.render

    if isinstance(flow_params["network"], str):
        print("""Passing of strings for network will be deprecated.
        Please pass the Network instance instead.""")
        module = __import__("flow.networks", fromlist=[flow_params["network"]])
        network_class = getattr(module, flow_params["network"])
    else:
        network_class = flow_params["network"]

    network = network_class(
        name=exp_tag,
        vehicles=vehicles,
        net_params=net_params,
        initial_config=initial_config,
        traffic_lights=traffic_lights,
    )

    flow_env = env_class(env_params=env_params,
                         sim_params=sim_params,
                         network=network,
                         simulator=flow_params['simulator'])

    env = offline_env.OfflineEnvWrapper(flow_env, **kwargs)
    return env
Exemplo n.º 8
0
 def __init__(self,
              name,
              vehicles,
              net_params,
              initial_config=InitialConfig(),
              traffic_lights=TrafficLightParams()):
     super(OSMScenario, self).__init__(name, vehicles, net_params,
                                       initial_config, traffic_lights)
Exemplo n.º 9
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')
Exemplo n.º 10
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Instantiate the base scenario class.

        Attributes
        ----------
        name : str
            A tag associated with the scenario
        vehicles : flow.core.params.VehicleParams
            see flow/core/params.py
        net_params : flow.core.params.NetParams
            see flow/core/params.py
        initial_config : flow.core.params.InitialConfig
            see flow/core/params.py
        traffic_lights : flow.core.params.TrafficLightParams
            see flow/core/params.py
        """
        # Invoke serializable if using rllab
        if Serializable is not object:
            Serializable.quick_init(self, locals())

        self.orig_name = name  # To avoid repeated concatenation upon reset
        self.name = name + time.strftime('_%Y%m%d-%H%M%S') + str(time.time())

        self.vehicles = vehicles
        self.net_params = net_params
        self.initial_config = initial_config
        self.traffic_lights = traffic_lights

        if net_params.netfile is None and net_params.osm_path is None:
            # specify the attributes of the nodes
            self.nodes = self.specify_nodes(net_params)
            # collect the attributes of each edge
            self.edges = self.specify_edges(net_params)
            # specify the types attributes (default is None)
            self.types = self.specify_types(net_params)
            # specify the connection attributes (default is None)
            self.connections = self.specify_connections(net_params)
        else:
            self.nodes = None
            self.edges = None
            self.types = None
            self.connections = None

        # specify routes vehicles can take
        self.routes = self.specify_routes(net_params)

        # optional parameters, used to get positions from some global reference
        self.edge_starts = self.specify_edge_starts()
        self.internal_edge_starts = self.specify_internal_edge_starts()
        self.intersection_edge_starts = self.specify_intersection_edge_starts()
Exemplo n.º 11
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
Exemplo n.º 12
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Instantiate the scenario class."""
        self.nodes_dict = dict()

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 13
0
def make_create_env(params, version=0, render=None):
    exp_tag = params["exp_tag"]

    env_name = params["env_name"] + '-v{}'.format(version)

    module = __import__("flow.scenarios", fromlist=[params["scenario"]])
    scenario_class = getattr(module, params["scenario"])

    env_params = params['env']
    net_params = params['net']
    initial_config = params.get('initial', InitialConfig())
    traffic_lights = params.get("tls", TrafficLightParams())

    def create_env(*_):
        sim_params = deepcopy(params['sim'])
        vehicles = deepcopy(params['veh'])

        scenario = scenario_class(
            name=exp_tag,
            vehicles=vehicles,
            net_params=net_params,
            initial_config=initial_config,
            traffic_lights=traffic_lights,
        )

        # accept new render type if not set to None
        sim_params.render = render or sim_params.render

        # check if the environment is a single or multiagent environment, and
        # get the right address accordingly
        single_agent_envs = [env for env in dir(flow.envs)
                             if not env.startswith('__')]

        if params['env_name'] in single_agent_envs:
            env_loc = 'flow.envs'
        else:
            env_loc = 'flow.envs.multiagent'

        try:
            register(
                id=env_name,
                entry_point=env_loc + ':{}'.format(params["env_name"]),
                kwargs={
                    "env_params": env_params,
                    "sim_params": sim_params,
                    "scenario": scenario,
                    "simulator": params['simulator']
                })
        except Exception:
            pass
        return gym.envs.make(env_name)

    return create_env, env_name
Exemplo n.º 14
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
Exemplo n.º 15
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Instantiate the scenario class."""
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 16
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a highway network."""
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        self.end_length = 500

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 17
0
def run_task(*_):
    """Implement the ``run_task`` method needed to run experiments with rllab.

    Note that the flow-specific parameters are imported at the start of this
    script and unzipped and processed here.
    """
    env_name = flow_params["env_name"]
    exp_tag = flow_params["exp_tag"]
    sumo_params = flow_params["sumo"]
    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())

    # 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)

    pass_params = (env_name, sumo_params, vehicles, env_params, net_params,
                   initial_config, scenario)

    env = GymEnv(env_name, record_video=False, register_params=pass_params)
    env = normalize(env)

    policy = GaussianMLPPolicy(env_spec=env.spec, hidden_sizes=(100, 50, 25))

    baseline = LinearFeatureBaseline(env_spec=env.spec)
    horizon = flow_params["env"].horizon

    algo = TRPO(
        env=env,
        policy=policy,
        baseline=baseline,
        batch_size=horizon * (N_ROLLOUTS - N_CPUS + 1),
        max_path_length=horizon,
        n_itr=500,
        discount=0.999,
        step_size=0.01,
    )
    algo.train(),
Exemplo n.º 18
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a two loop scenario.

        Requires from net_params:
        - ring_radius: radius of the loops
        - lane_length: length of the straight edges connected the outer loop to
          the inner loop
        - inner_lanes: number of lanes in the inner loop
        - outer_lanes: number of lanes in the outer loop
        - speed_limit: max speed limit in the network
        - resolution: resolution of the curved portions

        See flow/scenarios/base_scenario.py for description of params.
        """
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        radius = net_params.additional_params["ring_radius"]
        x = net_params.additional_params["lane_length"]

        self.inner_lanes = net_params.additional_params["inner_lanes"]
        self.outer_lanes = net_params.additional_params["outer_lanes"]

        self.junction_length = 0.3
        self.intersection_length = 25.5  # calibrate when the radius changes

        net_params.additional_params["length"] = \
            2 * x + 2 * pi * radius + \
            2 * self.intersection_length + 2 * self.junction_length

        num_vehicles = vehicles.num_vehicles
        num_merge_vehicles = sum("merge" in vehicles.get_type(veh_id)
                                 for veh_id in vehicles.ids)
        self.n_inner_vehicles = num_merge_vehicles
        self.n_outer_vehicles = num_vehicles - num_merge_vehicles

        radius = net_params.additional_params["ring_radius"]
        length_loop = 2 * pi * radius
        self.length_loop = length_loop

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 19
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams(),
                 inflow_edge_len=INFLOW_EDGE_LEN):
        """Initialize a triangle-merge scenario."""
        for p in additional_net_params.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        self.inflow_edge_len = inflow_edge_len

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
def make_create_env1(params, version=0, render=None):

    exp_tag = params["exp_tag"]

    env_name = params["env_name"] + '-v{}'.format(version)

    module = __import__("flow.scenarios", fromlist=[params["scenario"]])
    scenario_class = getattr(module, params["scenario"])

    env_params = params['env']
    net_params = params['net']
    initial_config = params.get('initial', InitialConfig())
    traffic_lights = params.get("tls", TrafficLightParams())

    def create_env(*_):
        sim_params = deepcopy(params['sim'])
        vehicles = deepcopy(params['veh'])

        scenario = scenario_class(
            name=exp_tag,
            vehicles=vehicles,
            net_params=net_params,
            initial_config=initial_config,
            traffic_lights=traffic_lights,
        )

        if render is not None:
            sim_params.render = render

        env_loc = 'envs'

        try:
            register(
                id=env_name,
                entry_point=env_loc + ':{}'.format(params["env_name"]),
                kwargs={
                    "env_params": env_params,
                    "sim_params": sim_params,
                    "scenario": scenario,
                    "simulator": params['simulator']
                })
        except Exception:
            pass
        return gym.envs.make(env_name)

    return create_env, env_name
Exemplo n.º 21
0
    def setUp(self):
        # add a traffic light to the top node
        traffic_lights = TrafficLightParams()
        traffic_lights.add("top")

        # create a ring road with two lanes
        additional_net_params = {
            "length": 230,
            "lanes": 2,
            "speed_limit": 30,
            "resolution": 40
        }
        net_params = NetParams(additional_params=additional_net_params)

        # create the environment and scenario classes for a ring road
        self.env, scenario = ring_road_exp_setup(
            net_params=net_params, traffic_lights=traffic_lights)
Exemplo n.º 22
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a highway scenario."""
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        self.length = net_params.additional_params["length"]
        self.lanes = net_params.additional_params["lanes"]
        self.num_edges = net_params.additional_params.get("num_edges", 1)

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 23
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)
    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)
Exemplo n.º 25
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize an nxm grid scenario."""
        optional = ["tl_logic"]
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params and p not in optional:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        for p in ADDITIONAL_NET_PARAMS["grid_array"].keys():
            if p not in net_params.additional_params["grid_array"]:
                raise KeyError(
                    'Grid array parameter "{}" not supplied'.format(p))

        # this is a (mx1)x(nx1)x2 array
        # the third dimension is vertical length, horizontal length
        self.grid_array = net_params.additional_params["grid_array"]

        vertical_lanes = net_params.additional_params["vertical_lanes"]
        horizontal_lanes = net_params.additional_params["horizontal_lanes"]

        self.horizontal_junction_len = 2.9 + 3.3 * vertical_lanes
        self.vertical_junction_len = 2.9 + 3.3 * horizontal_lanes
        self.row_num = self.grid_array["row_num"]
        self.col_num = self.grid_array["col_num"]
        self.num_edges = (self.col_num+1) * self.row_num * 2 \
            + (self.row_num+1) * self.col_num * 2 + self.row_num * self.col_num
        self.inner_length = self.grid_array["inner_length"]
        self.short_length = self.grid_array["short_length"]
        self.long_length = self.grid_array["long_length"]

        # this is a dictionary containing inner length, long outer length,
        # short outer length, and number of rows and columns
        self.grid_array = net_params.additional_params["grid_array"]

        self.node_mapping = defaultdict(list)
        self.name = "BobLoblawsLawBlog"  # DO NOT CHANGE

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 26
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize a figure 8 scenario.

        Requires from net_params:
        - ring_radius: radius of the circular portions of the network. Also
          corresponds to half the length of the perpendicular straight lanes.
        - resolution: number of nodes resolution in the circular portions
        - lanes: number of lanes in the network
        - speed: max speed of vehicles in the network

        In order for right-of-way dynamics to take place at the intersection,
        set "no_internal_links" in net_params to False.

        See flow/scenarios/base_scenario.py for description of params.
        """
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        ring_radius = net_params.additional_params["radius_ring"]
        self.ring_edgelen = ring_radius * np.pi / 2.
        self.intersection_len = 2 * ring_radius
        self.junction_len = 2.9 + 3.3 * net_params.additional_params["lanes"]
        self.inner_space_len = 0.28

        # instantiate "length" in net params
        net_params.additional_params["length"] = \
            6 * self.ring_edgelen + 2 * self.intersection_len + \
            2 * self.junction_len + 10 * self.inner_space_len

        self.radius_ring = net_params.additional_params["radius_ring"]
        self.length = net_params.additional_params["length"]
        self.lanes = net_params.additional_params["lanes"]
        self.resolution = net_params.additional_params["resolution"]

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 27
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        optional = ["tl_logic"]
        # retrieve all additional parameters
        # refer to the ADDITIONAL_NET_PARAMS dict for more documentation

        self.use_traffic_lights = net_params.additional_params.get(
            "traffic_lights", True)
        # radius of the inner nodes (ie of the intersections)
        self.inner_nodes_radius = 6.2

        # total number of edges in the network
        self.num_edges = 8

        # name of the network (DO NOT CHANGE)
        self.name = "BobLoblawsLawBlog"
        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 28
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Instantiate the scenario class.

        Requires from net_params:
        - scaling: the factor multiplying number of lanes

        In order for right-of-way dynamics to take place at the intersection,
        set "no_internal_links" in net_params to False.

        See flow/scenarios/base_scenario.py for description of params.
        """
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)
Exemplo n.º 29
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):
        """Initialize the I210 sub-network scenario."""
        for p in ADDITIONAL_NET_PARAMS.keys():
            if p not in net_params.additional_params:
                raise KeyError('Network parameter "{}" not supplied'.format(p))

        # The length of each edge and junction is a fixed term that can be
        # found in the xml file.
        self.length_with_ghost_edge = [
            ("ghost0", 573.08),
            (":300944378_0", 0.30),
            ("119257914", 61.28),
            (":300944379_0", 0.31),
            ("119257908#0", 696.97),
            (":300944436_0", 2.87),
            ("119257908#1-AddedOnRampEdge", 97.20),
            (":119257908#1-AddedOnRampNode_0", 3.24),
            ("119257908#1", 239.68),
            (":119257908#1-AddedOffRampNode_0", 3.24),
            ("119257908#1-AddedOffRampEdge", 98.50),
            (":1686591010_1", 5.46),
            ("119257908#2", 576.61),
            (":1842086610_1", 4.53),
            ("119257908#3", 17.49),
        ]

        super(I210SubNetwork, self).__init__(
            name=name,
            vehicles=vehicles,
            net_params=net_params,
            initial_config=initial_config,
            traffic_lights=traffic_lights,
        )
Exemplo n.º 30
0
    def __init__(self,
                 name,
                 vehicles,
                 net_params,
                 initial_config=InitialConfig(),
                 traffic_lights=TrafficLightParams()):

        self.speed_limit = net_params.additional_params["speed_limit"]
        self.use_traffic_lights = False
        self.len = [
            length["length_a"],
            length["length_b"],
            length["length_c"],
            length["length_d"],
            length["length_e"],
        ]
        self.num_edges = 25

        # name of the scenario (DO NOT CHANGE)
        self.name = "BobLoblawsLawBlog"

        super().__init__(name, vehicles, net_params, initial_config,
                         traffic_lights)