File size: 14,374 Bytes
d922ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Deterministic, whole-planet, ~5 km latitude-band grid for Earth and Mars.

No elevation data is required. All cells are permanently defined by a versioned
band catalog and a longitude column number. This is *not* a raster/image grid.

Usage:
    python planetary_grid.py build --out OUT
    python planetary_grid.py lookup --planet mars --lat 18.44 --lon 77.45 --out OUT
    python planetary_grid.py export-sample --out OUT

Only packages for basic indexing: standard library + pyproj + numpy.
GeoPackage sample export: geopandas + shapely (pyogrio optional).
"""
from __future__ import annotations
import argparse
import bisect
import csv
import json
import math
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from pyproj import Geod, CRS

TARGET_M = 5000.0
VERSION = 'latband5km-v1'

# WGS84 Earth geodetic latitudes. Mars uses a spherical *indexing reference*
# matching the 3,396,190 m spherical radius in the selected MOLA–HRSC map
# metadata; the map uses planetocentric latitude and positive-east longitude.
PLANETS = {
    'earth': {'a_m': 6378137.0, 'b_m': 6356752.314245179, 'prefix': 'E',
              'coordinates': 'WGS84 geodetic latitude, east longitude',
              'crs_proj': '+proj=longlat +datum=WGS84 +type=crs'},
    'mars': {'a_m': 3396190.0, 'b_m': 3396190.0, 'prefix': 'M',
             'coordinates': 'planetocentric latitude, positive-east longitude; sphere radius 3396190 m',
             'crs_proj': '+proj=longlat +a=3396190 +b=3396190 +no_defs +type=crs'},
}


@dataclass(frozen=True)
class PlanetBandGrid:
    planet: str
    edges_deg: np.ndarray
    column_counts: np.ndarray
    target_m: float = TARGET_M

    @classmethod
    def build(cls, planet: str, target_m: float = TARGET_M) -> 'PlanetBandGrid':
        p = PLANETS[planet]
        geod = Geod(a=p['a_m'], b=p['b_m'])
        # Equidistant NS strips, measured on the selected ellipsoid/sphere meridian.
        # For a symmetric ellipsoid the meridian arc from South Pole to North Pole
        # can be computed with inv; n_bands round(...) yields near-5km strips.
        meridian_m = geod.inv(0, -90, 0, 90)[2]
        n_bands = max(1, round(meridian_m / target_m))
        segment_m = meridian_m / n_bands
        distances = np.arange(n_bands + 1, dtype=np.float64) * segment_m
        # fwd is vectorized and gives the latitude at each meridian distance.
        longitudes, latitudes, back_az = geod.fwd(
            np.zeros(len(distances)),
            np.full(len(distances), -90.),
            np.zeros(len(distances)),
            distances,
        )
        latitudes[0], latitudes[-1] = -90.0, 90.0
        if not np.all(np.diff(latitudes) > 0):
            raise ValueError(f'Latitude edges not strictly increasing for {planet}')
        lat_centers = (latitudes[:-1] + latitudes[1:]) / 2
        a, b = p['a_m'], p['b_m']
        e2 = 1 - (b/a)**2
        sinphi = np.sin(np.deg2rad(lat_centers))
        radius_parallel = a * np.cos(np.deg2rad(lat_centers)) / np.sqrt(1 - e2 * sinphi**2)
        circumference = 2 * np.pi * radius_parallel
        counts = np.maximum(1, np.rint(circumference / target_m)).astype(np.int32)
        return cls(planet, latitudes, counts, target_m)

    @property
    def planet_conf(self): return PLANETS[self.planet]

    @property
    def number_of_cells(self) -> int:
        return int(np.sum(self.column_counts, dtype=np.int64))

    @property
    def geod(self):
        c = self.planet_conf
        return Geod(a=c['a_m'], b=c['b_m'])

    def lat_band(self, lat_deg: float) -> int:
        if not math.isfinite(lat_deg) or not (-90 <= lat_deg <= 90):
            raise ValueError('Latitude must be finite and in [-90,90]')
        if lat_deg == 90:
            return len(self.column_counts)-1
        return int(np.searchsorted(self.edges_deg, lat_deg, side='right')-1)

    @staticmethod
    def normalized_lon(lon_deg: float) -> float:
        if not math.isfinite(lon_deg):
            raise ValueError('Longitude must be finite')
        lon = (lon_deg + 180) % 360 - 180
        # remove negative zero
        return 0.0 if lon == 0 else lon

    def lookup(self, lat_deg: float, lon_deg: float) -> dict:
        band = self.lat_band(lat_deg)
        n = int(self.column_counts[band])
        # All longitudes refer to the same physical point at either pole.
        # Assign a unique canonical polar cell; the grid still has multiple
        # wedges in the polar band away from the exact pole.
        col = 0 if abs(lat_deg) == 90 else min(n-1, int((self.normalized_lon(lon_deg)+180) / 360 * n))
        return self.cell(band, col)

    def cell(self, band: int, col: int) -> dict:
        if not (0 <= band < len(self.column_counts)):
            raise IndexError('band out of range')
        n = int(self.column_counts[band])
        if not (0 <= col < n):
            raise IndexError('column out of range')
        lat_lo, lat_hi = float(self.edges_deg[band]), float(self.edges_deg[band+1])
        width_deg = 360.0/n
        lon_lo = -180 + width_deg * col
        lon_hi = -180 + width_deg * (col + 1)
        # Keep center exact and stable. Corner-to-corner physical width varies
        # inside each band, particularly at the poles.
        lon_mid = (lon_lo+lon_hi)/2
        return {
            'region_id': f"{self.planet_conf['prefix']}_{band:04d}_{col:05d}",
            'planet': self.planet,
            'grid_version': VERSION,
            'band': band, 'column': col,
            'lat_min': lat_lo, 'lat_max': lat_hi,
            'lon_min': lon_lo, 'lon_max': lon_hi,
            'center_lat': (lat_lo+lat_hi)/2, 'center_lon': lon_mid,
            'area_km2': float(self.cell_area_km2(band)),
        }

    def from_region_id(self, region_id: str) -> dict:
        """Resolve a saved permanent region ID back to bounds and area."""
        parts=region_id.split('_')
        if len(parts)!=3 or parts[0]!=self.planet_conf['prefix']:
            raise ValueError('Region ID is not for this planet or has wrong format')
        try:
            band=int(parts[1]); col=int(parts[2])
        except ValueError as exc:
            raise ValueError('Invalid band/column in region ID') from exc
        c=self.cell(band,col)
        if c['region_id']!=region_id:
            raise ValueError('Noncanonical region ID')
        return c

    def strip_area_m2(self) -> np.ndarray:
        """Exact area of all 360° longitude per latitude band, on a spheroid."""
        a, b = self.planet_conf['a_m'], self.planet_conf['b_m']
        e2 = 1-(b/a)**2
        u = np.sin(np.deg2rad(self.edges_deg))
        if e2 < 1e-15:
            primitive = u
        else:
            e = math.sqrt(e2)
            primitive = 0.5 * (u/(1-e2*u*u) + np.arctanh(e*u)/e)
        return 2*math.pi*a*a*(1-e2)*np.diff(primitive)

    def cell_area_km2(self, band: int) -> float:
        # Caller typically uses this for only a few sample bands.
        area = self.strip_area_m2()[band] / self.column_counts[band]
        return float(area / 1e6)

    def stats(self) -> dict:
        areas = self.strip_area_m2()/self.column_counts/1e6
        counts = self.column_counts
        return {
            'planet': self.planet,
            'reference': self.planet_conf['coordinates'],
            'n_latitude_bands': int(len(counts)),
            'n_total_cells': self.number_of_cells,
            'meridian_band_height_m_exact': float(self.geod.inv(0, float(self.edges_deg[0]), 0, float(self.edges_deg[1]))[2]),
            'min_area_km2': float(np.min(areas)),
            'max_area_km2': float(np.max(areas)),
            'mean_area_km2': float(np.sum(areas*counts)/self.number_of_cells),
            'total_area_km2': float(np.sum(self.strip_area_m2())/1e6),
            'polar_band_columns': [int(counts[0]), int(counts[-1])],
            'equator_band_columns': int(counts[self.lat_band(0)]),
        }

    def save_bands(self, path: Path):
        path.parent.mkdir(parents=True, exist_ok=True)
        a = self.strip_area_m2() / self.column_counts / 1e6
        offsets = np.concatenate(([0], np.cumsum(self.column_counts.astype(np.int64))))
        with path.open('w', newline='', encoding='utf8') as f:
            wr = csv.writer(f)
            wr.writerow(['grid_version','planet','band','lat_min','lat_max',
                         'n_longitude_columns','longitude_step_deg',
                         'area_per_region_km2','global_offset_start'])
            for i, n in enumerate(self.column_counts):
                wr.writerow([VERSION,self.planet,i,f'{self.edges_deg[i]:.12f}',
                             f'{self.edges_deg[i+1]:.12f}',int(n),
                             f'{360/int(n):.12f}',f'{a[i]:.8f}',int(offsets[i])])

    def geometry(self, band: int, col: int, max_step_degrees: float = 0.5):
        """Polygon bounded by latitude parallels and meridians; WGS84/Mars lonlat.

        Densified parallel edges prevent planar or geodesic polygon software
        from treating long polar arc edges as geodesic chords.
        """
        from shapely.geometry import Polygon
        c = self.cell(band, col)
        lo0, lo1 = c['lon_min'], c['lon_max']
        la0, la1 = c['lat_min'], c['lat_max']
        segments = max(1, math.ceil((lo1-lo0)/max_step_degrees))
        lons = np.linspace(lo0, lo1, segments+1)
        ring = [(float(lon),la0) for lon in lons]
        ring += [(float(lon),la1) for lon in lons[::-1]]
        poly = Polygon(ring)
        if not poly.is_valid:
            raise ValueError(f'invalid polygon {c["region_id"]}')
        return poly

    def sampled_geometry_area_km2(self, band: int, col: int) -> float:
        geom = self.geometry(band,col)
        lons, lats = zip(*geom.exterior.coords)
        return abs(self.geod.polygon_area_perimeter(lons,lats)[0])/1e6


def build_all(out: Path) -> dict:
    out.mkdir(parents=True, exist_ok=True)
    stats = {}
    for p in PLANETS:
        grid = PlanetBandGrid.build(p)
        grid.save_bands(out / f'{p}_global_bands.csv')
        stats[p] = grid.stats()
    with (out/'grid_manifest.json').open('w',encoding='utf8') as f:
        json.dump({
            'grid_version':VERSION,
            'target_meridian_north_south_m':TARGET_M,
            'geometry_method':'latitude bands equal meridional arc length; each band divided into rounded 5km-wide longitude cells at midpoint',
            'range_of_longitudes':'[-180,180), east-positive both planets; normalize other domains',
            'planet_definition':PLANETS,
            'statistics':stats,
            'index_storage':'compact band tables; every cell is permanently defined by (planet,band,column). To create a cell geometry, use the bundled Python function. Raw raster pixels are NOT in this index.',
        },f,indent=2)
    return stats


def export_sample(out: Path):
    """Create actual geographic polygons near land/planetary landmarks and edge cases."""
    import geopandas as gpd
    from shapely.geometry import Point
    out.mkdir(parents=True,exist_ok=True)
    sample_points = {
        'earth': [('Salda, Turkey', 37.55, 29.68),('Equator',0.0,0.0),
                  ('Dateline east',12.0,179.999),('Dateline west',-12.0,-179.999),
                  ('Arctic',89.90,90.0),('Antarctic',-89.90,-90.0),
                  ('North pole',90.0,0.0),('South pole',-90.0,0.0)],
        'mars': [('Jezero',18.44,77.45),('Equator',0.0,0.0),
                 ('Dateline east',12.0,179.999),('Dateline west',-12.0,-179.999),
                 ('North pole',90.0,0.0),('South pole',-90.0,0.0),
                 ('High north',89.90,90.0),('High south',-89.90,-90.0)],
    }
    lookup_rows=[]
    for name, points in sample_points.items():
        grid = PlanetBandGrid.build(name)
        region_candidates=set()
        for label,lat,lon in points:
            c=grid.lookup(lat,lon)
            lookup_rows.append({'sample':label, 'input_lat':lat,'input_lon':lon,**c})
            # Three latitude bands x three longitude columns around each point.
            for band in range(max(0,c['band']-1),min(len(grid.column_counts),c['band']+2)):
                n=int(grid.column_counts[band]); delta_deg=grid.normalized_lon(lon)+180
                cnum=min(n-1,int(delta_deg/360*n))
                for col in ((cnum-1)%n,cnum,(cnum+1)%n):
                    region_candidates.add((band,col))
        rows=[]
        for band,col in sorted(region_candidates):
            c=grid.cell(band,col)
            c['area_from_geodesic_polygon_km2']=grid.sampled_geometry_area_km2(band,col)
            c['area_error_percent']=100*(c['area_from_geodesic_polygon_km2']/c['area_km2']-1)
            c['geometry']=grid.geometry(band,col)
            rows.append(c)
        gdf=gpd.GeoDataFrame(rows,geometry='geometry',crs=CRS(grid.planet_conf['crs_proj']))
        filename = out / f'{name}_sample_regions.gpkg'
        gdf.to_file(filename,driver='GPKG',layer='regions',index=False)
        # independent round-trip check of index and CRS
        reopened=gpd.read_file(filename)
        assert len(reopened)==len(gdf)
        assert reopened.crs is not None
        assert set(reopened.region_id)==set(gdf.region_id)
    with (out/'example_coordinate_lookups.csv').open('w',newline='',encoding='utf8') as f:
        fieldnames=list(lookup_rows[0].keys())
        wr=csv.DictWriter(f,fieldnames=fieldnames)
        wr.writeheader(); wr.writerows(lookup_rows)


def main():
    parser=argparse.ArgumentParser(description='5km Earth/Mars latitude-band grid')
    sub=parser.add_subparsers(dest='command',required=True)
    for cmd in ['build','export-sample','lookup']:
        p=sub.add_parser(cmd)
        p.add_argument('--out',type=Path,default=Path('.'))
        if cmd=='lookup':
            p.add_argument('--planet',choices=PLANETS,required=True)
            p.add_argument('--lat',type=float,required=True)
            p.add_argument('--lon',type=float,required=True)
    args=parser.parse_args()
    if args.command=='build':
        print(json.dumps(build_all(args.out),indent=2))
    elif args.command=='export-sample':
        export_sample(args.out)
        print('Wrote sample GeoPackages and lookup CSV in',args.out)
    elif args.command=='lookup':
        grid=PlanetBandGrid.build(args.planet)
        print(json.dumps(grid.lookup(args.lat,args.lon),indent=2))

if __name__=='__main__':
    main()