### Install test dependencies Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Install the required dependencies for testing the installation. ```bash pip install geopandas geopy ``` -------------------------------- ### Install from GitHub with pip Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Install the package directly from the GitHub repository using pip, which compiles the Rust wheels. Requires Rust installed. ```bash pip install --no-cache-dir -e git+https://github.com/a-b-street/osm2streets.git#egg=osm2streets_python\&subdirectory=osm2streets-py ``` -------------------------------- ### Run installation test Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Run the test script to verify the package works. Expected output includes 'osm2streets_python imported successfully.' and 'PyStreetNetwork instance created successfully! - package installed correctly'. ```bash python osm2streets_test.py ``` -------------------------------- ### Build and install wheel with maturin Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Build the Python module with maturin and install the resulting wheel locally. Requires Rust and maturin installed. ```bash maturin build --release ``` ```bash cd ./target/wheels/ ``` ```bash pip install [name-wheel].whl ``` -------------------------------- ### Output of testcase iteration Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/osm2streets_py_test.ipynb Example output from running the iteration script. Shows the list of testcase subfolders, an initialization error for 'frederiksted', and successful processing of 'kingsway_junction' with byte count and GeoJSON generation. ```text osm2streets_python imported successfully. Subfolders: ['frederiksted', 'kingsway_junction', 'degenerate_bug', 'service_road_loop', 'cycleway_rejoin_road', 'seattle_triangle', 'roosevelt_cycletrack', 'aurora_sausage_link', 'perth_peanut_roundabout', 'arizona_highways', 'montlake_roundabout', 'oneway_loop', 'seattle_slip_lane', 'leeds_cycleway', 'taipei', 'fremantle_placement', 'st_georges_cycletrack', 'northgate_dual_carriageway', 'tempe_split', 'tiny_loop', 'i5_exit_ramp', 'neukolln', 'overlapping_service_roads', 'quad_intersection', 'perth_stretched_lights', 'bristol_sausage_links', 'tiny_roundabout', 'tempe_light_rail', 'borough_sausage_links', 'bristol_contraflow_cycleway'] Error during initialization of test: frederiksted Loaded 556231 bytes from ../tests/src/kingsway_junction/input.osm. PyStreetNetwork instance created successfully! GeoJSON output successfully generated! ``` -------------------------------- ### Expected test output Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Expected output when running the installation test script. ```bash python osm2streets_test.py osm2streets_python imported successfully. Loaded 1466704 bytes from ../tests/src/neukolln/input.osm. PyStreetNetwork instance created successfully! - package installed correctly ``` -------------------------------- ### Development build and import check Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Build the module in development mode with maturin, then verify the import works from another folder. Requires Rust and maturin installed. ```bash maturin develop ``` ```python import osm2streets_python ``` -------------------------------- ### Run a single testcase with PyStreetNetwork Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/osm2streets_py_test.ipynb Loads OSM XML and boundary GeoJSON, initializes a PyStreetNetwork with specified options, generates network, lane, and block GeoJSON outputs, and visualizes them with Matplotlib. The snippet includes error handling for each step and uses a helper function to convert GeoJSON strings to GeoDataFrames. ```python #Load OSM XML data as bytes osm_file_path = "../tests/src/neukolln/input.osm" with open(osm_file_path, "rb") as file: osm_input = file.read() print(f"Loaded {len(osm_input)} bytes from {osm_file_path}.") # Load the GeoJSON boundary for clipping with open("../tests/src/neukolln/boundary.json", "r") as f: clip_pts_geojson = json.load(f) # Convert the JSON object to a string format for input clip_pts_geojson = json.dumps(clip_pts_geojson) #Define input options for PyStreetNetwork input_options = { "debug_each_step": False, "dual_carriageway_experiment": False, "sidepath_zipping_experiment": False, "inferred_sidewalks": True, "inferred_kerbs": True, "date_time": None, "override_driving_side": "Right" } input_options_json = json.dumps(input_options) #Initialize PyStreetNetwork try: network = osm2streets_python.PyStreetNetwork(osm_input, clip_pts_geojson, input_options_json) print("PyStreetNetwork instance created successfully!") except Exception as e: print(f"Error during initialization: {e}") # Generate and visualize the outputs # Function to load geojson output and convert to GeoDataFrame def load_geojson_to_gdf(geojson_str, crs=4326): geojson_data = json.loads(geojson_str) return gpd.GeoDataFrame.from_features(geojson_data["features"], crs=crs) # Generate main network output try: geojson_output = network.to_geojson_plain() gdf = load_geojson_to_gdf(geojson_output) print("GeoJSON output successfully generated!") except Exception as e: print(f"Error generating main network GeoJSON: {e}") # Generate lane polygons output try: geojson_lane_output = network.to_lane_polygons_geojson() gdf_lanes = load_geojson_to_gdf(geojson_lane_output) print("Lane GeoJSON output successfully generated!") except Exception as e: print(f"Error generating lane polygons GeoJSON: {e}") # Find and generate block polygons try: # Call find_all_blocks with sidewalks=True to include sidewalks in the block generation blocks_json = network.find_all_blocks(sidewalks=False) gdf_blocks = load_geojson_to_gdf(blocks_json) print("Block data successfully generated!") except Exception as e: print(f"Error finding or visualizing blocks: {e}") # Visualize the outputs with Matplotlib fig, ax = plt.subplots(1, 1, figsize=(10, 10)) gdf_blocks.plot(ax=ax, color='grey', edgecolor='black', alpha=0.4) gdf.plot(ax=ax, color='blue', edgecolor='k', label='Network') gdf_lanes.plot(ax=ax, column="type", label='Lanes', legend=True, legend_kwds={'title': "Lane Types"}) plt.title("OSM2Streets Network, Lanes, and Blocks") # Subplots fig, axes = plt.subplots(1, 3, figsize=(18, 6)) # Plot 1: Network Map gdf.plot(ax=axes[0], color='blue', edgecolor='k') axes[0].set_title("OSM2Streets Network") axes[0].set_axis_off() # Hide axes for cleaner presentation # Plot 2: Lanes Map (by "type" if available in data) gdf_lanes.plot(ax=axes[1], column="type", legend=True) axes[1].set_title("Lanes") axes[1].set_axis_off() # Plot 3: Intersections Map gdf_blocks.plot(ax=axes[2], color='grey', edgecolor='k') axes[2].set_title("Blocks") axes[2].set_axis_off() # Adjust layout for better spacing plt.tight_layout() plt.show() ``` -------------------------------- ### PyStreetNetwork.new Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Initializes a new PyStreetNetwork from raw OSM data and transformation configurations. ```APIDOC ## PyStreetNetwork.new(osm_input, clip_pts_geojson, input) ### Description Initializes a new PyStreetNetwork from raw OSM data and transformation configurations. ### Method new ### Parameters - **osm_input** (byte array) - Required - Byte array representing OSM data. - **clip_pts_geojson** (string) - Optional - GeoJSON string defining the area to clip. - **input** (string) - Required - JSON string parsed as ImportOptions to configure the import settings. ### Returns A new PyStreetNetwork instance. ``` -------------------------------- ### Iterate through all testcases with PyStreetNetwork Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/osm2streets_py_test.ipynb Iterates over all testcase subfolders under ../tests/src, loading each input.osm and boundary.json, then creates a PyStreetNetwork instance with the given input options. Generates GeoJSON outputs for the network, lane polygons, and blocks, and visualizes them with Matplotlib. The snippet includes error handling for each step and prints progress messages. ```python import osm2streets_python import geopandas as gpd import json import matplotlib.pyplot as plt print("osm2streets_python imported successfully.") import os # Specify the path to the folder folder_path = "../tests/src" # List to store subfolder names subfolders = [] # Loop through entries in the folder for entry in os.listdir(folder_path): # Construct the full path full_path = os.path.join(folder_path, entry) # Check if the entry is a folder if os.path.isdir(full_path): subfolders.append(entry) print("Subfolders:", subfolders) for testcase in subfolders: try: # Load OSM XML data as bytes osm_file_path = f"../tests/src/{testcase}/input.osm" with open(osm_file_path, "rb") as file: osm_input = file.read() print(f"Loaded {len(osm_input)} bytes from {osm_file_path}.") # Load the GeoJSON boundary for clipping with open(f"../tests/src/{testcase}/boundary.json", "r") as f: clip_pts_geojson = json.load(f) # Convert the JSON object to a string format for input clip_pts_geojson = json.dumps(clip_pts_geojson) # Define input options for PyStreetNetwork input_options = { "debug_each_step": False, "dual_carriageway_experiment": False, "sidepath_zipping_experiment": False, "inferred_sidewalks": True, "inferred_kerbs": True, "date_time": None, "override_driving_side": "Right" } input_options_json = json.dumps(input_options) # Initialize PyStreetNetwork try: network = osm2streets_python.PyStreetNetwork(osm_input, clip_pts_geojson, input_options_json) print("PyStreetNetwork instance created successfully!") except Exception as e: print(f"Error during initialization: {e}") # Generate and visualize the outputs # Function to load geojson output and convert to GeoDataFrame def load_geojson_to_gdf(geojson_str, crs=4326): geojson_data = json.loads(geojson_str) return gpd.GeoDataFrame.from_features(geojson_data["features"], crs=crs) # Generate main network output try: geojson_output = network.to_geojson_plain() gdf = load_geojson_to_gdf(geojson_output) print("GeoJSON output successfully generated!") except Exception as e: print(f"Error generating main network GeoJSON: {e}") # Generate lane polygons output try: geojson_lane_output = network.to_lane_polygons_geojson() gdf_lanes = load_geojson_to_gdf(geojson_lane_output) print("Lane GeoJSON output successfully generated!") except Exception as e: print(f"Error generating lane polygons GeoJSON: {e}") # Find all blocks using find_all_blocks function and visualize output # Find and generate block polygons try: # Call find_all_blocks with sidewalks=True to include sidewalks in the block generation blocks_json = network.find_all_blocks(sidewalks=False) gdf_blocks = load_geojson_to_gdf(blocks_json) print("Block data successfully generated!") except Exception as e: print(f"Error finding or visualizing blocks: {e}") # Visualize the outputs with Matplotlib fig, ax = plt.subplots(1, 1, figsize=(10, 10)) gdf_blocks.plot(ax=ax, color='grey', edgecolor='black', alpha=0.4) gdf.plot(ax=ax, color='blue', edgecolor='k', label='Network') gdf_lanes.plot(ax=ax, column="type", label='Lanes', legend=True, legend_kwds={'title': "Lane Types"}) plt.title(f"{testcase} - OSM2Streets Network, Lanes, and Blocks") plt.show() except Exception as e: print(f"Error during initialization of test: {testcase}") ``` -------------------------------- ### Run osm2streets tests Source: https://github.com/a-b-street/osm2streets/blob/main/tests/README.md Clones the repository, navigates to the tests directory, and runs the test suite in release mode. Omit --release for faster compilation but slower execution. ```shell git clone https://github.com/a-b-street/osm2streets cd osm2streets/tests cargo test --release ``` -------------------------------- ### PyStreetNetwork.way_to_xml Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Converts a specified way to an XML representation including its OSM tags. ```APIDOC ## PyStreetNetwork.way_to_xml(id) ### Description Converts a specified way to an XML representation including its OSM tags. ### Method way_to_xml ### Parameters - **id** (OSM ID) - Required - OSM ID of the way. ### Returns XML representation of the way. ``` -------------------------------- ### osm2lanes-js demo: import, initialize, and calculate lane specs Source: https://github.com/a-b-street/osm2streets/blob/main/osm2lanes-js/example.html This is the main JavaScript code for the osm2lanes-js demo page. It imports the WASM module, initializes it, sets up text areas with default OSM tags and config, and provides a function to fetch OSM way data from the OpenStreetMap API and compute lane specifications. ```javascript import init, { getLaneSpecs } from "https://unpkg.com/osm2lanes-js/osm2lanes_js.js"; // Or uncomment below and follow the instructions on the page to build locally //import init, { getLaneSpecs } from "./pkg/osm2lanes_js.js"; // You have to do this once to set up the WASM API await init(); ``` ```javascript let inputTagsTextArea = document.getElementById("input-tags"); let inputConfigTextArea = document.getElementById("input-config"); let outputTextArea = document.getElementById("output"); // Start with something initially inputTagsTextArea.value = JSON.stringify( { highway: "residential", lanes: "2", sidewalk: "left", }, null, 2 ); inputConfigTextArea.value = JSON.stringify( { // Only the first two are useful to set. These can be easily looked // up from a single lat/lon coordinate; if it's helpful, that can be // added to the API. driving_side: "Right", country_code: "US", // You can generally leave the rest of these alone bikes_can_use_bus_lanes: true, inferred_sidewalks: false, inferred_kerbs: true, parallel_street_parking_spot_length: 8.0, vehicle_width_for_parking_spots: 3.0, turn_on_red: true, include_railroads: true, }, null, 2 ); outputTextArea.value = getLaneSpecs( JSON.parse(inputTagsTextArea.value), JSON.parse(inputConfigTextArea.value) ); ``` ```javascript window.calculateForWay = async function () { outputTextArea.value = "Calculating..."; let wayID = document.getElementById("wayID").value; let url = `https://api.openstreetmap.org/api/0.6/way/${wayID}.json`; try { let resp = await fetch(url); let json = await resp.json(); let tags = json.elements[0].tags; inputTagsTextArea.value = JSON.stringify(tags, null, 2); outputTextArea.value = getLaneSpecs( JSON.parse(inputTagsTextArea.value), JSON.parse(inputConfigTextArea.value) ); } catch (err) { outputTextArea.value = `Problem looking up OSM way: ${err}`; } }; ``` -------------------------------- ### Import osm2streets_python modules Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/osm2streets_py_test.ipynb Imports the required modules for using osm2streets_python and verifies the import with a success message. ```python #Import necessary modules import osm2streets_python import geopandas as gpd import json import matplotlib.pyplot as plt print("osm2streets_python imported successfully.") ``` -------------------------------- ### PyStreetNetwork.get_debug_steps Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Retrieves a list of PyDebugStreets objects representing each debugging step applied to the street network. ```APIDOC ## PyStreetNetwork.get_debug_steps() ### Description Retrieves a list of PyDebugStreets objects representing each debugging step applied to the street network. ### Method get_debug_steps ### Parameters None ### Returns List of PyDebugStreets objects. ``` -------------------------------- ### PyStreetNetwork.find_all_blocks Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Finds and exports all blocks in the network as GeoJSON polygons. ```APIDOC ## PyStreetNetwork.find_all_blocks(sidewalks) ### Description Finds and exports all blocks in the network as GeoJSON polygons. ### Method find_all_blocks ### Parameters - **sidewalks** (boolean) - Required - Boolean indicating if sidewalks should be included. ### Returns GeoJSON polygons representing all blocks. ``` -------------------------------- ### PyStreetNetwork.get_osm_tags_for_way Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Retrieves OSM tags for a specified way as a JSON string. ```APIDOC ## PyStreetNetwork.get_osm_tags_for_way(id) ### Description Retrieves OSM tags for a specified way as a JSON string. ### Method get_osm_tags_for_way ### Parameters - **id** (OSM ID) - Required - OSM ID of the way. ### Returns JSON string containing OSM tags. ``` -------------------------------- ### PyStreetNetwork.to_geojson_plain Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports the entire street network as a plain GeoJSON. ```APIDOC ## PyStreetNetwork.to_geojson_plain() ### Description Exports the entire street network as a plain GeoJSON. ### Method to_geojson_plain ### Parameters None ### Returns GeoJSON representation of the street network. ``` -------------------------------- ### PyStreetNetwork.debug_movements_from_lane_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports movement information from a specific lane as a GeoJSON. ```APIDOC ## PyStreetNetwork.debug_movements_from_lane_geojson(road, index) ### Description Exports movement information from a specific lane as a GeoJSON. ### Method debug_movements_from_lane_geojson ### Parameters - **road** (road ID) - Required - Road ID containing the lane. - **index** (lane index) - Required - Lane index within the road. ### Returns GeoJSON representation of movement information from the specified lane. ``` -------------------------------- ### PyDebugStreets.get_label Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Returns a label for the debug street. ```APIDOC ## PyDebugStreets.get_label() ### Description Returns a label for the debug street. ### Method get_label ### Parameters None ### Returns Label string. ``` -------------------------------- ### PyDebugStreets.to_debug_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports debug information as GeoJSON, if available. ```APIDOC ## PyDebugStreets.to_debug_geojson() ### Description Exports debug information as GeoJSON, if available. ### Method to_debug_geojson ### Parameters None ### Returns GeoJSON representation of debug information. ``` -------------------------------- ### PyStreetNetwork.zip_sidepath Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Zips a sidepath (e.g., a bike lane or sidewalk) alongside a specified road. ```APIDOC ## PyStreetNetwork.zip_sidepath(road) ### Description Zips a sidepath (e.g., a bike lane or sidewalk) alongside a specified road. ### Method zip_sidepath ### Parameters - **road** (road ID) - Required - Road ID containing the sidepath. ### Returns None. ``` -------------------------------- ### PyStreetNetwork.to_lane_markings_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports lane markings as a GeoJSON. ```APIDOC ## PyStreetNetwork.to_lane_markings_geojson() ### Description Exports lane markings as a GeoJSON. ### Method to_lane_markings_geojson ### Parameters None ### Returns GeoJSON representation of lane markings. ``` -------------------------------- ### PyStreetNetwork.debug_clockwise_ordering_for_intersection_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports clockwise ordering information for a specific intersection as a GeoJSON. ```APIDOC ## PyStreetNetwork.debug_clockwise_ordering_for_intersection_geojson(intersection) ### Description Exports clockwise ordering information for a specific intersection as a GeoJSON. ### Method debug_clockwise_ordering_for_intersection_geojson ### Parameters - **intersection** (intersection ID) - Required - Intersection ID to be debugged. ### Returns GeoJSON representation of clockwise ordering information for the specified intersection. ``` -------------------------------- ### PyStreetNetwork.debug_clockwise_ordering_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports clockwise ordering information for intersections as a GeoJSON for debugging road connections. ```APIDOC ## PyStreetNetwork.debug_clockwise_ordering_geojson() ### Description Exports clockwise ordering information for intersections as a GeoJSON for debugging road connections. ### Method debug_clockwise_ordering_geojson ### Parameters None ### Returns GeoJSON representation of clockwise ordering information. ``` -------------------------------- ### PyStreetNetwork.to_lane_polygons_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports lane polygons as a GeoJSON. ```APIDOC ## PyStreetNetwork.to_lane_polygons_geojson() ### Description Exports lane polygons as a GeoJSON. ### Method to_lane_polygons_geojson ### Parameters None ### Returns GeoJSON representation of lane polygons. ``` -------------------------------- ### PyStreetNetwork.to_json Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports the entire StreetNetwork structure as a JSON string. ```APIDOC ## PyStreetNetwork.to_json() ### Description Exports the entire StreetNetwork structure as a JSON string. ### Method to_json ### Parameters None ### Returns JSON string representing the StreetNetwork. ``` -------------------------------- ### PyStreetNetwork.find_block Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Finds and exports a block (polygon) on a specific side of the road. ```APIDOC ## PyStreetNetwork.find_block(road, left, sidewalks) ### Description Finds and exports a block (polygon) on a specific side of the road. ### Method find_block ### Parameters - **road** (road ID) - Required - Road ID. - **left** (boolean) - Required - Boolean indicating if the left side of the road should be used. - **sidewalks** (boolean) - Required - Boolean indicating if sidewalks should be included. ### Returns GeoJSON polygon representing the block. ``` -------------------------------- ### PyStreetNetwork.collapse_short_road Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Collapses a specified short road by merging it with neighboring segments. ```APIDOC ## PyStreetNetwork.collapse_short_road(road) ### Description Collapses a specified short road by merging it with neighboring segments. ### Method collapse_short_road ### Parameters - **road** (road ID) - Required - Road ID. ### Returns None. ``` -------------------------------- ### PyStreetNetwork.overwrite_osm_tags_for_way Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Updates OSM tags for a specific way and applies changes to all affected roads and intersections. ```APIDOC ## PyStreetNetwork.overwrite_osm_tags_for_way(id, tags) ### Description Updates OSM tags for a specific way and applies changes to all affected roads and intersections. ### Method overwrite_osm_tags_for_way ### Parameters - **id** (OSM ID) - Required - OSM ID of the way. - **tags** (JSON string) - Required - JSON string representing the new OSM tags. ### Returns None. ``` -------------------------------- ### PyStreetNetwork.get_geometry_for_way Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Retrieves the buffered geometry of a specified way as a GeoJSON. ```APIDOC ## PyStreetNetwork.get_geometry_for_way(id) ### Description Retrieves the buffered geometry of a specified way as a GeoJSON. ### Method get_geometry_for_way ### Parameters - **id** (OSM ID) - Required - OSM ID of the way. ### Returns GeoJSON representation of the buffered geometry. ``` -------------------------------- ### PyStreetNetwork.collapse_intersection Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Collapses an intersection if it connects only two roads. ```APIDOC ## PyStreetNetwork.collapse_intersection(intersection) ### Description Collapses an intersection if it connects only two roads. ### Method collapse_intersection ### Parameters - **intersection** (intersection ID) - Required - Intersection ID. ### Returns None. ``` -------------------------------- ### PyStreetNetwork.debug_roads_connected_to_intersection_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports roads connected to a specified intersection as a GeoJSON. ```APIDOC ## PyStreetNetwork.debug_roads_connected_to_intersection_geojson(i) ### Description Exports roads connected to a specified intersection as a GeoJSON. ### Method debug_roads_connected_to_intersection_geojson ### Parameters - **i** (intersection ID) - Required - Intersection ID. ### Returns GeoJSON representation of roads connected to the specified intersection. ``` -------------------------------- ### PyStreetNetwork.to_intersection_markings_geojson Source: https://github.com/a-b-street/osm2streets/blob/main/osm2streets-py/README.md Exports intersection markings as a GeoJSON. ```APIDOC ## PyStreetNetwork.to_intersection_markings_geojson() ### Description Exports intersection markings as a GeoJSON. ### Method to_intersection_markings_geojson ### Parameters None ### Returns GeoJSON representation of intersection markings. ```