# -*- coding: utf-8 -*- """The SWORD v17c reaches and nodes of the Columbia, with their FlowNest numbers, for Figure 10. Output: ../Data/Data06l_columbia_sword_{reaches,nodes,unplaced_nodes}.parquet and ../Data/Data06l_columbia_sword_summary.json Input: ../Data (Data06j), the SWORD crosswalk (paths.SWORD_XW) and the global release (paths.GLOBAL). Usage: python Data06l_columbia_sword_new_numbers.py """ import os, json, hashlib import numpy as np, pandas as pd, pyarrow.parquet as pq import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH HERE = os.path.dirname(os.path.abspath(__file__)) DATD = os.path.join(os.path.dirname(HERE), 'Data') DATJ = DATD XW = os.path.join(PTH.SWORD_XW, 'flownest_merit90m_crosswalk_sword_v17c_%s.parquet') META = os.path.join(PTH.GLOBAL, 'metadata.json') CG = 47 def consecutive(seq, count, what): """the numbers seq are consecutive, and the first one's count covers exactly them.""" s = np.sort(seq) assert (np.diff(s) == 1).all(), what assert count[np.argmin(seq)] == len(s), what return int(s[0]), int(s[-1]) def main(): J = json.load(open(os.path.join(DATJ, 'Data06j_columbia_summary.json'))) K = pd.read_csv(os.path.join(DATJ, 'Data06j_columbia_gauges.csv')) first, last = J['first'], J['last'] g = K[K.k == CG].iloc[0]; assert g.grdc_station_id == 4115346 c0, c1 = int(g.pixel_seq_id), int(g.pixel_seq_id + g.upstream_channel_pixel_count - 1) meta = json.load(open(META)); gt = meta['grid']['geotransform'] xmeta = json.load(open(os.path.join(os.path.dirname(XW), 'metadata.json'))) assert meta['code_version'] == '10.61' and xmeta['code_version'] == '10.66' assert xmeta['release']['metadata_sha256'] == hashlib.sha256(open(META, 'rb').read()).hexdigest(), 'the crosswalk is made on _20261113_195421' assert abs(gt[1] - 1 / 1200) < 1e-12 and abs(gt[5] + 1 / 1200) < 1e-12 # ---- the reaches R = pd.read_parquet(XW % 'reach', columns=['sword_reach_id', 'sword_reach_seq_id', 'upstream_sword_reach_count', 'most_downstream_pixel_seq_id', 'sword_type', 'sword_lakeflag', 'sword_river_name', 'nodes', 'nodes_placed']) R = R[R.most_downstream_pixel_seq_id.between(first, last)].sort_values('sword_reach_seq_id').reset_index(drop=True) R['in_clark_fork'] = R.most_downstream_pixel_seq_id.between(c0, c1) ra = consecutive(R.sword_reach_seq_id.values, R.upstream_sword_reach_count.values, 'Columbia reaches') X = R[R.in_clark_fork] # the Clark Fork range starts below its first reach (at the pixel of gauge 47): its numbers are consecutive, no single count covers them s = np.sort(X.sword_reach_seq_id.values); assert (np.diff(s) == 1).all(); rx = (int(s[0]), int(s[-1])) assert ra == (226283, 227349) and len(R) == 1067 and rx == (226655, 226771) and len(X) == 117 # ---- the nodes placed in the Columbia cols = ['sword_node_id', 'sword_node_seq_id', 'upstream_sword_node_count', 'sword_reach_id', 'sword_lon', 'sword_lat', 'pixel_seq_id', 'row', 'col', 'distance_to_pixel_m', 'upstream_area_km2'] N = pq.read_table(XW % 'node', columns=cols, filters=[('pixel_seq_id', '>=', first), ('pixel_seq_id', '<=', last)]).to_pandas() N = N.sort_values('sword_node_seq_id').reset_index(drop=True) na = consecutive(N.sword_node_seq_id.values, N.upstream_sword_node_count.values, 'Columbia nodes') N['lon'] = gt[0] + (N['col'] + 0.5) * gt[1]; N['lat'] = gt[3] + (N['row'] + 0.5) * gt[5] # the pixel centre and the SWORD position agree with the distance in the table (within 1 %, the table uses another formula) p = np.radians; d = 2 * 6371008.8 * np.arcsin(np.sqrt(np.sin((p(N.lat) - p(N.sword_lat)) / 2) ** 2 + np.cos(p(N.lat)) * np.cos(p(N.sword_lat)) * np.sin((p(N.lon) - p(N.sword_lon)) / 2) ** 2)) e = np.abs(d - N.distance_to_pixel_m); print("distance check: max %.1f m, max ratio %.4f" % (e.max(), (e / np.maximum(d, 1)).max())); assert (e <= 0.01 * d + 1).all() N['in_clark_fork'] = N.pixel_seq_id.between(c0, c1) nx = N[N.in_clark_fork]; s = nx.sword_node_seq_id.values; assert (np.diff(s) == 1).all(); nxr = (int(s[0]), int(s[-1])) assert set(N.sword_reach_id) == set(R.sword_reach_id) # the reaches are those of the nodes placed N = N.merge(R[['sword_reach_id', 'sword_reach_seq_id', 'upstream_sword_reach_count']], on='sword_reach_id', how='left') # ---- the nodes not placed, in the bounding box of the basin (the figure keeps those inside it) U = pq.read_table(XW % 'node', columns=['sword_node_id', 'sword_reach_id', 'sword_lon', 'sword_lat', 'sword_lakeflag', 'pixel_seq_id'], filters=[('pixel_seq_id', '==', 0), ('sword_lon', '>=', -125.0), ('sword_lon', '<=', -108.0), ('sword_lat', '>=', 40.0), ('sword_lat', '<=', 54.0)]).to_pandas() S = dict(release='flownest_merit90m_crosswalk_sword_v17c_20261113_195421', columbia_reaches=len(R), columbia_reach_numbers=ra, clark_fork_reaches=len(X), clark_fork_reach_numbers=rx, columbia_nodes=len(N), columbia_node_numbers=na, clark_fork_nodes=int(N.in_clark_fork.sum()), clark_fork_node_numbers=nxr, clark_fork_node_reaches=int(N[N.in_clark_fork].sword_reach_id.nunique()), unplaced_nodes_in_box=len(U)) for rid in (78266300191, 78266800041, 78266600041, 78266400011): r = R[R.sword_reach_id == rid].iloc[0] q = N[N.sword_reach_id == rid].iloc[0] # its first node in number order: the most downstream one assert q.sword_node_id == rid // 10 * 10000 + 11 and q.pixel_seq_id == r.most_downstream_pixel_seq_id assert r.sword_reach_seq_id + r.upstream_sword_reach_count - 1 <= rx[1] S['reach_%d' % rid] = dict(name=r.sword_river_name, reach_number=int(r.sword_reach_seq_id), reach_count=int(r.upstream_sword_reach_count), node_id=int(q.sword_node_id), node_number=int(q.sword_node_seq_id), node_count=int(q.upstream_sword_node_count), pixel_seq_id=int(q.pixel_seq_id)) R.to_parquet(os.path.join(DATD, 'Data06l_columbia_sword_reaches.parquet'), index=False) N.to_parquet(os.path.join(DATD, 'Data06l_columbia_sword_nodes.parquet'), index=False) U.to_parquet(os.path.join(DATD, 'Data06l_columbia_sword_unplaced_nodes.parquet'), index=False) json.dump(S, open(os.path.join(DATD, 'Data06l_columbia_sword_summary.json'), 'w'), indent=1) print(json.dumps(S, indent=1)) if __name__ == '__main__': main()