# -*- coding: utf-8 -*- """HydroSHEDS v1 (HydroRIVERS and HydroBASINS level 12) for the Clark Fork above GRDC gauge 4115348, for Figure A2. Input: ../Data/DataA4_flownest_clarkfork_*, ../Data/DataA1_nhdplus_clarkfork_littleblackfoot.json, HydroBASINS and the 15" flow directions (paths.HYDROSHEDS_DIR) and HydroRIVERS (paths.HYDRORIVERS_ZIP). Output: ../Data/DataA2_hydrosheds_v1_clarkfork_littleblackfoot.gpkg (layers unit and reach) and a JSON. Usage: python DataA2_hydrosheds_v1_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 import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH warnings.filterwarnings('ignore', message='Measured') HYD = PTH.HYDROSHEDS_DIR HBZ = '/vsizip/' + HYD + '/HydroBASINS_v1c/hybas_na_lev01-12_v1c.zip/' HR = '/vsizip/' + PTH.HYDRORIVERS_ZIP + '/HydroRIVERS_v10_na_shp/HydroRIVERS_v10_na.shp' DIR = HYD + '/dir_15s_north-america/hyd_na_dir_15s.tif' # only its grid is read: where the cell centres lie DATD = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'Data') STEM = os.path.join(DATD, 'DataA2_hydrosheds_v1_clarkfork_littleblackfoot') D01 = os.path.join(DATD, 'DataA1_nhdplus_clarkfork_littleblackfoot.json') # Figure A.1 (NHDPlus): its junction must be the same one D04 = os.path.join(DATD, 'DataA4_flownest_clarkfork_%s') # the files that DataA4_flownest_clarkfork_gauge50.py cut out of the FlowNest release flownest_merit90m_global_20261113_195421 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 pixel of gauge 50 (Clark Fork below Missoula) EPSG = 5070 SOURCES = dict( hydrorivers=dict(product='HydroRIVERS v1.0 (Lehner and Grill, 2013), North America and Caribbean', file='HydroRIVERS_v10_na_shp.zip', url='https://data.hydrosheds.org/file/HydroRIVERS/HydroRIVERS_v10_na_shp.zip', bytes=66335898, downloaded='2026-09-29'), hydrobasins=dict(product='HydroBASINS v1c (Lehner and Grill, 2013, doi:10.1002/hyp.9740), North America, levels 1 to 12', file='hybas_na_lev01-12_v1c.zip', url='https://data.hydrosheds.org/file/hydrobasins/standard/hybas_na_lev01-12_v1c.zip', bytes=316655770), flow_directions=dict(product='HydroSHEDS v1, drainage directions, 15 arc-seconds, North America', file='hyd_na_dir_15s.tif', url='https://data.hydrosheds.org/file/hydrosheds-v1-dir/hyd_na_dir_15s.zip', zip_sha1='531cfe190acf832fca72dd7def281e7b0e073ecb'), licence='HydroSHEDS licence (v1 terms)') def lev(L): return HBZ + 'hybas_na_lev%02d_v1c.shp' % L def ints(df, cols): for c in cols: df[c] = df[c].round().astype('int64') return df def above(kids, h): got, stack = set(), [int(h)] while stack: x = stack.pop(); got.add(x); stack += kids.get(x, []) return got # ---------------------------------------------------------------- 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_DELTA = float(px.at[MOUTH_PIX, 'upstream_area_km2']) # the area at the gauge-50 pixel 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 with rasterio.open(DIR) as src: tf = src.transform; CELL = tf.a assert tf.b == 0 and tf.d == 0 and abs(tf.a + tf.e) < 1e-12 and abs(CELL - 1 / 240.0) < 1e-12, 'the grid is not north-up with 15 arc-second cells' # ================================================================ HydroBASINS: the sub-basins of the Clark Fork above gauge 50 ua = ints(pyogrio.read_dataframe(lev(12), bbox=BOX), ['HYBAS_ID', 'NEXT_DOWN', 'NEXT_SINK', 'MAIN_BAS', 'PFAF_ID', 'SORT', 'ORDER', 'COAST']) ua['pfaf'] = ua.PFAF_ID.astype(str) low = ua[ua.to_crs(EPSG).contains(FN_JUNC)] # walk down from the Little Blackfoot junction assert len(low) == 1, 'the FlowNest junction does not lie in one sub-basin' walk = [low.iloc[0]] while walk[-1].UP_AREA < 1.2 * A_DELTA: # down the Clark Fork past gauge 50 nxt = ua[ua.HYBAS_ID == walk[-1].NEXT_DOWN] if len(nxt) != 1: break walk.append(nxt.iloc[0]) k_low = int(np.argmin([abs(w.UP_AREA / A_DELTA - 1) for w in walk])); low = walk[k_low] assert k_low + 1 < len(walk), 'the walk down ends at the sub-basin nearest gauge 50' clark_unit = walk[k_low + 1] # the sub-basin below the basin, on the Clark Fork print('walk down from the junction: %s; the basin ends with %d (%.1f km²); the next sub-basin %d drains %.1f km²' % (', '.join('%d (%.1f km²)' % (w.HYBAS_ID, w.UP_AREA) for w in walk), low.HYBAS_ID, low.UP_AREA, clark_unit.HYBAS_ID, clark_unit.UP_AREA)) ukids = {} for h, d in zip(ua.HYBAS_ID, ua.NEXT_DOWN): ukids.setdefault(int(d), []).append(int(h)) ua['in_basin'] = ua.HYBAS_ID.isin(above(ukids, low.HYBAS_ID)) u = ua[ua.in_basin].copy() ub = u.total_bounds assert BOX[0] < ub[0] and BOX[1] < ub[1] and ub[2] < BOX[2] and ub[3] < BOX[3], 'the sub-basins of the basin reach beyond the box read' PRE = os.path.commonprefix(list(u.pfaf)) # the code of the smallest Pfafstetter unit that holds the whole basin u['code'] = [p[len(PRE):].rstrip('0') for p in u.pfaf] ua['code'] = ua.HYBAS_ID.map(dict(zip(u.HYBAS_ID, u.code))).fillna('') print('sub-basins of the basin: %d, SUB_AREA sum %.1f km², UP_AREA of the lowest %.1f km² (FlowNest at the mouth %.2f km²); level-%d code %s' % (len(u), u.SUB_AREA.sum(), low.UP_AREA, A_DELTA, len(PRE), PRE)) assert abs(low.UP_AREA / A_DELTA - 1) < 0.03 and abs(u.SUB_AREA.sum() - low.UP_AREA) < 0.05 * len(u), 'the sub-basins do not add up to the area at gauge 50' p0 = int(PRE) * 10 ** (12 - len(PRE)) # every level-12 sub-basin whose code begins with PRE, wherever it lies nb = ints(pyogrio.read_dataframe(lev(12), read_geometry=False, where='PFAF_ID >= %d AND PFAF_ID < %d' % (p0, p0 + 10 ** (12 - len(PRE))), columns=['HYBAS_ID', 'NEXT_DOWN', 'PFAF_ID', 'SUB_AREA', 'UP_AREA']), ['HYBAS_ID', 'NEXT_DOWN', 'PFAF_ID']) nb = nb[~nb.HYBAS_ID.isin(u.HYBAS_ID)].sort_values('PFAF_ID') print(' the level-%d unit %s holds %d more sub-basins (%.1f km²), below gauge 50' % (len(PRE), PRE, len(nb), nb.SUB_AREA.sum())) # ================================================================ HydroRIVERS: the reaches of the basin ra = ints(pyogrio.read_dataframe(HR, bbox=BOX), ['HYRIV_ID', 'NEXT_DOWN', 'MAIN_RIV', 'HYBAS_L12', 'ORD_CLAS', 'ORD_STRA', 'ORD_FLOW']) assert all(g.geom_type == 'LineString' for g in ra.geometry), 'a reach is not a single line' r = ra[ra.HYBAS_L12.isin(u.HYBAS_ID)].copy() kids = {} for h, d in zip(ra.HYRIV_ID, ra.NEXT_DOWN): kids.setdefault(int(d), []).append(int(h)) mouth = r[~r.NEXT_DOWN.isin(r.HYRIV_ID)] assert len(mouth) == 1, 'the basin does not drain through one reach' mouth = mouth.iloc[0] assert set(r.HYRIV_ID) == above(kids, mouth.HYRIV_ID), 'the reaches of the sub-basins are not the reaches upstream of the mouth reach' assert int(mouth.HYBAS_L12) == int(low.HYBAS_ID) and abs(mouth.UPLAND_SKM - low.UP_AREA) < 1.0, 'the mouth reach does not drain the lowest sub-basin' m5 = gpd.GeoSeries([mouth.geometry], crs=4326).to_crs(EPSG).iloc[0] d_end = Point(m5.coords[-1]).distance(OUTLET) oc_, upland, dist_up = (dict(zip(r.HYRIV_ID, r[c])) for c in ('ORD_CLAS', 'UPLAND_SKM', 'DIST_UP_KM')) MC = int(mouth.ORD_CLAS) # the ORD_CLAS of the main stem at gauge 50 assert (r.ORD_CLAS >= MC).all(), 'a reach of the basin has a lower ORD_CLAS than the mouth reach' ms, x, alt = [int(mouth.HYRIV_ID)], int(mouth.HYRIV_ID), [] while True: # from the mouth reach upstream, the one reach that keeps ORD_CLAS MC one = [k for k in kids.get(x, []) if oc_[k] == MC] if not one: break assert len(one) == 1, 'ORD_CLAS %d continues in two reaches above %d' % (MC, x) big = max(kids[x], key=lambda k: upland[k]) if big != one[0]: alt.append(dict(at=str(x), ord_clas_1=str(one[0]), larger=str(big), upland_km2=[float(upland[one[0]]), float(upland[big])], dist_up_km=[float(dist_up[one[0]]), float(dist_up[big])])) x = one[0]; ms.append(x) assert set(ms) == set(r.HYRIV_ID[r.ORD_CLAS == MC]) and not kids.get(x), 'ORD_CLAS %d is not one path from the mouth reach to a source' % MC r['main'] = r.HYRIV_ID.isin(ms) last = {int(h): np.array(g.coords[-1][:2]) for h, g in zip(ra.HYRIV_ID, ra.geometry)} first = {int(h): np.array(g.coords[0][:2]) for h, g in zip(ra.HYRIV_ID, ra.geometry)} r5 = r.to_crs(EPSG) tm = r5[r5.NEXT_DOWN.isin(ms) & ~r5.main].copy() tm['d_j'] = [Point(g.coords[-1]).distance(FN_JUNC) for g in tm.geometry] trib = r.loc[tm.d_j.idxmin()]; d_trib = float(tm.d_j.min()) a_fn = float(px.at[TRIB_PIX, 'upstream_area_km2']) # the tributary may differ by up to 30% in area between the products; its end may lie up to 3 cells from the FlowNest junction assert d_trib < 3 * CELL * 111320 and abs(trib.UPLAND_SKM / a_fn - 1) < 0.3, 'no reach of the Little Blackfoot ends at the FlowNest junction' r['trib'] = r.HYRIV_ID.isin(above(kids, trib.HYRIV_ID)) down = r[r.HYRIV_ID == trib.NEXT_DOWN].iloc[0] upst = r[(r.NEXT_DOWN == down.HYRIV_ID) & r.main] assert down.main and len(upst) == 1, 'the main stem does not pass the junction as one reach in, one out' upst = upst.iloc[0] three = [('above', upst), ('trib', trib), ('below', down)] print('reaches: %d; mouth reach %d (%.1f km², ends %.0f m from the FlowNest mouth pixel); main stem (ORD_CLAS %d) %d reaches' % (len(r), mouth.HYRIV_ID, mouth.UPLAND_SKM, d_end, MC, r.main.sum())) for a_ in alt: # where the main stem does not take the branch of the larger UPLAND_SKM print(' above reach %s the main stem takes %s (%.1f km², %.1f km to its source), not %s (%.1f km², %.1f km)' % (a_['at'], a_['ord_clas_1'], a_['upland_km2'][0], a_['dist_up_km'][0], a_['larger'], a_['upland_km2'][1], a_['dist_up_km'][1])) assert a_['dist_up_km'][0] > a_['dist_up_km'][1], 'the main stem takes neither the larger nor the longer branch' print(' the Little Blackfoot: tributary reach %d (%.1f km²; FlowNest %.2f km²), ends %.0f m from the FlowNest junction; %d reaches' % (trib.HYRIV_ID, trib.UPLAND_SKM, a_fn, d_trib, r.trib.sum())) fill = set(r.HYBAS_L12[r.trib]) == {int(trib.HYBAS_L12)} and bool((r.trib == (r.HYBAS_L12 == trib.HYBAS_L12)).all()) print(' the reaches of the Little Blackfoot lie in one sub-basin and fill it: %s' % fill) if not fill: print(' NOTE: the tributary is not one sub-basin') # ---------------------------------------------------------------- what the fields are, checked on the data inb = r[r.NEXT_DOWN.isin(r.HYRIV_ID)] n_ok = sum(np.abs(last[int(h)] - first[int(d)]).max() < 1e-9 for h, d in zip(inb.HYRIV_ID, inb.NEXT_DOWN)) print('NEXT_DOWN: the last vertex of a reach is the first vertex of the reach it names: %d of %d reaches inside the basin' % (n_ok, len(inb))) assert n_ok == len(inb) def off_centre(xy): """Distance of each vertex from the nearest cell centre of the grid, in cells.""" v = (np.asarray(xy)[:, :2] - [tf.c, tf.f]) / [tf.a, tf.e] - 0.5 return np.abs(v - np.round(v)).max(axis=1) n_on = n_all = n_first = 0 for g in r.geometry: o = off_centre(np.asarray(g.coords)) n_all += len(o); n_on += int((o < 1e-4).sum()); n_first += int(o[0] >= 1e-4 and (o[1:] < 1e-4).all()) print('reach vertices on cell centres of the grid: %d of %d; the rest are the first vertex of %d reaches (it lies on the edge of the first cell)' % (n_on, n_all, n_first)) assert n_all - n_on == n_first seg = np.vstack([np.diff(np.asarray(p.exterior.coords)[:, :2], axis=0) for g in u.geometry for p in (g.geoms if g.geom_type == 'MultiPolygon' else [g])]) / CELL share_par = float(np.mean((np.abs(seg[:, 0]) < 1e-6) | (np.abs(seg[:, 1]) < 1e-6))) print('sub-basin outlines: %d segments, %.0f%% of them parallel to the cell edges (the polygons are generalised, they do not follow the cells)' % (len(seg), 100 * share_par)) mr = ints(pyogrio.read_dataframe(HR, where='HYRIV_ID = %d' % int(mouth.MAIN_RIV), columns=['HYRIV_ID', 'NEXT_DOWN', 'MAIN_RIV', 'ORD_CLAS', 'UPLAND_SKM', 'HYBAS_L12']), ['HYRIV_ID', 'NEXT_DOWN', 'MAIN_RIV', 'ORD_CLAS', 'HYBAS_L12']).iloc[0] cf = ra[ra.HYRIV_ID == mouth.NEXT_DOWN].iloc[0] # the Clark Fork reach below gauge 50 print('MAIN_RIV %d: NEXT_DOWN %d, ORD_CLAS %d, UPLAND_SKM %.1f (the Columbia at the sea); MAIN_RIV is the same for the %d reaches: %s; the mouth reach flows into %d (ORD_CLAS %d, %.1f km², the Clark Fork below gauge 50)' % (mr.HYRIV_ID, mr.NEXT_DOWN, mr.ORD_CLAS, mr.UPLAND_SKM, len(r), r.MAIN_RIV.nunique() == 1, cf.HYRIV_ID, cf.ORD_CLAS, cf.UPLAND_SKM)) assert mr.NEXT_DOWN == 0 and mr.ORD_CLAS == 1 and mr.UPLAND_SKM > 600000 and r.MAIN_RIV.nunique() == 1 and int(cf.MAIN_RIV) == int(mr.HYRIV_ID), 'MAIN_RIV is not the reach where the Columbia reaches the sea' mb = ints(pyogrio.read_dataframe(lev(12), read_geometry=False, where='HYBAS_ID = %d' % int(low.MAIN_BAS), columns=['HYBAS_ID', 'NEXT_DOWN', 'PFAF_ID', 'UP_AREA']), ['HYBAS_ID', 'NEXT_DOWN', 'PFAF_ID']).iloc[0] print('MAIN_BAS %d: NEXT_DOWN %d, PFAF_ID %d, UP_AREA %.1f; NEXT_SINK and MAIN_BAS are the same for the %d sub-basins: %s' % (mb.HYBAS_ID, mb.NEXT_DOWN, mb.PFAF_ID, mb.UP_AREA, len(u), u.MAIN_BAS.nunique() == 1 and bool((u.NEXT_SINK == u.MAIN_BAS).all()))) assert mb.NEXT_DOWN == 0 and int(mb.HYBAS_ID) == int(mr.HYBAS_L12) and u.MAIN_BAS.nunique() == 1, 'MAIN_BAS is not the sub-basin of the MAIN_RIV reach' print('ORD_CLAS of the Little Blackfoot mouth reach: %d (a tributary of the main stem, ORD_CLAS %d)' % (trib.ORD_CLAS, MC)) assert trib.ORD_CLAS == MC + 1, 'the Little Blackfoot is not a tributary of the main stem in ORD_CLAS' u['main'] = u.HYBAS_ID.isin(set(r.HYBAS_L12[r.main])) t_unit = int(trib.HYBAS_L12) # the sub-basins of the Little Blackfoot: its mouth sub-basin and every one above it, unless that sub-basin is on the main stem u['trib'] = u.HYBAS_ID.isin(above(ukids, t_unit)) & ~u.main if t_unit not in set(u.HYBAS_ID[u.main]) else False print(' the Little Blackfoot: %d sub-basins of its own (%.1f km²); its reaches lie in %d sub-basins' % (u.trib.sum(), u.SUB_AREA[u.trib].sum(), len(set(r.HYBAS_L12[r.trib])))) print('sub-basins that hold a reach of the main stem: %s; of the Little Blackfoot: %s' % (sorted(u.code[u.main]), sorted(u.code[u.trib]))) levels = []; area_of = {} low_pf = u.pfaf[u.HYBAS_ID == int(low.HYBAS_ID)].iloc[0] for L in range(1, 12): # at level L a sub-basin is coded with the first L digits of its level-12 code codes = sorted(set(int(p[:L]) for p in u.pfaf)) d = pyogrio.read_dataframe(lev(L), read_geometry=(L > len(PRE)), where='PFAF_ID IN (%s)' % ','.join(map(str, codes)), columns=['HYBAS_ID', 'PFAF_ID', 'SUB_AREA', 'UP_AREA']) ok = sorted(d.PFAF_ID.round().astype('int64')) == codes part = [] if ok and L > len(PRE): # and its polygon holds the level-12 sub-basins that begin with its code; for c_, g in zip(d.PFAF_ID.round().astype('int64'), d.geometry): # it is all of them, except for the units that hold the basin outlet mine = u[u.pfaf.str.startswith(str(c_))] whole = abs(g.area - mine.geometry.union_all().area) < 1e-6 * g.area ok = ok and len(mine) > 0 and all(g.buffer(1e-9).contains(q.representative_point()) for q in mine.geometry) and (whole or low_pf.startswith(str(c_))) if not whole: part.append(str(c_)) area_of.update({(L, str(int(round(c_)))): float(a_) for c_, a_ in zip(d.PFAF_ID, d.SUB_AREA)}) levels.append(dict(level=L, codes=[str(c) for c in codes], found=int(len(d)), sub_area=[float(v) for v in d.SUB_AREA], ok=bool(ok), outlet_units_partly_in_basin=part)) print(' level %2d: %d codes, found %d %s%s' % (L, len(codes), len(d), 'ok' if ok else 'CHECK', ('; partly in the basin (they hold its outlet): %s' % part) if part else '')) assert all(v['ok'] for v in levels), 'a coarser level does not carry the leading digits of the code' splits = [] for c9, grp in u.groupby(u.pfaf.str[:9]): # a sub-basin of level 9 larger than 250 km² is split along its main stem at level 10 a9 = float(grp.SUB_AREA.sum()); cut = grp.pfaf.str[:10].nunique() > 1 if cut: g10 = grp.groupby(grp.pfaf.str[:10]) # the level-10 pieces form one chain, each flowing to the piece before it heads = sorted(g10.groups) lo10 = {c: g.loc[g.UP_AREA.idxmax()] for c, g in g10} ok = all(int(lo10[heads[i]].NEXT_DOWN) in set(g10.get_group(heads[i - 1]).HYBAS_ID) for i in range(1, len(heads))) else: ok = True whole = abs(area_of[(9, c9)] - a9) < 0.5 splits.append(dict(code=c9, area_km2=a9, unit_area_km2=area_of[(9, c9)], pieces=sorted(grp.code), split=cut, chain=bool(ok), on_main_stem=bool(grp.main.all()))) if not whole: print(' level 9 %s: %.1f km² of it in the basin (the unit is %.1f km² and holds the basin outlet)' % (c9, a9, area_of[(9, c9)])); continue assert cut == (a9 > 250), 'the split of %s is not the forced split of the technical documentation' % c9 print('level 9: %d units, %d split at level 10 (all of them larger than 250 km²)' % (len(splits), sum(v['split'] for v in splits))) # ================================================================ the junction J = first[int(down.HYRIV_ID)] # the junction: first vertex of the downstream reach assert np.abs(last[int(upst.HYRIV_ID)] - J).max() < 1e-9 and np.abs(last[int(trib.HYRIV_ID)] - J).max() < 1e-9, 'the three reaches do not meet in one vertex' for k, s_ in three: # the ends of the three reaches lie on cell centres, so each end names one cell; h_ = int(s_.HYRIV_ID) # a headwater reach starts on the edge of its first cell ends = [first[h_], last[h_]] if kids.get(h_) else [last[h_]] assert off_centre(ends).max() < 1e-4, 'an end of the %s reach is not on a cell centre' % k if not kids.get(h_): assert off_centre([first[h_]]).max() >= 1e-4 J5 = gpd.GeoSeries([Point(*J)], crs=4326).to_crs(EPSG).iloc[0] s1 = json.load(open(D01)); j_nhd = {k: gpd.GeoSeries([Point(*s1[k]['junction_lonlat'])], crs=4326).to_crs(EPSG).iloc[0] for k in ('v2', 'hr')} off = dict(flownest_m=float(J5.distance(FN_JUNC)), nhdplus_v2_m=float(J5.distance(j_nhd['v2'])), nhdplus_hr_m=float(J5.distance(j_nhd['hr']))) print('junction %.6f, %.6f: %.0f m from the FlowNest junction pixel, %.0f m from the NHDPlus V2 junction, %.0f m from the HR one; a cell is %.0f m from north to south' % (J[0], J[1], off['flownest_m'], off['nhdplus_v2_m'], off['nhdplus_hr_m'], CELL * 111320)) assert off['flownest_m'] < 3 * CELL * 111320, 'this is not the junction of Figures A.1 and A.4' # ================================================================ the records of the three reaches and their sub-basins unit_of = {k: u[u.HYBAS_ID == int(s_.HYBAS_L12)].iloc[0] for k, s_ in three} records = [] for k, s_ in three: q = unit_of[k] records.append(dict(key=k, HYRIV_ID=str(int(s_.HYRIV_ID)), reach_NEXT_DOWN=str(int(s_.NEXT_DOWN)), MAIN_RIV=str(int(s_.MAIN_RIV)), ORD_CLAS=int(s_.ORD_CLAS), ORD_STRA=int(s_.ORD_STRA), ORD_FLOW=int(s_.ORD_FLOW), HYBAS_L12=str(int(s_.HYBAS_L12)), LENGTH_KM=float(s_.LENGTH_KM), UPLAND_SKM=float(s_.UPLAND_SKM), HYBAS_ID=str(int(q.HYBAS_ID)), unit_NEXT_DOWN=str(int(q.NEXT_DOWN)), MAIN_BAS=str(int(q.MAIN_BAS)), PFAF_ID=str(int(q.PFAF_ID)), code=q.code, SORT=int(q.SORT), ORDER=int(q.ORDER), SUB_AREA=float(q.SUB_AREA), UP_AREA=float(q.UP_AREA))) print(pd.DataFrame(records).set_index('key').T.to_string()) print('sub-basins of the three reaches:', {k: unit_of[k].code for k in unit_of}) # ================================================================ write key_r = {int(s_.HYRIV_ID): k for k, s_ in three}; key_u = {int(s_.HYBAS_L12): k for k, s_ in three} ra['in_basin'] = ra.HYRIV_ID.isin(r.HYRIV_ID); ra['main'] = ra.HYRIV_ID.isin(r.HYRIV_ID[r.main]); ra['trib'] = ra.HYRIV_ID.isin(r.HYRIV_ID[r.trib]) ra['role'] = ra.HYRIV_ID.map(key_r) ua['main'] = ua.HYBAS_ID.isin(u.HYBAS_ID[u.main]); ua['trib'] = ua.HYBAS_ID.isin(u.HYBAS_ID[u.trib]); ua['role'] = ua.HYBAS_ID.map(key_u) os.makedirs(DATD, exist_ok=True) ua.drop(columns='pfaf').to_file(STEM + '.gpkg', layer='unit', driver='GPKG') ra.to_file(STEM + '.gpkg', layer='reach', 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=float(bs.upstream_area_km2), junction_pixel_seq_id=JUNC_PIX, junction_lonlat=ll(FN_JUNC), trib_pixel_seq_id=TRIB_PIX, trib_area_km2=a_fn), basin=dict(prefix_code=PRE, prefix_level=len(PRE), units=int(len(u)), lowest_unit=str(int(low.HYBAS_ID)), clark_fork_unit=str(int(clark_unit.HYBAS_ID)), clark_fork_up_area_km2=float(clark_unit.UP_AREA), up_area_km2=float(low.UP_AREA), sub_area_sum_km2=float(u.SUB_AREA.sum()), codes=sorted(u.code), main_units=sorted(u.code[u.main]), trib_unit=str(u.code[u.HYBAS_ID == int(trib.HYBAS_L12)].iloc[0]), more_units_in_prefix=[dict(PFAF_ID=str(p), HYBAS_ID=str(h), SUB_AREA=float(a)) for p, h, a in zip(nb.PFAF_ID, nb.HYBAS_ID, nb.SUB_AREA)]), reaches=dict(n=int(len(r)), mouth=str(int(mouth.HYRIV_ID)), mouth_upland_km2=float(mouth.UPLAND_SKM), mouth_end_from_outlet_m=float(d_end), main_stem=int(r.main.sum()), trib=int(r.trib.sum()), trib_reach=str(int(trib.HYRIV_ID)), trib_upland_km2=float(trib.UPLAND_SKM), trib_end_from_flownest_junction_m=d_trib, main_stem_ord_clas=MC, clark_fork_reach=str(int(cf.HYRIV_ID)), clark_fork_upland_km2=float(cf.UPLAND_SKM), main_riv=str(int(mr.HYRIV_ID)), main_riv_upland_km2=float(mr.UPLAND_SKM)), main_bas=dict(HYBAS_ID=str(int(mb.HYBAS_ID)), PFAF_ID=str(int(mb.PFAF_ID)), UP_AREA=float(mb.UP_AREA)), checks=dict(next_down_vertex=[int(n_ok), int(len(inb))], vertices_on_cell_centres=[n_on, n_all, n_first], outline_share_parallel=share_par, main_stem_not_larger_branch=alt, trib_fills_one_unit=fill, splits=splits), junction_lonlat=[float(J[0]), float(J[1])], junction_from=off, cell_deg=float(CELL), levels=levels, records=records, sources=SOURCES) json.dump(summary, open(STEM + '.json', 'w'), indent=1) print('written', STEM + '.gpkg / .json')