### Install mosstool Package Source: https://mosstool.readthedocs.io/en/latest/index.html Install the mosstool package using pip. Ensure you are using Python 3.9 or higher. ```bash pip install mosstool ``` -------------------------------- ### build Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.builder.builder.html Initiates the map building process for a given map name. This is a primary function to start the map construction pipeline. ```APIDOC ## build ### Description Builds the map data for the specified map name. This function orchestrates the various steps involved in constructing the road network. ### Method `build(_name: str)` ### Parameters #### Path Parameters - **_name** (str) - Required - The name of the map to build. ``` -------------------------------- ### MultiPoint Geometry Example Source: https://mosstool.readthedocs.io/en/latest/03-data-format/01-map-format.html Represents a junction or a point of interest. The 'properties' field includes IDs of roads connected to this point. ```json { "type": "Feature", "id": 50000000013, "geometry": { "type": "MultiPoint", "coordinates": [ [ 113.906995, 22.552684 ] ] }, "properties": { "id": 50000000013, "in_ways": [ 974379908 ], "out_ways": [ 25436150, 953806719 ] } } ``` -------------------------------- ### LineString Geometry Example Source: https://mosstool.readthedocs.io/en/latest/03-data-format/01-map-format.html Represents a road segment with multiple coordinates. The 'properties' field contains detailed information about the road, such as lanes, speed limit, and highway type. ```json { "type": "Feature", "id": 25409666, "geometry": { "type": "LineString", "coordinates": [ [ 113.902208, 22.590202 ], [ 113.894869, 22.59406 ] ] }, "properties": { "id": 25409666, "lanes": 3, "highway": "motorway_link", "max_speed": 8.333333333333334, "name": "", "turn": ["ALS","S","SR"], # Around, Left, Staright | Staright | Staright, Right "width": 3.2 } } ``` -------------------------------- ### Building Class Initialization Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm.building.html Initializes the Building class with optional parameters for spatial bounds, projection, and proxy settings. ```APIDOC ## Class: Building ### Description Process OSM raw data to AOI as geojson format files. ### Initialization ```python Building(_proj_str: Optional[str] = None, _max_longitude: Optional[float] = None, _min_longitude: Optional[float] = None, _max_latitude: Optional[float] = None, _min_latitude: Optional[float] = None, _wikipedia_name: Optional[str] = None, _proxies: Optional[dict[str, str]] = None) ``` ### Args: * `proj_str` (Optional[str]): projection string, e.g. ‘epsg:3857’ * `max_longitude` (Optional[float]): max longitude * `min_longitude` (Optional[float]): min longitude * `max_latitude` (Optional[float]): max latitude * `min_latitude` (Optional[float]): min latitude * `wikipedia_name` (Optional[str]): wikipedia name of the area in OSM. * `proxies` (Optional[dict[str, str]]): proxies for requests, e.g. {‘http’: ‘http://localhost:1080’, ‘https’: ‘http://localhost:1080’} ``` -------------------------------- ### RoutingClient Initialization Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.route.client.html Initializes the RoutingClient with the server address and an option for a secure connection. ```APIDOC ## RoutingClient ### Description Client side of Routing service. ### Initialization Constructor of RoutingClient ### Args - **server_address** (str): Routing server address - **secure** (bool, optional): Whether to use a secure connection. Defaults to False. ``` -------------------------------- ### get_start_vector Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.line.html Retrieves the starting vector of a LineString. ```APIDOC ## get_start_vector ### Description Retrieves the starting vector of a LineString. ### Parameters #### Path Parameters - **_line** (shapely.geometry.LineString) - Required - The LineString for which to get the start vector. ### Returns - **vector**: The start vector of the LineString. ``` -------------------------------- ### get_start_vector Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.line.html Retrieves the starting vector of a LineString. ```APIDOC ## get_start_vector ### Description Get the start vector of a LineString. ### Parameters (Details not provided in source) ### Returns (Details not provided in source) ### Example (Details not provided in source) ``` -------------------------------- ### Generate Map Output with RoadNet and Building Source: https://mosstool.readthedocs.io/en/latest/02-quick-start/01-map-building.html This snippet demonstrates how to initialize RoadNet and Building objects with projection strings and bounding box coordinates, create road network and building data from GeoJSON files, and then use a Builder to construct the map. Finally, it converts the map to a protobuf format and saves it to a file. Ensure the 'cache' and 'data/temp' directories exist. ```python from mosstool.map.osm import RoadNet, Building from mosstool.map.builder import Builder from mosstool.util.format_converter import dict2pb from mosstool.type import Map rn = RoadNet( proj_str="+proj=tmerc +lat_0=22.54095 +lon_0=113.90899", max_latitude=39.92, min_latitude=39.78, max_longitude=116.32, min_longitude=116.40, ) roadnet = rn.create_road_net("cache/topo.geojson") building = Building( proj_str="+proj=tmerc +lat_0=22.54095 +lon_0=113.90899", max_latitude=39.92, min_latitude=39.78, max_longitude=116.32, min_longitude=116.40, ) aois = building.create_building("cache/aois.geojson") builder = Builder( net=roadnet, aois=aois, proj_str="+proj=tmerc +lat_0=22.54095 +lon_0=113.90899", ) m = builder.build("map_name") pb = dict2pb(m, Map()) with open("data/temp/map.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### _get_geo_pop Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.util.geo_match_pop.html Internal function to get geographic population data. ```APIDOC ## _get_geo_pop ### Description Internal function to get geographic population data. ### Method Not specified (likely a utility function within the module). ### Endpoint Not applicable (Python module function). ### Parameters Not specified in the source. ### Request Example Not applicable. ### Response Not specified in the source. ``` -------------------------------- ### mosstool.trip.sumo Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.html This subpackage handles integration with SUMO for trip-related functionalities. ```APIDOC ## `mosstool.trip.sumo` ### Description Handles trip-related functionalities integrated with SUMO. ### Submodules - `mosstool.trip.sumo.route`: For SUMO-specific route generation. ``` -------------------------------- ### merge_line_start_end Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.line.html Merges two line segments, preserving the start point of the first and the end point of the second. ```APIDOC ## merge_line_start_end ### Description Merges two line segments, preserving the start point of the first and the end point of the second. ### Parameters #### Path Parameters - **_line_start** (shapely.geometry.LineString) - Required - The first LineString, its start point is preserved. - **_line_end** (shapely.geometry.LineString) - Required - The second LineString, its end point is preserved. ### Returns - **LineString**: The merged LineString. ``` -------------------------------- ### Initialize UniformTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initialize `UniformTemplateGenerator` with minimum and maximum bounds for uniform distributions of vehicle attributes. ```python from mosstool.trip.generator import UniformTemplateGenerator ug = UniformTemplateGenerator( max_speed_min=90, max_speed_max=110, ) ``` -------------------------------- ### merge_line_start_end Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.line.html Merges two lines, keeping the start point of the first and the end point of the second unchanged. ```APIDOC ## merge_line_start_end ### Description Keep the start point of line_start and the end point of line_end unchanged, return merged result of the two lines. ### Parameters (Details not provided in source) ### Returns (Details not provided in source) ### Example (Details not provided in source) ``` -------------------------------- ### Convert SUMO Map and Route to Protobuf Source: https://mosstool.readthedocs.io/en/latest/04-move-from-sumo/02-trip-from-sumo.html This snippet demonstrates loading a SUMO map file, converting it to MOSS Protobuf Map format, and then converting SUMO trip routes to MOSS Protobuf Persons format. Ensure the `route_path` points to your SUMO trip file. ```python from mosstool.map.sumo.map import MapConverter from mosstool.trip.sumo.route import RouteConverter from mosstool.type import Map, Persons from mosstool.util.format_converter import dict2pb s2m = MapConverter( net_path="data/sumo/shenzhen.net.xml", ) m = s2m.convert_map() id2uid = s2m.get_sumo_id_mappings() map_pb = dict2pb(m, Map()) s2r = RouteConverter( converted_map=map_pb, sumo_id_mappings=id2uid, route_path="./data/sumo/trips.xml", ) r = s2r.convert_route() pb = dict2pb(r, Persons()) with open("data/temp/sumo_persons.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### Fill in Person Schedules with Routes Source: https://mosstool.readthedocs.io/en/latest/02-quick-start/02-trip-generation.html Connects to a local routing service to pre-route person schedules. It filters for persons with at least one valid trip and saves the results to a protobuf file. Ensure the routing service is active before running. The `RoutingClient` connects to the service, and `pre_route` asynchronously fetches the route. ```python client = RoutingClient("http://localhost:52101") ok_persons = [] for p in persons: p = await pre_route(client, p) if len(p.schedules) > 0 and len(p.schedules[0].trips) > 0: ok_persons.append(p) print(ok_persons) print("final length: ", len(ok_persons)) pb = Persons(persons=ok_persons) with open("data/temp/persons.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### Initialize ProbabilisticTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initialize `ProbabilisticTemplateGenerator` with discrete probabilities and ranges for generating vehicle attributes. ```python from mosstool.trip.generator import ProbabilisticTemplateGenerator g = ProbabilisticTemplateGenerator( headway_values=[1.5, 2, 2.5], headway_probabilities=[1, 1, 1] ) ``` -------------------------------- ### merge_way_nodes Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm._wayutil.html Merges two groups of nodes. It requires that at least one pair of endpoints of the two groups of nodes are the same. If not, an error will be reported. Examples: [1,2,3], [3,4,5] -> [1,2,3,4,5]; [3,2,1], [3,4,5] -> [3,2,1,4,5]. ```APIDOC ## Function: merge_way_nodes ### Description Merges two groups of nodes. It requires that at least one pair of endpoints of the two groups of nodes are the same. If not, an error will be reported. Examples: [1,2,3], [3,4,5] -> [1,2,3,4,5]; [3,2,1], [3,4,5] -> [3,2,1,4,5]. ### Parameters - **group1** (list) - The first group of nodes. - **group2** (list) - The second group of nodes. ``` -------------------------------- ### Initialize GaussianTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initialize `GaussianTemplateGenerator` with mean and standard deviation for Gaussian distributions of vehicle attributes. ```python from mosstool.trip.generator import GaussianTemplateGenerator gg = GaussianTemplateGenerator( max_speed_mean=50, max_speed_std=10, ) ``` -------------------------------- ### STA Class Initialization Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.gmns.sta.html Initializes the STA class with a map and working directory to perform static traffic assignment. ```APIDOC ## STA ### Description Initializes the STA class with a map and working directory. ### Parameters - **_map** (mosstool.type.Map_): The GMNS map object. - **_work_dir** (str_): The working directory for operations. ``` -------------------------------- ### Initialize CalibratedTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initialize `CalibratedTemplateGenerator` to generate `Person` objects with vehicle attributes calibrated for Chinese drivers. ```python from mosstool.trip.generator import CalibratedTemplateGenerator cg = CalibratedTemplateGenerator() ``` -------------------------------- ### Initialize and Generate O-D Matrix with Gravity Model Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initialize `GravityGenerator` and load area and population data to generate an O-D matrix. Requires `geopandas` and `numpy`. ```python import numpy as np import geopandas as gpd from mosstool.trip.generator import GravityGenerator gravity_generator = GravityGenerator( Lambda=0.2, Alpha=0.5, Beta=0.5, Gamma=0.5 ) area = gpd.read_file("data/gravitygenerator/Beijing-shp/beijing.shp") pops = np.load("data/gravitygenerator/worldpop.npy")[:, 0] gravity_generator.load_area(area) od_matrix = gravity_generator.generate(pops) ``` -------------------------------- ### mosstool.trip Module Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.html The mosstool.trip module provides functionalities for trip generation, routing, and integration with SUMO. ```APIDOC ## `mosstool.trip` ### Description Provides tools for generating and manipulating trips, including route planning and Sumo integration. ### Subpackages - `mosstool.trip.route`: For route-related functionalities. - `mosstool.trip.generator`: For generating various types of trips. - `mosstool.trip.sumo`: For integrating with SUMO (Simulation of Urban Mobility). - `mosstool.trip.gmns`: For GMNS (General Model for National Networks) related trip functionalities. ``` -------------------------------- ### Convert SUMO Traffic Lights to MOSS Map Source: https://mosstool.readthedocs.io/en/latest/04-move-from-sumo/01-map-from-sumo.html Incorporate SUMO traffic light data into the MOSS map by providing the `traffic_light_path` during `MapConverter` initialization. This allows for the conversion of traffic light configurations, including default fixed-time lights for junctions meeting specified criteria. ```python from mosstool.map.sumo.map import MapConverter from mosstool.type import Map from mosstool.util.format_converter import dict2pb s2m = MapConverter( net_path="data/sumo/shenzhen.net.xml", traffic_light_path="data/sumo/shenzhen.tll.xml" ) m = s2m.convert_map() pb = dict2pb(m, Map()) with open("data/temp/sumo_map_with_traffic_lights.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### GravityGenerator Class Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.gravity.html Initializes the GravityGenerator with parameters for the gravity model. ```APIDOC ## Class: GravityGenerator ### Description Generates an OD matrix within a given area, based on the gravity model. ### Initialization Args: * _Lambda (float): Parameter Lambda for the gravity model. * _Alpha (float): Parameter Alpha for the gravity model. * _Beta (float): Parameter Beta for the gravity model. * _Gamma (float): Parameter Gamma for the gravity model. * pops (list[int]): The population of each area. * dists (np.ndarray): The distance matrix between each pair of areas. ``` -------------------------------- ### mosstool.map.builder Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.html Utilities for building and constructing map data. ```APIDOC ## `mosstool.map.builder` ### Description Utilities for building and constructing map data. ### Module - `mosstool.map.builder.builder` ``` -------------------------------- ### RoadNet Class Initialization Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm.roadnet.html Initializes the RoadNet object with optional parameters for projection, bounding box, proxies, and way filtering. ```APIDOC ## RoadNet ### Description Processes OSM raw data to road and junction as geojson formats. ### Initialization ```python RoadNet(_proj_str : Optional[str] = None, _max_longitude : Optional[float] = None, _min_longitude : Optional[float] = None, _max_latitude : Optional[float] = None, _min_latitude : Optional[float] = None, _wikipedia_name : Optional[str] = None, _proxies : Optional[dict[str, str]] = None, _way_filter : Optional[list[str]] = None) ``` ### Args: - **proj_str** (Optional[str]): projection string, e.g. ‘epsg:3857’ - **max_longitude** (Optional[float]): max longitude - **min_longitude** (Optional[float]): min longitude - **max_latitude** (Optional[float]): max latitude - **min_latitude** (Optional[float]): min latitude - **wikipedia_name** (Optional[str]): wikipedia name of the area in OSM. - **proxies** (Optional[dict[str, str]]): proxies for requests, e.g. {‘http’: ‘http://localhost:1080’, ‘https’: ‘http://localhost:1080’} - **way_filter** (Optional[list[str]]): filter for ways when quering OSM ``` -------------------------------- ### _create_aio_channel Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.route.client.html Creates an asynchronous gRPC channel for client-server communication. ```APIDOC ## Function: _create_aio_channel ### Description Create a gRPC asynchronous channel. This is an internal helper function used for establishing communication with the routing service. ### Parameters This function does not explicitly list parameters in the provided documentation, but typically gRPC channel creation involves host and port information. ### Usage ```python # This is an internal function, direct usage might not be intended or stable. # Example of how it might be called internally: # channel = _create_aio_channel(host='localhost', port=50051) ``` ``` -------------------------------- ### Builder Class Initialization Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.builder.builder.html Initializes the Builder class to construct a map from road network data. It accepts various optional parameters to customize map generation, including areas of interest, points of interest, public transport data, and environmental data like population density and land use. ```APIDOC ## Class mosstool.map.builder.builder.Builder ### Description Builds a map from geojson format files. ### Initialization ```python Builder( net: Union[geojson.FeatureCollection, mosstool.type.Map], proj_str: Optional[str] = None, aois: Optional[geojson.FeatureCollection] = None, pois: Optional[geojson.FeatureCollection] = None, public_transport: Optional[dict[str, list]] = None, pop_tif_path: Optional[str] = None, landuse_shp_path: Optional[str] = None, traffic_light_min_direction_group: int = 3, default_lane_width: float = 3.2, gen_sidewalk_speed_limit: float = 0, gen_sidewalk_length_limit: float = 5.0, expand_roads: bool = False, road_expand_mode: Union[Literal[L], Literal[M], Literal[R]] = 'R', aoi_mode: Union[Literal[append], Literal[overwrite]] = 'overwrite', traffic_light_mode: Union[Literal[green_red], Literal[green_yellow_red], Literal[green_yellow_clear_red]] = 'green_yellow_clear_red', multiprocessing_chunk_size: int = 500, green_time: float = 30.0, yellow_time: float = 5.0, strict_mode: bool = False, merge_aoi: bool = True, correct_green_time: bool = False, split_too_long_walking_lanes: bool = False, max_walking_lane_length: float = 100.0, aoi_matching_distance_threshold: float = 30.0, pt_station_matching_distance_threshold: float = 30.0, pt_station_matching_distance_relaxation_threshold: float = 30.0, output_lane_length_check: bool = False, default_lane_turn_num_dict: dict[str, int] = {'AUXILIARY_SMALL_LEFT': 1, 'AUXILIARY_SMALL_RIGHT': 1, 'AUXILIARY_LARGE_LEFT': 1, 'AUXILIARY_LARGE_RIGHT': 1, 'AUXILIARY_AROUND': 1, 'MAIN_AROUND': 1, 'MAIN_SMALL_LEFT': 1, 'MAIN_LARGE_LEFT': 2, 'MAIN_SMALL_RIGHT': 1, 'MAIN_LARGE_RIGHT': 2}, min_straight_main_lane_ratio: float = 0.5, enable_tqdm: bool = False, workers: int = cpu_count() ) ``` ### Args: * **net** (Union[geojson.FeatureCollection, mosstool.type.Map]): road network * **proj_str** (str): projection string, if not provided, all coordinates in input geojson files will be seen as xyz coords. * **aois** (geojson.FeatureCollection): area of interest * **pois** (geojson.FeatureCollection): point of interest * **public_transport** (dict[str, list]): public transports in json format * **pop_tif_path** (str): path to population tif file * **landuse_shp_path** (str): path to landuse shape file * **traffic_light_min_direction_group** (int): minimum number of lane directions for traffic-light generation * **default_lane_width** (float): default lane width * **gen_sidewalk_speed_limit** (float): speed limit to generate sidewalk * **gen_sidewalk_length_limit** (float): length limit to generate sidewalk * **expand_roads** (bool): expand roads according to junction type * **road_expand_mode** (str): road expand mode * **aoi_mode** (str): aoi appending mode. `append` takes effect when the input `net` is Map, incrementally adding the input AOIs; `overwrite` only adds the input AOIs, ignoring existing ones. * **traffic_light_mode** (str): fixed time traffic-light generation mode. `green_red` means only green and red light will be generated, `green_yellow_red` means there will be yellow light between green and red light, `green_yellow_clear_red` add extra pedestrian clear red light. * **multiprocessing_chunk_size** (int): the maximum size of each multiprocessing chunk * **green_time** (float): green time * **yellow_time** (float): yellow time * **strict_mode** (bool): when enabled, causes the program to exit whenever a warning occurs * **merge_aoi** (bool): merge nearby aois * **correct_green_time** (bool): whether to correct green time, if true, the green time will be corrected to the minimum green time that satisfies one person to walk across the junction. * **split_too_long_walking_lanes** (bool): whether to split too long walking lanes * **max_walking_lane_length** (float): the maximum length of walking lanes, if the length of a walking lane is larger than this value, it will be split into two lanes. * **aoi_matching_distance_threshold** (float): Only AOIs whose distance to the road network is less than this value will be added to the map. * **pt_station_matching_distance_threshold** (float): Only stations whose distance to the road network is less than this value will be added to the map. * **pt_station_matching_distance_relaxation_threshold** (float): The relaxation distance threshold for stations whose distance to road network is larger than `pt_station_matching_distance_threshold`. * **output_lane_length_check** (bool): when enabled, will do value checks lane lengths in output map. * **default_lane_turn_num_dict** (dict[str,int]): default lane turn number dictionary. * **min_straight_main_lane_ratio** (float): the minimum ratio of straight main lanes to total main lanes. * **enable_tqdm** (bool): when enabled, use tqdm to show the progress bars. * **workers** (int): number of workers ``` -------------------------------- ### Initialize TripGenerator and Generate Trips Source: https://mosstool.readthedocs.io/en/latest/05-advanced-usage/02-trip-generation.html Initializes the TripGenerator with a given scenario 'm' and generates origin-destination (OD) persons based on an OD matrix and area data. The generated persons are then serialized and saved to a file. ```python from mosstool.trip.generator import TripGenerator tg = TripGenerator( m=m, ) od_persons = tg.generate_persons( od_matrix=od_matrix, areas=area, agent_num=10000, ) pb = Persons(persons=od_persons) with open("data/temp/persons.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### mosstool.trip.route Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.html This subpackage handles route-specific operations. ```APIDOC ## `mosstool.trip.route` ### Description Handles route-specific operations within the trip module. ### Submodules - `mosstool.trip.route.preroute`: For pre-routing calculations. - `mosstool.trip.route.client`: For client-side routing functionalities. ``` -------------------------------- ### Convert SUMO Map to MOSS Protobuf Source: https://mosstool.readthedocs.io/en/latest/04-move-from-sumo/01-map-from-sumo.html Use `MapConverter` to load a SUMO road network file and convert it into the MOSS Protobuf Map format. The converted map is then serialized and saved to a file. Ensure the `net_path` points to your SUMO `.net.xml` file. ```python from mosstool.map.sumo.map import MapConverter from mosstool.type import Map from mosstool.util.format_converter import dict2pb s2m = MapConverter( net_path="data/sumo/shenzhen.net.xml" ) m = s2m.convert_map() pb = dict2pb(m, Map()) with open("data/temp/sumo_map.pb", "wb") as f: f.write(pb.SerializeToString()) ``` -------------------------------- ### convert_route Method Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.sumo.route.html Public method to initiate the route conversion process. ```APIDOC ## Method convert_route() ### Description Converts the SUMO route file into the internal route format. ### Method `convert_route()` ``` -------------------------------- ### STA.run Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.gmns.sta.html Runs static traffic assignment on a GMNS map with persons, slicing trips into time intervals. ```APIDOC ## STA.run ### Description Runs static traffic assignment on a GMNS map with persons. Trips are sliced into time intervals, and static traffic assignment is performed for each interval. Route results are saved into persons. EXPERIMENTAL: This method is intended for trips with deterministic departure times. Other cases will be skipped. ### Parameters - **_persons** (mosstool.type.Persons_): Persons object containing trips. - **_time_interval** (int_): Time interval (in minutes) for static traffic assignment slicing. Recommended to be larger than the trip's travel time. Defaults to 60. - **_reset_routes** (bool_): Whether to reset routes of persons before running static traffic assignment. Defaults to False. - **_column_gen_num** (int_): Number of column generation iterations for static traffic assignment. Defaults to 10. - **_column_update_num** (int_): Number of column update iterations for static traffic assignment. Defaults to 10. ### Return - Persons: Persons object with updated route results. - dict: Statistics of the static traffic assignment. ``` -------------------------------- ### UniformTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.template.html Initializes a UniformTemplateGenerator with various parameters to define the distribution of trip characteristics. ```APIDOC ## UniformTemplateGenerator ### Description Initializes a UniformTemplateGenerator with various parameters to define the distribution of trip characteristics. ### Class Signature `_mosstool.trip.generator.template.UniformTemplateGenerator(_max_speed_min : Optional[float] = None_, _max_speed_max : Optional[float] = None_, _max_acceleration_min : Optional[float] = None_, _max_acceleration_max : Optional[float] = None_, _max_braking_acceleration_min : Optional[float] = None_, _max_braking_acceleration_max : Optional[float] = None_, _usual_braking_acceleration_min : Optional[float] = None_, _usual_braking_acceleration_max : Optional[float] = None_, _headway_min : Optional[float] = None_, _headway_max : Optional[float] = None_, _min_gap_min : Optional[float] = None_, _min_gap_max : Optional[float] = None_, _seed : int = 0_, _template : Optional[pycityproto.city.person.v2.person_pb2.Person] = None_) ### Initialization Args * `max_speed_min` (Optional[float]): Lower bound of the Uniform distribution for maximum speeds. * `max_speed_max` (Optional[float]): Higher bound of the Uniform distribution for maximum speeds. * `max_acceleration_min` (Optional[float]): Lower bound of the Uniform distribution for maximum accelerations. * `max_acceleration_max` (Optional[float]): Higher bound of the Uniform distribution for maximum accelerations. * `max_braking_acceleration_min` (Optional[float]): Lower bound of the Uniform distribution for maximum braking accelerations. * `max_braking_acceleration_max` (Optional[float]): Higher bound of the Uniform distribution for maximum braking accelerations. * `usual_braking_acceleration_min` (Optional[float]): Lower bound of the Uniform distribution for usual braking accelerations. * `usual_braking_acceleration_max` (Optional[float]): Higher bound of the Uniform distribution for usual braking accelerations. * `headway_min` (Optional[float]): Lower bound of the Uniform distribution for safe time headways. * `headway_max` (Optional[float]): Higher bound of the Uniform distribution for safe time headways. * `min_gap_min` (Optional[float]): Lower bound of the Uniform distribution for minimum gaps. * `min_gap_max` (Optional[float]): Higher bound of the Uniform distribution for minimum gaps. * `seed` (int): Seed value for the random number generator. * `template` (Optional[Person]): The template function of generated person object. ``` -------------------------------- ### mosstool.trip.generator Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.html This subpackage provides tools for generating trips. ```APIDOC ## `mosstool.trip.generator` ### Description Provides various methods for generating trips. ### Submodules - `mosstool.trip.generator.random`: For generating random trips. - `mosstool.trip.generator.template`: For generating trips based on templates. - `mosstool.trip.generator.AIGC`: For generating trips using AI. - `mosstool.trip.generator.generate_from_od`: For generating trips from Origin-Destination pairs. - `mosstool.trip.generator.gravity`: For generating trips using gravity models. ``` -------------------------------- ### mosstool.map.sumo Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.html Tools for converting map data to SUMO format. ```APIDOC ## `mosstool.map.sumo` ### Description Tools for converting map data to SUMO format. ### Module - `mosstool.map.sumo.map` ``` -------------------------------- ### Available Phase Structure Source: https://mosstool.readthedocs.io/en/latest/03-data-format/01-map-format.html Represents the feasible phases for a junction, typically used for algorithms like max pressure. It consists of the lighting control situation for each lane in the junction. ```protobuf message AvailablePhase { list[LightState] states } ``` -------------------------------- ### __all__ Data Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.bezier.html The __all__ variable defines the public API of the module. ```APIDOC ## Data __all__ ### Description Defines the module's public interface. ### Type list ### Value (The specific contents of __all__ are not detailed in the source.) ``` -------------------------------- ### Protobuf Map Header Format Source: https://mosstool.readthedocs.io/en/latest/03-data-format/01-map-format.html Contains metadata for a map, including its name, creation date, and bounding box coordinates. This format is compact and suitable for computer processing. ```json { "class": "header", "data": { "name": "hangzhou", "date": "Fri Aug 19 15:12:01 2023", "north": 20047.15060441926, "south": -32338.87769681991, "west": -18106.391120057444, "east": 23241.800579354865, "projection": "+proj=tmerc +lat_0=30.2435 +lon_0=120.1648" } } ``` -------------------------------- ### Bezier.Curve Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.bezier.html Generates a Bezier curve by interpolating points for a list of parameter values. ```APIDOC ## Bezier.Curve ### Description Returns a point interpolated by the Bezier process. ### Method Signature `_static _Curve(_t_values : Union[collections.abc.Sequence[float], numpy.ndarray]_, _points : list[numpy.ndarray]_) → numpy.ndarray` ### Parameters #### Arguments - **t_values** (Union[collections.abc.Sequence[float], numpy.ndarray]) - A list of floats or integers representing the parameterization values. - **points** (list[numpy.ndarray]) - A list of numpy arrays representing the points. ### Returns - **curve** (list[numpy.ndarray]) - A list of interpolated points forming the curve. ``` -------------------------------- ### mosstool.trip.route API Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.route.html The mosstool.trip.route module provides functionalities for route planning and manipulation. It exposes 'RoutingClient' for client-based routing operations and 'pre_route' for pre-routing computations. ```APIDOC ## Package Contents ### API mosstool.trip.route.__all__ [‘RoutingClient’, ‘pre_route’] ``` -------------------------------- ### TripGenerator Class Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.generate_from_od.html Initializes the TripGenerator with map data and various parameters controlling trip generation and mode assignment. ```APIDOC class TripGenerator(_m: mosstool.type.Map_, _pop_tif_path: Optional[str] = None, _activity_distributions: Optional[dict] = None, _driving_speed: float = 30 / 3.6, _parking_fee: float = 20.0, _driving_penalty: float = 0.0, _subway_speed: float = 35 / 3.6, _subway_penalty: float = 600.0, _subway_expense: float = 10.0, _bus_speed: float = 15 / 3.6, _bus_penalty: float = 600.0, _bus_expense: float = 5.0, _bike_speed: float = 10 / 3.6, _bike_penalty: float = 0.0, _template_func: collections.abc.Callable[[], mosstool.type.Person] = default_person_template_generator_, _add_pop: bool = False, _multiprocessing_chunk_size: int = 500, _workers: int = cpu_count()) ``` -------------------------------- ### Helper Functions Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.generate_from_od.html This section details various helper functions used within the `generate_from_od` module for processing and generating trip data. ```APIDOC ## Functions ### `geo_coords` #### Description Converts geographical coordinates to a specific format. ### `_get_mode` #### Description Determines the transportation mode based on input parameters. ### `_get_mode_with_distribution` #### Description Selects a transportation mode considering its distribution. ### `_match_aoi_unit` #### Description Matches an area of interest (AOI) unit. ### `_generate_unit` #### Description Generates a unit of trip data. ### `_process_agent_unit` #### Description Processes a unit of agent data for trip generation. ### `_fill_sch_unit` #### Description Fills schedule units. ### `_fill_person_schedule_unit` #### Description Fills personal schedule units. ``` -------------------------------- ### Building.create_building Method Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm.building.html Creates AOIs (Areas of Interest) from OpenStreetMap data, optionally using cached data and specifying an output path. ```APIDOC ## Method: create_building ### Description Create AOIs from OpenStreetMap. ### Signature ```python create_building(_output_path: Optional[str] = None, _osm_data_cache: Optional[list[dict]] = None, _osm_cache_check: bool = False) ``` ### Args: * `osm_data_cache` (Optional[list[dict]]): OSM data cache. * `output_path` (str): GeoJSON file output path. * `osm_cache_check` (bool): check the format of input OSM data cache. ### Returns: * AOIs in GeoJSON format. ``` -------------------------------- ### UniformTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.template.html A class for generating trip templates using uniform distributions. ```APIDOC ## Class: UniformTemplateGenerator ### Description Generates trip templates using uniform distributions, where all values within a range have an equal probability of being selected. ### Usage Create an instance of this class to generate uniform trip templates. ### Methods (Specific methods are not detailed in the source text.) ### Parameters (Parameters are not detailed in the source text.) ### Returns (Return values are not detailed in the source text.) ``` -------------------------------- ### ProbabilisticTemplateGenerator Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.template.html A class for generating trip templates based on probabilistic distributions. ```APIDOC ## Class: ProbabilisticTemplateGenerator ### Description Generates trip templates using probabilistic models. This class is designed to create diverse and realistic trip patterns by leveraging probability distributions. ### Usage Instantiate the class and use its methods to generate templates. ### Methods (Specific methods are not detailed in the source text, but would typically include initialization and generation functions.) ### Parameters (Parameters are not detailed in the source text.) ### Returns (Return values are not detailed in the source text.) ``` -------------------------------- ### create_pois Method Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm.point_of_interest.html Creates POIs from OpenStreetMap data. It can use cached OSM data or fetch new data, and save the output to a GeoJSON file. ```APIDOC ## PointOfInterest.create_pois ### Description Create POIs from OpenStreetMap. ### Args * `osm_data_cache` (Optional[list[dict]]): OSM data cache. * `output_path` (str): GeoJSON file output path. * `osm_cache_check` (bool): check the format of input OSM data cache. ### Returns * POIs in GeoJSON format. ``` -------------------------------- ### RouteConverter Class Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.sumo.route.html The RouteConverter class handles the conversion of SUMO route files. It takes a converted map, SUMO ID mappings, and the path to the route file as input. ```APIDOC ## Class RouteConverter ### Description Initializes the RouteConverter with map data, ID mappings, and route file paths. ### Initialization Args: * `converted_map` (pycityproto.city.map.v2.map_pb2.Map_): The converted map from SUMO network. * `sumo_id_mappings` (dict): The mapping from SUMO id to the unique id in the converted map. * `route_path` (str): The path to the SUMO route file. * `additional_path` (Optional[str]): The path to the additional file containing bus stops, charging stations, and parking areas. Defaults to None. * `seed` (Optional[int]): The random seed. Defaults to 0. ``` -------------------------------- ### Bezier.Points Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map._util.bezier.html Interpolates a list of points using the Bezier process for a given parameterization. ```APIDOC ## Bezier.Points ### Description Returns a list of points interpolated by the Bezier process. ### Method Signature `_static _Points(_t : float_, _points : list[numpy.ndarray]_) → list[numpy.ndarray]` ### Parameters #### Arguments - **t** (float/int) - A parameterization. - **points** (list[numpy.ndarray]) - A list of numpy arrays representing the points. ### Returns - **new_points** (list[numpy.ndarray]) - A list of interpolated points. ``` -------------------------------- ### test_pb2dict2pb Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.util.test.test_format_conveter.html Tests the conversion of Protocol Buffer messages to dictionaries and back to Protocol Buffer messages. ```APIDOC ## test_pb2dict2pb() ### Description Tests the conversion of Protocol Buffer messages to dictionaries and back to Protocol Buffer messages. ### Function Signature `mosstool.util.test.test_format_conveter.test_pb2dict2pb()` ``` -------------------------------- ### mosstool.trip.gmns Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.html This subpackage provides GMNS-specific trip functionalities. ```APIDOC ## `mosstool.trip.gmns` ### Description Provides GMNS (General Model for National Networks) specific trip functionalities. ### Submodules - `mosstool.trip.gmns.sta`: For GMNS static trip data. ``` -------------------------------- ### Dictionary to Protobuf Conversion Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.util.format_converter.html Converts a Python dictionary into a Protobuf message. ```APIDOC ## dict2pb ### Description Convert a Python dictionary to a protobuf message. ### Method `dict2pb(data_dict, message_type)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data_dict** (dict) - Required - The Python dictionary to convert. - **message_type** (ProtobufMessageType) - Required - The type of the Protobuf message to create. ``` -------------------------------- ### Builder Methods Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.builder.builder.html A collection of methods available on the Builder class for map construction and data processing. ```APIDOC ## Builder Methods This section lists the public methods of the `Builder` class that can be used to construct and manipulate map data. ### `Builder._junction_keys()` ### `Builder.map_roads()` ### `Builder.map_junctions()` ### `Builder.lane2data()` ### `Builder.map_lanes()` ### `Builder.no_left_walk()` ### `Builder.no_right_walk()` ### `Builder._connect_lane_group()` ### `Builder._delete_lane()` ### `Builder._reset_lane_uids()` ### `Builder.draw_junction()` ### `Builder.draw_walk_junction()` ### `Builder._classify()` ### `Builder._classify_main_way_ids()` ### `Builder._expand_roads()` ### `Builder._expand_remain_roads()` ### `Builder._add_sidewalk()` ### `Builder._create_junction_walk_pairs()` ### `Builder._create_junction_for_1_n()` ### `Builder._create_junction_for_n_n()` ### `Builder._create_walking_lanes()` ### `Builder._add_junc_lane_overlaps()` ### `Builder._add_driving_lane_group()` ### `Builder._add_traffic_light()` ### `Builder._add_public_transport()` ### `Builder._add_reuse_aoi()` ### `Builder._add_input_aoi()` ### `Builder._add_all_aoi()` ### `Builder.write2json()` ### `Builder._post_process()` ### `Builder.get_output_map()` ### `Builder.write2db()` ### `Builder.build()` ``` -------------------------------- ### fetch_overpass Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.map.osm._overpass.html POSTs a query to a public Overpass API interpreter and returns the JSON response. It attempts to use HTTPS mirrors in order and raises a RuntimeError if all attempts fail. It's recommended to set a descriptive User-Agent and Accept header to avoid 406 errors from some servers. ```APIDOC ## fetch_overpass ### Description POST `query` to a public interpreter and return JSON (decoded dict). Tries HTTPS mirrors in order; raises RuntimeError only if every attempt fails. ### Method POST ### Endpoint `/api/interpreter` (uses endpoints defined in `INTERPRETER_ENDPOINTS`) ### Parameters #### Path Parameters None #### Query Parameters - **_query** (str) - Required - The Overpass QL query string. - **_proxies** (Optional[dict[str, str]]) - Optional - Dictionary of proxy servers to use for the request. - **_timeout** (float) - Optional - The timeout in seconds for the request. Defaults to 300. ### Request Example ```python from mosstool.map.osm import _overpass query = "" proxies = { "http": "http://user:pass@host:port", "https": "http://user:pass@host:port", } timeout = 60 # Example of calling fetch_overpass (actual query string needed) # data = _overpass.fetch_overpass(query, _proxies=proxies, _timeout=timeout) ``` ### Response #### Success Response (200) - **dict[str, Any]** - A dictionary representing the decoded JSON response from the Overpass API. ``` -------------------------------- ### fill_person_schedules Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.trip.generator.generate_from_od.html Generates trip schedules for a given list of person objects. ```APIDOC ## fill_person_schedules ### Description Generates trip schedules for a given list of person objects, utilizing an OD matrix and area data. ### Method `fill_person_schedules(_input_persons : list[mosstool.type.Person]_, _od_matrix : mosstool.map._map_util.const.np.ndarray_, _areas : geopandas.geodataframe.GeoDataFrame_, _available_trip_modes : list[str] = ['drive', 'walk', 'bus', 'subway', 'taxi']_, _departure_time_curve : Optional[list[float]] = None_, _seed : int = 0_) → list[mosstool.type.Person]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **input_persons** (list[Person]) - Required - Input Person objects. * **od_matrix** (numpy.ndarray) - Required - The OD matrix. * **areas** (GeoDataFrame) - Required - The area data. Must contain a ‘geometry’ column with geometric information and a defined `crs` string. * **available_trip_modes** (list[str]) - Optional - available trip modes for person schedules. Defaults to ['drive', 'walk', 'bus', 'subway', 'taxi']. * **departure_time_curve** (Optional[list[float]]) - Optional - The departure time of a day (24h). The resolution must >=1h. * **seed** (int) - Optional - The random seed. Defaults to 0. ### Returns * **list[Person]** - The person objects with generated schedules. ### Request Example ```python # Example usage (assuming input_persons, od_matrix, and areas are defined) # persons_with_schedules = fill_person_schedules(input_persons, od_matrix, areas) ``` ### Response #### Success Response (200) * **list[Person]** - A list of Person objects with their schedules filled. ``` -------------------------------- ### dict2pb Source: https://mosstool.readthedocs.io/en/latest/apidocs/mosstool/mosstool.util.format_converter.html Convert a Python dictionary to a protobuf message. ```APIDOC ## dict2pb ### Description Convert a Python dictionary to a protobuf message. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (Python function) ### Endpoint None (Python function) ### Request Example None ### Response #### Success Response - **return value** (T) - The protobuf message. ### Response Example None ```