mappymatch.maps.nx.nx_map#
Classes
|
A road network map implementation using NetworkX graphs. |
- class mappymatch.maps.nx.nx_map.NxMap(graph: MultiDiGraph)[source]#
A road network map implementation using NetworkX graphs.
NxMap wraps a NetworkX MultiDiGraph to represent a road network, providing efficient graph operations and spatial queries. It uses an R-tree spatial index for fast nearest-neighbor searches and supports both distance and time-based routing.
The underlying graph must have: - A pyproj CRS stored in graph.graph['crs'] - Road geometries (LineStrings) for each edge - Optional distance and time weights for routing
NxMap is the primary map implementation in mappymatch and integrates well with OSMnx for downloading OpenStreetMap data.
- Attributes:
g: The NetworkX MultiDiGraph representing the road network crs: The coordinate reference system of the map
- Examples:
>>> from mappymatch.maps.nx import NxMap >>> from mappymatch.constructs.geofence import Geofence >>> >>> # Load from a saved file >>> road_map = NxMap.from_file('network.pickle') >>> >>> # Create from OpenStreetMap data >>> geofence = Geofence.from_geojson('study_area.geojson') >>> road_map = NxMap.from_geofence( ... geofence, ... network_type=NetworkType.DRIVE, ... xy=True # Use Web Mercator for accurate distances ... ) >>> >>> # Use the map for routing and queries >>> nearest = road_map.nearest_road(coordinate) >>> path = road_map.shortest_path(origin, destination) >>> >>> # Save for later use >>> road_map.to_file('network.pickle')
- property distance_weight: str#
Get the name of the edge attribute used for distance-based routing.
This property identifies which edge attribute should be used when computing shortest paths based on physical distance (as opposed to time or other metrics).
- Returns:
The name of the distance weight attribute (e.g., 'kilometers', 'miles', 'length')
- property time_weight: str#
Get the name of the edge attribute used for time-based routing.
This property identifies which edge attribute should be used when computing fastest paths based on travel time (as opposed to distance or other metrics).
- Returns:
The name of the time weight attribute (e.g., 'minutes', 'seconds', 'travel_time')
- road_by_id(road_id: RoadId) Road | None[source]#
Get a road by its id
- Args:
road_id: The id of the road to get
- Returns:
The road with the given id, or None if it does not exist
- set_road_attributes(attributes: Dict[RoadId, Dict[str, Any]])[source]#
Add or update attributes for specific roads in the network.
This allows you to enrich the road network with custom data like measured speeds, traffic volumes, pavement conditions, etc. The new attributes become part of the road metadata and can be accessed in matching results.
- Args:
attributes: A dictionary mapping RoadId objects to dictionaries of attribute name-value pairs.
- Note:
After setting attributes, the internal spatial index is rebuilt. For bulk updates, it's more efficient to set all attributes in a single call.
- Examples:
>>> # Add custom speed data >>> speed_data = { ... RoadId('1', '2', 0): {'measured_speed_mph': 32.5}, ... RoadId('2', '3', 0): {'measured_speed_mph': 28.3} ... } >>> road_map.set_road_attributes(speed_data) >>> >>> # Access the new attributes >>> road = road_map.road_by_id(RoadId('1', '2', 0)) >>> print(road.metadata['measured_speed_mph']) # 32.5
- property roads: List[Road]#
Get a list of all the roads in the map
- Returns:
A list of all the roads in the map
- classmethod from_file(file: str | Path) NxMap[source]#
Load a NxMap from a saved file.
Supports loading from pickle (.pickle) or JSON (.json) formats. Pickle files are smaller and faster to load, while JSON files are human-readable and portable.
- Args:
file: Path to the saved map file (must have .pickle or .json extension)
- Returns:
A NxMap instance loaded from the file
- Raises:
TypeError: If the file extension is not .pickle or .json
- Examples:
>>> # Load from pickle (recommended for large networks) >>> road_map = NxMap.from_file('network.pickle') >>> >>> # Load from JSON >>> road_map = NxMap.from_file('network.json')
- classmethod from_geofence(geofence: Geofence, xy: bool = True, network_type: NetworkType = NetworkType.DRIVE, custom_filter: str | None = None, additional_metadata_keys: set | list | None = None, filter_to_largest_component: bool = True) NxMap[source]#
Download and create a NxMap from OpenStreetMap data within a geofence.
This method uses OSMnx to download road network data from OpenStreetMap for the specified geographic area. It's the primary way to create maps from online sources.
- Args:
geofence: A Geofence defining the area to download. Must be in EPSG:4326 (lat/lon). xy: If True, convert the network to Web Mercator (EPSG:3857) for accurate distance calculations. If False, keep in EPSG:4326. Default is True. network_type: The type of road network to download. Options include DRIVE, WALK, BIKE, DRIVE_SERVICE, ALL, etc. Default is DRIVE. custom_filter: A custom OSMnx filter string for advanced queries. Example: '["highway"~"motorway|primary"]' for only major roads. additional_metadata_keys: Set or list of OSM tag keys to preserve in road metadata. Example: {'maxspeed', 'highway', 'name', 'surface'} filter_to_largest_component: If True (default), keep only the largest strongly connected component to ensure routing works. If False, keep all components (may cause routing failures between disconnected parts).
- Returns:
A new NxMap with roads downloaded from OpenStreetMap
- Raises:
TypeError: If the geofence is not in EPSG:4326 MapException: If OSMnx is not installed
- Examples:
>>> from mappymatch.maps.nx import NxMap, NetworkType >>> from mappymatch.constructs.geofence import Geofence >>> >>> # Download driving network for a city >>> geofence = Geofence.from_geojson('city_boundary.geojson') >>> road_map = NxMap.from_geofence(geofence, network_type=NetworkType.DRIVE) >>> >>> # Download with additional metadata >>> road_map = NxMap.from_geofence( ... geofence, ... network_type=NetworkType.DRIVE, ... additional_metadata_keys={'maxspeed', 'lanes', 'name'} ... ) >>> >>> # Custom filter for only highways >>> road_map = NxMap.from_geofence( ... geofence, ... network_type=NetworkType.DRIVE, ... custom_filter='["highway"~"motorway|trunk|primary"]' ... )
- to_file(outfile: str | Path)[source]#
Save the map to a file for later use.
Saves the entire NxMap including the graph structure, geometries, CRS, and all metadata. Supports pickle (.pickle) and JSON (.json) formats.
- Args:
- outfile: Path where the file should be saved (extension determines format:
.pickle for binary pickle format, .json for JSON format)
- Raises:
TypeError: If the file extension is not .pickle or .json
- Examples:
>>> # Save as pickle (recommended - faster and smaller) >>> road_map.to_file('network.pickle') >>> >>> # Save as JSON (portable and human-readable) >>> road_map.to_file('network.json')
- nearest_road(coord: Coordinate) Road[source]#
A helper function to get the nearest road.
- Args:
coord: The coordinate to find the nearest road to
- Returns:
The nearest road to the coordinate
- shortest_path(origin: Coordinate, destination: Coordinate, weight: str | Callable | None = None) List[Road][source]#
Computes the shortest path between an origin and a destination
- Args:
origin: The origin coordinate destination: The destination coordinate weight: The weight to use for the path, either a string or a function
- Returns:
A list of roads that form the shortest path