Return the distance from *point* to the line **segment** between *line_start* and *line_end*. When the perpendicular projection of *point* onto the infinite line falls within the segment, this equals the perpendicular distance to that line. When the projection falls outside the segm
(
point: tuple[float, float],
line_start: tuple[float, float],
line_end: tuple[float, float],
)
| 31 | |
| 32 | |
| 33 | def _perpendicular_distance( |
| 34 | point: tuple[float, float], |
| 35 | line_start: tuple[float, float], |
| 36 | line_end: tuple[float, float], |
| 37 | ) -> float: |
| 38 | """Return the distance from *point* to the line **segment** between |
| 39 | *line_start* and *line_end*. |
| 40 | |
| 41 | When the perpendicular projection of *point* onto the infinite line falls |
| 42 | within the segment, this equals the perpendicular distance to that line. |
| 43 | When the projection falls outside the segment, the distance to the nearest |
| 44 | endpoint is returned instead (projection clamped to [0, 1]). |
| 45 | |
| 46 | This is the correct distance measure for the Ramer-Douglas-Peucker |
| 47 | algorithm: using the infinite-line distance can incorrectly discard points |
| 48 | whose projection lies beyond a segment endpoint. |
| 49 | |
| 50 | >>> _perpendicular_distance((4.0, 0.0), (0.0, 0.0), (0.0, 3.0)) |
| 51 | 4.0 |
| 52 | >>> # order of line_start and line_end does not affect the result |
| 53 | >>> _perpendicular_distance((4.0, 0.0), (0.0, 3.0), (0.0, 0.0)) |
| 54 | 4.0 |
| 55 | >>> _perpendicular_distance((4.0, 1.0), (0.0, 1.0), (0.0, 4.0)) |
| 56 | 4.0 |
| 57 | >>> _perpendicular_distance((2.0, 1.0), (-2.0, 1.0), (-2.0, 4.0)) |
| 58 | 4.0 |
| 59 | >>> # projection falls outside the segment; distance to nearest endpoint |
| 60 | >>> round(_perpendicular_distance((0.0, 2.0), (1.0, 0.0), (3.0, 0.0)), 6) |
| 61 | 2.236068 |
| 62 | """ |
| 63 | px, py = point |
| 64 | ax, ay = line_start |
| 65 | bx, by = line_end |
| 66 | dx, dy = bx - ax, by - ay |
| 67 | seg_len_sq = dx * dx + dy * dy |
| 68 | if seg_len_sq == 0.0: |
| 69 | # line_start and line_end coincide; fall back to point-to-point distance |
| 70 | return _euclidean_distance(point, line_start) |
| 71 | # Project point onto the segment line, then clamp t to [0, 1] so the |
| 72 | # nearest point is always on the segment rather than the infinite line. |
| 73 | t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / seg_len_sq)) |
| 74 | nearest_x = ax + t * dx |
| 75 | nearest_y = ay + t * dy |
| 76 | return math.hypot(px - nearest_x, py - nearest_y) |
| 77 | |
| 78 | |
| 79 | def ramer_douglas_peucker( |
no test coverage detected