Ejemplo n.º 1
0
  def generate_incomplete_routes_flow(self,
                                      time_point,
                                      time_step_size,
                                      incomplete_routes_demands,
                                      routes_file):
    """Generates incomplete routes.

    All traffic flow should be sorted by the departure time.

    Args:
      time_point: the time point for scheduled demands.
      time_step_size: time step size for the demands.
      incomplete_routes_demands: incomplete_routes_demands =
      [('700010432', '706447588#1', 1.2), ('700010432', '5018655', 1)].
      routes_file: output demand file.
    """
    for edge_from, edge_to, rate in incomplete_routes_demands:
      flow_id = edge_from + '_to_' + edge_to + '_' + str(time_point)
      num_cars = np.random.poisson(time_step_size * rate, 1)
      token = ('    <flow id="%s" begin="%d" end="%d" number="%d" ' %
               (flow_id, time_point, time_point + time_step_size, num_cars))
      token += ('from="%s" to="%s" ' % (edge_from, edge_to))
      token += 'departPos="base" departLane="best" departSpeed="max"/>'
      if routes_file:
        file_util.append_line_to_file(routes_file, token)
    def generate_routes_flow(self, time_point, time_step_size, routes,
                             routes_demands, routes_file):
        """Generates traffic according to the demand rates.

    Args:
      time_point: The timestamp of the traffic.
      time_step_size: Time step size.
      routes: A list of routes.
      routes_demands: A list of route indices and corresponding demand rates.
      routes_file: Output file.
    """
        for route_index, rate in routes_demands:
            route_id = routes[route_index]['route_id']
            flow_id = route_id + '_' + str(time_point)
            num_cars = np.random.poisson(time_step_size * rate, 1)
            token = ('    <flow id="%s" begin="%d" end="%d" number="%d" ' % (
                flow_id,
                time_point,
                time_point + time_step_size,
                num_cars,
            ))
            token += ('route="%s" ' % (route_id))
            token += 'departPos="base" departLane="best" departSpeed="max"/>'
            if routes_file:
                file_util.append_line_to_file(routes_file, token)
    def write_evacuation_vehicle_path_demands(cls, zipped_demands,
                                              routes_file):
        r"""Generates demands for residential vehicles.

    The output demand xml file is in the following format. Each entry has the
    information for each vehicle.

    <routes>
        <vType id="passenger" vClass="passenger"/>
        <vehicle id="0" type="passenger" depart="0.00" departLane="best" \
            departPos="base" departSpeed="max">
            <route edges="-8943413#1 -8943413#0  8936970#3 -8936970#3"/>
        </vehicle>
        <vehicle id="0" type="passenger" depart="0.00" departLane="best" \
            departPos="base" departSpeed="max">
            <route edges="-8943413#1 -8943413#0  8936970#3 -8936970#3"/>
        </vehicle>
    </routes>

    Args:
      zipped_demands: The zipped demands from function
          `create_evacuation_shortest_path_demands`.
      routes_file: Output file.
    """
        demands = sorted(zipped_demands, key=lambda x: x.time)

        # Write demands file.
        if file_util.f_exists(routes_file):
            raise ValueError('%s already exists.' % routes_file)
        token = '<routes>\n'
        file_util.append_line_to_file(routes_file, token)
        token = '    <vType id="passenger" vClass="passenger"/>\n'
        file_util.append_line_to_file(routes_file, token)
        for demand in demands:
            if demand.num_cars == 0:
                logging.info('Road edge %s is too short, no demands.',
                             demand.origin)
                continue
            if demand.destination is None:
                logging.warning('Road edge %s is not connected to any exit.',
                                demand.origin)
                continue
            for vehicle_id in range(demand.num_cars):
                token = '    <vehicle id="%s" type="passenger" ' % (
                    demand.origin + '_' + str(vehicle_id))
                token += 'depart="%s" ' % demand.time
                token += 'departLane="best" departPos="random" departSpeed="max" '
                token += 'arrivalPos="max">\n'
                # Remember to add the origin edge to the path list. The shortest path
                # acquired from `create_evacuation_shortest_path_demands` does not
                # include the origin edge. This is due to the algorithm in
                # `sumolib.net.getRestrictedShortestPathsTreeToEdge`.
                token += '        <route edges="%s"/>' % (
                    demand.origin + ' ' + ' '.join(demand.route))
                token += '\n    </vehicle>'
                file_util.append_line_to_file(routes_file, token)
        token = '\n</routes>'
        file_util.append_line_to_file(routes_file, token)
        logging.info('Save file to: %s', routes_file)
Ejemplo n.º 4
0
    def test_append_line_to_file(self):
        r"""Tests the output file.

    The output file contains the following.
    hello world
    (hello) "world"
    (hello) !!!!!!!!!!! @~#$%^&*()_+"world"
    aaaaaaaa
    bbbbbbbbbb
    backslash\ backslash
    backslash\ backslash
    backslash\\ backslash
    backslash\\\ backslash
    backslash\\ backslash
    """
        input_lines = [
            'hello world', '(hello) "world"',
            '(hello) !!!!!!!!!!! @~#$%^&*()_+"world"', 'aaaaaaaa\nbbbbbbbbbb',
            r'backslash\ backslash', 'backslash\\ backslash',
            r'backslash\\ backslash', r'backslash\\\ backslash',
            'backslash\\\\ backslash'
        ]
        file_path = os.path.join(self._output_dir,
                                 'test_append_line_to_file.txt')
        for line in input_lines:
            file_util.append_line_to_file(file_path, line)
        self.assertTrue(file_util.f_exists(file_path))
        # Note that the linebreak in the input_lines[3].
        target_lines = [
            'hello world', '(hello) "world"',
            '(hello) !!!!!!!!!!! @~#$%^&*()_+"world"', 'aaaaaaaa',
            'bbbbbbbbbb', r'backslash\ backslash', 'backslash\\ backslash',
            r'backslash\\ backslash', r'backslash\\\ backslash',
            'backslash\\\\ backslash'
        ]
        with file_util.f_open(file_path, 'r') as actual_file:
            line_counter = 0
            read_lines = actual_file.readlines()
            for line in read_lines:
                # Linebreak is appended to the target string.
                self.assertEqual(line, target_lines[line_counter] + '\n')
                line_counter += 1
        target_line_number = len(target_lines)
        self.assertEqual(target_line_number, line_counter)
Ejemplo n.º 5
0
 def test_generate_incomplete_routes_flow(self):
     """This is an example of creating incomplete routes demands."""
     routes_file = os.path.join(self._output_dir,
                                'incomplete_route_demands.xml')
     token = '<routes>\n'
     file_util.append_line_to_file(routes_file, token)
     token = (
         '    <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
         'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
     file_util.append_line_to_file(routes_file, token)
     incomplete_routes_demands = [('700010432', '706447588#1', 1.2),
                                  ('700010432', '5018655', 1.0),
                                  ('700010432', '416943886#2', 0.2),
                                  ('700010432', '694409909#6', 0.2),
                                  ('27628577#0', '392017177#1', 0.2),
                                  ('27628577#0', '694409909#6', 0.2)]
     time_step_size = 100
     for time_point in range(0, 1200, time_step_size):
         self._random_traffic_generator.generate_incomplete_routes_flow(
             time_point, time_step_size, incomplete_routes_demands,
             routes_file)
     token = '\n</routes>'
     file_util.append_line_to_file(routes_file, token)
     # Test by counting number of lines in the file.
     with file_util.f_open(routes_file, 'r') as f:
         self.assertLen(f.readlines(), 78)
Ejemplo n.º 6
0
  def write_evacuation_vehicle_auto_routing_demands(cls,
                                                    zipped_demands,
                                                    exit_taz,
                                                    routes_file):
    r"""Generates demands for residential vehicles.

    The output demand xml file is in the following format. Each entry has the
    information for each vehicle. The exits are grouped into a traffic analysis
    zone (TAZ). See the link https://sumo.dlr.de/docs/Definition_of_Vehicles,
    _Vehicle_Types,_and_Routes.html#traffic_assignement_zones_taz for details.

    <routes>
        <vType id="passenger" vClass="passenger"/>
        <trip id="veh_1" depart="11" from="gneE8" departLane="best" \
            departPos="random" departSpeed="max" toTaz="exit_taz"/>
        <trip id="veh_2" depart="13" from="gneE9" departLane="best" \
            departPos="random" departSpeed="max"toTaz="exit_taz"/>
    </routes>

    Args:
      zipped_demands: The zipped demands from function
          `create_evacuation_demands`.
      exit_taz: The name of the TAZ.
      routes_file: Output file.
    """
    sorted_demands = sorted(zipped_demands, key=lambda x: x.time)

    if file_util.f_exists(routes_file):
      raise ValueError('%s already exists.' % routes_file)
    token = '<routes>\n'
    file_util.append_line_to_file(routes_file, token)
    token = '    <vType id="passenger" vClass="passenger"/>\n'
    file_util.append_line_to_file(routes_file, token)
    for demand in sorted_demands:
      if demand.num_cars == 0:
        logging.info('Road edge %s is too short, no demands.', demand.origin)
        continue
      for vehicle in range(demand.num_cars):
        token = '    <trip id="%s" type="passenger" ' % (
            demand.origin + '_' + str(vehicle))
        token += 'depart="%s" ' % demand.time
        token += 'from="%s" ' % demand.origin
        token += 'departLane="best" departPos="random" departSpeed="max" '
        token += 'arrivalPos="max" '
        token += 'toTaz="%s"/>' % exit_taz
        file_util.append_line_to_file(routes_file, token)
    token = '\n</routes>'
    file_util.append_line_to_file(routes_file, token)
    logging.info('Saved file to: %s', routes_file)
Ejemplo n.º 7
0
    def test_generate_freeway_routes_flow(self):
        """Test for the freeway demands generation workflow.

    All the unit tests have been done above, and there is no calculation in this
    test. So this one just verifies nothing is block in the workflow.
    """
        routes_file = os.path.join(self._output_dir,
                                   'freeway_routes_demands.xml')
        token = '<routes>\n'
        file_util.append_line_to_file(routes_file, token)
        token = (
            '    <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
            'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
        file_util.append_line_to_file(routes_file, token)
        input_output = self._random_traffic_generator.get_freeway_input_output(
        )
        token = '    <!-- freeway routes -->'
        file_util.append_line_to_file(routes_file, token)
        freeway_routes = self._random_traffic_generator.setup_shortest_routes(
            input_output,
            edge_type_list=random_traffic_generator.FREEWAY_EDGE_TYPES,
            routes_file=routes_file,
            figures_folder=self._output_dir)
        token = '    <!-- freeway demands -->'
        file_util.append_line_to_file(routes_file, token)
        time_step_size = 100
        for time_point in range(0, 1200, time_step_size):
            freeway_routes_demands = [(0, 0.3), (1, 0.3)]
            self._random_traffic_generator.generate_routes_flow(
                time_point, time_step_size, freeway_routes,
                freeway_routes_demands, routes_file)
        token = '\n</routes>'
        file_util.append_line_to_file(routes_file, token)
        # Test by counting number of lines in the file.
        with file_util.f_open(routes_file, 'r') as f:
            self.assertLen(f.readlines(), 36)
    def setup_shortest_routes(self,
                              input_output_pairs,
                              edge_type_list=None,
                              vehicle_type_list='passenger',
                              routes_file=None,
                              figures_folder=None):
        """Generates the routes on freeways only.

    Args:
      input_output_pairs: Input-->output pairs of edges.
      edge_type_list: Restrict the type of edges.
      vehicle_type_list: Restrict the type of vehicles.
      routes_file: The name of the output route file.
      figures_folder: Whether to create figures for the routes. If it is set as
          None, then no output figures. Since there chould be many figures for
          all the routes, individual figures are named, for example
          "edgeidfrom_edgeidto_route.pdf", automatically.

    Returns:
      A list of routes. Each entry has `edge_from`, `edge_to`, `path_edges`,
          `edges_ids`, `route_length`, `route_id`.
    """
        routes = []
        route_counter = 0
        for from_to_pair in input_output_pairs:
            valid_path = False
            edge_from, edge_to = from_to_pair
            path_edges, route_length = self._net.getRestrictedShortestPath(
                edge_from,
                edge_to,
                vehicleClass=vehicle_type_list,
                edgeType=edge_type_list)
            # Regardless of whether there is a path between them.
            if figures_folder is not None:
                selected_edges = [([edge_from], 'lime', 1),
                                  ([edge_to], 'red', 1)]
            if route_length < float('inf'):
                valid_path = True
                route_counter += 1
                edges_ids = [edge.getID() for edge in path_edges]
                edges_ids = ' '.join(edges_ids)
                route_id = (edge_from.getID() + '_to_' + edge_to.getID() +
                            '_' + str(route_counter))
                token = '    <route id="%s" edges="%s"/>' % (route_id,
                                                             edges_ids)
                if routes_file:
                    file_util.append_line_to_file(routes_file, token)
                route = {}
                route['edge_from'] = edge_from
                route['edge_to'] = edge_to
                route['path_edges'] = path_edges
                route['edges_ids'] = edges_ids
                route['route_length'] = route_length
                route['route_id'] = route_id
                routes.append(route)
            if figures_folder is not None and valid_path:
                selected_edges = [(path_edges, 'darkblue', 1)] + selected_edges
                figure_path = os.path.join(
                    figures_folder,
                    (edge_from.getID() + '_' + edge_to.getID() + '_route.pdf'))
                self._map_visualizer.plot_edges(selected_edges,
                                                output_figure_path=figure_path)
        if routes_file:
            file_util.append_line_to_file(routes_file, '')
        return routes
Ejemplo n.º 9
0
def generate_arterial_routes_demands_main(_):
    """This is an example of generating demands only on arterial and freeways.

  The generated routes do no have the ones only on freeways.
  """
    net = sumolib.net.readNet(FLAGS.sumo_net_file)
    traffic_generator = random_traffic_generator.RandomTrafficGenerator(net)
    routes_file = os.path.join(FLAGS.output_dir, 'arterial_routes_demands.xml')
    token = '<routes>\n'
    file_util.append_line_to_file(routes_file, token)
    token = ('    <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
             'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
    file_util.append_line_to_file(routes_file, token)
    # Setup freeway routes.
    figure_path = os.path.join(FLAGS.output_dir, 'freeway_routes.pdf')
    input_output = traffic_generator.get_freeway_input_output(
        figure_path=figure_path)
    token = '    <!-- freeway routes -->'
    file_util.append_line_to_file(routes_file, token)
    freeway_routes = traffic_generator.setup_shortest_routes(
        input_output,
        edge_type_list=random_traffic_generator.FREEWAY_EDGE_TYPES,
        routes_file=routes_file,
        figure_folder=None)
    # Setup arterial roads routes.
    figure_path = os.path.join(FLAGS.output_dir, 'arterial_routes.pdf')
    input_output = traffic_generator.get_arterial_input_output(
        figure_path=figure_path)
    token = '    <!-- arterial routes -->'
    file_util.append_line_to_file(routes_file, token)
    arterial_routes = traffic_generator.setup_shortest_routes(
        input_output,
        edge_type_list=(random_traffic_generator.FREEWAY_EDGE_TYPES +
                        random_traffic_generator.ARTERIAL_EDGE_TYPES),
        routes_file=routes_file,
        figure_folder=None)
    token = '    <!-- freeway + arterial roads demands -->'
    file_util.append_line_to_file(routes_file, token)
    time_step_size = 100
    for time_point in range(0, FLAGS.simulation_duration, time_step_size):
        freeway_routes_demands = [(0, 0.5), (1, 0.5), (2, 0.5), (3, 0.5)]
        traffic_generator.generate_routes_flow(time_point, time_step_size,
                                               freeway_routes,
                                               freeway_routes_demands,
                                               routes_file)
        arterial_routes_demands = []
        # arterial_routes_demands = [(route_id, 0.002) for route_id in
        #                            range(len(arterial_routes))]
        for route_index, route in enumerate(arterial_routes):
            if (route['edge_from'].getID() == '27628577#0'
                    and  # 101E to shoreN
                    route['edge_to'].getID() == '694409909#6'):
                arterial_routes_demands.append((route_index, 0.2))
            elif (route['edge_from'].getID() == '367132267#0'
                  and  # 85S to shoreN
                  route['edge_to'].getID() == '694409909#6'):
                arterial_routes_demands.append((route_index, 0.15))
            elif (route['edge_from'].getID() == '416943871#1'
                  and  # shoreS to shoreN
                  route['edge_to'].getID() == '694409909#6'):
                arterial_routes_demands.append((route_index, 0.15))
            else:
                arterial_routes_demands.append((route_index, 0.01))
        traffic_generator.generate_routes_flow(time_point, time_step_size,
                                               arterial_routes,
                                               arterial_routes_demands,
                                               routes_file)
    token = '\n</routes>'
    file_util.append_line_to_file(routes_file, token)