Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129#!/usr/bin/env python3"""Add to dbt/seeds/h3_res4_us_cells.csv the cells the grid is missing.
The seed began as h3.polygon_to_cells over each state, which keeps a cell onlywhen its centre falls inside the state. On a coast that loses the cell holdingthe land: Miami's cell is centred in the Atlantic, Key West had no cell withintwo rings, Cape Hatteras none within one, and a reader there was handedUS-wide lists -- Paper Birch as Miami's top native tree. iNat's ranges coverthose cells regardless: 8,918 of them contain the centre of Miami's.
So the grid is every resolution-4 cell that touches land in a lower-48 state orthe District. Land is the county outlines (counties.geojson, what dim_countyand int_cell__county read), not admin1.geojson: the state outlines are toocoarse to hold the Florida Keys or the Outer Banks at all. Alaska and Hawaiiare left as they are.
Existing rows are never changed, so their ecoregions stay what RESOLVE said.A new row gets:
state the state whose counties hold the most of the cell's land; its centre is sea or another country for every cell added lat/lng the cell's centre eco/biome empty. RESOLVE is kept out of the pipeline (see dim_cell), and an added cell's centre is offshore or abroad, which is where the seed already has no ecoregion.
Then one rule the centres cannot express: a place too small to be any cell'sstate takes the cell holding the most of its land. That is the District, 177km2 against a cell's 1,770, which would otherwise never be a cell's state, soits sites would read Maryland's outline and counts.
Idempotent: a second run adds nothing and moves nothing.
uv run python scripts/extend_grid.py"""import csvimport jsonimport os
import duckdbimport h3
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")SEED = os.path.join(ROOT, "dbt", "seeds", "h3_res4_us_cells.csv")BOUNDARIES = os.path.join(os.environ.get("DATACACHE", os.path.join(ROOT, "data")), "raw", "boundaries")# Alaska, Hawaii, and Puerto Rico's municipios, which counties.geojson carries.SKIP = {"02", "15", "72"}
def hexagon(cell): ring = h3.cell_to_boundary(h3.int_to_str(cell)) return "POLYGON((" + ", ".join(f"{lng} {lat}" for lat, lng in ring + ring[:1]) + "))"
def main(): with open(SEED, newline="", encoding="utf-8") as f: reader = csv.DictReader(f) fields = reader.fieldnames rows = {int(r["cell"]): r for r in reader}
# A state's name the way the seed and dim_place spell it, by FIPS code -- # admin1's 'US06' is FIPS 10-4, whose state half is a county's first two # digits, as stg_boundaries__admin1 reads it. with open(os.path.join(BOUNDARIES, "admin1.geojson"), encoding="utf-8") as f: name_of = {ft["properties"]["fips"][-2:]: ft["properties"]["name"] for ft in json.load(f)["features"] if ft["properties"].get("fips")} with open(os.path.join(BOUNDARIES, "counties.geojson"), encoding="utf-8") as f: counties = [(name_of[ft["properties"]["STATE"]], ft["geometry"]) for ft in json.load(f)["features"] if ft["properties"]["STATE"] not in SKIP]
touching = {} for state, geometry in counties: shape = h3.geo_to_h3shape(geometry) for c in h3.h3shape_to_cells_experimental(shape, 4, contain="overlap"): touching.setdefault(h3.str_to_int(c), set()).add(state)
con = duckdb.connect() con.execute("install spatial") con.execute("load spatial") con.execute("create table county (state varchar, g geometry)") con.executemany("insert into county values (?, ST_GeomFromGeoJSON(?::varchar))", [(s, json.dumps(g)) for s, g in counties])
def land(cells): """(cell, state, area of the cell in that state's counties), planar degrees.""" if not cells: return [] con.execute("create or replace temp table hex (cell ubigint, g geometry)") con.executemany("insert into hex values (?, ST_GeomFromText(?::varchar))", [(c, hexagon(c)) for c in cells]) return con.execute(""" select h.cell, c.state, sum(ST_Area(ST_Intersection(h.g, c.g))) from hex h join county c on ST_Intersects(h.g, c.g) group by 1, 2 """).fetchall()
new = sorted(set(touching) - set(rows)) best = {} for cell, state, area in land(new): if area > best.get(cell, ("", 0))[1]: best[cell] = (state, area) for cell in new: lat, lng = h3.cell_to_latlng(h3.int_to_str(cell)) rows[cell] = {"cell": str(cell), "state": best[cell][0], "lat": repr(lat), "lng": repr(lng), "eco_id": "", "biome_id": ""}
moved = [] named = {r["state"] for r in rows.values()} for state in sorted({s for s, _ in counties} - named): mine = [c for c, states in touching.items() if state in states] cell = max(((c, a) for c, s, a in land(mine) if s == state), key=lambda x: x[1])[0] moved.append((cell, rows[cell]["state"], state)) rows[cell]["state"] = state
with open(SEED, "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n") w.writeheader() for cell in sorted(rows): w.writerow(rows[cell]) print(f"{SEED}: {len(rows):,} cells, {len(new)} added") for cell, was, now in moved: print(f" {h3.int_to_str(cell)}: {was} -> {now}")
if __name__ == "__main__": main()