# -*- coding: utf-8 -*- """Readers for Figures A1-A4: FlowNest (DataA4), NHDPlus (DataA1), HydroSHEDS (DataA2) and TDX-Hydro with MNSI (DataA3), each brought to the same window of the Clark Fork. """ import os, sys, json import numpy as np, geopandas as gpd from shapely.geometry import LineString sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from FigA_common_clarkfork import (DATD, read04, LO, HI, PID, TR, GT, TRIB_PIX, JUNC_PIX, JUNCTION, EPSG, HALF, KEYS, ROLE, T_MAIN, T_TRIB, num, grid, polygon, order_row, arcset) D01 = os.path.join(DATD, 'DataA1_nhdplus_clarkfork_littleblackfoot') # what was taken from NHDPlus V2 and HR D02 = os.path.join(DATD, 'DataA2_hydrosheds_v1_clarkfork_littleblackfoot') # what was taken from HydroRIVERS and HydroBASINS D03 = os.path.join(DATD, 'DataA3_tdx_mmw_clarkfork_littleblackfoot') # what was taken from TDX-Hydro, with the numbers of Model My Watershed def load_nhd(): S = json.load(open(D01 + '.json')); t = S['v2']['records']['trib']; ids = {k: S['v2']['records'][k]['COMID'] for k in KEYS} fl = gpd.read_file(D01 + '.gpkg', layer='v2_flowline').to_crs(EPSG) # V2 flowlines around the basin, with their value-added attributes ct = gpd.read_file(D01 + '.gpkg', layer='v2_catchment').to_crs(EPSG) hr = gpd.read_file(D01 + '.gpkg', layer='hr_flowline', ignore_geometry=True) # HR flowlines of the basin cls = lambda d: np.where(d.trib, 'trib', np.where(d.main, 'main', 'other')) sub = fl[fl.in_basin].copy(); sub['cls'] = cls(sub); hr['cls'] = cls(hr) assert len(sub) == S['v2']['flowlines'] and sub.COMID.is_unique and len(hr) == S['hr']['flowlines'] cin = ct[ct.in_basin] seq2c = dict(zip(sub.HYDROSEQ, sub.COMID)); by = lambda k: sub.sort_values(k) sub['RC'] = sub.REACHCODE.astype(str); hr['RC'] = hr.ReachCode.astype(str) codes = sorted(set(sub.RC) | set(hr.RC)); pos = {c: i for i, c in enumerate(codes)}; kept = len(set(sub.RC) & set(hr.RC)) def code_row(l1, d, field): # both resolutions on one axis: every reach code of either, in order cl = d.groupby('RC').cls.agg(lambda x: x.mode().iloc[0]); by_pos = {pos[c]: k for c, k in cl.items()} return dict(group=None, l1=l1, level='reach level', field=field, kind='axis', present=np.array(sorted(by_pos)), lo=0, hi=len(codes) - 1, cls_n=lambda q: by_pos[q]) o_, h_ = by('COMID'), by('HYDROSEQ'); ix = {int(c): i for i, c in enumerate(o_.COMID)}; ih = {int(h): i for i, h in enumerate(h_.HYDROSEQ)} extra = dict(unit='flowline', brackets=[], arcsets={0: arcset([ix.get(int(seq2c.get(h, -1)), -1) for h in o_.DNHYDROSEQ], {k: ix[ids[k]] for k in KEYS}), # where a flowline divides, the main path 1: arcset([ih.get(int(h), -1) for h in h_.DNHYDROSEQ], {k: list(h_.COMID).index(ids[k]) for k in KEYS})}, ledger=[('identifier', [('COMID', 1), (' %d' % t['COMID'], 0)]), ('order', [('HYDROSEQ', 1), (' %d, smaller downstream' % t['HYDROSEQ'], 0)]), ('flows to', [('DNHYDROSEQ', 1), (' %d, ' % t['DNHYDROSEQ'], 0), ('TOCOMID', 1), (' %d' % t['TOCOMID'], 0)]), ('upstream', [('UPHYDROSEQ', 1), (' %d (main path only)' % t['UPHYDROSEQ'], 0)]), ('its river', [('LEVELPATHI', 1), (' %d (its lowest ' % t['LEVELPATHI'], 0), ('HYDROSEQ', 1), (')', 0)]), ('a point', [('REACHCODE', 1), (' %s + measure' % t['REACHCODE'], 0)]), ('density', [('–', 2), (' matched across scales by REACHCODE', 2)]), ('raster', [('GRIDCODE', 1), (' %d' % t['GRIDCODE'], 0), (' → ', 3), ('FEATUREID', 1), (' = COMID', 0)]), # 3: a glyph that Helvetica lacks ('numberings', [(0, 4), (1, 4), (2, 4), (3, 4)])], numbering={'COMID': 0, 'TOCOMID': 0, 'FEATUREID': 0, 'HYDROSEQ': 1, 'DNHYDROSEQ': 1, 'UPHYDROSEQ': 1, 'LEVELPATHI': 1, 'REACHCODE': 2, 'GRIDCODE': 3}, vals={f: str(t[f]) for f in ('COMID', 'TOCOMID', 'DNHYDROSEQ', 'UPHYDROSEQ', 'LEVELPATHI')}, # the values of the tributary flowline, for (b) lp=(sub[sub.main].LEVELPATHI.nunique(), sub[sub.trib].LEVELPATHI.nunique())) # LEVELPATHI: one value per path, not per flowline print('LEVELPATHI values: %d on the main stem, %d on the Little Blackfoot with its tributaries' % extra['lp']) return dict( extra=extra, stem='FigA1_variables_nhdplus_v2_clarkfork', name='NHDPlus V2', codes=(kept, sub.RC.nunique(), len(set(hr.RC) - set(sub.RC))), loc_poly=cin, loc_line=sub, zoom=dict(kind='vector', poly=ct, line=fl, junction=JUNCTION, # each catchment is one whole: labelled with the COMID of its flowline (= its FEATUREID) labels={k: [ROLE[k], 'COMID %d' % ids[k]] for k in KEYS}, at={'trib': (860, 475), 'below': (-800, -751), 'above': (860, -914)}, bar='left'), # metres from the junction: no label or the bar touches a line rows=[order_row(None, '%d flowlines (1:100,000)' % len(sub), 'reach level', 'COMID', o_.cls, (str(sub.COMID.min()), str(sub.COMID.max()))), order_row(None, 'the same flowlines', 'reach level', 'HYDROSEQ', h_.cls, (str(sub.HYDROSEQ.min()), str(sub.HYDROSEQ.max()))), code_row('%d flowlines (V2, 1:100,000)' % len(sub), sub, 'REACHCODE'), code_row('%s flowlines (HR, 1:24,000)' % num(len(hr)), hr, 'same REACHCODE')]) def load_hyd(): S = json.load(open(D02 + '.json')); rec = {r['key']: r for r in S['records']}; t = rec['trib'] un = gpd.read_file(D02 + '.gpkg', layer='unit').to_crs(EPSG) # level-12 sub-basins (HydroBASINS) around the basin rc = gpd.read_file(D02 + '.gpkg', layer='reach').to_crs(EPSG) # river reaches (HydroRIVERS) around the basin ub = un[un.in_basin].sort_values('PFAF_ID').reset_index(drop=True); rb = rc[rc.in_basin].sort_values('HYRIV_ID').reset_index(drop=True) assert len(ub) == S['basin']['units'] and len(rb) == S['reaches']['n'] and list(ub.code) == S['basin']['codes'] cls = lambda d: np.where(d.trib, 'trib', np.where(d.main, 'main', 'other')) ix = {int(h): i for i, h in enumerate(rb.HYRIV_ID)}; iu = {int(h): i for i, h in enumerate(ub.HYBAS_ID)} code = dict(zip(ub.HYBAS_ID.astype('int64'), ub.code)); l8 = S['basin']['prefix_code']; assert S['basin']['prefix_level'] == 5 and l8 == '78266' k12 = cls(ub); it = np.nonzero(ub.trib.values)[0]; c7 = t['PFAF_ID'][:len(l8) + 2] # the Little Blackfoot is the level-7 tributary basin 7826696 assert c7 == '7826696' and (np.diff(it) == 1).all() and len(it) == 9 and set(ub.code[ub.trib]) == {c for c in ub.code if c.startswith('96')}, 'its 9 sub-basins: one block' assert code[int(t['HYBAS_ID'])] == '9601', 'the tributary element lies in the lowest of them' f1 = ub.code.str[0].astype(int).values; nd = [iu.get(int(d), -1) for d in ub.NEXT_DOWN] # level 6: 5 the outlet (partly in the region), 6 Bitterroot, 7, 8 Blackfoot, 9 upper Clark Fork assert [ub.code[q] for q in range(len(ub)) if nd[q] < 0] == ['50905'] and all(f1[q] % 2 == 1 for q in range(len(ub)) if k12[q] == 'main') assert all(k12[nd[q]] == 'main' and ub.code[nd[q]] < ub.code[q] for q in range(len(ub)) if k12[q] == 'main' and nd[q] >= 0), 'down the main stem the code gets smaller' assert all(code[int(rec[k]['HYBAS_ID'])] == rec[k]['PFAF_ID'][len(l8):].rstrip('0') for k in KEYS), 'the boxes are the digits after the level-5 code' extra = dict(unit='reach', brackets=[(1, int(it[0]), int(it[-1]) + 1, 'the Little Blackfoot: PFAF_ID %s…, one block' % c7, T_TRIB, 'center')], pfaf_prefix=l8, pfaf_example=t['PFAF_ID'], pfaf_trib=c7, n_trib_units=len(it), splits=S['checks']['splits'], vals=dict(reach_NEXT_DOWN=t['reach_NEXT_DOWN'], unit_NEXT_DOWN=t['unit_NEXT_DOWN'], HYBAS_L12=t['HYBAS_L12']), arcsets={0: arcset([ix.get(int(d), -1) for d in rb.NEXT_DOWN], {k: ix[int(rec[k]['HYRIV_ID'])] for k in KEYS}), 1: arcset([iu.get(int(d), -1) for d in ub.NEXT_DOWN], {k: iu[int(rec[k]['HYBAS_ID'])] for k in KEYS})}, ledger=[('identifier', [('HYRIV_ID', 1), (' ' + t['HYRIV_ID'], 0)]), ('order', [('–', 2), (' none for reaches; its sub-basin: ', 2), ('SORT', 1), (' %s' % t['SORT'], 0)]), # SORT: downstream to upstream ('flows to', [('NEXT_DOWN', 1), (' ' + t['reach_NEXT_DOWN'], 0)]), ('upstream', [('PFAF_ID', 1), (' %s via ' % t['PFAF_ID'], 0), ('HYBAS_L12', 1)]), ('its river', [('–', 2), (' no identifier; ', 2), ('ORD_CLAS', 1), (' %s (classical order)' % t['ORD_CLAS'], 0)]), # 2: every tributary of the main stem ('a point', [('–', 2), (' none', 2)]), ('density', [('–', 2), (' one river network; 12 levels of sub-basins by ', 2), ('PFAF_ID', 1)]), ('raster', [('–', 2), (' no identifier in the rasters (DEM, DIR, ACC, flow length)', 2)]), # the rasters of the TechDoc, section 5 ('numberings', [(0, 4), (1, 4), (2, 4), (3, 4)])], numbering={'HYRIV_ID': 0, 'NEXT_DOWN': 0, 'HYBAS_L12': 1, 'PFAF_ID': 2, 'SORT': 3}) return dict( extra=extra, stem='FigA2_variables_hydrosheds_v1_clarkfork', name='HydroSHEDS v1', loc_poly=ub, loc_line=rb, zoom=dict(kind='vector', poly=un, line=rc, junction=JUNCTION, labels={k: [ROLE[k], 'HYRIV_ID', rec[k]['HYRIV_ID'], 'PFAF_ID', rec[k]['PFAF_ID']] for k in KEYS}, stack=True, at={'trib': (960, 680), 'below': (-980, -680), 'above': (980, -930)}, bar='top'), # metres from the junction: no label touches a line or the bar, 3/4 of it in its own sub-basin; 'above' raised 150 m so its full PFAF_ID clears the river rows=[order_row(None, '%d river reaches' % len(rb), 'reach level', 'HYRIV_ID', cls(rb), (str(int(rb.HYRIV_ID.iloc[0])), str(int(rb.HYRIV_ID.iloc[-1])))), order_row(None, '%d sub-basins (Pfafstetter level 12)' % len(ub), 'sub-basin level', 'PFAF_ID', cls(ub), (str(int(ub.PFAF_ID.iloc[0])), str(int(ub.PFAF_ID.iloc[-1]))))]) # the level-12 sub-basins, one row; 179 boxes are too narrow for their codes def load_tdx(): S = json.load(open(D03 + '.json')); rec = {r['key']: r for r in S['records']}; t = rec['trib']; hd = S['region']['header'] lk = gpd.read_file(D03 + '.gpkg', layer='link').to_crs(EPSG) # TDX links around the basin, with the numbers that MMW adds sub = lk[lk.in_basin].copy(); assert len(sub) == S['river']['links'] and sub.LINKNO.is_unique cls = lambda d: np.where(d.trib, 'trib', np.where(d.main, 'main', 'other')); sub['cls'] = cls(sub) o1, o2 = sub.sort_values('LINKNO'), sub.sort_values('DISCOVER_TIME'); ids = {k: int(rec[k]['LINKNO']) for k in KEYS} ix = {int(c): i for i, c in enumerate(o1.LINKNO)}; idt = {int(c): i for i, c in enumerate(o2.LINKNO)} i0 = idt[ids['trib']]; i1 = i0 + t['FINISH_TIME'] - t['DISCOVER_TIME'] # the Little Blackfoot and every link upstream of it assert set(o2.cls.iloc[i0:i1]) == {'trib'} and (o2.cls == 'trib').sum() == i1 - i0 jn = ft = 0 # junctions of the main stem, and those where the walk enters the tributary first for L_ in sub.LINKNO[sub.cls == 'main']: u = sub[sub.DSLINKNO == L_]; um, uo = u[u.cls == 'main'], u[u.cls != 'main'] if len(um) == 1 and len(uo): jn += 1; ft += int(uo.DISCOVER_TIME.min() < um.DISCOVER_TIME.iloc[0]) dt = dict(zip(sub.LINKNO.astype(int), sub.DISCOVER_TIME.astype(int))); two = sub[(sub.USLINKNO1 > 0) & (sub.USLINKNO2 > 0)] # every junction of the basin assert len(two) and all(dt[int(b)] < dt[int(a)] for a, b in zip(two.USLINKNO1, two.USLINKNO2)), 'the depth-first order enters USLINKNO2 first' assert dt[ids['trib']] < dt[ids['above']] and int(rec['above']['DSLINKNO']) == ids['below'] == int(t['DSLINKNO']), 'at the Little Blackfoot junction: the tributary first' so = dict(zip(sub.LINKNO.astype(int), sub.strmOrder.astype(int))) assert all(so[int(b)] <= so[int(a)] for a, b in zip(two.USLINKNO1, two.USLINKNO2)), 'USLINKNO2 never has the higher stream order' off = hd * 10 ** 7; assert int(t['LINKNO']) - int(t['LINKNO_region']) == off, 'LINKNO = streamID + header x 10^7' out_ = sub[~sub.DSLINKNO.isin(sub.LINKNO)]; assert list(out_.LINKNO.astype(int)) == [int(S['outlet']['LINKNO'])] and (sub.ROOT_ID == int(t['ROOT_ID'])).all() assert int(t['ROOT_ID']) not in set(sub.LINKNO) and int(out_.FINISH_TIME.iloc[0]) - int(out_.DISCOVER_TIME.iloc[0]) == len(sub) # the Clark Fork above gauge 50 is not a tree of its own; ROOT_ID is the outlet link of the Columbia, and the links of the region are one range below its outlet's FINISH_TIME extra = dict(unit='link', walk=(ft, jn, len(sub)), outlet_link=(int(out_.LINKNO.iloc[0]), int(out_.DISCOVER_TIME.iloc[0]), int(out_.FINISH_TIME.iloc[0])), vals=dict(DSLINKNO=t['DSLINKNO'], LINKNO_region=t['LINKNO_region'], DISCOVER_TIME=str(t['DISCOVER_TIME']), FINISH_TIME=str(t['FINISH_TIME']), ROOT_ID=t['ROOT_ID'], LINKNO_offset='{:,}'.format(off)), brackets=[(1, i0, i1, 'one range: DISCOVER_TIME [{:,}, {:,})'.format(int(t['DISCOVER_TIME']), int(t['FINISH_TIME'])), T_TRIB, 'center')], arcsets={0: arcset([ix.get(int(d), -1) for d in o1.DSLINKNO], {k: ix[ids[k]] for k in KEYS}), 1: arcset([idt.get(int(d), -1) for d in o2.DSLINKNO], {k: idt[ids[k]] for k in KEYS})}, ledger=[('identifier', [('LINKNO', 1), (' ' + t['LINKNO'], 0)]), ('order', [('DISCOVER_TIME', 1), (' %d, a depth-first rank' % t['DISCOVER_TIME'], 0)]), ('flows to', [('DSLINKNO', 1), (' ' + t['DSLINKNO'], 0)]), ('upstream', [('[', 0), ('DISCOVER_TIME', 1), (' %d, ' % t['DISCOVER_TIME'], 0), ('FINISH_TIME', 1), (' %d) in ' % t['FINISH_TIME'], 0), ('ROOT_ID', 1)]), ('its river', [('–', 2), (' none stored; follow the larger drainage area', 2)]), ('a point', [('–', 2), (' none', 2)]), ('density', [('–', 2), (' one network, delineated at 5 km²', 2)]), # Technical Document, section 5.7 ('raster', [('–', 2), (' no identifier raster; polygon streamID %s' % t['LINKNO_region'], 2)]), ('numberings', [(0, 4), (1, 4)])], numbering={'LINKNO': 0, 'DSLINKNO': 0, 'ROOT_ID': 0, 'DISCOVER_TIME': 1, 'FINISH_TIME': 1}) no_poly = gpd.GeoDataFrame({'role': [], 'trib': []}, geometry=[], crs=EPSG) # unit-catchment polygons are not drawn return dict( extra=extra, stem='FigA3_variables_tdx_mmw_clarkfork', name='TDX-Hydro + Model My Watershed', loc_poly=no_poly, loc_line=sub, zoom=dict(kind='vector', poly=no_poly, line=lk, junction=JUNCTION, labels={k: [ROLE[k], 'LINKNO', str(ids[k])] for k in KEYS}, stack=True, at={'trib': (880, 400), 'below': (-560, -780), 'above': (760, -560)}, bar='left'), # metres from the junction: searched so that no label touches a line or the bar rows=[order_row(None, '%d links' % len(sub), 'reach level', 'LINKNO', o1.cls, (str(int(o1.LINKNO.iloc[0])), str(int(o1.LINKNO.iloc[-1])))), order_row(None, 'the same links', 'reach level', 'DISCOVER_TIME', o2.cls, (num(o2.DISCOVER_TIME.iloc[0]), num(o2.DISCOVER_TIME.iloc[-1])), rng={'trib': '%d–%d' % (t['DISCOVER_TIME'], t['FINISH_TIME'] - 1)})]) def load_fn(): p = read04('pixel_1km2').set_index('pixel_id') # the channel pixels of the Clark Fork above gauge 50 at 1 km² rb = read04('reach_1km2').sort_values('reach_id').reset_index(drop=True) o_, e_ = rb.outlet_pixel_id.values, rb.upstream_end_pixel_id.values; assert (np.diff(o_) > 0).all(), 'reach_id follows pixel_id' assert (o_[1:] == e_[:-1] + 1).all() and o_[0] == LO and e_[-1] - o_[0] + 1 == len(p), 'the reaches tile pixel_id: each reach is one range' g_ = rb.reset_index().groupby('river_id')['index'].agg(['min', 'max', 'count']); assert ((g_['max'] - g_['min'] + 1) == g_['count']).all(), 'each river is one range' def ridx(px): # the place, in reach_id order, of the 1 km² reach that holds the channel pixel px j_ = int(np.searchsorted(o_, px, 'right')) - 1; assert o_[j_] <= px <= e_[j_] return j_ main_rid = int(rb.river_id[o_ == LO].iloc[0]); main_last = int(e_[rb.river_id.values == main_rid].max()) trib = TRIB_PIX; b0, b1 = trib, int(p.at[trib, 'upstream_pixel_id_max']) junc = int(p.at[trib, 'next_down_pixel_id']); above = junc + 1 assert junc == JUNC_PIX and LO < junc < main_last and int(p.at[above, 'next_down_pixel_id']) == junc, 'the Little Blackfoot joins the main stem' cls_n = lambda n: 'main' if LO <= n <= main_last else 'trib' if b0 <= n <= b1 else 'other' rng = {k: (int(o_[ridx(px)]), int(e_[ridx(px)])) for k, px in (('below', junc), ('above', above), ('trib', trib))} assert rng['below'][1] == junc and rng['above'][0] == above and rng['trib'][0] == trib, 'three reaches meet at the junction' tr_ = rb.iloc[ridx(trib)]; assert int(tr_.river_id) == 33798307 and int(tr_.next_down_reach_id) == int(rb.reach_id.iloc[ridx(junc)]) # (a) the region with the land of the Little Blackfoot, and every channel pixel as a line to the pixel it flows to a = np.abs(PID); in_all = (a >= LO) & (a <= HI); in_bear = (a >= b0) & (a <= b1) loc_poly = gpd.GeoDataFrame({'trib': [False, True]}, geometry=[polygon(in_all & ~in_bear, TR), polygon(in_bear, TR)], crs=4326).to_crs(EPSG) lon, lat = GT * (p['col'].values + 0.5, p['row'].values + 0.5); xy = dict(zip(p.index, zip(lon, lat))) seg = [(q, LineString([xy[q], xy[d]])) for q, d in zip(p.index, p.next_down_pixel_id) if d] loc_line = gpd.GeoDataFrame({'main': [cls_n(q) == 'main' for q, _ in seg], 'trib': [cls_n(q) == 'trib' for q, _ in seg]}, geometry=[g for _, g in seg], crs=4326).to_crs(EPSG) # (a) the window, 3.2 km around the junction, in pixels of the raster rj, cj = int(p.at[junc, 'row']), int(p.at[junc, 'col']) mx, my = 111320 * np.cos(np.radians(xy[junc][1])) * GT.a, 110950 * abs(GT.e); hx, hy = int(round(HALF / mx)), int(round(HALF / my)) v = grid(rj - hy, rj + hy + 1, cj - hx, cj + hx + 1) hr_, hc_ = np.nonzero((v < 0) & (-v >= rng['trib'][0]) & (-v <= rng['trib'][1])); q = int(np.argmin(hr_ ** 2 + hc_ ** 2)) # a hillslope pixel of the Little Blackfoot near the top left of the window # (c) the rows: reaches in reach_id order, and channel pixels and raster pixels on the axis of pixel_id first = int(rb.reach_id.iloc[0]); down = [int(d) - first if d else -1 for d in rb.next_down_reach_id] jump = p[(p.next_down_pixel_id.values != p.index.values - 1) & (p.next_down_pixel_id.values != 0)] # river outlets: the only pixels not flowing to pixel_id - 1 n_t = {T: int((p.upstream_area_km2.values >= np.float32(T)).sum()) for T in (1, 5, 25)} def axis_row(l1, field, T=None): present = np.arange(LO, HI + 1) if T is None else p.index.values[p.upstream_area_km2.values >= np.float32(T)] return dict(group=None, l1=l1, level='pixel level', field=field, kind='axis', present=present, lo=LO, hi=HI, cls_n=cls_n) extra = dict(unit='pixel', brackets=[(1, LO - 0.5, main_last + 0.5, 'one river_id', T_MAIN, 'left'), (1, b0 - 0.5, b1 + 0.5, '[pixel_id, upstream_pixel_id_max]', T_TRIB, 'center')], arcsets={1: dict(pairs=list(zip(jump.index, jump.next_down_pixel_id)), hot={'trib': (trib, junc)}, at={'above': above, 'trib': trib, 'below': junc}), 0: arcset(down, {'below': ridx(junc), 'above': ridx(above), 'trib': ridx(trib)})}, ledger=[('identifier', [('pixel_id', 1), (' %s' % num(trib), 0)]), ('order', [('pixel_id', 1), (' is itself the depth-first rank', 0)]), ('flows to', [('next_down_pixel_id', 1), (' %s, not ' % num(junc), 0), ('pixel_id', 1), (' − 1', 0)]), # a river outlet; inside a river it is pixel_id - 1 ('upstream', [('pixel_id', 1), (' to ', 0), ('upstream_pixel_id_max', 1), (' %s' % num(b1), 0)]), ('its river', [('river_id', 1), (' %s, ' % num(tr_.river_id), 0), ('river_level', 1), (' %d' % tr_.river_level, 0)]), ('a point', [('pixel_id', 1), (' of any channel pixel', 0)]), ('density', [('pixel_id', 1), (', kept while ', 0), ('upstream_area_km2', 1), (' ≥ threshold', 0)]), ('raster', [('pixel_id', 1), ('; on hillslopes with a minus sign', 0)]), ('numberings', [(0, 4), (' ', 0), ('reach_id', 1), (' and ', 0), ('river_id', 1), (' count objects in its order', 0)])], numbering={'pixel_id': 0, 'next_down_pixel_id': 0, 'upstream_pixel_id_max': 0}, track=int(-v[hr_[q], hc_[q]])) return dict( extra=extra, stem='FigA4_variables_flownest_clarkfork', name='FlowNest', loc_poly=loc_poly, loc_line=loc_line, zoom=dict(kind='pixels', v=v, mx=mx, my=my, rng=rng, cls_n=cls_n, centre=JUNCTION, pix={'below': junc, 'above': above, 'trib': trib}, lead={'trib': (5.0, 7.5, 'left'), 'above': (4.0, 2.5, 'left'), 'below': (-5.0, 4.0, 'right')}, word_at={'above': (17.2, 38.5), 'below': (15.4, 10.0), 'trib': (10.9, 40.0)}, # (row, col) of the window, clear of the channels hill=(int(hr_[q]), int(hc_[q]), -2.5, int(hr_[q]) - 3.1, 'right')), # its three lines sit in the top left of the window guides=(LO, HI, [main_last + 0.5, b0 - 0.5, b1 + 0.5]), rows=[order_row(None, '%s reaches (threshold 1 km²)' % num(len(rb)), 'reach level', 'reach_id', [cls_n(int(o)) for o in o_], (num(first), num(rb.reach_id.iloc[-1]))), axis_row('%s channel pixels (threshold 1 km²)' % num(n_t[1]), 'pixel_id', T=1), axis_row('%s channel pixels (threshold 5 km²)' % num(n_t[5]), 'same pixel_id', T=5), axis_row('%s channel pixels (threshold 25 km²)' % num(n_t[25]), 'same pixel_id', T=25), axis_row('%s raster pixels (90 m)' % num(int(in_all.sum())), 'pixel_id of its channel pixel')]) if __name__ == '__main__': D = load_fn(); Z = D['zoom']; v = Z['v']; cls_n = Z['cls_n'] print('window %d x %d pixels (%.1f x %.1f m each); junction pixel at row %d, col %d of the window' % (v.shape[0], v.shape[1], Z['my'], Z['mx'], v.shape[0] // 2, v.shape[1] // 2)) ch = {'main': 'M', 'trib': 'T', 'other': 'o'}; rk = {k: Z['rng'][k] for k in Z['rng']} for r_ in range(v.shape[0]): # the window as letters: M T o channel pixels; a b t the land of the three reaches; . other land s = '' for c_ in range(v.shape[1]): x = int(v[r_, c_]) if x > 0: s += ch[cls_n(x)] if x not in Z['pix'].values() else '*' else: s += next((k[0] if k != 'trib' else 't' for k in rk if rk[k][0] <= -x <= rk[k][1]), '.') print('%2d %s' % (r_, s)) print('track', D['extra']['track'], 'hill', Z['hill'], {k: num(x) for k, x in Z['pix'].items()}, Z['rng'])