# -*- coding: utf-8 -*- """NHDPlus V2 and NHDPlus HR for the Clark Fork above GRDC gauge 4115348, for Figure A1. The gauge sits on FlowNest pixel 1,088,820,338. The script clips the NHDPlus V2 flowlines, catchments and areas and the NHDPlus HR flowlines to the FlowNest catchment of that pixel. Input: ../Data/DataA4_flownest_clarkfork_*, NHDPlus V2 (paths.NHDPLUS_V2_DIR) and NHDPlus HR (paths.NHDPLUS_HR_GPKG). Output: ../Data/DataA1_nhdplus_clarkfork_littleblackfoot.gpkg (layers v2_flowline, v2_catchment, v2_area, hr_flowline) and a JSON. Usage: python DataA1_nhdplus_clarkfork_littleblackfoot.py """ import os, json, warnings 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 from shapely.ops import unary_union import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH warnings.filterwarnings('ignore', message='Measured') V2 = PTH.NHDPLUS_V2_DIR HR = PTH.NHDPLUS_HR_GPKG DATD = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'Data') STEM = os.path.join(DATD, 'DataA1_nhdplus_clarkfork_littleblackfoot') D04 = os.path.join(DATD, 'DataA4_flownest_clarkfork_%s') # what DataA4_flownest_clarkfork_gauge50.py cut out of the release flownest_merit90m_global_20261113_195421 RIVER, TRIB_NAME = 'Clark Fork', 'Little Blackfoot River' UNITS = ('17010201', '17010202', '17010203', '17010204', '17010205') # Upper Clark Fork, Flint-Rock, Blackfoot, Middle Clark Fork, Bitterroot MOUTH_PIX = 1088820338 # the FlowNest pixel of gauge 50 (Clark Fork below Missoula) JUNC_PIX = 1088822414 # the FlowNest pixel that the Little Blackfoot flows to EPSG = 5070 SOURCES = dict( v2='NHDPlus V2.1, Pacific Northwest, vector processing unit 17: NHDPlusV21_PN_17_NHDSnapshot_08 (NHDFlowline.shp), ' 'NHDPlusV21_PN_17_NHDPlusAttributes_10 (PlusFlowlineVAA.dbf, PlusFlow.dbf), NHDPlusV21_PN_17_NHDPlusCatchment_02 (Catchment.shp)', hr=dict(file='NHDPLUS_H_1701_HU4_GPKG.gpkg', url='https://prd-tnm.s3.amazonaws.com/StagedProducts/Hydrography/NHDPlusHR/VPU/Current/GPKG/NHDPLUS_H_1701_HU4_GPKG.zip', zip_sha256='633239923f25ce628f782e1d8914e1083c43043b481aa44c38696ddb1c1d3db6', downloaded='2026-11-09 13:53 Beijing time', content_dated='2024-02-29')) # the columns that play the same part in the two products N2 = dict(id='COMID', seq='HYDROSEQ', dn='DNHYDROSEQ', up='UPHYDROSEQ', lp='LEVELPATHI', name='GNIS_NAME', area='TOTDASQKM', rc='REACHCODE', div='DIVERGENCE') NH = dict(id='NHDPlusID', seq='HydroSeq', dn='DnHydroSeq', up='UpHydroSeq', lp='LevelPathI', name='GNIS_Name', area='TotDASqKm', rc='ReachCode', div='Divergence') def ints(df, cols): for c in cols: df[c] = df[c].fillna(0).round().astype('int64') return df def plain(v): """A value as json takes it (numpy numbers to Python, missing to None).""" if v is None or (isinstance(v, float) and np.isnan(v)): return None return int(v) if isinstance(v, (np.integer, int)) else float(v) if isinstance(v, (np.floating, float)) else str(v) # ---------------------------------------------------------------- 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') 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] assert int(bs.outlet_pixel_seq_id) == MOUTH_PIX OUTLET, FN_JUNC = centre(MOUTH_PIX), centre(JUNC_PIX) A_DELTA = float(px.at[MOUTH_PIX, 'upstream_area_km2']) # the FlowNest area at the mouth BOX = (BB.left - 0.03, BB.bottom - 0.03, BB.right + 0.03, BB.top + 0.03) # the window of the region and 0.03° more on each side def cut(vaa, fl, N, name): """The basin above the FlowNest outlet in one product. vaa: value-added attributes of the whole (sub)region; fl: the flowlines read in BOX, with their names and reach codes; N: the product's column names.""" I, S, D, L, A, M = N['id'], N['seq'], N['dn'], N['lp'], N['area'], N['name'] kids = {} for h, d in zip(vaa[S].values, vaa[D].values): kids.setdefault(int(d), []).append(int(h)) def up(h): got, stack = set(), [int(h)] while stack: x = stack.pop(); got.add(x); stack += kids.get(x, []) return got near = fl[fl[M] == RIVER].to_crs(EPSG).merge(vaa[[I, A, N['div']]], on=I) near = near[near[N['div']] != 2]; pick = near.loc[near.distance(OUTLET).idxmin()] # the Clark Fork braids at the gauge: the flowline of the main path nearest the gauge pixel mouth = vaa[vaa[I] == int(pick[I])].iloc[0]; d_mouth = float(pick.geometry.distance(OUTLET)) print('%s: mouth %.2f km², FlowNest at the mouth %.2f km² (%+.1f%%), %.0f m apart' % (name, mouth[A], A_DELTA, 100 * (mouth[A] / A_DELTA - 1), d_mouth)) assert d_mouth < 300 and abs(mouth[A] / A_DELTA - 1) < 0.10, '%s: no flowline named %s at the FlowNest gauge-50 pixel' % (name, RIVER) bas = vaa[vaa[S].isin(up(mouth[S]))].merge(fl.drop(columns='geometry'), on=I, how='left', indicator=True) assert (bas._merge == 'both').all(), '%s: flowlines of the basin outside the box read' % name bas = bas.drop(columns='_merge'); bas['main'] = bas[L] == mouth[L] tc = bas[(bas[M] == TRIB_NAME) & bas[D].isin(set(bas[S][bas.main]))] assert len(tc), '%s: no %s flows into the main stem' % (name, TRIB_NAME) trib = tc.loc[tc[A].idxmax()] bas['trib'] = bas[S].isin(up(trib[S])) below = bas[bas[S] == trib[D]].iloc[0] above = bas[(bas[D] == below[S]) & bas.main] assert below.main and len(above) == 1, '%s: the main stem does not pass the junction as one flowline in, one out' % name three = dict(above=above.iloc[0], trib=trib, below=below) bas['role'] = bas[I].map({int(r[I]): k for k, r in three.items()}) # what the numbers are, checked on the whole (sub)region rather than taken from the documentation lp_min = vaa.groupby(L)[S].min(); lp_ok = lp_min.index.values == lp_min.values dn = bas[bas[D] > 0] assert (dn[D] < dn[S]).all(), '%s: a flowline flows to a larger HydroSeq' % name for k in ('trib', 'below'): assert lp_min[three[k][L]] == three[k][L], '%s: the level path of %s is not numbered by its smallest HydroSeq' % (name, k) huc8 = sorted(set(str(c)[:8] for c in bas[N['rc']])) print(' hydrologic units of the flowlines:', bas[N['rc']].astype(str).str[:8].value_counts().to_dict()) assert bas[N['rc']].astype(str).str[:8].isin(UNITS).mean() > 0.99, '%s: the basin is not in units %s: %s' % (name, UNITS, huc8) huc8 = [u for u in UNITS if u in huc8] print('%s: mouth %d (%.2f km², %.0f m from the FlowNest gauge-50 pixel); %d flowlines, %d reach codes, %d level paths, units %s' % (name, mouth[I], mouth[A], d_mouth, len(bas), bas[N['rc']].nunique(), bas[L].nunique(), ','.join(huc8))) print(' LevelPathI is the smallest HydroSeq on its level path for %d of %d level paths of the (sub)region; HydroSeq decreases downstream for all %d links of the basin' % (lp_ok.sum(), len(lp_ok), len(dn))) print(' main stem %d flowlines | %s: %d (%.2f km²), %d flowlines | below %d | above %d' % (bas.main.sum(), TRIB_NAME, trib[I], trib[A], bas.trib.sum(), below[I], three['above'][I])) return bas, mouth, d_mouth, three, huc8 def junction(fl, N, three): """The end of the flowline below that is nearest the tributary (EPSG 5070).""" g = fl.to_crs(EPSG).set_index(N['id']).geometry gb, gt = g[int(three['below'][N['id']])], g[int(three['trib'][N['id']])] ends = [Point(c[:2]) for p_ in (gb.geoms if gb.geom_type.startswith('Multi') else [gb]) for c in (p_.coords[0], p_.coords[-1])] return min(ends, key=gt.distance) # ================================================================ NHDPlus V2 I2 = ['COMID', 'HYDROSEQ', 'DNHYDROSEQ', 'UPHYDROSEQ', 'LEVELPATHI', 'TERMINALPA', 'FROMNODE', 'TONODE'] v2 = pyogrio.read_dataframe(V2 + '/NHDPlusAttributes/PlusFlowlineVAA.dbf', read_geometry=False, columns=['ComID', 'Hydroseq', 'DnHydroseq', 'UpHydroseq', 'LevelPathI', 'TerminalPa', 'FromNode', 'ToNode', 'StreamOrde', 'Divergence', 'TotDASqKM']) v2.columns = [c.upper() for c in v2.columns]; v2 = ints(v2, I2 + ['STREAMORDE', 'DIVERGENCE']); v2 = v2[v2.HYDROSEQ > 0] f2 = pyogrio.read_dataframe(V2 + '/NHDSnapshot/Hydrography/NHDFlowline.shp', bbox=BOX, columns=['COMID', 'GNIS_ID', 'GNIS_NAME', 'REACHCODE', 'FTYPE']) f2['COMID'] = f2.COMID.round().astype('int64'); f2['geometry'] = f2.geometry.force_2d() b2, m2, d2, t2, huc2 = cut(v2, f2, N2, 'NHDPlus V2') pf = pyogrio.read_dataframe(V2 + '/NHDPlusAttributes/PlusFlow.dbf', read_geometry=False, columns=['FROMCOMID', 'TOCOMID']) pf = ints(pf, ['FROMCOMID', 'TOCOMID']); pf = pf[pf.FROMCOMID.isin(set(b2.COMID))] to2 = pf.groupby('FROMCOMID').TOCOMID.agg(list) seq2c = dict(zip(v2.HYDROSEQ, v2.COMID)) for k, r in t2.items(): # the flow table and the sequence numbers name the same flowline downstream assert to2[r.COMID] == [seq2c[r.DNHYDROSEQ]], 'V2 %s: PlusFlow gives %s, DNHYDROSEQ gives %d' % (k, to2[r.COMID], seq2c[r.DNHYDROSEQ]) ct = pyogrio.read_dataframe(V2 + '/NHDPlusCatchment/Catchment.shp', bbox=BOX, columns=['GRIDCODE', 'FEATUREID', 'AreaSqKM']) ct = ints(ct, ['GRIDCODE', 'FEATUREID']) gc2 = dict(zip(ct.FEATUREID, ct.GRIDCODE)) cls2 = dict(zip(b2.COMID, np.where(b2.trib, 'trib', np.where(b2.main, 'main', 'other')))) ct['in_basin'] = ct.FEATUREID.isin(set(b2.COMID)); ct['cls'] = ct.FEATUREID.map(cls2); ct['trib'] = ct.cls == 'trib' ct['role'] = ct.FEATUREID.map(dict(zip(b2.COMID, b2.role))) cin = ct[ct.in_basin] area2 = unary_union(cin.to_crs(EPSG).geometry.buffer(0)) print(' %d catchments in the basin (%.2f km² by AreaSqKM, %.2f km² by their outline); %d flowlines have none; %d flowlines with more than one row in PlusFlow' % (len(cin), cin.AreaSqKM.sum(), area2.area / 1e6, len(b2) - len(cin), (to2.str.len() > 1).sum())) f2 = f2.merge(v2[I2[1:] + ['COMID', 'TOTDASQKM']], on='COMID', how='left'); f2 = ints(f2, I2[1:]) f2['in_basin'] = f2.COMID.isin(set(b2.COMID)); f2['main'] = f2.COMID.isin(set(b2.COMID[b2.main])); f2['trib'] = f2.COMID.isin(set(b2.COMID[b2.trib])) f2['role'] = f2.COMID.map(dict(zip(b2.COMID, b2.role))) j2 = junction(f2, N2, t2) # ================================================================ NHDPlus HR IH = ['NHDPlusID', 'HydroSeq', 'DnHydroSeq', 'UpHydroSeq', 'LevelPathI', 'TerminalPa', 'FromNode', 'ToNode'] vh = pyogrio.read_dataframe(HR, layer='NHDPlusFlowlineVAA', read_geometry=False, columns=IH + ['StreamOrde', 'Divergence', 'TotDASqKm']) vh = ints(vh, IH + ['StreamOrde', 'Divergence']); vh = vh[vh.HydroSeq > 0] fh = pyogrio.read_dataframe(HR, layer='NHDFlowline', bbox=BOX, columns=['NHDPlusID', 'Permanent_Identifier', 'GNIS_ID', 'GNIS_Name', 'ReachCode', 'FType']) fh['NHDPlusID'] = fh.NHDPlusID.round().astype('int64'); fh['geometry'] = fh.geometry.force_2d() bh, mh, dh, th, huch = cut(vh, fh, NH, 'NHDPlus HR') ids = ','.join(str(int(r.NHDPlusID)) for r in th.values()) fw = ints(pyogrio.read_dataframe(HR, layer='NHDPlusFlow', read_geometry=False, columns=['FromNHDPID', 'ToNHDPID'], where='FromNHDPID IN (%s)' % ids), ['FromNHDPID', 'ToNHDPID']) toh = fw.groupby('FromNHDPID').ToNHDPID.agg(list) seqh = dict(zip(vh.HydroSeq, vh.NHDPlusID)) for k, r in th.items(): assert toh[r.NHDPlusID] == [seqh[r.DnHydroSeq]], 'HR %s: NHDPlusFlow gives %s, DnHydroSeq gives %d' % (k, toh[r.NHDPlusID], seqh[r.DnHydroSeq]) ch = ints(pyogrio.read_dataframe(HR, layer='NHDPlusCatchment', read_geometry=False, columns=['NHDPlusID', 'GridCode'], where='NHDPlusID IN (%s)' % ids), ['NHDPlusID', 'GridCode']) gch = dict(zip(ch.NHDPlusID, ch.GridCode)) jh = junction(fh, NH, th) hr_fl = gpd.GeoDataFrame(bh.merge(fh[['NHDPlusID', 'geometry']], on='NHDPlusID'), geometry='geometry', crs=fh.crs) # ================================================================ the two products side by side for k in ('above', 'trib', 'below'): # HR can split a flowline into more reach codes than V2, so only report print('the %s flowline: REACHCODE %s in V2, %s in HR%s' % (k, t2[k].REACHCODE, th[k].ReachCode, '' if t2[k].REACHCODE == th[k].ReachCode else ' (differ)')) assert j2.distance(jh) < 1000, 'the V2 and HR junctions are %.0f m apart' % j2.distance(jh) rc2, rch = set(b2.REACHCODE), set(bh.ReachCode) kept3 = [k for k in ('above', 'trib', 'below') if t2[k].REACHCODE == th[k].ReachCode] print('reach codes: %d in V2, %d in HR, %d in both, %d only in HR, %d only in V2; of the three flowlines at the junction, %s keep theirs in HR' % (len(rc2), len(rch), len(rc2 & rch), len(rch - rc2), len(rc2 - rch), ', '.join(kept3) or 'none')) print('junction: V2 and HR %.0f m apart; FlowNest pixel %d is %.0f m from V2, %.0f m from HR' % (j2.distance(jh), JUNC_PIX, FN_JUNC.distance(j2), FN_JUNC.distance(jh))) rec = lambda r, cols, extra: dict({c: plain(r[c]) for c in cols}, **extra) C2 = ['COMID', 'GNIS_NAME', 'GNIS_ID', 'REACHCODE', 'FTYPE', 'HYDROSEQ', 'DNHYDROSEQ', 'UPHYDROSEQ', 'LEVELPATHI', 'TERMINALPA', 'FROMNODE', 'TONODE', 'STREAMORDE', 'TOTDASQKM'] CH = ['NHDPlusID', 'Permanent_Identifier', 'GNIS_Name', 'GNIS_ID', 'ReachCode', 'FType', 'HydroSeq', 'DnHydroSeq', 'UpHydroSeq', 'LevelPathI', 'TerminalPa', 'FromNode', 'ToNode', 'StreamOrde', 'TotDASqKm'] ll = lambda p: [float(v) for v in gpd.GeoSeries([p], crs=EPSG).to_crs(4326).iloc[0].coords[0]] summary = dict( river=RIVER, tributary=TRIB_NAME, flownest=dict(basin_id=int(bs.basin_id), mouth_pixel_seq_id=MOUTH_PIX, upstream_area_km2=float(bs.upstream_area_km2), mouth_lonlat=[float(bs.outlet_lon), float(bs.outlet_lat)], junction_pixel_seq_id=JUNC_PIX, junction_lonlat=ll(FN_JUNC), note='the region is the run of channel pixels upstream of the gauge-50 pixel inside basin 32 (the Columbia)'), v2=dict(mouth=int(m2.COMID), mouth_area_km2=float(m2.TOTDASQKM), mouth_from_outlet_m=d2, hydrologic_units=huc2, flowlines=len(b2), catchments=len(cin), catchment_area_km2=float(cin.AreaSqKM.sum()), reach_codes=len(rc2), level_paths=int(b2.LEVELPATHI.nunique()), main_stem_flowlines=int(b2.main.sum()), trib_flowlines=int(b2.trib.sum()), trib_area_km2=float(t2['trib'].TOTDASQKM), junction_lonlat=ll(j2), records={k: rec(r, C2, dict(TOCOMID=to2[r.COMID][0], GRIDCODE=plain(gc2.get(int(r.COMID))))) for k, r in t2.items()}), hr=dict(mouth=int(mh.NHDPlusID), mouth_area_km2=float(mh.TotDASqKm), mouth_from_outlet_m=dh, hydrologic_units=huch, flowlines=len(bh), reach_codes=len(rch), level_paths=int(bh.LevelPathI.nunique()), main_stem_flowlines=int(bh.main.sum()), trib_flowlines=int(bh.trib.sum()), trib_area_km2=float(th['trib'].TotDASqKm), junction_lonlat=ll(jh), records={k: rec(r, CH, dict(ToNHDPID=toh[r.NHDPlusID][0], GridCode=plain(gch.get(int(r.NHDPlusID))))) for k, r in th.items()}), reach_codes=dict(v2=len(rc2), hr=len(rch), both=len(rc2 & rch), hr_only=len(rch - rc2), v2_only=len(rc2 - rch), junction_flowlines_same_in_hr=kept3), note_hr_area='NHDPlus HR stores less drainage area than V2 and FlowNest here: %.0f km² at gauge 50 (V2 %.0f, FlowNest %.0f) and %.0f km² on the main stem below the junction (V2 %.0f); ' 'the figures take only the flowlines and reach codes of HR, not its areas' % (mh.TotDASqKm, m2.TOTDASQKM, A_DELTA, th['below'].TotDASqKm, t2['below'].TOTDASQKM), sources=SOURCES) os.makedirs(DATD, exist_ok=True) f2.to_file(STEM + '.gpkg', layer='v2_flowline', driver='GPKG') ct.to_file(STEM + '.gpkg', layer='v2_catchment', driver='GPKG') gpd.GeoDataFrame(dict(part=['basin']), geometry=[area2], crs=EPSG).to_crs(4269).to_file(STEM + '.gpkg', layer='v2_area', driver='GPKG') hr_fl.to_file(STEM + '.gpkg', layer='hr_flowline', driver='GPKG') json.dump(summary, open(STEM + '.json', 'w'), indent=1) print(pd.DataFrame({k: summary['v2']['records'][k] for k in ('above', 'trib', 'below')}).to_string()) print(pd.DataFrame({k: summary['hr']['records'][k] for k in ('above', 'trib', 'below')}).to_string()) print('written', STEM + '.gpkg / .json')