Implement PointSequence class

Implement PointSequence class to encapsulate functionality for handling
closed and open point sequences
This commit is contained in:
XANTRONIX 2025-03-22 14:32:55 -04:00
parent b980943b10
commit 3e519568db

View file

@ -2,8 +2,12 @@ import re
import math import math
import shapely import shapely
def load_poly_from_file(path: str) -> shapely.Polygon: from typing import Self
points = list()
class PointSequence(list):
@staticmethod
def from_file(path: str) -> Self:
ret = PointSequence()
with open(path, 'r') as fh: with open(path, 'r') as fh:
data = fh.read() data = fh.read()
@ -14,9 +18,44 @@ def load_poly_from_file(path: str) -> shapely.Polygon:
lat, lon = re.split(r'\s*,\s*', line) lat, lon = re.split(r'\s*,\s*', line)
points.append((float(lon), float(lat))) ret.add(float(lon), float(lat))
return shapely.Polygon(points) return ret
def __init__(self, points: list=None):
super().__init__()
self.poly = None
for point in points:
typeof = type(point)
if typeof is tuple:
self.add(*point)
elif typeof is shapely.Point:
self.append(point)
def add(self, lon: float, lat: float):
self.append(shapely.Point(lon, lat))
def is_closed(self) -> bool:
return self[-1] == self[0]
def close(self):
if self[-1] != self[0]:
self.append(self[0])
self.poly = shapely.Polygon(self)
def nearest_index(self, point: shapely.Point) -> int:
indices = list()
for i in range(0, len(self)):
indices.append((i, self[i].distance(point)))
indices.sort(key=lambda i: i[1])
return indices[0][0]
def line_heading(p1: shapely.Point, p2: shapely.Point) -> float: def line_heading(p1: shapely.Point, p2: shapely.Point) -> float:
dx = p2.x - p1.x dx = p2.x - p1.x