# -*- coding: utf-8 -*- """The global map of Figure 11a: which SWORD reach each 0.05-degree cell drains to. Output: ../Data/Data06m_sword_reach_land_globe_005deg.tif (int32: sword_reach_seq_id, 0 no reach downstream, -1 land not numbered, -2 sea) and ../Data/Data06m_sword_reach_land_summary.json Input: the global release (paths.GLOBAL) and the SWORD crosswalk (paths.SWORD_XW). Usage: python Data06m_sword_reach_land_globe.py """ import os, sys, json, time, hashlib from multiprocessing import Pool import numpy as np, pandas as pd, rasterio, pyarrow.parquet as pq from affine import Affine from rasterio.enums import Resampling T0 = time.time() HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH from flownest import Release # noqa: E402 RELEASE = PTH.GLOBAL PIX_TAB = os.path.join(RELEASE, 'flownest_merit90m_pixel_1km2.parquet') XW = os.path.join(PTH.SWORD_XW, 'flownest_merit90m_crosswalk_sword_v17c_reach.parquet') DATD = os.path.join(os.path.dirname(HERE), 'Data') assert json.load(open(os.path.join(os.path.dirname(XW), 'metadata.json')))['release']['metadata_sha256'] == \ hashlib.sha256(open(os.path.join(RELEASE, 'metadata.json'), 'rb').read()).hexdigest(), 'the crosswalk is made on _20261113_195421' F = 60 # 60 x 3″ = 0.05° NPROC = 8 def log(m): print('[%5.0f s] %s' % (time.time() - T0, m), flush=True) def _rows(args): g, locs = args t = pq.ParquetFile(PIX_TAB).read_row_group(g, columns=['upstream_channel_pixel_count', 'upstream_area_km2']) return t.column('upstream_channel_pixel_count').to_numpy()[locs], t.column('upstream_area_km2').to_numpy()[locs] def lookup(p): """n and upstream area of the channel pixels p (> 0, sorted, unique); the table is 1, 2, 3 ... so row = p - 1.""" f = pq.ParquetFile(PIX_TAB); md = f.metadata start = np.cumsum([0] + [md.row_group(i).num_rows for i in range(md.num_row_groups)]) ci = f.schema_arrow.get_field_index('pixel_seq_id') for g in range(md.num_row_groups): st = md.row_group(g).column(ci).statistics assert st.min == start[g] + 1 and st.max == start[g + 1], 'pixel table not consecutive at group %d' % g assert p[0] > 0 and (np.diff(p) > 0).all() rg = np.searchsorted(start, p - 1, side='right') - 1 gs = np.unique(rg) nn, aa = np.empty(len(p), np.int64), np.empty(len(p), np.float64) with Pool(NPROC) as pool: for g, (a, b) in zip(gs, pool.imap(_rows, [(int(g), p[rg == g] - 1 - start[g]) for g in gs])): nn[rg == g] = a; aa[rg == g] = b return nn, aa def main(): rel = Release(RELEASE); ND = rel.nodata R = pd.read_parquet(XW, columns=['sword_reach_id', 'sword_reach_seq_id', 'upstream_sword_reach_count', 'most_downstream_pixel_seq_id', 'sword_river_name', 'sword_type', 'matched_at_step']) R = R[R.sword_reach_seq_id > 0].sort_values('sword_reach_seq_id').reset_index(drop=True) N = len(R) assert N == 240111 and (R.sword_reach_seq_id.values == np.arange(1, N + 1)).all() assert (R.most_downstream_pixel_seq_id > 0).all() and (np.diff(R.most_downstream_pixel_seq_id.values) >= 0).all() assert (R.matched_at_step != 'not_matched').sum() == 236613 # n at the most downstream pixel of every reach up = np.unique(R.most_downstream_pixel_seq_id.values.astype(np.int64)) nn, aa = lookup(up) k = np.searchsorted(up, R.most_downstream_pixel_seq_id.values) R['n'] = nn[k]; R['upstream_area_km2'] = aa[k] log('lookup done: %d reaches on %d pixels' % (N, len(up))) # the reaches of a range are consecutive: reach r holds [r, r + count), and so does its pixel range lo_all = R.most_downstream_pixel_seq_id.values.astype(np.int64); hi_all = lo_all + R.n.values - 1 last = R.sword_reach_seq_id.values + R.upstream_sword_reach_count.values - 1 j = np.searchsorted(lo_all, hi_all, side='right') # reaches with p <= hi are 1..j assert (j == last).all(), 'reach numbers against pixel ranges' log('reach ranges = pixel ranges: ok') G = R.drop_duplicates('most_downstream_pixel_seq_id', keep='last') # on one pixel, the most upstream reach (largest number) shared = N - len(G) lo, num = G.most_downstream_pixel_seq_id.values.astype(np.int64), G.sword_reach_seq_id.values.astype(np.int64) hi = lo + G.n.values.astype(np.int64) - 1 n = len(lo) cut = np.unique(np.concatenate([lo, hi + 1])); owner = np.zeros(len(cut), np.int64); stack = []; i = 0 for kk, x in enumerate(cut): while i < n and lo[i] <= x: stack.append(i); i += 1 while stack and hi[stack[-1]] < x: stack.pop() owner[kk] = num[stack[-1]] if stack else 0 def owner_of(v): a = np.abs(np.asarray(v, np.int64)); q = np.searchsorted(cut, a, side='right') - 1 return np.where(q >= 0, owner[np.clip(q, 0, None)], 0) assert (owner_of(lo) == num).all() and (owner_of(-hi) == owner_of(hi)).all() log('owners of %d pieces' % len(cut)) with rasterio.open(rel.file('pixel_seq_id_1km2.tif'), OVERVIEW_LEVEL='NONE') as src: v = src.read(1, out_shape=(src.height // F, src.width // F), resampling=Resampling.nearest).astype(np.int64) tr = src.transform * Affine.scale(F) log('raster read %s' % (v.shape,)) sea = v == ND; numbered = ~sea & (v != 0) out = np.where(sea, -2, np.where(~numbered, -1, owner_of(np.where(numbered, v, 0)))).astype(np.int32) with rasterio.open(os.path.join(DATD, 'Data06m_sword_reach_land_globe_005deg.tif'), 'w', driver='GTiff', width=out.shape[1], height=out.shape[0], count=1, dtype='int32', crs='EPSG:4326', transform=tr, compress='deflate') as d: d.write(out, 1) # area check: the land with a SWORD reach downstream against the outermost ranges A_WGS, F_WGS = 6378137.0, 1 / 298.257223563 E2 = F_WGS * (2 - F_WGS); E1 = np.sqrt(E2) def _q(lat): s = np.sin(np.radians(lat)) return s / (1 - E2 * s * s) + np.log((1 + E1 * s) / (1 - E1 * s)) / (2 * E1) le = tr.f + tr.e * np.arange(out.shape[0] + 1) rk = A_WGS ** 2 * (1 - E2) / 2 * np.radians(abs(tr.a)) * np.abs(_q(le[:-1]) - _q(le[1:])) / 1e6 W = np.repeat(rk[:, None], out.shape[1], axis=1) land = out >= 0 a_owned = float(W[out > 0].sum()); a_land = float(W[land].sum()) outer = np.r_[True, lo[1:] > np.maximum.accumulate(hi)[:-1]] # not inside an earlier range a_outer = float(G.upstream_area_km2.values[outer].sum()) shown = np.unique(out[out > 0]) # the outermost SWORD systems, largest first, with their range of reach numbers O = G[outer].copy(); O['last'] = O.sword_reach_seq_id + O.upstream_sword_reach_count - 1 O = O.sort_values('upstream_area_km2', ascending=False) top = [dict(name=r.sword_river_name, sword_reach_id=int(r.sword_reach_id), first=int(r.sword_reach_seq_id), last=int(r['last']), reaches=int(r.upstream_sword_reach_count), upstream_area_km2=round(float(r.upstream_area_km2), 1), pixel_seq_id=int(r.most_downstream_pixel_seq_id)) for _, r in O.head(25).iterrows()] S = dict(release='flownest_merit90m_crosswalk_sword_v17c_20261113_195421', flownest_release=os.path.basename(RELEASE), reaches_numbered=N, reaches_matched_to_a_path=int((R.matched_at_step != 'not_matched').sum()), reaches_sharing_a_pixel_with_a_reach_upstream=shared, ranges=int(n), outermost_ranges=int(outer.sum()), reaches_in_picture=int(len(shown)), shape=list(out.shape), land_area_km2=round(a_land), land_with_sword_reach_downstream_km2=round(a_owned), share_of_land_pct=round(100 * a_owned / a_land, 2), outermost_upstream_area_km2=round(a_outer), picture_vs_outermost_pct=round(100 * (a_owned / a_outer - 1), 3), largest_systems=top) assert abs(a_owned / a_outer - 1) < 0.01, S json.dump(S, open(os.path.join(DATD, 'Data06m_sword_reach_land_summary.json'), 'w'), indent=1, ensure_ascii=False) print(json.dumps({k: v for k, v in S.items() if k != 'largest_systems'}, indent=1)) for t in top[:12]: print(t) log('done') if __name__ == '__main__': main()