# -*- coding: utf-8 -*- """Checks behind the gauge and SWORD numbers of the text. B1 the gauge - node pairs against the GRDC catchment areas (52,341 pairs, 56 on the same pixel); B2 the river names of the 4,365 pairs with names on both sides (pairs with different names are written out); B3 the pairs by SWORD type and match confidence; T04 the SWORD links against the placement on FlowNest. Input: paths.GLOBAL, paths.GRDC_XW, paths.SWORD_XW, the GRDC catchment shapefiles (paths.GRDC_SHP_DIR) and the SWORD v17c GeoPackages (paths.SWORD_GPKG_DIR). Output: ../Data/Data22_checks_gauges_sword.json, ../Data/Data22_pairs_different_river_names.csv and ../Data/Data22_sword_links_not_agreeing.csv Usage: python Data22_checks_gauges_sword.py """ import os, re, glob, json, time, difflib, unicodedata, warnings import numpy as np, pandas as pd, pyarrow.parquet as pq, pyogrio import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH warnings.filterwarnings('ignore', category=RuntimeWarning) HERE = os.path.dirname(os.path.abspath(__file__)) DATD = os.path.join(os.path.dirname(HERE), 'Data') TAG = '20261113_195421' GLOB = PTH.GLOBAL GRDC = os.path.join(PTH.GRDC_XW, 'flownest_merit90m_crosswalk_grdc_burek2023.parquet') SWD = PTH.SWORD_XW PAIR = os.path.join(PTH.GRDC_XW, 'flownest_merit90m_crosswalk_grdc_burek2023_sword_v17c_node_pair.parquet') SHP = PTH.GRDC_SHP_DIR SWORD_GPKG = sorted(glob.glob(os.path.join(PTH.SWORD_GPKG_DIR, 'sword_*_v17c.gpkg'))) assert len(SWORD_GPKG) == 6 t0 = time.time(); out = {'release': TAG} def pct(a, b): return round(100.0 * a / b, 1) # ================================================================ B1 gauge pairs and reported areas G = pq.read_table(GRDC, columns=['station_seq_id', 'grdc_station_id', 'grdc_reported_area_km2', 'pixel_seq_id', 'upstream_station_count']).to_pandas().sort_values('station_seq_id', ignore_index=True) n = len(G); assert n == 10241 and (G.station_seq_id.values == np.arange(1, n + 1)).all() cnt = G.upstream_station_count.values.astype(np.int64) s_idx = np.repeat(np.arange(n), cnt - 1) u_idx = s_idx + 1 + (np.arange(s_idx.size) - np.repeat(np.cumsum(cnt - 1) - (cnt - 1), cnt - 1)) assert s_idx.size == 52341 and (u_idx < s_idx + cnt[s_idx]).all() and (u_idx < n).all() pix = G.pixel_seq_id.values.astype(np.int64) assert (pix[u_idx] >= pix[s_idx]).all() # an upstream gauge never has a smaller pixel number same = pix[u_idx] == pix[s_idx]; assert same.sum() == 56 a = G.grdc_reported_area_km2.values.astype('f8'); a[~(a > 0)] = np.nan au, ad = a[u_idx], a[s_idx]; both = np.isfinite(au) & np.isfinite(ad) def b1(mask): m = mask & both; r = au[m] / ad[m] return {'pairs': int(mask.sum()), 'both_areas': int(m.sum()), 'upstream_smaller': int((r < 1).sum()), 'equal': int((r == 1).sum()), 'upstream_larger': int((r > 1).sum()), 'upstream_larger_by_more_than_5pct': int((r > 1.05).sum()), 'upstream_larger_by_more_than_10pct': int((r > 1.10).sum())} out['B1'] = {'all': b1(np.ones_like(same)), 'different_pixel': b1(~same), 'same_pixel': b1(same), 'gauges_with_reported_area': int(np.isfinite(a).sum())} d = out['B1']['different_pixel'] d['share_upstream_larger_pct'] = pct(d['upstream_larger'], d['both_areas']) d['share_upstream_larger_by_more_than_10pct_pct'] = pct(d['upstream_larger_by_more_than_10pct'], d['both_areas']) # Adjacent pairs: each gauge with the next gauge downstream of it only, i.e. the innermost range that holds it # (largest s with u in [s+1, s+cnt(s))). Pairs of gauges far apart along a river pass the test easily; these do not. assert (u_idx + cnt[u_idx] <= s_idx + cnt[s_idx]).all() # the ranges nest next_down = np.full(n, -1, dtype=np.int64); np.maximum.at(next_down, u_idx, s_idx) adj = s_idx == next_down[u_idx] assert adj.sum() == (next_down >= 0).sum() # one adjacent pair per gauge that has a gauge downstream out['B1']['adjacent_different_pixel'] = b1(adj & ~same) out['B1']['adjacent_same_pixel'] = b1(adj & same) e = out['B1']['adjacent_different_pixel'] e['share_upstream_smaller_pct'] = pct(e['upstream_smaller'], e['both_areas']) e['share_upstream_larger_by_more_than_10pct_pct'] = pct(e['upstream_larger_by_more_than_10pct'], e['both_areas']) print('B1', out['B1'], '%.0f s' % (time.time() - t0)) # ================================================================ SWORD tables used by B2, B3, T04 SR = pq.read_table(os.path.join(SWD, 'flownest_merit90m_crosswalk_sword_v17c_reach.parquet'), columns=['sword_reach_id', 'sword_type', 'sword_lakeflag', 'sword_main_side', 'matched_at_step', 'most_downstream_pixel_seq_id', 'fix_note']).to_pandas() assert len(SR) == 248673 cols = ['reach_id', 'n_rch_down', 'rch_id_dn_1', 'rch_id_dn_2', 'rch_id_dn_3', 'rch_id_dn_4', 'main_side', 'lakeflag', 'river_name', 'river_name_en', 'river_name_local'] SW = pd.concat([pyogrio.read_dataframe(f, layer='reaches', columns=cols, read_geometry=False) for f in SWORD_GPKG], ignore_index=True) assert len(SW) == 248673 and SW.reach_id.is_unique and set(SW.reach_id) == set(SR.sword_reach_id) # ================================================================ B2 river names of the 4,365 pairs P = pq.read_table(PAIR).to_pandas(); assert len(P) == 10241 P = P[P.pair_within_10pct.fillna(False).astype(bool)].copy(); assert len(P) == 4365 names = [] for f in sorted(glob.glob(os.path.join(SHP, '*.dbf'))): t = pyogrio.read_dataframe(f, columns=['grdc_no', 'river'], read_geometry=False) names.append(t) GN = pd.concat(names, ignore_index=True); GN['grdc_no'] = GN.grdc_no.astype('int64') GN = GN.drop_duplicates('grdc_no'); assert GN.grdc_no.is_unique P = P.merge(GN.rename(columns={'grdc_no': 'grdc_station_id', 'river': 'grdc_river'}), on='grdc_station_id', how='left') P = P.merge(SW[['reach_id', 'river_name', 'river_name_en', 'river_name_local']].rename(columns={'reach_id': 'pair_sword_reach_id'}), on='pair_sword_reach_id', how='left') assert len(P) == 4365 and P.pair_sword_reach_id.notna().all() GENERIC = {'RIVER', 'RIV', 'R', 'RIO', 'RIVIERE', 'RIVIER', 'FLEUVE', 'FLUSS', 'GANG', 'KAWA', 'GAWA', 'NADI', 'NAHR', 'OUED', 'WADI', 'JIANG', 'HE', 'DO', 'DA', 'DOS', 'DAS', 'DE', 'DEL', 'DI', 'LA', 'LE', 'LES', 'DU', 'DES', 'OF', 'THE'} SUFFIX = ('RIVIER', 'GANG', 'GAWA', 'KAWA') # e.g. BERGRIVIER = BERG + RIVIER, NAKDONGGANG = NAKDONG + GANG def latin(s): if s is None or isinstance(s, float): return '' return unicodedata.normalize('NFKD', str(s)).encode('ascii', 'ignore').decode().upper() def tokens(s): out = [] for w in re.sub(r"[^A-Z0-9 ]", ' ', re.sub(r"['`]", '', s)).split(): if w in GENERIC: continue for suf in SUFFIX: if w.endswith(suf) and len(w) > len(suf) + 2: w = w[:-len(suf)]; break out.append(w) return out def sword_names(row): out = [] for c in ('river_name', 'river_name_en', 'river_name_local'): v = row[c] if v is None or isinstance(v, float) or v == 'NODATA': continue for part in re.split(r'[;/,]', str(v)): tk = tokens(latin(part)) if tk: out.append(tk) return out def compare(g, ss): gt = tokens(latin(g)) if not gt: return 'no_gauge_name' if not ss: return 'no_sword_name' gj = ''.join(gt); best = 0.0 for st in ss: sj = ''.join(st) if set(gt) <= set(st) or set(st) <= set(gt) or gj == sj: return 'same' best = max(best, difflib.SequenceMatcher(None, gj, sj).ratio()) return 'same_other_spelling' if best >= 0.8 else 'different' P['name_check'] = [compare(g, s) for g, s in zip(P.grdc_river, P.apply(sword_names, axis=1))] vc = P.name_check.value_counts().to_dict() both_named = vc.get('same', 0) + vc.get('same_other_spelling', 0) + vc.get('different', 0) out['B2'] = {k: int(v) for k, v in vc.items()} out['B2']['both_named'] = int(both_named) out['B2']['same_or_other_spelling'] = int(vc.get('same', 0) + vc.get('same_other_spelling', 0)) out['B2']['same_or_other_spelling_pct'] = pct(out['B2']['same_or_other_spelling'], both_named) assert sum(vc.values()) == 4365 P[P.name_check == 'different'][['station_seq_id', 'grdc_station_id', 'grdc_river', 'pair_sword_reach_id', 'river_name', 'river_name_en', 'river_name_local', 'pair_side', 'pair_area_ratio']] \ .to_csv(os.path.join(DATD, 'Data22_pairs_different_river_names.csv'), index=False) print('B2', out['B2'], '%.0f s' % (time.time() - t0)) # ================================================================ B3 pairs by node type and confidence ND = pq.read_table(os.path.join(SWD, 'flownest_merit90m_crosswalk_sword_v17c_node.parquet'), columns=['sword_node_seq_id', 'sword_reach_id', 'match_confidence', 'pixel_seq_id', 'reach_seq_id_1km2']).to_pandas() Q = P.merge(ND[['sword_node_seq_id', 'sword_reach_id', 'match_confidence']].dropna(subset=['sword_node_seq_id']) .astype({'sword_node_seq_id': 'int64'}).rename(columns={'sword_node_seq_id': 'pair_sword_node_seq_id'}), on='pair_sword_node_seq_id', how='left') assert len(Q) == 4365 and (Q.sword_reach_id == Q.pair_sword_reach_id).all() Q = Q.merge(SR[['sword_reach_id', 'sword_type']], on='sword_reach_id', how='left') tab = pd.crosstab(Q.sword_type, Q.match_confidence) out['B3'] = {'by_type_and_confidence': {str(k): {str(c): int(v) for c, v in r.items()} for k, r in tab.iterrows()}, 'type1_high': int(((Q.sword_type == 1) & (Q.match_confidence == 'high')).sum()), 'type1': int((Q.sword_type == 1).sum()), 'high': int((Q.match_confidence == 'high').sum())} out['B3']['type1_high_pct'] = pct(out['B3']['type1_high'], 4365) print('B3', out['B3'], '%.0f s' % (time.time() - t0)) # ================================================================ T04 SWORD links against the placement RU = pq.read_table(os.path.join(GLOB, 'flownest_merit90m_reach_1km2.parquet'), columns=['upstream_reach_count']).column(0).to_numpy() UPC = np.r_[0, RU.astype(np.int64)] # index by reach_seq_id S1 = SR[SR.matched_at_step.isin(['3x3', '5x5', '7x7']) & SR.most_downstream_pixel_seq_id.notna()].copy() # = match_stage 1 S1['px'] = S1.most_downstream_pixel_seq_id.astype(np.int64) S1['sw'] = S1.fix_note.fillna('').str.contains('through_path_switch|upstream_continuation_switch|area_guided_switch').values # moved onto a SWORD neighbor's path later pr = ND.dropna(subset=['pixel_seq_id', 'reach_seq_id_1km2']).astype({'pixel_seq_id': 'int64', 'reach_seq_id_1km2': 'int64'}) pr = pr[pr.pixel_seq_id.isin(S1.px)].drop_duplicates('pixel_seq_id')[['pixel_seq_id', 'reach_seq_id_1km2']] S1 = S1.merge(pr.rename(columns={'pixel_seq_id': 'px', 'reach_seq_id_1km2': 'rc'}), on='px', how='left') assert S1.rc.notna().all() out['T04'] = {'stage1_reaches': int(SR.matched_at_step.isin(['3x3', '5x5', '7x7']).sum()), 'stage1_reaches_with_pixel': int(len(S1)), 'stage1_reaches_switched': int(S1.sw.sum())} assert out['T04']['stage1_reaches_switched'] == 528 L = [] for k in (1, 2, 3, 4): t = SW[['reach_id', 'rch_id_dn_%d' % k, 'n_rch_down', 'main_side', 'lakeflag']].rename(columns={'rch_id_dn_%d' % k: 'dn'}) L.append(t[t.dn.notna() & (t.dn > 0)]) L = pd.concat(L, ignore_index=True).astype({'dn': 'int64'}) out['T04']['sword_links'] = int(len(L)) k1 = S1[['sword_reach_id', 'px', 'rc', 'sword_lakeflag', 'sw']] L = L.merge(k1.rename(columns={'sword_reach_id': 'reach_id', 'px': 'pr', 'rc': 'cr', 'sword_lakeflag': 'lk_r', 'sw': 'sw_r'}), on='reach_id') \ .merge(k1.rename(columns={'sword_reach_id': 'dn', 'px': 'pd', 'rc': 'cd', 'sword_lakeflag': 'lk_d', 'sw': 'sw_d'}), on='dn') pr_, pd_, cr, cd = (L[c].values.astype(np.int64) for c in ('pr', 'pd', 'cr', 'cd')) def upstream(px_a, c_a, px_b, c_b): # is pixel a at or upstream of pixel b return np.where(c_a == c_b, px_a >= px_b, (c_a > c_b) & (c_a < c_b + UPC[c_b])) r_up, d_up = upstream(pr_, cr, pd_, cd), upstream(pd_, cd, pr_, cr) cls = np.where(pr_ == pd_, 'same_pixel', np.where(r_up, 'agrees', np.where(d_up, 'reversed', 'apart'))) L['cls'] = cls def tally(m): v = pd.Series(cls[m]).value_counts().to_dict(); tot = int(m.sum()) return {'links': tot, **{k: int(v.get(k, 0)) for k in ('agrees', 'same_pixel', 'reversed', 'apart')}, 'agrees_pct': pct(v.get('agrees', 0), tot) if tot else None} one = (L.n_rch_down.values == 1); main = (L.main_side.values == 0); lake = (L.lk_r.values > 0) | (L.lk_d.values > 0) keep = ~(L.sw_r.values | L.sw_d.values) for name, m in (('all_stage1', np.ones(len(L), bool)), ('no_switch', keep)): out['T04'][name] = {'both_stage1': tally(m), 'single_downstream': tally(m & one), 'single_downstream_main_no_lake': tally(m & one & main & ~lake), 'multiple_downstream': tally(m & ~one), 'side_channel_or_secondary_outlet': tally(m & ~main), 'lake_or_reservoir_involved': tally(m & lake)} assert out['T04']['all_stage1']['both_stage1']['links'] == 194556 L[keep & L.cls.isin(['reversed', 'apart']).values][['reach_id', 'dn', 'n_rch_down', 'main_side', 'lk_r', 'lk_d', 'pr', 'pd', 'cr', 'cd', 'cls']] \ .to_csv(os.path.join(DATD, 'Data22_sword_links_not_agreeing.csv'), index=False) print('T04', json.dumps(out['T04'], indent=1), '%.0f s' % (time.time() - t0)) json.dump(out, open(os.path.join(DATD, 'Data22_checks_gauges_sword.json'), 'w'), indent=1) print('wrote Data22_checks_gauges_sword.json, %.0f s' % (time.time() - t0))