### Install mosstool Package Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/README.md Install the MObility Simulation System (MOSS) Toolbox using pip. This command is used for initial setup. ```bash pip install mosstool ``` -------------------------------- ### Protobuf Map Header Example Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/01-map-format.md This example demonstrates the structure of the header in the Protobuf map format. It includes metadata such as the map name, creation date, and bounding box coordinates. ```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" } } ``` -------------------------------- ### Complete Workflow: Map Building and Trip Generation Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt An end-to-end example demonstrating the creation of a road network, extraction of buildings, map building, and synthetic trip generation. Outputs are saved as Protocol Buffers. ```python from mosstool.map.osm import RoadNet, Building from mosstool.map.builder import Builder from mosstool.trip.generator import RandomGenerator, PositionMode from mosstool.util.format_converter import dict2pb from mosstool.type import Map, Persons from pycityproto.city.trip.v2.trip_pb2 import TripMode # Step 1: Create road network proj_str = "+proj=tmerc +lat_0=39.85 +lon_0=116.36" bbox = {"min_lat": 39.78, "max_lat": 39.92, "min_lon": 116.32, "max_lon": 116.40} roadnet = RoadNet(proj_str=proj_str, **{k.replace('_', '_'): v for k, v in [ ("min_latitude", bbox["min_lat"]), ("max_latitude", bbox["max_lat"]), ("min_longitude", bbox["min_lon"]), ("max_longitude", bbox["max_lon"]) ]}) roadnet = roadnet.create_road_net() # Step 2: Extract buildings/AOIs building = Building(proj_str=proj_str, min_latitude=bbox["min_lat"], max_latitude=bbox["max_lat"], min_longitude=bbox["min_lon"], max_longitude=bbox["max_lon"]) aois = building.create_building() # Step 3: Build complete map builder = Builder(net=roadnet, aois=aois, proj_str=proj_str, enable_tqdm=True) output_map = builder.build("simulation_map") pb_map = dict2pb(output_map, Map()) # Step 4: Generate trips generator = RandomGenerator(m=pb_map, position_modes=[PositionMode.AOI, PositionMode.AOI], trip_mode=TripMode.TRIP_MODE_DRIVE_ONLY) persons = generator.uniform(num=500, first_departure_time_range=(25200, 32400), schedule_interval_range=(3600, 7200), seed=42) # Step 5: Save outputs with open("map.pb", "wb") as f: f.write(pb_map.SerializeToString()) pb_persons = Persons(persons=persons) with open("persons.pb", "wb") as f: f.write(pb_persons.SerializeToString()) print(f"Created map with {len(output_map['lanes'])} lanes and {len(persons)} persons") ``` -------------------------------- ### Example Schedule Configuration Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/02-trip-format.md This JSON structure demonstrates a sample configuration for a schedule, including trip details, loop count, and departure time. It is used to define how a sequence of trips should be executed. ```json { "class": "person", "data": { "attribute": {}, "home": { "lane_position": { "lane_id": 130104, "s": 115.71712716462363 } }, "schedules": [ { "trips": [ { "mode": 2, "end": { "lane_position": { "lane_id": 22867, "s": 57.59639027707855 } }, "activity": "education", "routes": [ { "type": 1, "driving": { "road_ids": [ 200018684, 200007666, 200011019, 200000708, 200000709, 200000710, 200011018 ], "eta": 994.2598904793631 } } ] } ], "loop_count": 1, "departure_time": 31793.10010598981 } ], "vehicle_attribute": { "lane_change_length": 10, "min_gap": 1, "headway":1.5, "length": 5, "width": 2, "max_speed": 41.666666666666664, "max_acceleration": 3, "max_braking_acceleration": -10, "usual_acceleration": 2, "usual_braking_acceleration": -4.5, "model": "normal", "lane_max_speed_recognition_deviation": 1, "emission_attribute" { "weight": 18000, "type": 1, "coefficient_drag": 0.251, "lambda_s": 0.29, "frontal_area": 2.52, "fuel_efficiency": { "energy_conversion_efficiency": 0.013230000000000002 } } }, "bike_attribute": { "speed": 5 }, "pedestrian_attribute": { "speed": 1.34 }, "id": 0, "labels": {} } } ``` -------------------------------- ### Example Request Body Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/02-trip-format.md An example JSON payload demonstrating the structure of a request, including detailed vehicle and other attributes. ```APIDOC ## Example Request Body ### Description This example showcases a complete JSON object for a request, illustrating the nested structure of attributes like `home`, `schedules`, `vehicle_attribute`, and `emission_attribute`. ### Request Body Example ```json { "class": "person", "data": { "attribute": {}, "home": { "lane_position": { "lane_id": 130104, "s": 115.71712716462363 } }, "schedules": [ { "trips": [ { "mode": 2, "end": { "lane_position": { "lane_id": 22867, "s": 57.59639027707855 } }, "activity": "education", "routes": [ { "type": 1, "driving": { "road_ids": [ 200018684, 200007666, 200011019, 200000708, 200000709, 200000710, 200011018 ], "eta": 994.2598904793631 } } ] } ], "loop_count": 1, "departure_time": 31793.10010598981 } ], "vehicle_attribute": { "lane_change_length": 10, "min_gap": 1, "headway":1.5, "length": 5, "width": 2, "max_speed": 41.666666666666664, "max_acceleration": 3, "max_braking_acceleration": -10, "usual_acceleration": 2, "usual_braking_acceleration": -4.5, "model": "normal", "lane_max_speed_recognition_deviation": 1, "emission_attribute": { "weight": 18000, "type": 1, "coefficient_drag": 0.251, "lambda_s": 0.29, "frontal_area": 2.52, "fuel_efficiency": { "energy_conversion_efficiency": 0.013230000000000002 } } }, "bike_attribute": { "speed": 5 }, "pedestrian_attribute": { "speed": 1.34 }, "id": 0, "labels": {} } } ``` ``` -------------------------------- ### Get Start Vector Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map._util.line.md Retrieves the starting vector of a LineString. ```APIDOC ## mosstool.map._util.line.get_start_vector ### Description Calculates and returns the vector representing the start of a LineString. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **start_vector** (tuple or similar) - The vector at the start of the line. #### Response Example N/A ``` -------------------------------- ### AOI OSM Tags Example Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/01-map-format.md This example shows the structure of OSM tags for an Area of Interest (AOI), including landuse and name fields. The 'osm_tags' field can contain multiple dictionaries. ```json { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ 31.129645, 29.976933 ], [ 31.130864, 29.976937 ], [ 31.131819, 29.97694 ], [ 31.131828, 29.975046 ], [ 31.129654, 29.975039 ] ] ] }, "properties": { "id": 0, "osm_tags": [ { "landuse":"retail", "name:en": "Pyramid of Khafre", "name:zh": "卡夫拉金字塔" } ] } } ``` -------------------------------- ### MultiPoint Feature Example Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/01-map-format.md This is an example of a MultiPoint GeoJSON feature, commonly used to represent points on a map. ```json { "type": "Feature", "id": 50000000013, "geometry": { "type": "MultiPoint", "coordinates": [ [ 113.906995, 22.552684 ] ] }, "properties": { "id": 50000000013, "in_ways": [ 974379908 ], "out_ways": [ 25436150, 953806719 ] } } ``` -------------------------------- ### Connect Split Lines Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map._util.line.md Connects a list of split LineStrings, optionally with a start point. ```APIDOC ## mosstool.map._util.line.connect_split_lines ### Description Connects a list of LineStrings that may have been split. Can optionally use a start point and has a maximum line length parameter. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **connected_lines** (list) - A list of connected LineStrings. #### Response Example N/A ``` -------------------------------- ### Merge Line Start and End Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map._util.line.md Merges the start of one LineString with the end of another. ```APIDOC ## mosstool.map._util.line.merge_line_start_end ### Description Merges the start point of `line_start` with the end point of `line_end`. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **merged_line** (shapely.geometry.LineString) - The resulting merged LineString. #### Response Example N/A ``` -------------------------------- ### STA Class Initialization and Methods Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.trip.gmns.sta.md Details on how to initialize the STA class and its primary methods for running simulations. ```APIDOC ## class mosstool.trip.gmns.sta.STA ### Description Represents a Static Traffic Assignment (STA) model. ### Initialization ```python STA(map: mosstool.type.Map, work_dir: str) ``` #### Parameters - **map** (mosstool.type.Map) - The map object for the simulation. - **work_dir** (str) - The working directory for the simulation. ### Methods #### _get_od(start: mosstool.type.Position, end: mosstool.type.Position) ##### Description Internal method to get Origin-Destination (OD) pairs. #### _check_connection(start_road_id: int, end_road_id: int) ##### Description Internal method to check the connection between two road IDs. #### run(persons: mosstool.type.Persons, time_interval: int = 60, reset_routes: bool = False, column_gen_num: int = 10, column_update_num: int = 10) ##### Description Runs the STA simulation. ##### Parameters - **persons** (mosstool.type.Persons) - The persons object for the simulation. - **time_interval** (int) - The time interval for the simulation. Defaults to 60. - **reset_routes** (bool) - Whether to reset routes. Defaults to False. - **column_gen_num** (int) - Number of columns to generate. Defaults to 10. - **column_update_num** (int) - Number of columns to update. Defaults to 10. ``` -------------------------------- ### RoutingClient Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.trip.route.client.md Initializes the RoutingClient with the server address and security settings. ```APIDOC ## RoutingClient Initialization ### Description Initializes the RoutingClient with the server address and security settings. ### Parameters #### Path Parameters - **server_address** (str) - Required - The address of the routing server. - **secure** (bool) - Optional - Whether to use a secure connection (defaults to False). ### Request Example ```json { "server_address": "localhost:50051", "secure": false } ``` ### Response #### Success Response (200) - **Initialization successful** (None) - Indicates the client was successfully initialized. #### Response Example ```json { "message": "Client initialized successfully" } ``` ``` -------------------------------- ### AmapSubway Class Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.public_transport.get_subway.md Initializes the AmapSubway class with city information, projection, and Amap API key. ```APIDOC ## AmapSubway Class ### Description Provides functionality to retrieve and process public transport subway data using Amap. ### Initialization ```python AmapSubway(city_name_en_us: str, proj_str: str, amap_ak: str) ``` #### Parameters - **city_name_en_us** (str) - Required - The English name of the city. - **proj_str** (str) - Required - The projection string for the map data. - **amap_ak** (str) - Required - Your Amap API key. ``` -------------------------------- ### LineString GeoJSON Example Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/01-map-format.md This is an example of a LineString feature in GeoJSON format. It includes geometry with coordinates and properties such as road ID, lanes, highway type, speed limit, name, and turn restrictions. ```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"], "width": 3.2 } } ``` -------------------------------- ### Building Class Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.osm.building.md Details the parameters available for initializing the Building class, which is used for handling OpenStreetMap building data. ```APIDOC ## Class: Building ### Description Represents and processes building data from OpenStreetMap. ### 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) ``` ### Parameters #### Initialization Parameters - **proj_str** (Optional[str]) - Projection string for coordinate transformations. - **max_longitude** (Optional[float]) - Maximum longitude for the bounding box. - **min_longitude** (Optional[float]) - Minimum longitude for the bounding box. - **max_latitude** (Optional[float]) - Maximum latitude for the bounding box. - **min_latitude** (Optional[float]) - Minimum latitude for the bounding box. - **wikipedia_name** (Optional[str]) - Name to use for Wikipedia-based queries. - **proxies** (Optional[dict[str, str]]) - Dictionary of proxies to use for network requests. ``` -------------------------------- ### Get Line Angle Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map._util.line.md Calculates the angle of a LineString. ```APIDOC ## mosstool.map._util.line.get_line_angle ### Description Calculates the angle of a LineString. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **angle** (float) - The angle of the line. #### Response Example N/A ``` -------------------------------- ### Convert SUMO Networks to MOSS Protobuf Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Initializes MapConverter to convert SUMO road network files (.net.xml) to MOSS protobuf format, preserving lane configurations and traffic lights. Uses dict2pb to convert the resulting dictionary to a MOSS Map protobuf object. ```python from mosstool.map.sumo import MapConverter from mosstool.util.format_converter import dict2pb from mosstool.type import Map ``` -------------------------------- ### Convert SUMO Trips to MOSS Protobuf Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/04-move-from-sumo/02-trip-from-sumo.md Use this script to convert SUMO trip files (XML) to the MOSS Protobuf format. Ensure you have already performed a map conversion. The `route_path` can point to files containing either incomplete trips or complete routes. ```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()) ``` -------------------------------- ### GET /mosstool.map.public_transport/get_subway Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/index.md Retrieves subway-related public transport data. ```APIDOC ## GET /mosstool.map.public_transport/get_subway ### Description Retrieves subway-related public transport data. ### Method GET ### Endpoint /mosstool.map.public_transport/get_subway ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### GET /mosstool.map.public_transport/get_transitland Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/index.md Retrieves public transport data from Transitland. ```APIDOC ## GET /mosstool.map.public_transport/get_transitland ### Description Retrieves public transport data from the Transitland platform. ### Method GET ### Endpoint /mosstool.map.public_transport/get_transitland ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Initialize and Convert SUMO Network Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Initializes the MapConverter with SUMO network files and converts the map. Optional parameters include AOI/POI, bus stops, and signal timing files. ```python from mosstool.map.sumo import MapConverter from mosstool.util.format_converter import dict2pb from mosstool.type import Map # Initialize converter with SUMO network file converter = MapConverter( net_path="input/sumo_network.net.xml", default_lane_width=3.2, green_time=60.0, yellow_time=5.0, poly_path="input/sumo_poly.xml", # Optional: AOI/POI file additional_path="input/additional.xml", # Optional: bus stops traffic_light_path="input/traffic.xml", # Optional: signal timing traffic_light_min_direction_group=3, merge_aoi=False, enable_tqdm=True, ) # Convert the map converted_map = converter.convert_map() sumo_id_mappings = converter.get_sumo_id_mappings() # Save to protobuf pb_map = dict2pb(converted_map, Map()) with open("output/converted_map.pb", "wb") as f: f.write(pb_map.SerializeToString()) print(f"ID mappings: {len(sumo_id_mappings)} SUMO IDs converted") ``` -------------------------------- ### RandomGenerator Initialization and Methods Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.trip.generator.random.md Details on initializing the RandomGenerator and its primary methods for generating trips. ```APIDOC ## Class: RandomGenerator ### Description Generates random trips based on a given map, position modes, and trip mode. ### Initialization ```python RandomGenerator(m: pycityproto.city.map.v2.map_pb2.Map, position_modes: list[mosstool.trip.generator.random.PositionMode], trip_mode: pycityproto.city.trip.v2.trip_pb2.TripMode, template_func: collections.abc.Callable[[], pycityproto.city.person.v2.person_pb2.Person] = default_person_template_generator) ``` ### Methods #### _rand_position ##### Description Selects a random position from a list of candidates. ##### Parameters - **candidates** (Union[list[pycityproto.city.map.v2.map_pb2.Aoi], list[pycityproto.city.map.v2.map_pb2.Lane]]) - Description not available #### uniform ##### Description Generates a specified number of random trips with given time and schedule constraints. ##### Parameters - **num** (int) - The number of trips to generate. - **first_departure_time_range** (tuple[float, float]) - The range for the first departure time. - **schedule_interval_range** (tuple[float, float]) - The range for the schedule interval. - **seed** (Optional[int]) - An optional seed for the random number generator. - **start_id** (Optional[int]) - An optional starting ID for the generated trips. ##### Returns - list[pycityproto.city.person.v2.person_pb2.Person] - A list of generated person objects representing trips. ``` -------------------------------- ### GET /mosstool.map.public_transport/get_bus Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/index.md Retrieves bus-related public transport data. ```APIDOC ## GET /mosstool.map.public_transport/get_bus ### Description Retrieves bus-related public transport data. ### Method GET ### Endpoint /mosstool.map.public_transport/get_bus ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Get End Vector Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map._util.line.md Retrieves the ending vector of a LineString. ```APIDOC ## mosstool.map._util.line.get_end_vector ### Description Calculates and returns the vector representing the end of a LineString. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **end_vector** (tuple or similar) - The vector at the end of the line. #### Response Example N/A ``` -------------------------------- ### Building Class Methods Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.osm.building.md Documentation for the methods available within the Building class, including data querying, transformation, and creation. ```APIDOC ## Building Class Methods ### `_query_raw_data` #### Description Queries raw data, potentially from a cache. #### Method Internal method, typically not called directly. ### `_make_raw_aoi` #### Description Prepares raw Area of Interest data. #### Method Internal method, typically not called directly. ### `_transform_coordinate` #### Description Transforms a given coordinate. #### Method Internal method, typically not called directly. #### Parameters ##### Path Parameters - **c** (tuple[float, float]) - The coordinate tuple to transform. #### Returns - **list[float]** - The transformed coordinate as a list of floats. ### `create_building` #### Description Creates building data, optionally saving it to a file or using cached data. #### Method `create_building(output_path: Optional[str] = None, osm_data_cache: Optional[list[dict]] = None, osm_cache_check: bool = False)` #### Parameters ##### Path Parameters - **output_path** (Optional[str]) - The path to save the output data. If None, data is not saved to a file. - **osm_data_cache** (Optional[list[dict]]) - A list of dictionaries representing cached OSM data to use. - **osm_cache_check** (bool) - If True, checks for existing cache before querying. ``` -------------------------------- ### Construct Complete Map from GeoJSON Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Initializes a Builder with road network and AOI GeoJSON data, along with various simulation parameters. It then builds the map, converts it to protobuf format using dict2pb, and saves it to a file. Reports the number of lanes, roads, and junctions created. ```python from mosstool.map.builder import Builder from mosstool.util.format_converter import dict2pb from mosstool.type import Map from geojson import FeatureCollection # Load previously created GeoJSON files import json with open("output/topo.geojson") as f: roadnet = json.load(f) with open("output/aois.geojson") as f: aois = json.load(f) # Initialize Builder with road network and AOIs builder = Builder( net=FeatureCollection(roadnet["features"]), proj_str="+proj=tmerc +lat_0=39.85 +lon_0=116.36", aois=FeatureCollection(aois["features"]), pois=None, # Optional POI data public_transport=None, # Optional bus/subway routes pop_tif_path=None, # Optional WorldPop data default_lane_width=3.2, traffic_light_min_direction_group=3, green_time=30.0, yellow_time=5.0, traffic_light_mode="green_yellow_clear_red", aoi_matching_distance_threshold=30.0, enable_tqdm=True, workers=4, ) # Build the map and convert to protobuf output_map = builder.build("my_city_map") pb_map = dict2pb(output_map, Map()) # Save to file with open("output/map.pb", "wb") as f: f.write(pb_map.SerializeToString()) print(f"Built map with {len(output_map['lanes'])} lanes, " f"{len(output_map['roads'])} roads, " f"{len(output_map['junctions'])} junctions") ``` -------------------------------- ### Default Vehicle Template Generator Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Generates a Person object with fixed vehicle attributes. Useful for consistent simulation setups. ```python Person( attribute=PersonAttribute(), vehicle_attribute=VehicleAttribute( length=5, width=2, max_speed=150 / 3.6, max_acceleration=3, max_braking_acceleration=-10, usual_acceleration=2, usual_braking_acceleration=-4.5, headway=1.5, lane_max_speed_recognition_deviation=1.0, lane_change_length=10, min_gap=1, emission_attribute=EmissionAttribute( weight=2100, type=VehicleEngineType.VEHICLE_ENGINE_TYPE_FUEL, coefficient_drag=0.251, lambda_s=0.29, frontal_area=2.52, fuel_efficiency=VehicleEngineEfficiency( energy_conversion_efficiency=0.27 * 0.049 ), ), model="normal", ), pedestrian_attribute=PedestrianAttribute(speed=1.34, model="normal"), bike_attribute=BikeAttribute(speed=5, model="normal"), ) ``` -------------------------------- ### Create Road Network from OpenStreetMap Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Initializes RoadNet with geographic bounds and projection, then creates a road network topology saved to GeoJSON. Accesses default lane and speed settings. ```python from mosstool.map.osm import RoadNet # Initialize RoadNet with geographic bounds and projection rn = RoadNet( proj_str="+proj=tmerc +lat_0=39.85 +lon_0=116.36", max_latitude=39.92, min_latitude=39.78, max_longitude=116.40, min_longitude=116.32, wikipedia_name=None, # Optional: filter by OSM area name proxies=None, # Optional: HTTP proxies for requests way_filter=None, # Optional: custom road type filter ) # Create road network and save to GeoJSON roadnet = rn.create_road_net( output_path="output/topo.geojson", osm_data_cache=None, # Optional: pre-loaded OSM data osm_cache_check=False, # Validate cache format ) # Access default lane settings settings = rn.default_way_settings print(f"Default lanes: {settings['lane']}") print(f"Max speeds: {settings['max_speed']}") ``` -------------------------------- ### Lane Data Structure Example Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/03-data-format/01-map-format.md This JSON object represents a single lane within a road network. It includes geometric information, connectivity to adjacent lanes, and other relevant attributes. ```json { "class": "lane", "data": { "id": 0, "type": 1, "turn": 1, "max_speed": 11.11111111111111, "length": 405.77050412705626, "width": 3.2, "center_line": { "nodes": [ { "x": -333.409877363847, "y": 3892.689241038861 }, { "x": -270.3333568115683, "y": 3896.3202265304885 }, { "x": -150.42210531337474, "y": 3900.0537339189864 }, ] }, "predecessors": [ { "id": 89785, "type": 2 }, { "id": 89788, "type": 2 } ], "successors": [ { "id": 89790, "type": 1 }, { "id": 89791, "type": 1 } ], "left_lane_ids": [], "right_lane_ids": [], "parent_id": 200000000, "overlaps": [], "aoi_ids": [ 500001796, 500010169, 500010170, ] } } ``` -------------------------------- ### Protocol Buffer Conversion Utilities Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Provides functions for converting between Protocol Buffers, Python dictionaries, JSON strings, and MongoDB collections. Demonstrates conversion to and from dictionary, JSON, and MongoDB. ```python from mosstool.util.format_converter import ( pb2dict, dict2pb, pb2json, json2pb, pb2coll, coll2pb ) from mosstool.type import Map from pymongo import MongoClient # Load a protobuf map with open("output/map.pb", "rb") as f: pb_map = Map() pb_map.ParseFromString(f.read()) # Convert protobuf to dictionary map_dict = pb2dict(pb_map) print(f"Map has {len(map_dict['lanes'])} lanes") # Convert protobuf to JSON string map_json = pb2json(pb_map) print(f"JSON length: {len(map_json)} characters") # Convert dictionary back to protobuf new_pb_map = dict2pb(map_dict, Map()) # Convert JSON back to protobuf restored_map = json2pb(map_json, Map()) # MongoDB integration client = MongoClient("mongodb://localhost:27017") db = client["simulation"] collection = db["maps"] ``` -------------------------------- ### RoadNet Class Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.osm.roadnet.md Initializes the RoadNet object with optional parameters to define the bounding box, projection, and proxy settings for downloading OpenStreetMap data. ```APIDOC ## RoadNet Initialization ### Description Initializes the RoadNet object. Allows specifying the projection string, geographical boundaries (min/max longitude and latitude), a Wikipedia name for context, proxy settings for network requests, and a filter for ways. ### Method `__init__` ### Parameters - **proj_str** (Optional[str]) - The projection string for the coordinate system. - **max_longitude** (Optional[float]) - The maximum longitude for the bounding box. - **min_longitude** (Optional[float]) - The minimum longitude for the bounding box. - **max_latitude** (Optional[float]) - The maximum latitude for the bounding box. - **min_latitude** (Optional[float]) - The minimum latitude for the bounding box. - **wikipedia_name** (Optional[str]) - A name associated with the location, potentially for Wikipedia linking. - **proxies** (Optional[dict[str, str]]) - A dictionary of proxy servers to use for network requests. - **way_filter** (Optional[list[str]]) - A list of way IDs to filter the data. ### Request Example ```python from mosstool.map.osm.roadnet import RoadNet road_net = RoadNet(min_longitude=-74.0, max_longitude=-73.9, min_latitude=40.7, max_latitude=40.8, wikipedia_name='New York City') ``` ### Response Initializes the RoadNet object. No explicit return value for initialization. ``` -------------------------------- ### Calibrated Template Generator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Initializes a template generator using calibrated driving behavior parameters for Chinese drivers. Ideal for simulating realistic Chinese traffic scenarios. ```python from mosstool.trip.generator import CalibratedTemplateGenerator cg = CalibratedTemplateGenerator() ``` -------------------------------- ### Initialize TripGenerator and Generate Trips Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Initializes the TripGenerator with a map and generates person trips from an O-D matrix. The generated trips are then serialized and saved to a protobuf file. Requires `m`, `od_matrix`, and `area` to be defined. ```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()) ``` -------------------------------- ### AmapBus Class Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.public_transport.get_bus.md Initializes the AmapBus class with necessary city and API details. ```APIDOC ## AmapBus Class Initialization ### Description Initializes the AmapBus class with city names in English and Chinese, bus head information, and an Amap API key. ### Method Constructor ### Parameters - **city_name_en_us** (str) - Required - The English name of the city. - **city_name_zh_cn** (str) - Required - The Chinese name of the city. - **bus_heads** (str) - Required - Information about bus heads. - **amap_ak** (str) - Required - Your Amap API key. ``` -------------------------------- ### Save and Load Map from MongoDB Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Demonstrates saving a map to a MongoDB collection and loading it back. Ensure MongoDB is accessible and the collection is properly configured. ```python pb2coll(pb_map, collection, insert_chunk_size=500, drop=True) # Load from MongoDB collection loaded_map = coll2pb(collection, Map()) print(f"Loaded map: {loaded_map.header.name}") ``` -------------------------------- ### Convert SUMO Map to MOSS Protobuf Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/04-move-from-sumo/01-map-from-sumo.md Use MapConverter to load a SUMO net XML file and convert it to the MOSS Protobuf Map format. The converted map is then serialized and saved to a .pb file. Ensure the 'net_path' points to your SUMO road net XML. ```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()) ``` -------------------------------- ### MapConverter Class Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.map.sumo.map.md Details the parameters required for initializing the MapConverter class, which is used for converting SUMO map data. ```APIDOC ## Class: mosstool.map.sumo.map.MapConverter ### Description Initializes the MapConverter for processing SUMO map files. ### Parameters #### Initialization Parameters - **net_path** (str) - Required - Path to the SUMO network file. - **default_lane_width** (float) - Optional - Default width for lanes. Defaults to 3.2. - **green_time** (float) - Optional - Default green light duration. Defaults to 60.0. - **yellow_time** (float) - Optional - Default yellow light duration. Defaults to 5.0. - **poly_path** (Optional[str]) - Optional - Path to polygon files. - **additional_path** (Optional[str]) - Optional - Path for additional map data. - **traffic_light_path** (Optional[str]) - Optional - Path to traffic light configuration files. - **traffic_light_min_direction_group** (int) - Optional - Minimum direction group for traffic lights. Defaults to 3. - **merge_aoi** (bool) - Optional - Whether to merge AOI (Area of Interest) data. Defaults to False. - **enable_tqdm** (bool) - Optional - Whether to enable tqdm progress bars. Defaults to False. - **multiprocessing_chunk_size** (int) - Optional - Chunk size for multiprocessing. Defaults to 500. - **traffic_light_mode** (Union[Literal['green_red'], Literal['green_yellow_red'], Literal['green_yellow_clear_red']]) - Optional - Mode for traffic light timing. Defaults to 'green_yellow_clear_red'. - **workers** (int) - Optional - Number of worker processes to use. Defaults to CPU count. ``` -------------------------------- ### Probabilistic Template Generator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Initializes a template generator with discrete probabilities for vehicle attributes like headway. Use when specific headway values are known with associated probabilities. ```python from mosstool.trip.generator import ProbabilisticTemplateGenerator pg = ProbabilisticTemplateGenerator( headway_values=[1.5, 2, 2.5], headway_probabilities=[1, 1, 1] ) ``` -------------------------------- ### Convert SUMO Routes to MOSS Persons Source: https://context7.com/tsinghua-fib-lab/mosstool/llms.txt Initializes the RouteConverter with a converted map and SUMO ID mappings to convert SUMO route files to MOSS person format. Requires the converted map protobuf and SUMO ID mappings from MapConverter. ```python from mosstool.trip.sumo import RouteConverter from mosstool.util.format_converter import dict2pb from mosstool.type import Map, Persons # Load converted map with open("output/converted_map.pb", "rb") as f: m = Map() m.ParseFromString(f.read()) # Initialize route converter route_converter = RouteConverter( converted_map=m, sumo_id_mappings=sumo_id_mappings, # From MapConverter route_path="input/routes.rou.xml", additional_path="input/additional.xml", # Optional: stops seed=42, ) # Convert routes to persons persons_dict = route_converter.convert_route() # Save to protobuf pb_persons = dict2pb(persons_dict, Persons()) with open("output/persons.pb", "wb") as f: f.write(pb_persons.SerializeToString()) print(f"Converted {len(persons_dict['persons'])} agents") ``` -------------------------------- ### GravityGenerator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.trip.generator.gravity.md Initializes the GravityGenerator with specific parameters that influence gravity calculations. ```APIDOC ## GravityGenerator Initialization ### Description Initializes the GravityGenerator with parameters Lambda, Alpha, Beta, and Gamma. ### Parameters - **Lambda** (float) - Description of Lambda parameter. - **Alpha** (float) - Description of Alpha parameter. - **Beta** (float) - Description of Beta parameter. - **Gamma** (float) - Description of Gamma parameter. ``` -------------------------------- ### Generate Protobuf Map Format Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/02-quick-start/01-map-building.md This script fetches road network and AOI data, processes them into GeoJSON, and then converts them into a Protobuf Map format. Ensure the bounding box coordinates and projection string are correctly set for your area of interest. The output is saved as a binary Protobuf file. ```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()) ``` -------------------------------- ### Gaussian Template Generator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Initializes a template generator with Gaussian distributions for vehicle attributes, such as max speed. Suitable for simulations requiring normally distributed variations. ```python from mosstool.trip.generator import GaussianTemplateGenerator gg = GaussianTemplateGenerator( max_speed_mean=50, max_speed_std=10, ) ``` -------------------------------- ### Uniform Template Generator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/05-advanced-usage/02-trip-generation.md Initializes a template generator with uniform distributions for vehicle attributes, like max speed. Use when attributes can vary within a defined range. ```python from mosstool.trip.generator import UniformTemplateGenerator ug = UniformTemplateGenerator( max_speed_min=90, max_speed_max=110, ) ``` -------------------------------- ### TripGenerator Initialization Source: https://github.com/tsinghua-fib-lab/mosstool/blob/main/docs/apidocs/mosstool/mosstool.trip.generator.generate_from_od.md Initializes the TripGenerator with various parameters that influence trip generation. ```APIDOC ## TripGenerator Initialization ### Description Initializes the TripGenerator with map data and optional parameters for activity distributions, driving speeds, penalties, and other simulation settings. ### Method `__init__` ### Parameters - **m** (mosstool.type.Map) - Required - The map object to be used for trip generation. - **pop_tif_path** (Optional[str]) - Optional - Path to a population TIF file. - **activity_distributions** (Optional[dict]) - Optional - Dictionary of activity distributions. - **driving_speed** (float) - Optional - Default: 30 / 3.6 - Driving speed in meters per second. - **parking_fee** (float) - Optional - Default: 20.0 - Parking fee. - **driving_penalty** (float) - Optional - Default: 0.0 - Penalty for driving. - **subway_speed** (float) - Optional - Default: 35 / 3.6 - Subway speed in meters per second. - **subway_penalty** (float) - Optional - Default: 600.0 - Penalty for subway. - **subway_expense** (float) - Optional - Default: 10.0 - Expense for subway. - **bus_speed** (float) - Optional - Default: 15 / 3.6 - Bus speed in meters per second. - **bus_penalty** (float) - Optional - Default: 600.0 - Penalty for bus. - **bus_expense** (float) - Optional - Default: 5.0 - Expense for bus. - **bike_speed** (float) - Optional - Default: 10 / 3.6 - Bike speed in meters per second. - **bike_penalty** (float) - Optional - Default: 0.0 - Penalty for bike. - **template_func** (collections.abc.Callable[[], mosstool.type.Person]) - Optional - Default: default_person_template_generator - Function to generate person templates. - **add_pop** (bool) - Optional - Default: False - Whether to add population. - **multiprocessing_chunk_size** (int) - Optional - Default: 500 - Chunk size for multiprocessing. - **workers** (int) - Optional - Default: cpu_count() - Number of workers for multiprocessing. ```