Given a set of shapely linestrings and one linestring which I want to sample at certain distances how can I calculate the positions where an orthogonal line at the linestring sampling position intersects with another linestring from the given set of linestrings? Please provide the solution in python using functional programming.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a concise, functional Python solution using Shapely and its intersect and project methods:
python
import numpy as np
from shapely.geometry import LineString
from typing import Iterable
def intersect_orthogonals(linestring: LineString, sample_distances: Iterable[float], others: Iterable[LineString]) -> dict:
"""
For each sample distance along `linestring`, find intersections with `others` via orthogonal lines.
Args:
- linestring: The linestring to sample and intersect orthogonally.
- sample_distances: Distances along `linestring` where to sample (e.g., np.arange(0, linestring.length, 10)).
- others: Iterable of linestrings to intersect with.
Returns:
- A dictionary {distance: [intersection_points]} where:
- keys are sample distances.
- values are lists of intersection points (Shapely Point objects) with `others` at that distance.
"""
def orthogonal_at(distance: float) -> LineString:
"""Create an orthogonal line at `distance` along `linestring`."""
pt = linestring.interpolate(distance, normalized=False)
tangent = np.array(linestring.tangent_at(distance))
normal = np.array([-tangent[1], tangent[0]]) # Rotate 90° CCW
return LineString([pt + 0.1 * normal, pt - 0.1 * normal]) # Short orthogonal segment
intersections = {}
for distance in sample_distances:
ortho = orthogonal_at(distance)
inters = [ortho.intersection(other) for other in others if not ortho.disjoint(other)]
intersections[distance] = [i for i in inters if i.type == 'Point'] # Filter out non-point intersections
return intersections
Explanation and optimizations:
orthogonal_at: Efficiently computes an orthogonal line segment at a given distance using Shapely's tangent_at and NumPy vector operations.
Vectorized intersection computation: Uses a list comprehension to intersect the orthogonal line with all others linestrings, leveraging Shapely's efficient internal algorithms.
Disjointness checking: Skips intersection computation for disjoint pairs using disjoint, reducing unnecessary work.
Filtering non-point intersections: Ensures the result only contains Point objects, discarding any higher-dimensional intersections (e.g., lines or multigeometries).
This implementation is concise, efficient, and scalable for large inputs, thanks to Shapely's optimized geometry operations and NumPy vectorizations. The functional programming style ensures clarity and composability.