Search code examples
pythongraphtruncateosmnx

Truncating osmnx by bbox (or polygon): How to create dummy nodes at boundaries?


I am trying to truncate an osmnx graph by bbox. It works as per the documentation. The reproducible self-explanatory code is given below:

import numpy as np
import osmnx as ox
import geopandas as gpd
import networkx as nx
import matplotlib.pyplot as plt

N, S, E, W = 1.3235381983186159, 1.319982801681384, \
                           103.85361309942331 , 103.84833190057668,
graph = ox.graph_from_bbox(N, S, E, W, \
                           network_type='drive')
nodes= ox.graph_to_gdfs(graph, nodes=True, edges=False)
edges= ox.graph_to_gdfs(graph, edges=True, nodes=False)
fig, ax = ox.plot.plot_graph(
                graph,
                ax=None,
                figsize=(10, 10),
                bgcolor="white",
                node_color="red",
                node_size=5,
                node_alpha=None,
                node_edgecolor="none",
                node_zorder=1,
                edge_color="black",
                edge_linewidth=0.1,
                edge_alpha=None,
                show=False,
                close=False,
                save=False,
                bbox=None,
            )
W_ = W + (E-W) * 0.8
S_ = S + (N-S)*0.7
width = (E - W)*0.07 
height = (N - S)*0.1 

rect = plt.Rectangle((W_, S_), width, height, facecolor="green", alpha=0.3, edgecolor=None)
ax.add_patch(rect)
plt.show()

g_truncated = ox.truncate.truncate_graph_bbox(graph, S_ + height, S_, W_+width, W_, truncate_by_edge=False)
ox.plot_graph(g_truncated)

The bbox and the extracted graphs are shown below:

enter image description here

enter image description here

If I want to extract the subgraph such that I introduce dummy nodes at the boundaries, how can I do that? To be specific, I am trying to get a subgraph as it is visible in the picture. (i.e. a subgraph with 6 nodes in black as shown below:

enter image description here

Given the wide popularity of osmnx, does there exist a simple/straightforward way to acheive this?


Solution

  • - LOOP over edges in graph
      - LOOP over sides in box
         - IF box side intersects edge
            - remove edge
            - Add vertex at intersection point
            - Add edges between intersection vertex and original edge end points
    

    You will need to google 'calculate intersection point of two line segments'