# -*- coding: utf-8 -*- """TDX-Hydro (region 7020014250) with the MNSI numbers of Model My Watershed, for Figure A3. The MNSI code is _vendor_mmw/mnsi.py, copied unchanged from WikiWatershed/global-hydrography (commit 5ff54aa, MIT). Input: ../Data/DataA4_flownest_clarkfork_*, ../Data/DataA{1,2}_*_clarkfork_littleblackfoot.json and TDX-Hydro (paths.TDX_HYDRO_DIR). Output: ../Data/DataA3_tdx_mmw_clarkfork_littleblackfoot.gpkg (layer link) and a JSON. Usage: python DataA3_tdx_mmw_clarkfork_littleblackfoot.py """ import os, json, time, warnings, importlib.util os.environ.setdefault('OMP_NUM_THREADS', '1'); os.environ.setdefault('PROJ_NETWORK', 'OFF') import numpy as np, pandas as pd, geopandas as gpd, pyogrio, rasterio from affine import Affine from shapely.geometry import Point import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH warnings.filterwarnings('ignore', message='Measured') HERE = os.path.dirname(os.path.abspath(__file__)) TDX = PTH.TDX_HYDRO_DIR REGION = 7020014250 HEADER = 72 # GEOGLOWS header number of this region, from the file that MMW reads: # https://geoglows-v2.s3-us-west-2.amazonaws.com/tdxhydro-processing/tdx_header_numbers.json NET = os.path.join(TDX, str(REGION), 'TDX_streamnet_%d_01.gpkg' % REGION) DATD = os.path.join(os.path.dirname(HERE), 'Data') STEM = os.path.join(DATD, 'DataA3_tdx_mmw_clarkfork_littleblackfoot') D01 = os.path.join(DATD, 'DataA1_nhdplus_clarkfork_littleblackfoot.json') # Figures A.1 (NHDPlus) and A.2 (HydroSHEDS): the junction must be the same one D02 = os.path.join(DATD, 'DataA2_hydrosheds_v1_clarkfork_littleblackfoot.json') D04 = os.path.join(DATD, 'DataA4_flownest_clarkfork_%s') JUNC_PIX, TRIB_PIX = 1088822414, 1088848706 # the FlowNest pixel that the Little Blackfoot flows to, and the outlet pixel of the Little Blackfoot MOUTH_PIX = 1088820338 # the FlowNest mouth pixel of the basin (gauge 50) EPSG = 5070 SOURCES = dict( streamnet=dict(product='TDX-Hydro (NGA, 2023), region %d, stream network' % REGION, file=os.path.basename(NET), bytes=824647680, sha256='2d2fff7009ba3257e1aa801bfc8e22201aed8f25751ee533d967f3b05047d705', downloaded='2026-10-30', url='https://www.arcgis.com/home/item.html?id=365e8b16f1fb438690b11716acd0d459', note='the ArcGIS Online copy of the NGA file; the NGA site (https://earth-info.nga.mil/) refused the connection'), header=dict(file='tdx_header_numbers.json', value=HEADER, note='GEOGLOWS header number of the region, as Model My Watershed uses it', url='https://geoglows-v2.s3-us-west-2.amazonaws.com/tdxhydro-processing/tdx_header_numbers.json'), mmw=dict(code='WikiWatershed/global-hydrography 5ff54aa, src/global_hydrography/delineation/mnsi.py, unchanged (MIT)'), licence='CC BY-SA 4.0') spec = importlib.util.spec_from_file_location('mmw_mnsi', os.path.join(HERE, '_vendor_mmw', 'mnsi.py')) mmw = importlib.util.module_from_spec(spec); spec.loader.exec_module(mmw) D, F, R = mmw.DISCOVER, mmw.FINISH, mmw.ROOT # ---------------------------------------------------------------- 1-3: read and preprocess as MMW does t0 = time.time() net = pyogrio.read_dataframe(NET, read_geometry=False) header = HEADER HD = header * 10_000_000 for c in ('LINKNO', 'DSLINKNO', 'USLINKNO1', 'USLINKNO2'): net[c] = net[c].astype('int64') net.loc[net[c] > -1, c] += HD net = net.drop(columns=['WSNO', 'DSNODEID']) K = len(net) print('region %d: %d links, header %d, read in %.0f s' % (REGION, K, header, time.time() - t0)) # ---------------------------------------------------------------- 4: MMW's function, unchanged t0 = time.time() net = mmw.modified_nest_set_index(net) print('MNSI computed in %.0f s; %d roots' % (time.time() - t0, net[R].nunique())) by = net.set_index('LINKNO') kids = {} for v, dn in zip(net.LINKNO.values, net.DSLINKNO.values): kids.setdefault(int(dn), []).append(int(v)) def above(v): got, st = set(), [int(v)] while st: y = st.pop(); got.add(y); st += kids.get(y, []) return got # where two links meet, which one the walk enters first: MMW pushes USLINKNO1, then USLINKNO2, and takes the last pushed first two = net[(net.USLINKNO1 != -1) & (net.USLINKNO2 != -1)] a1, a2 = by.DSContArea.reindex(two.USLINKNO1).values, by.DSContArea.reindex(two.USLINKNO2).values one_up = int(((net.USLINKNO1 != -1) ^ (net.USLINKNO2 != -1)).sum()) print('junctions: %d; USLINKNO2 drains less than USLINKNO1 at %.3f%% (the walk enters the smaller first), the same at %d; links with one upstream link: %d' % (len(two), 100 * np.mean(a2 < a1), int(np.sum(a2 == a1)), one_up)) # ---------------------------------------------------------------- the FlowNest outlet and junction, and the box to read bs = pd.read_parquet(D04 % 'basin.parquet').iloc[0] px = pd.read_parquet(D04 % 'pixel_1km2.parquet', columns=['pixel_seq_id', 'row', 'col', 'upstream_area_km2']).set_index('pixel_seq_id') assert int(bs.outlet_pixel_seq_id) == MOUTH_PIX with rasterio.open(D04 % 'pixel_seq_id_1km2.tif') as r_: TR, BB = r_.transform, r_.bounds GT = TR * Affine.translation(-int(bs.col_min), -int(bs.row_min)) centre = lambda pid: gpd.GeoSeries([Point(*(GT * (px.at[pid, 'col'] + 0.5, px.at[pid, 'row'] + 0.5)))], crs=4326).to_crs(EPSG).iloc[0] OUTLET, FN_JUNC = centre(MOUTH_PIX), centre(JUNC_PIX) A_MOUTH = float(px.at[MOUTH_PIX, 'upstream_area_km2']) BOX = (BB.left - 0.05, BB.bottom - 0.05, BB.right + 0.05, BB.top + 0.05) # the FlowNest basin window and 0.05° more on each side geo = pyogrio.read_dataframe(NET, bbox=BOX, columns=['LINKNO']) geo['LINKNO'] = geo['LINKNO'].astype('int64') + HD # every LINKNO is > -1 geo = geo.merge(net, on='LINKNO'); g5 = geo.to_crs(EPSG); gi, g5i = geo.set_index('LINKNO').geometry, g5.set_index('LINKNO').geometry assert all(g.geom_type == 'LineString' for g in geo.geometry), 'a link is not a single line' first = {int(v): Point(g.coords[0][:2]) for v, g in gi.items()}; last = {int(v): Point(g.coords[-1][:2]) for v, g in gi.items()} # ================================================================ the basin in TDX-Hydro, and the tree it belongs to big = g5[(g5.DSContArea > 20000e6) & (g5.DSContArea < 27000e6)]; d_out = big.distance(OUTLET).values outlet = int(big.LINKNO.iloc[int(np.argmin(d_out))]) assert d_out.min() < 1500, 'no link of 20,000 to 27,000 km² passes the FlowNest mouth pixel' bas_ = above(outlet) assert bas_ <= set(geo.LINKNO), 'the box does not hold every link of the basin' cf = int(by.at[outlet, 'DSLINKNO']) # the Clark Fork link below gauge 50 assert cf != -1 and by.at[cf, 'DSContArea'] > by.at[outlet, 'DSContArea'], 'the link below the outlet link does not drain more' path, v = [], outlet while v != -1: path.append(v); v = int(by.at[v, 'DSLINKNO']) root = path[-1]; tree = above(root) assert int(by.at[outlet, R]) == root and set(by.index[by[R] == root]) == tree, 'ROOT_ID is not the link at the mouth of the tree' assert by.at[root, 'DSContArea'] > 600000e6, 'the tree is not the Columbia' # the lines run upstream: the first vertex of a link is the last vertex of the link it flows to (checked for the basin and its outlet link) n_v = sum(first[v].equals(last[int(by.at[v, 'DSLINKNO'])]) for v in bas_) d_end = gpd.GeoSeries([first[outlet]], crs=4326).to_crs(EPSG).iloc[0].distance(OUTLET) print('basin above gauge 50: outlet link %d (%.2f km², FlowNest %.2f km²; passes %.0f m from the FlowNest mouth pixel, ends %.0f m from it), %d links, magnitude %d; it flows into link %d (%.1f km², the Clark Fork below)' % (outlet, by.at[outlet, 'DSContArea'] / 1e6, A_MOUTH, d_out.min(), d_end, len(bas_), by.at[outlet, 'Magnitude'], cf, by.at[cf, 'DSContArea'] / 1e6)) print(' below it, %d more links to the mouth link %d of the Columbia (%.0f km², ROOT_ID); the tree holds %d links' % (len(path) - 1, root, by.at[root, 'DSContArea'] / 1e6, len(tree))) print(' first vertex of a link = last vertex of the link it flows to: %d of %d' % (n_v, len(bas_))) assert n_v == len(bas_), 'the links of the basin do not join end to end' # ---------------------------------------------------------------- the main stem and the Little Blackfoot main, v = [], outlet while True: main.append(v); k_ = kids.get(v, []) if not k_: break v = max(k_, key=lambda u: by.at[u, 'DSContArea']) via1 = sum(int(by.at[u, 'USLINKNO1']) == w for u, w in zip(main[:-1], main[1:]) if len(kids.get(u, [])) == 2) print('main stem: %d links, %.1f km; it goes on through USLINKNO1 at %d of its %d junctions' % (len(main), by.loc[main, 'Length'].sum() / 1e3, via1, sum(len(kids.get(u, [])) == 2 for u in main[:-1]))) cand = [(u, t) for u in main for t in kids.get(u, []) if t not in main and 700e6 < by.at[t, 'DSContArea'] < 1500e6] # the Little Blackfoot: 1,074.87 km² in NHDPlus V2, 1,066.03 km² in FlowNest below, trib = min(cand, key=lambda ut: g5i[ut[1]].distance(FN_JUNC)) above_ = [u for u in kids[below] if u != trib] assert len(above_) == 1 and above_[0] in main, 'the main stem does not pass the junction as one link in, one out' up_ = above_[0] J = last[below] # the junction: the vertex the three links share assert first[trib].equals(J) and first[up_].equals(J), 'the three links do not meet in one vertex' J5 = gpd.GeoSeries([J], crs=4326).to_crs(EPSG).iloc[0] a_fn = float(px.at[TRIB_PIX, 'upstream_area_km2']); bear = above(trib) print('the Little Blackfoot: link %d (%.2f km²; FlowNest %.2f km²), %d links; junction %.0f m from the FlowNest junction pixel' % (trib, by.at[trib, 'DSContArea'] / 1e6, a_fn, len(bear), J5.distance(FN_JUNC))) assert J5.distance(FN_JUNC) < 1500 and abs(by.at[trib, 'DSContArea'] / 1e6 / a_fn - 1) < 0.3, 'this is not the Little Blackfoot junction of Figures A.1, A.2 and A.4' s1, s2 = json.load(open(D01)), json.load(open(D02)) P5 = lambda ll: gpd.GeoSeries([Point(*ll)], crs=4326).to_crs(EPSG).iloc[0] off = dict(flownest_m=float(J5.distance(FN_JUNC)), nhdplus_v2_m=float(J5.distance(P5(s1['v2']['junction_lonlat']))), nhdplus_hr_m=float(J5.distance(P5(s1['hr']['junction_lonlat']))), hydrosheds_m=float(J5.distance(P5(s2['junction_lonlat'])))) print('junction %.6f, %.6f: %s' % (J.x, J.y, ', '.join('%s %.0f' % kv for kv in off.items()))) # ---------------------------------------------------------------- MMW's query against tracing, for every link of the tree bad = 0 for v in bas_: r = by.loc[v] q = set(by.index[(by[R] == r[R]) & (by[D] >= r[D]) & (by[F] <= r[F])]) bad += q != above(v) print('links of the basin whose MMW query differs from tracing DSLINKNO: %d of %d' % (bad, len(bas_))) assert bad == 0 o = by.loc[outlet]; ds = np.sort(by.loc[sorted(bas_), D].values) order = by.loc[sorted(bas_)].sort_values(D).index.values runs = lambda m: int(1 + np.sum(np.diff(np.nonzero(m)[0]) > 1)) if np.any(m) else 0 main_runs, trib_runs = runs(np.isin(order, main)), runs(np.isin(order, list(bear))) contig = bool(ds[-1] - ds[0] + 1 == len(bas_) and ds[0] == o[D] and o[F] == ds[-1] + 1) print('basin DISCOVER_TIME %d to %d (%d links, one range: %s), FINISH_TIME of the outlet link %d; main stem in %d runs, the Little Blackfoot in %d' % (ds[0], ds[-1], len(bas_), contig, o[F], main_runs, trib_runs)) # ================================================================ the records of the three links records = [] for k, x in (('above', up_), ('trib', trib), ('below', below)): r = by.loc[x] records.append(dict(key=k, LINKNO=str(x), LINKNO_region=str(x - HD), DSLINKNO=str(int(r.DSLINKNO)), USLINKNO1=str(int(r.USLINKNO1)), USLINKNO2=str(int(r.USLINKNO2)), ROOT_ID=str(int(r[R])), DISCOVER_TIME=int(r[D]), FINISH_TIME=int(r[F]), strmOrder=int(r.strmOrder), Magnitude=int(r.Magnitude), Length_m=float(r.Length), DSContArea_km2=float(r.DSContArea / 1e6), USContArea_km2=float(r.USContArea / 1e6))) print(pd.DataFrame(records).set_index('key').T.to_string()) # ================================================================ write role = {up_: 'above', trib: 'trib', below: 'below'} lk = geo.copy() lk['in_basin'] = lk.LINKNO.isin(bas_); lk['in_tree'] = lk.LINKNO.isin(tree); lk['main'] = lk.LINKNO.isin(main); lk['trib'] = lk.LINKNO.isin(bear) lk['role'] = lk.LINKNO.map(role) for c in (R, D, F): lk[c] = lk[c].astype('int64') os.makedirs(DATD, exist_ok=True) lk.to_file(STEM + '.gpkg', layer='link', driver='GPKG') ll = lambda p: [float(v) for v in gpd.GeoSeries([p], crs=EPSG).to_crs(4326).iloc[0].coords[0]] summary = dict( flownest=dict(basin_id=int(bs.basin_id), mouth_pixel_seq_id=MOUTH_PIX, upstream_area_km2=A_MOUTH, junction_pixel_seq_id=JUNC_PIX, junction_lonlat=ll(FN_JUNC), trib_pixel_seq_id=TRIB_PIX, trib_area_km2=a_fn), region=dict(id=REGION, header=header, links=K, roots=int(net[R].nunique()), junctions=int(len(two)), uslinkno2_smaller_share=float(np.mean(a2 < a1)), uslinkno2_equal=int(np.sum(a2 == a1)), links_with_one_upstream=one_up, mmw_code=SOURCES['mmw']['code']), outlet=dict(LINKNO=str(outlet), DSContArea_km2=float(o.DSContArea / 1e6), passes_outlet_m=float(d_out.min()), downstream_end_from_outlet_m=float(d_end), DSLINKNO=str(cf), DSLINKNO_DSContArea_km2=float(by.at[cf, 'DSContArea'] / 1e6)), tree=dict(root=str(root), root_DSContArea_km2=float(by.at[root, 'DSContArea'] / 1e6), links=len(tree), links_below_outlet=len(path) - 1, path_to_root_links=len(path)), river=dict(links=len(bas_), magnitude=int(o.Magnitude), length_km=float(by.loc[sorted(bas_), 'Length'].sum() / 1e3), main_stem=len(main), main_stem_km=float(by.loc[main, 'Length'].sum() / 1e3), main_via_uslinkno1=[int(via1), int(sum(len(kids.get(u, [])) == 2 for u in main[:-1]))], trib=len(bear), discover_range=[int(ds[0]), int(ds[-1])], finish_outlet=int(o[F]), one_range=contig, main_runs_by_discover=main_runs, trib_runs_by_discover=trib_runs), records=records, junction_lonlat=[float(J.x), float(J.y)], junction_from=off, checks=dict(query_vs_tracing_mismatches=int(bad), links_checked=len(bas_), vertex_joins=[int(n_v), len(bas_)]), sources=SOURCES) json.dump(summary, open(STEM + '.json', 'w'), indent=1) print('written', STEM + '.gpkg / .json')