"""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()