To modify your script so that trench lines (connections) are preferentially drawn on one side of the roads, with the option to use the opposite side only as a last resort, you can follow these steps:
- Define Side Preference: Decide whether you want to favor the left or right side of the roads.
- Offset Lines: Use
shapely's parallel_offset to shift the connection lines to the preferred side.
- Check for Road Crossings: Ensure that the offset lines do not cross any road geometries.
- Fallback Mechanism: If shifting to the preferred side causes crossings, attempt to shift to the opposite side.
Below is the modified script incorporating these changes:
import geopandas as gpd
import osmnx as ox
import numpy as np
from shapely.geometry import Point, LineString
from shapely.ops import unary_union
import networkx as nx
from fastkml import kml
# Define verbose logging function
def log(message):
print(message)
# Parameters
SIDE_PREFERENCE = 'left' # Options: 'left', 'right'
OFFSET_DISTANCE = 0.00001 # Degrees; adjust as needed
# Load the input shapefile
input_layer_path = r"D:\Piketberg Erven.shp"
log("Loading shapefile...")
erven_gdf = gpd.read_file(input_layer_path)
# Generate centroids for all the polygons
log("Calculating centroids...")
erven_gdf['centroid'] = erven_gdf.geometry.centroid
centroids_gdf = gpd.GeoDataFrame(geometry=erven_gdf['centroid'], crs=erven_gdf.crs)
# Create a buffered area around the polygons
log("Creating buffered area...")
buffer_distance = 0.00005 # Adjust buffer distance as needed
buffered_gdf = erven_gdf.buffer(buffer_distance)
dissolved_buffer = gpd.GeoDataFrame(geometry=[unary_union(buffered_gdf.geometry)], crs=erven_gdf.crs)
# Get the bounds for OSM data download
bounds = dissolved_buffer.total_bounds # (west, south, east, north)
west, south, east, north = bounds
# Download road network data within the buffered area
try:
log("Downloading road network data from OSM...")
G = ox.graph_from_bbox(north, south, east, west, network_type='drive')
log("OSM data successfully loaded.")
except ox._errors.InsufficientResponseError:
log("No data found for the specified area. Please check the bounding box or network type.")
exit(1)
# Convert graph to GeoDataFrames
node_gdf, edge_gdf = ox.graph_to_gdfs(G)
# Get dissolved polygon edges as network lines
log("Extracting dissolved polygon edges...")
dissolved_lines = edge_gdf[edge_gdf.geometry.intersects(dissolved_buffer.geometry.iloc[0])]
# Create aggregation nodes (boundary boxes)
log("Creating boundary boxes for aggregation nodes...")
boundary_boxes = []
for idx in range(0, len(erven_gdf), 2): # One box for every two erven polygons
subset = erven_gdf.geometry.iloc[idx:idx+2]
box_geometry = subset.unary_union.envelope
boundary_boxes.append(box_geometry)
boundary_boxes_gdf = gpd.GeoDataFrame(geometry=boundary_boxes, crs=erven_gdf.crs)
# Place a central node
log("Calculating central point...")
central_point = dissolved_buffer.geometry.iloc[0].centroid
# Create an aggregation node GeoDataFrame
aggregation_nodes_gdf = gpd.GeoDataFrame(geometry=[central_point], crs=erven_gdf.crs)
aggregation_nodes_gdf['label'] = 'Central Node'
# Snap centroids and the central point to the nearest nodes in the graph
def snap_to_nearest_node(point, graph):
nearest_node = ox.distance.nearest_nodes(graph, point.x, point.y)
return nearest_node
# Find the nearest nodes for each centroid and the central point
log("Finding nearest nodes for centroids...")
centroid_nodes = [snap_to_nearest_node(centroid, G) for centroid in centroids_gdf.geometry]
central_node = snap_to_nearest_node(central_point, G)
# Check if nodes are valid
valid_centroid_nodes = [node for node in centroid_nodes if node in G.nodes()]
if not valid_centroid_nodes:
log("No valid centroid nodes found within the network.")
exit(1)
# Define function to offset LineString to a preferred side
def offset_line(line, side, distance):
try:
offset = line.parallel_offset(distance, side=side, join_style=2, resolution=16)
# parallel_offset can return MultiLineString if the offset causes splitting
if offset.type == 'MultiLineString':
# Merge into single LineString
offset = unary_union(offset)
return offset
except Exception as e:
log(f"Offsetting failed: {e}")
return line # Return original line if offset fails
# Function to create trench lines with side preference
def create_trench_lines(G, centroids, central_node, side_pref, offset_dist, roads_gdf):
trench_lines = []
for centroid_node in centroids:
try:
path = nx.shortest_path(G, source=centroid_node, target=central_node, weight='length')
# Get the geometry of the path
path_lines = ox.utils_graph.get_route_edge_attributes(G, path, 'geometry')
if not path_lines:
# If geometry is missing, create LineStrings between nodes
path_lines = []
for u, v in zip(path[:-1], path[1:]):
point_u = Point((G.nodes[u]['x'], G.nodes[u]['y']))
point_v = Point((G.nodes[v]['x'], G.nodes[v]['y']))
path_lines.append(LineString([point_u, point_v]))
# Merge all segments into a single LineString or MultiLineString
path_geom = unary_union(path_lines)
# Offset the trench line to the preferred side
offset_geom = offset_line(path_geom, side_pref, offset_dist)
# Check for intersections with roads
if roads_gdf.geometry.intersects(offset_geom).any():
# If intersects, try the opposite side
opposite_side = 'right' if side_pref == 'left' else 'left'
log(f"Trench line from node {centroid_node} intersects roads. Trying opposite side.")
offset_geom = offset_line(path_geom, opposite_side, offset_dist)
# If still intersects, use original path without offset
if roads_gdf.geometry.intersects(offset_geom).any():
log(f"Trench line from node {centroid_node} still intersects roads after offset. Using original path.")
offset_geom = path_geom
trench_lines.append(offset_geom)
except nx.NetworkXNoPath:
log(f"No path found from centroid node {centroid_node} to central node {central_node}.")
return trench_lines
# Create trench lines with side preference
log("Creating trench lines with side preference...")
roads_gdf = edge_gdf # Assuming roads_gdf contains road geometries
trench_lines = create_trench_lines(
G,
valid_centroid_nodes,
central_node,
SIDE_PREFERENCE,
OFFSET_DISTANCE,
roads_gdf
)
# Create a GeoDataFrame for trench lines
trench_gdf = gpd.GeoDataFrame(geometry=trench_lines, crs=erven_gdf.crs)
# Create KML output
log("Creating KML output...")
k = kml.KML()
document = kml.Document(ns='http://www.opengis.net/kml/2.2')
k.append(document)
# Add central node to KML
placemark_central = kml.Placemark(ns='http://www.opengis.net/kml/2.2')
placemark_central.name = "Central Node"
placemark_central.geometry = central_point
document.append(placemark_central)
# Add boundary boxes to KML
for idx, boundary in enumerate(boundary_boxes):
placemark_boundary = kml.Placemark(ns='http://www.opengis.net/kml/2.2')
placemark_boundary.name = f'Boundary Box {idx+1}'
placemark_boundary.geometry = boundary.centroid
document.append(placemark_boundary)
# Add trench lines to KML
for idx, trench in trench_gdf.geometry.iteritems():
placemark_line = kml.Placemark(ns='http://www.opengis.net/kml/2.2')
placemark_line.name = f"Trench Line {idx+1}"
placemark_line.geometry = trench
document.append(placemark_line)
# Add centroid points to KML
for idx, centroid in enumerate(centroids_gdf.geometry):
placemark_centroid = kml.Placemark(ns='http://www.opengis.net/kml/2.2')
placemark_centroid.name = f"Centroid {idx+1}"
placemark_centroid.geometry = centroid
document.append(placemark_centroid)
# Save KML
output_kml_path = "output.kml"
with open(output_kml_path, "w") as f:
f.write(k.to_string(prettyprint=True))
log(f"KML output saved to '{output_kml_path}'")
Explanation of Modifications
-
Side Preference and Offset:
-
Parameters Added:
SIDE_PREFERENCE = 'left' # Options: 'left', 'right'
OFFSET_DISTANCE = 0.00001 # Degrees; adjust as needed
These parameters allow you to set which side of the road the trench lines should favor and by how much to offset them.
-
Offset Function:
def offset_line(line, side, distance):
try:
offset = line.parallel_offset(distance, side=side, join_style=2, resolution=16)
if offset.type == 'MultiLineString':
offset = unary_union(offset)
return offset
except Exception as e:
log(f"Offsetting failed: {e}")
return line # Return original line if offset fails
This function offsets a given LineString to the specified side by the given distance. If the parallel_offset results in a MultiLineString, it merges them into a single LineString.
-
Creating Trench Lines with Side Preference:
def create_trench_lines(G, centroids, central_node, side_pref, offset_dist, roads_gdf):
trench_lines = []
for centroid_node in centroids:
try:
path = nx.shortest_path(G, source=centroid_node, target=central_node, weight='length')
# Get the geometry of the path
path_lines = ox.utils_graph.get_route_edge_attributes(G, path, 'geometry')
if not path_lines:
# If geometry is missing, create LineStrings between nodes
path_lines = []
for u, v in zip(path[:-1], path[1:]):
point_u = Point((G.nodes[u]['x'], G.nodes[u]['y']))
point_v = Point((G.nodes[v]['x'], G.nodes[v]['y']))
path_lines.append(LineString([point_u, point_v]))
# Merge all segments into a single LineString or MultiLineString
path_geom = unary_union(path_lines)
# Offset the trench line to the preferred side
offset_geom = offset_line(path_geom, side_pref, offset_dist)
# Check for intersections with roads
if roads_gdf.geometry.intersects(offset_geom).any():
# If intersects, try the opposite side
opposite_side = 'right' if side_pref == 'left' else 'left'
log(f"Trench line from node {centroid_node} intersects roads. Trying opposite side.")
offset_geom = offset_line(path_geom, opposite_side, offset_dist)
# If still intersects, use original path without offset
if roads_gdf.geometry.intersects(offset_geom).any():
log(f"Trench line from node {centroid_node} still intersects roads after offset. Using original path.")
offset_geom = path_geom
trench_lines.append(offset_geom)
except nx.NetworkXNoPath:
log(f"No path found from centroid node {centroid_node} to central node {central_node}.")
return trench_lines
Important Considerations
-
Offset Distance: The OFFSET_DISTANCE parameter is set in degrees. Depending on your CRS (Coordinate Reference System), you might want to adjust this to a more meaningful unit like meters. If your CRS is in a projected coordinate system (e.g., UTM), you can set this to meters accordingly.
-
CRS Selection: Ensure that your GeoDataFrames are in a projected CRS that makes distance calculations meaningful. If your data is in geographic coordinates (latitude and longitude), consider projecting them to a suitable CRS before performing offset operations.
-
Road Geometry Quality: The success of the trench line offsetting depends on the complexity and layout of the road network. Highly intersecting roads may cause multiple attempts to offset, potentially reverting to original paths frequently.
-
Performance: For large datasets, the offset and intersection checks might be computationally intensive. Optimize by limiting the number of centroids or simplifying geometries if necessary.
Final Notes
This modification provides a systematic way to favor one side of roads when drawing trench lines while ensuring that they do not undesirably cross roads. Adjust the SIDE_PREFERENCE and OFFSET_DISTANCE parameters to suit your specific requirements and dataset characteristics.