# -*- coding: utf-8 -*- """The zoom chain of Figure 5, from the globe down to one pixel. globe > level-1 group 7 > level-2 group 78 > level-3 group 782 > the basins of 782 > the Columbia (basin_id 32) > the Little Blackfoot > Telegraph Creek > one path > one reach > pixel p (the fifth pixel of the most downstream reach of Telegraph Creek), and the flow path of p to the outlet. Every object is one range of numbers. Input: the global release (paths.GLOBAL) and ../Data/Data04_flownest_littleblackfoot.json Output: ../Data/Data05_flownest_littleblackfoot_zoom_chain.json and ../Data/Data05_flownest_telegraph_path_reach_1km2.parquet Usage: python Data05_flownest_zoom_chain_littleblackfoot.py """ import os, json import numpy as np, pandas as pd import pyarrow.parquet as pq import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH REL = PTH.GLOBAL L1, L2, L3, BASIN = 7, 78, 782, 32 # the Columbia: FullBasin basin 32 MOUTH = 1088848706 # the mouth pixel of the Little Blackfoot River (Data04_flownest_littleblackfoot.py) TRIB_PIX = 1088850437 # the downstream-end pixel of Telegraph Creek (local 1,732) HERE = os.path.dirname(os.path.abspath(__file__)) DATD = os.path.join(os.path.dirname(HERE), 'Data'); os.makedirs(DATD, exist_ok=True) OUT = os.path.join(DATD, 'Data05_flownest_%s') J4 = json.load(open(os.path.join(DATD, 'Data04_flownest_littleblackfoot.json'))) assert J4['release'] == os.path.basename(REL) and J4['basin_id'] == BASIN f_ = lambda k: os.path.join(REL, 'flownest_merit90m_%s.parquet' % k) meta = json.load(open(os.path.join(REL, 'metadata.json'))) assert meta['code_version'] == '10.61' and meta['numbering_version'] == '0.2' and meta['numbering_sha256'][:12] == 'c485dec56c3a' def run(first, count, **kw): first, count = int(first), int(count) return dict(first=first, last=first + count - 1, count=count, **kw) def rows(kind, first, last, cols): """Rows first-1 .. last-1 of a global table keyed by its number (pixel or reach), read by row group.""" f = pq.ParquetFile(f_(kind)); n = [f.metadata.row_group(k).num_rows for k in range(f.metadata.num_row_groups)] start = np.cumsum([0] + n); g0, g1 = (int(np.searchsorted(start, i, side='right') - 1) for i in (first - 1, last - 1)) t = pd.concat([f.read_row_group(g, columns=cols).to_pandas() for g in range(g0, g1 + 1)], ignore_index=True) t = t.iloc[first - 1 - start[g0]: last - start[g0]].reset_index(drop=True) key = cols[0]; assert (t[key].values == np.arange(first, last + 1)).all(), 'row r - 1 holds number r' return t # ---------------------------------------------------------------- the globe, Level-1, Level-2, Level-3: the Level-3 groups of metadata.json G = pd.DataFrame(meta['flowdivide_level3_groups']).sort_values('first_pixel_seq_id').reset_index(drop=True) assert len(G) == meta['flowdivide_level3_group_count'] and G.basin_count.sum() == meta['basin_count'] assert G.first_pixel_seq_id.iloc[0] == 1 and (G.first_pixel_seq_id.values[1:] == (G.first_pixel_seq_id + G.channel_pixel_count).values[:-1]).all() assert (G.first_pixel_seq_id + G.channel_pixel_count).iloc[-1] - 1 == meta['channel_pixel_count'] and len(G) == 313 def agg(g, key): out = [] for c, x in g.groupby(key, sort=False): assert (np.diff(x.index) == 1).all(), '%s %d is one run of Level-3 groups' % (key, c) out.append(dict(code=int(c), **run(x.first_pixel_seq_id.iloc[0], x.channel_pixel_count.sum()), basins=int(x.basin_count.sum()))) return sorted(out, key=lambda d: d['first']) globe = dict(**run(1, meta['channel_pixel_count']), parts=agg(G, 'flowdivide_level1_id')) g1 = G[G.flowdivide_level1_id == L1]; g2 = G[G.flowdivide_level2_id == L2]; g3 = G[G.flowdivide_level3_id == L3].iloc[0] level1 = dict(code=L1, **run(g1.first_pixel_seq_id.iloc[0], g1.channel_pixel_count.sum()), parts=agg(g1, 'flowdivide_level2_id')) level2 = dict(code=L2, **run(g2.first_pixel_seq_id.iloc[0], g2.channel_pixel_count.sum()), parts=agg(g2, 'flowdivide_level3_id')) assert [d['code'] for d in level2['parts']] == [781, 782, 783] and len(globe['parts']) == 34 # ---------------------------------------------------------------- the basins of Level-3 group 782: the basin table and the pixel table B = pd.read_parquet(f_('basin')).sort_values('basin_id').reset_index(drop=True) assert (B.basin_id.values == np.arange(1, len(B) + 1)).all() and len(B) == 340991 # basin b on row b - 1 b3 = B[B.flowdivide_level3_id == L3].sort_values('outlet_pixel_seq_id').reset_index(drop=True) # the 27 basins of at least 1 km² G3LO, G3HI = int(g3.first_pixel_seq_id), int(g3.first_pixel_seq_id + g3.channel_pixel_count - 1) XG = rows('pixel_1km2', G3LO, G3HI, ['pixel_seq_id', 'basin_id', 'upstream_area_km2', 'upstream_channel_pixel_count']) # every basin of the group is one run of pixels, its outlet first (the outlet holds the whole run upstream of it) cut = np.flatnonzero(np.diff(XG.basin_id.values) != 0) + 1; st = np.r_[0, cut]; ln = np.diff(np.r_[st, len(XG)]) assert len(np.unique(XG.basin_id.values[st])) == len(st) == g3.basin_count == 121, 'each basin is one run' assert (XG.upstream_channel_pixel_count.values[st] == ln).all() parts = pd.DataFrame(dict(basin_id=XG.basin_id.values[st], outlet=XG.pixel_seq_id.values[st], n=ln, area=XG.upstream_area_km2.values[st].astype('float64'))) inb = parts.basin_id.isin(b3.basin_id) assert inb.sum() == len(b3) == 27 and (parts[inb].basin_id.values == b3.basin_id.values).all() assert (parts[inb].outlet.values == b3.outlet_pixel_seq_id.values).all() and (parts[inb].n.values == b3.channel_pixel_count.values).all() assert (np.abs(parts[inb].area.values - b3.upstream_area_km2.values.astype('float64')) < 1e-3).all() assert (parts[~inb].n == 1).all() and (parts[~inb].area < 1).all() and not parts[~inb].basin_id.isin(B.basin_id).any() # the 94 one-pixel basins under 1 km² assert (np.diff(parts.area.values) <= 2e-3).all(), 'in a group the basins follow from the largest down' level3 = dict(code=L3, **run(g3.first_pixel_seq_id, g3.channel_pixel_count), basins=dict(count=int(g3.basin_count), in_basin_table=int(inb.sum())), area_km2=float(parts.area.sum()), parts=[dict(code=int(b), **run(o, n), in_basin_table=bool(t)) for b, o, n, t in zip(parts.basin_id, parts.outlet, parts.n, inb)], paths=run(g3.first_path_seq_id_1km2, g3.path_count_1km2), reaches=run(g3.first_reach_seq_id_1km2, g3.reach_count_1km2)) bs = B.loc[BASIN - 1]; assert bs.basin_id == BASIN and bs.flowdivide_level3_id == L3 and bs.flowdivide_level2_id == L2 and bs.flowdivide_level1_id == L1 LO, HI = int(bs.outlet_pixel_seq_id), int(bs.outlet_pixel_seq_id + bs.channel_pixel_count - 1) basin = dict(basin_id=BASIN, **run(LO, bs.channel_pixel_count), area_km2=float(bs.upstream_area_km2), outlet_lon=float(bs.outlet_lon), outlet_lat=float(bs.outlet_lat), rank_in_l3=int(np.flatnonzero(parts.basin_id.values == BASIN)[0] + 1)) assert basin['rank_in_l3'] == 1 and LO == G3LO names = {} for b_ in b3.nlargest(6, 'upstream_area_km2').basin_id.tolist(): r_ = B.loc[b_ - 1]; names[int(b_)] = dict(flowdivide_level3_id=int(r_.flowdivide_level3_id), area_km2=float(r_.upstream_area_km2), lon=float(r_.outlet_lon), lat=float(r_.outlet_lat)) # ---------------------------------------------------------------- the Columbia: its pixels and reaches X = rows('pixel_1km2', LO, HI, ['pixel_seq_id', 'upstream_channel_pixel_count', 'reach_seq_id', 'path_seq_id', 'basin_id', 'upstream_area_km2']) assert (X.basin_id == BASIN).all() upc = X.upstream_channel_pixel_count.values # index: pixel - LO assert upc[0] == HI - LO + 1 R = pq.read_table(f_('reach_1km2'), filters=[('basin_id', '=', BASIN)]).to_pandas().sort_values('reach_seq_id').reset_index(drop=True) LC = pq.read_table(f_('reach_location_1km2'), filters=[('reach_seq_id', '>=', int(R.reach_seq_id.min())), ('reach_seq_id', '<=', int(R.reach_seq_id.max()))], columns=['reach_seq_id', 'downstream_end_lon', 'downstream_end_lat']).to_pandas() R = R.merge(LC, on='reach_seq_id', how='left', validate='one_to_one'); assert len(LC) == len(R) and R.downstream_end_lon.notna().all() assert (np.diff(R.reach_seq_id) == 1).all() and R.downstream_end_pixel_seq_id.iloc[0] == LO and R.channel_pixel_count.sum() == HI - LO + 1 assert (R.downstream_end_pixel_seq_id.values[1:] == (R.downstream_end_pixel_seq_id + R.channel_pixel_count).values[:-1]).all(), 'reaches follow each other' paths = np.unique(R.path_seq_id); assert (np.diff(paths) == 1).all() RI = R.set_index('reach_seq_id') def nd_pixel(r): """The pixel below the downstream end of reach r (README rule): the upstream-end pixel of the next-down reach; at a basin outlet its own.""" d = int(r.next_down_reach_seq_id) if d == int(r.reach_seq_id): return int(r.downstream_end_pixel_seq_id) x = RI.loc[d]; return int(x.downstream_end_pixel_seq_id + x.channel_pixel_count - 1) def path_of(pid): s = R[R.path_seq_id == pid]; assert (np.diff(s.reach_seq_id) == 1).all() return s, int(s.downstream_end_pixel_seq_id.iloc[0]), int(s.downstream_end_pixel_seq_id.iloc[-1] + s.channel_pixel_count.iloc[-1] - 1) def branches(o, h): """The path [o, h], then the network [t, t + upstream_channel_pixel_count - 1] of every tributary it receives, one after another.""" out, t, end = [], h + 1, o + int(upc[o - LO]) - 1 while t <= end: e = t + int(upc[t - LO]) - 1; assert e <= end; out.append([int(t), int(e)]); t = e + 1 assert t == end + 1 return out def network(o, name): """The network upstream of the outlet pixel o of a path: its path (main stem), its tributaries, its reaches and paths.""" s, a, h = path_of(int(X.path_seq_id.iloc[o - LO])); assert a == o n = int(upc[o - LO]); sub = X.iloc[o - LO: o - LO + n] return dict(name=name, **run(o, n), area_km2=float(X.upstream_area_km2.iloc[o - LO]), main_stem=dict(path_seq_id=int(s.path_seq_id.iloc[0]), path_level=int(s.path_level.iloc[0]), **run(a, h - a + 1), reaches=run(s.reach_seq_id.iloc[0], len(s)), length_km=float(s.length_km.sum())), tributaries=branches(a, h), reaches=run(s.reach_seq_id.iloc[0], sub.reach_seq_id.nunique()), paths=run(sub.path_seq_id.min(), sub.path_seq_id.nunique())), s col, cs = network(LO, 'Columbia') lb, ls = network(MOUTH, 'Little Blackfoot River') tg, ts = network(TRIB_PIX, 'Telegraph Creek') assert (lb['first'], lb['last']) == (MOUTH, 1088857147), 'the range of the cut-out of Data04' assert lb['count'] == 8442 and lb['reaches']['count'] == 512 and lb['paths']['count'] == 258 assert lb['reaches']['first'] == J4['mouth']['reach_seq_id'] and lb['paths']['first'] == J4['mouth']['path_seq_id'] # where the Little Blackfoot lies in the Columbia: inside one tributary network of the main stem, and inside one of the main stem of that hold = [t for t in col['tributaries'] if t[0] <= MOUTH <= t[1]]; assert len(hold) == 1 and hold[0][1] >= lb['last'] hn, hs = network(hold[0][0], 'holder') assert [MOUTH, lb['last']] in hn['tributaries'], 'the Little Blackfoot is the network of one tributary of the main stem of that network' col['holder_index'] = col['tributaries'].index(hold[0]); col['holder'] = {k: v for k, v in hn.items() if k != 'tributaries'} col['holder']['lb_index'] = hn['tributaries'].index([MOUTH, lb['last']]); col['holder']['n_tributaries'] = len(hn['tributaries']) col['holder']['outlet'] = dict(lon=float(hs.downstream_end_lon.iloc[0]), lat=float(hs.downstream_end_lat.iloc[0])) col['holder']['source'] = dict(lon=float(hs.downstream_end_lon.iloc[-1]), lat=float(hs.downstream_end_lat.iloc[-1])) assert [TRIB_PIX, tg['last']] in lb['tributaries'], 'Telegraph Creek is the network of one tributary of the Little Blackfoot' tg['index_among_tributaries'] = lb['tributaries'].index([TRIB_PIX, tg['last']]) # the path of Telegraph Creek and the reach that holds p ts = ts.copy(); ts['last_pixel'] = ts.downstream_end_pixel_seq_id + ts.channel_pixel_count - 1 rh = ts.iloc[0]; P = int(rh.downstream_end_pixel_seq_id) + 4 # p: the fifth pixel of the reach assert int(rh.channel_pixel_count) >= 5 and int(X.reach_seq_id.iloc[P - LO]) == int(rh.reach_seq_id) and P == TRIB_PIX + 4 reach = dict(reach_seq_id=int(rh.reach_seq_id), **run(rh.downstream_end_pixel_seq_id, rh.channel_pixel_count), length_km=float(rh.length_km), upstream_reach_count=int(rh.upstream_reach_count), upstream_channel_pixel_count=int(rh.upstream_channel_pixel_count), next_down_pixel=nd_pixel(rh), next_down_reach_seq_id=int(rh.next_down_reach_seq_id)) pr = rows('pixel_1km2', P, P, ['pixel_seq_id', 'row', 'col', 'reach_seq_id', 'path_seq_id', 'basin_id', 'upstream_area_km2', 'upstream_channel_pixel_count']).iloc[0] gt = meta['grid']['geotransform'] pixel = dict(pixel_seq_id=P, **run(P, pr.upstream_channel_pixel_count), grid_row=int(pr.row), grid_col=int(pr.col), upstream_area_km2=float(pr.upstream_area_km2), lon=gt[0] + gt[1] * (int(pr.col) + 0.5), lat=gt[3] + gt[5] * (int(pr.row) + 0.5)) # the flow path of p to the outlet of the Columbia: down each path to its downstream-end pixel, then to the pixel it flows to (the basin outlet points to itself) flow_path, q, seen = [], P, [] while True: s, a, h = path_of(int(X.path_seq_id.iloc[q - LO])); assert a <= q <= h flow_path.append([a, int(q)]); r0 = s.iloc[0]; seen.append(dict(path_seq_id=int(r0.path_seq_id), path_level=int(r0.path_level), downstream_end_lon=float(r0.downstream_end_lon), downstream_end_lat=float(r0.downstream_end_lat))) if int(r0.next_down_reach_seq_id) == int(r0.reach_seq_id): assert a == LO; break q = nd_pixel(r0) assert len(flow_path) == int(rh.path_level) and [p_['path_level'] for p_ in seen] == list(range(len(seen), 0, -1)) assert flow_path[0] == [TRIB_PIX, P] and flow_path[1][0] == MOUTH and flow_path[1][1] == reach['next_down_pixel'] S = dict(source='flownest_merit90m_global_20261113_195421 (code %s, numbering_version %s, numbering %s)' % (meta['code_version'], meta['numbering_version'], meta['numbering_sha256'][:12]), globe=globe, level1=level1, level2=level2, level3=level3, basin=basin, names=names, columbia=dict(main_stem=col['main_stem'], tributaries=col['tributaries'], holder_index=col['holder_index'], holder=col['holder'], paths=run(paths[0], len(paths)), reaches=run(R.reach_seq_id.iloc[0], len(R))), littleblackfoot=dict(lb, local_offsets=dict(pixel=MOUTH - 1, reach=lb['reaches']['first'] - 1, path=lb['paths']['first'] - 1)), telegraph=tg, reach=reach, pixel=pixel, flow_path=flow_path, flow_path_paths=seen, junction_pixel=reach['next_down_pixel']) json.dump(S, open(OUT % 'littleblackfoot_zoom_chain.json', 'w'), indent=1) ts.to_parquet(OUT % 'telegraph_path_reach_1km2.parquet', index=False) loc = lambda v: v - MOUTH + 1 print('globe 1-%s, %d Level-1 groups' % (format(globe['last'], ','), len(globe['parts']))) for k, d in (('level1', level1), ('level2', level2), ('level3', level3)): print(k, d['code'], format(d['first'], ','), format(d['last'], ','), format(d['count'], ','), [p_['code'] for p_ in d['parts']][:12]) print('L3 basins', level3['basins'], 'paths', level3['paths'], 'reaches', level3['reaches']) print('basin', basin, 'paths', len(paths), 'reaches', len(R)) print('columbia main stem', col['main_stem'], 'tributaries', len(col['tributaries']), 'holder', col['holder_index'], col['holder']) for k, d in (('lb', lb), ('tg', tg)): print(k, {a: b for a, b in d.items() if a != 'tributaries'}, 'tribs', len(d['tributaries']), 'local', loc(d['first']), loc(d['last'])) print('reach', reach, 'local pixels', loc(reach['first']), loc(reach['last'])) print('p', pixel, 'local', loc(P)) print('flow path', flow_path, seen) print('names', names)