# -*- coding: utf-8 -*- """The SWORD numbers and the GRDC gauge - SWORD node pairs. A gauge and a node make a pair when one is upstream of the other on FlowNest and their drainage areas differ by at most 10%. The numbers go to the abstract, Sections 5.2-5.3, Appendix B and Table B1. Input: the global release (paths.GLOBAL), the GRDC crosswalk (paths.GRDC_XW) and the SWORD crosswalk (paths.SWORD_XW, or the first argument). Output: Data06n_sword_numbers_and_gauge_pairs.json and Data06n_grdc_gauge_sword_pairs.csv in ../Data (or the second argument). Usage: python Data06n_sword_numbers_and_gauge_pairs.py [ ] """ import os, sys, json, time, hashlib from multiprocessing import Pool import numpy as np, pandas as pd, pyarrow.parquet as pq from numba import njit sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH T0 = time.time() HERE = os.path.dirname(os.path.abspath(__file__)) FN_RELEASE = 'flownest_merit90m_global_20261113_195421' PIX_TAB = os.path.join(PTH.GLOBAL, 'flownest_merit90m_pixel_1km2.parquet') GRDC_XW = os.path.join(PTH.GRDC_XW, 'flownest_merit90m_crosswalk_grdc_burek2023.parquet') XWD = sys.argv[1] if len(sys.argv) > 1 else PTH.SWORD_XW XWD_NAME = os.path.basename(sys.argv[1].rstrip('/')) if len(sys.argv) > 1 else PTH.SWORD_XW_NAME DATA = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(HERE), 'Data') PRE = 'flownest_merit90m_crosswalk_sword_v17c_' NPROC = 8 def log(m): print('[%5.0f s] %s' % (time.time() - T0, m), flush=True) def parts(s, code): """rows whose '; '-separated text s holds the code""" return s.fillna('').str.split('; ').apply(lambda x: code in x).values def _rows(args): g, locs = args t = pq.ParquetFile(PIX_TAB).read_row_group(g, columns=['upstream_channel_pixel_count', 'upstream_area_km2', 'basin_id']) return (t.column('upstream_channel_pixel_count').to_numpy()[locs], t.column('upstream_area_km2').to_numpy()[locs], t.column('basin_id').to_numpy()[locs]) def lookup(p): """for the channel pixels p (> 0): the sorted unique pixels u and their n, upstream area and basin_id; 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 u = np.unique(np.asarray(p, np.int64)); assert u[0] > 0 rg = np.searchsorted(start, u - 1, side='right') - 1 gs = np.unique(rg) nn, aa, bb = np.empty(len(u), np.int64), np.empty(len(u), np.float64), np.empty(len(u), np.int64) with Pool(NPROC) as pool: for g, (a, b, c) in zip(gs, pool.imap(_rows, [(int(g), u[rg == g] - 1 - start[g]) for g in gs])): nn[rg == g] = a; aa[rg == g] = b; bb[rg == g] = c return u, nn, aa, bb @njit(cache=True) def innermost(starts, ends, q_sorted): """for each q (ascending): index of the innermost range [start, end] holding q, or -1 (ranges nested or disjoint, by start ascending).""" out = np.full(len(q_sorted), -1, np.int64) stack = np.empty(len(starts) + 1, np.int64); top = 0; i = 0 for k in range(len(q_sorted)): q = q_sorted[k] while i < len(starts) and starts[i] <= q: while top > 0 and ends[stack[top - 1]] < starts[i]: top -= 1 stack[top] = i; top += 1; i += 1 while top > 0 and ends[stack[top - 1]] < q: top -= 1 if top > 0: out[k] = stack[top - 1] return out @njit(cache=True) def range_argmax(vals, lo, hi): """argmax of vals[lo:hi] for each (lo, hi); -1 if empty.""" out = np.full(len(lo), -1, np.int64) for k in range(len(lo)): best = -1.0 for j in range(lo[k], hi[k]): if vals[j] > best: best = vals[j]; out[k] = j return out def appendix_b(S, R, N): """the numbers of Section 5.2, Appendix B and Table B1""" A = {} A['subnetworks'] = int(len(S)); A['subnetworks_with_basin'] = int((S.basin_id > 0).sum()) A['reaches'] = int(len(R)) step = R.matched_at_step.value_counts().to_dict(); A['reaches_by_step'] = step grp = {'3x3': ['3x3'], '5x5': ['5x5'], '7x7': ['7x7'], 'beyond_7x7': ['beyond_7x7'], 'between_neighbors_or_against_flow': ['between_neighbors', 'against_flow'], 'stricter_rules': ['partly_on_neighbor_path', 'within_water_surface', 'land_part_cover'], 'by_drainage_area': ['area_guided_rescue', 'area_guided_switch'], 'continued_nodes': ['continued_from_neighbor']} assert sorted(sum(grp.values(), []) + ['not_matched']) == sorted(step), sorted(step) A['reaches_matched_by_group'] = {k: int(sum(step.get(s, 0) for s in v)) for k, v in grp.items()} matched = (R.matched_at_step != 'not_matched').values A['reaches_matched'] = int(matched.sum()); assert A['reaches_matched'] == sum(A['reaches_matched_by_group'].values()) A['reaches_matched_pct'] = round(100 * matched.mean(), 1) by_lines = matched & (R.matched_at_step != 'continued_from_neighbor').values A['reaches_matched_by_lines'] = int(by_lines.sum()) numbered = (R.sword_reach_seq_id > 0).values A['reaches_numbered'] = int(numbered.sum()); A['reaches_numbered_without_path'] = int((numbered & ~matched).sum()) assert (R.sword_reach_seq_id[numbered].sort_values().values == np.arange(1, numbered.sum() + 1)).all() searched_in = np.where(R.own_basin_id.values > 0, R.own_basin_id.values, R.sword_subnetwork_id.map(S.set_index('sword_subnetwork_id').basin_id).values) nb = numbered & ~matched & (R.basin_id.values != searched_in) A['numbered_without_path_basin_differs'] = int(nb.sum()) A['numbered_without_path_basin_differs_tidal'] = int((nb & (R.sword_lakeflag.values == 3)).sum()) A['numbered_with_path_basin_differs'] = int((numbered & matched & (R.basin_id.values != searched_in)).sum()) pl = (N.pixel_seq_id > 0).values A['nodes'] = int(len(N)); A['nodes_placed'] = int(pl.sum()); A['nodes_placed_pct'] = round(100 * pl.mean(), 1) A['nodes_placed_by'] = N.placed_by.fillna('').value_counts().to_dict() assert (N.sword_node_seq_id[pl].sort_values().values == np.arange(1, pl.sum() + 1)).all() and (N.sword_node_seq_id[~pl] == 0).all() d = N.distance_to_pixel_m.values A['node_distance_m_median_p90'] = [round(float(np.median(d[pl])), 1), round(float(np.percentile(d[pl], 90)), 1)] by = {} for t in sorted(N.sword_type.unique()): k = (N.sword_type == t).values; p = k & pl by[int(t)] = dict(reaches=int((R.sword_type == t).sum()), reaches_matched=int(((R.sword_type == t).values & matched).sum()), nodes=int(k.sum()), nodes_placed=int(p.sum()), placed_pct=round(100 * p.sum() / k.sum(), 1), distance_m_median=round(float(np.median(d[p])), 1), distance_m_p90=round(float(np.percentile(d[p], 90)), 1)) A['by_sword_type'] = by A['nodes_far_from_pixel'] = int(parts(N.confidence_reason, 'far_from_pixel').sum()) A['reaches_most_nodes_far_from_pixel'] = int(parts(R.confidence_reason, 'most_nodes_far_from_pixel').sum()) o = R.orientation.fillna('').values A['orientation'] = pd.Series(o).value_counts().to_dict() assert ((o != '') == by_lines).all() # oriented = matched by lines A['reversed'] = int((o == 'reversed').sum()); A['reversed_pct_of_by_lines'] = round(100 * A['reversed'] / by_lines.sum(), 1) t1 = (R.sword_type == 1).values A['reversed_river_type1'] = int(((o == 'reversed') & t1).sum()); A['oriented_river_type1'] = int(((o != '') & t1).sum()) A['reversed_river_type1_pct'] = round(100 * A['reversed_river_type1'] / A['oriented_river_type1'], 1) A['file_size_mb'] = {t: round(os.path.getsize(os.path.join(XWD, PRE + t + '.parquet')) / 1e6, 1) for t in ('subnetwork', 'reach', 'node')} return A def pair_gauges(N): """Section 5.3: each gauge with its candidate down and up node, paired within +-10% of upstream area.""" g = pd.read_parquet(GRDC_XW, columns=['grdc_station_id', 'station_seq_id', 'pixel_class', 'pixel_seq_id', 'basin_id', 'upstream_area_km2']) assert len(g) == 10241 and (g.pixel_class == 'channel_pixel').all() and (g.pixel_seq_id > 0).all() pg = g.pixel_seq_id.values.astype(np.int64) ug, ng, ag, bg = lookup(pg); i = np.searchsorted(ug, pg) assert (g.basin_id.values == bg[i]).all() and (np.abs(g.upstream_area_km2.values / ag[i] - 1) < 1e-6).all() # step 10 writes float32 og, Ag = pg + ng[i] - 1, ag[i] placed = N[N.pixel_seq_id > 0] u, nu, Au, _ = lookup(placed.pixel_seq_id.values) ends = u + nu - 1 order = np.argsort(pg, kind='stable') down = np.full(len(g), -1, np.int64); down[order] = innermost(u, ends, pg[order]) lo = np.searchsorted(u, pg, 'right'); hi = np.searchsorted(u, og, 'right') # strictly upstream: p_g < p_n <= p_g + n_g - 1 up = range_argmax(Au, lo, hi) Ad = np.where(down >= 0, Au[np.maximum(down, 0)], np.nan); Aup = np.where(up >= 0, Au[np.maximum(up, 0)], np.nan) rd = np.abs(np.log(Ad / Ag)); ru = np.abs(np.log(Aup / Ag)) use_up = np.nan_to_num(ru, nan=np.inf) < np.nan_to_num(rd, nan=np.inf) pair = np.where(use_up, up, down); ratio = np.where(use_up, Aup, Ad) / Ag pp = np.where(pair >= 0, u[np.maximum(pair, 0)], 0) first = placed.sort_values('sword_node_id').drop_duplicates('pixel_seq_id').set_index('pixel_seq_id').reindex(pp) m10 = (pair >= 0) & (np.abs(ratio - 1) <= 0.10) res = dict(gauges=int(len(g)), gauges_with_node_downstream=int((down >= 0).sum()), gauges_with_node_upstream=int((up >= 0).sum()), gauges_with_any_node_on_flow_line=int(((down >= 0) | (up >= 0)).sum()), paired_within={'%d%%' % t: int(np.sum((pair >= 0) & (np.abs(ratio - 1) <= t / 100))) for t in (5, 10, 20)}, paired_10pct=int(m10.sum()), paired_10pct_down=int((m10 & ~use_up).sum()), paired_10pct_down_same_pixel=int((m10 & ~use_up & (pp == pg)).sum()), paired_10pct_up=int((m10 & use_up).sum())) pairs = pd.DataFrame({'grdc_station_id': g.grdc_station_id, 'station_seq_id': g.station_seq_id, 'pixel_seq_id': pg, 'upstream_area_km2': Ag, 'pair_side': np.where(pair < 0, 'none', np.where(use_up, 'up', 'down')), 'pair_pixel_seq_id': pp, 'pair_sword_node_id': first.sword_node_id.values, 'pair_sword_reach_id': first.sword_reach_id.values, 'pair_area_ratio': np.round(ratio, 4), 'paired_10pct': m10}) return res, pairs def main(): meta = json.load(open(os.path.join(XWD, 'metadata.json'))) fn_meta = open(os.path.join(PTH.GLOBAL, 'metadata.json'), 'rb').read() assert meta['release']['metadata_sha256'] == hashlib.sha256(fn_meta).hexdigest(), meta['release'] # each crosswalk package names its release by the sha256 of its metadata.json S = pd.read_parquet(os.path.join(XWD, PRE + 'subnetwork.parquet'), columns=['sword_subnetwork_id', 'basin_id']) R = pd.read_parquet(os.path.join(XWD, PRE + 'reach.parquet')) N = pd.read_parquet(os.path.join(XWD, PRE + 'node.parquet'), columns=['sword_node_id', 'sword_reach_id', 'sword_node_seq_id', 'pixel_seq_id', 'placed_by', 'distance_to_pixel_m', 'confidence_reason']) N = N.merge(R[['sword_reach_id', 'sword_type']], on='sword_reach_id', how='left', validate='many_to_one') assert N.sword_type.notna().all() log('package %s: subnetworks %d, reaches %d, nodes %d' % (os.path.basename(XWD.rstrip('/')), len(S), len(R), len(N))) OUT = dict(sword_crosswalk=XWD_NAME, code_version=meta.get('code_version'), code_commit=meta.get('code_commit'), flownest_release=FN_RELEASE, grdc_crosswalk=PTH.GRDC_XW_NAME) OUT['appendix_b'] = appendix_b(S, R, N) log('appendix B: %s' % json.dumps({k: v for k, v in OUT['appendix_b'].items() if k != 'by_sword_type'})) OUT['gauge_pairs'], pairs = pair_gauges(N) log('gauge pairs: %s' % OUT['gauge_pairs']) os.makedirs(DATA, exist_ok=True) pairs.to_csv(os.path.join(DATA, 'Data06n_grdc_gauge_sword_pairs.csv'), index=False) OUT['seconds'] = round(time.time() - T0, 1) json.dump(OUT, open(os.path.join(DATA, 'Data06n_sword_numbers_and_gauge_pairs.json'), 'w'), indent=1, default=int) log('written %s' % DATA) if __name__ == '__main__': main()