Cotton code
54 lines · 2.3 KB · PythonRaw
"""Build-time point-in-polygon lookup over the pinned timezone GeoJSON."""import jsonimport mathimport zipfilefrom collections import defaultdictclass Ring:    def __init__(self, points):        self.bands = defaultdict(list)        for (x1, y1), (x2, y2) in zip(points, points[1:] + points[:1]):            if (x1, y1) == (x2, y2):                continue            edge = (x1, y1, x2, y2)            for band in range(math.floor(min(y1, y2)), math.floor(max(y1, y2)) + 1):                self.bands[band].append(edge)    def contains(self, x, y):        inside = False        for x1, y1, x2, y2 in self.bands[math.floor(y)]:            cross = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)            if abs(cross) < 1e-12 and min(x1, x2) <= x <= max(x1, x2) and min(y1, y2) <= y <= max(y1, y2):                return True            if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:                inside = not inside        return insideclass ZoneIndex:    def __init__(self, source):        with zipfile.ZipFile(source) as archive:            data = json.loads(archive.read("combined-with-oceans.json"))        self.polygons = []        for feature in data["features"]:            geometry = feature["geometry"]            if geometry["type"] not in ("Polygon", "MultiPolygon"):                raise ValueError("Unexpected timezone geometry")            polygons = [geometry["coordinates"]] if geometry["type"] == "Polygon" else geometry["coordinates"]            for polygon in polygons:                outer = polygon[0]                xs, ys = zip(*outer)                self.polygons.append((feature["properties"]["tzid"], (min(xs), min(ys), max(xs), max(ys)), polygon))        self.polygons.sort(key=lambda p: p[0])        self.rings = {}    def zone(self, lon, lat):        for i, (zone, (west, south, east, north), points) in enumerate(self.polygons):            if west <= lon <= east and south <= lat <= north:                if i not in self.rings:                    self.rings[i] = [Ring(p) for p in points]                outer, *holes = self.rings[i]                if outer.contains(lon, lat) and not any(h.contains(lon, lat) for h in holes):                    return zone        raise ValueError(f"No timezone polygon contains {lat}, {lon}")