# -*- coding: utf-8 -*- """Cut the Little Blackfoot River out of the global FlowNest release. The Little Blackfoot is one range of channel pixels inside the Columbia (basin_id 32): its mouth pixel and the pixels upstream of it. The script reads that range from the 1 km2 pixel and reach tables, adds the alias_* columns that follow from the rules of the release README, and checks every rule on the cut-out. Used by: Figures 5, 6 and 7 and the numbers of the Little Blackfoot in the text. Input: the global release (paths.GLOBAL). Output: ../Data/Data04_flownest_littleblackfoot_{basin,pixel_1km2,reach_1km2}.parquet, ../Data/Data04_flownest_littleblackfoot_pixel_seq_id_1km2.tif and ../Data/Data04_flownest_littleblackfoot.json Usage: python Data04_flownest_littleblackfoot.py """ import os, json import numpy as np, pandas as pd, rasterio import pyarrow as pa, pyarrow.parquet as pq from rasterio.windows import Window import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH REL = PTH.GLOBAL rel = lambda kind: os.path.join(REL, 'flownest_merit90m_%s.parquet' % kind) BASIN, MOUTH = 32, 1088848706 # the Columbia; the mouth pixel of the Little Blackfoot TRIB_PIX = 1088850437 # the downstream-end pixel of Telegraph Creek DATD = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'Data') OUT = os.path.join(DATD, 'Data04_flownest_littleblackfoot_%s') meta = json.load(open(os.path.join(REL, 'metadata.json'))) assert meta['code_version'] == '10.61' and meta['base_threshold_km2'] == 1 and meta['numbering_sha256'][:12] == 'c485dec56c3a' # the basin row of the Columbia, for its first pixel (local numbers count from 1 at the Columbia outlet) cb = pq.read_table(rel('basin'), filters=[('basin_id', '=', BASIN)]).to_pandas(); assert len(cb) == 1; cb = cb.iloc[0] C_LO = int(cb.outlet_pixel_seq_id) # the channel pixels of the Little Blackfoot m = pq.read_table(rel('pixel_1km2'), filters=[('pixel_seq_id', '=', MOUTH)]).to_pandas(); assert len(m) == 1; m = m.iloc[0] LO, N = MOUTH, int(m.upstream_channel_pixel_count); HI = LO + N - 1 px = pq.read_table(rel('pixel_1km2'), filters=[('pixel_seq_id', '>=', LO), ('pixel_seq_id', '<=', HI)]) p = px.to_pandas().sort_values('pixel_seq_id').reset_index(drop=True) assert (p.pixel_seq_id.values == np.arange(LO, HI + 1)).all(), 'the channel pixels upstream of a pixel are one run' assert (p.basin_id == BASIN).all() and C_LO < LO and HI < C_LO + int(cb.channel_pixel_count) assert (p.upstream_channel_pixel_count.values >= 1).all() and (p.pixel_seq_id + p.upstream_channel_pixel_count - 1 <= HI).all() # its reaches at 1 km²: those whose downstream-end pixel lies in the run rc = pq.read_table(rel('reach_1km2'), filters=[('basin_id', '=', BASIN), ('downstream_end_pixel_seq_id', '>=', LO), ('downstream_end_pixel_seq_id', '<=', HI)]) r = rc.to_pandas().sort_values('reach_seq_id').reset_index(drop=True) lc = pq.read_table(rel('reach_location_1km2'), filters=[('reach_seq_id', '>=', int(r.reach_seq_id.min())), ('reach_seq_id', '<=', int(r.reach_seq_id.max()))]).to_pandas() r = r.merge(lc, on='reach_seq_id', how='left', validate='one_to_one'); assert r.downstream_end_lon.notna().all() and len(lc) == len(r) # the pixel below each reach, by the README rule: the upstream-end pixel of the next-down reach (own downstream end at a basin outlet) nxt = set(int(x) for x in r.next_down_reach_seq_id) - set(int(x) for x in r.reach_seq_id) ex = pq.read_table(rel('reach_1km2'), filters=[('reach_seq_id', 'in', sorted(nxt))], columns=['reach_seq_id', 'downstream_end_pixel_seq_id', 'channel_pixel_count']).to_pandas() ue = {int(a): int(b) + int(c) - 1 for a, b, c in zip(pd.concat([r, ex]).reach_seq_id, pd.concat([r, ex]).downstream_end_pixel_seq_id, pd.concat([r, ex]).channel_pixel_count)} r_nd_pix = np.array([int(o) if int(d) == int(s_) else ue[int(d)] for s_, d, o in zip(r.reach_seq_id, r.next_down_reach_seq_id, r.downstream_end_pixel_seq_id)], 'int64') o_, n_ = r.downstream_end_pixel_seq_id.values, r.channel_pixel_count.values assert o_[0] == LO and (o_[1:] == o_[:-1] + n_[:-1]).all() and o_[-1] + n_[-1] - 1 == HI, 'the reaches tile the run: each reach is one range' assert (np.diff(r.reach_seq_id.values) == 1).all(), 'the reaches of the Little Blackfoot are one run of reach_seq_id' R_LO = int(r.reach_seq_id.iloc[0]); assert int(r.upstream_reach_count.iloc[0]) == len(r) mouth_r = r.iloc[0]; below_mouth = int(r_nd_pix[0]) assert below_mouth != LO and not (LO <= below_mouth <= HI), 'the Little Blackfoot flows out of the run into the Clark Fork' assert (r.next_down_reach_seq_id.iloc[1:].between(R_LO, R_LO + len(r) - 1)).all() assert (r.reach_seq_id.values == p.reach_seq_id.values[o_ - LO]).all() and np.array_equal(np.repeat(r.reach_seq_id.values, n_), p.reach_seq_id.values) # the pixel below every channel pixel, and the alias columns nd = p.pixel_seq_id.values - 1 nd[o_ - LO] = r_nd_pix; nd[0] = 0 # 0: the outlet of the cut-out assert (nd[1:] >= LO).all() and (nd[1:] < p.pixel_seq_id.values[1:]).all(), 'every pixel flows to a smaller number' p['alias_pixel_id'] = p.pixel_seq_id p['alias_upstream_pixel_id_max'] = p.pixel_seq_id + p.upstream_channel_pixel_count - 1 p['alias_next_down_pixel_id'] = nd p['alias_reach_id'] = p.reach_seq_id p['alias_river_id'] = p.path_seq_id # the upstream run of every pixel is its own pixel and the runs of the pixels flowing into it cnt = np.ones(N, 'int64') for i in range(N - 1, 0, -1): cnt[nd[i] - LO] += cnt[i] assert np.array_equal(cnt, p.upstream_channel_pixel_count.values), 'upstream_channel_pixel_count is the number of pixels flowing to each pixel' r['alias_reach_id'] = r.reach_seq_id r['alias_outlet_pixel_id'] = r.downstream_end_pixel_seq_id r['alias_upstream_end_pixel_id'] = r.downstream_end_pixel_seq_id + r.channel_pixel_count - 1 r['alias_upstream_pixel_id_max'] = r.downstream_end_pixel_seq_id + r.upstream_channel_pixel_count - 1 r['alias_next_down_pixel_id'] = np.where(r.reach_seq_id == R_LO, 0, r_nd_pix) r['alias_next_down_reach_id'] = np.where(r.reach_seq_id == R_LO, 0, r.next_down_reach_seq_id) r['alias_upstream_reach_id_max'] = r.reach_seq_id + r.upstream_reach_count - 1 r['alias_river_id'] = r.path_seq_id r['alias_river_level'] = r.path_level g = r.reset_index().groupby('path_seq_id')['index'].agg(['min', 'max', 'count']) assert ((g['max'] - g['min'] + 1) == g['count']).all(), 'each path is one run of reaches' assert (r.upstream_area_km2.values == p.upstream_area_km2.values[o_ - LO]).all() and (r.upstream_channel_pixel_count.values == p.upstream_channel_pixel_count.values[o_ - LO]).all() # Telegraph Creek t = p.iloc[TRIB_PIX - LO]; tj = int(nd[TRIB_PIX - LO]); tr = r[r.downstream_end_pixel_seq_id == TRIB_PIX] assert len(tr) == 1 and tj != TRIB_PIX - 1, 'Telegraph Creek starts a reach and flows into another path' tr = tr.iloc[0]; T_HI = TRIB_PIX + int(t.upstream_channel_pixel_count) - 1 assert int(p.reach_seq_id.iloc[tj - LO]) != int(tr.reach_seq_id) and int(p.path_seq_id.iloc[tj - LO]) == int(mouth_r.path_seq_id), 'it joins the main stem of the Little Blackfoot' # the raster window: the catchment of the mouth reach c0, r0 = int(mouth_r.upstream_catchment_col_min), int(mouth_r.upstream_catchment_row_min) w = Window(c0, r0, int(mouth_r.upstream_catchment_col_max) - c0, int(mouth_r.upstream_catchment_row_max) - r0) with rasterio.open(os.path.join(REL, 'flownest_merit90m_pixel_seq_id_1km2.tif')) as src: v = src.read(1, window=w); prof = dict(driver='GTiff', width=w.width, height=w.height, count=1, dtype='int32', crs=src.crs, transform=src.window_transform(w), nodata=src.nodata, compress='deflate', predictor=2) full = src.read(1, window=Window(c0 - 1, r0 - 1, w.width + 2, w.height + 2)) a = np.abs(v.astype('int64')); inb = (a >= LO) & (a <= HI) af = np.abs(full.astype('int64')); assert ((af >= LO) & (af <= HI)).sum() == inb.sum(), 'the window holds all the land of the Little Blackfoot' rr, cc = np.nonzero(v > 0); vv = v[rr, cc]; sel = (vv >= LO) & (vv <= HI) on = pd.DataFrame({'pixel_seq_id': vv[sel], 'row': rr[sel] + r0, 'col': cc[sel] + c0}).sort_values('pixel_seq_id') assert np.array_equal(on.pixel_seq_id.values, p.pixel_seq_id.values), 'every channel pixel is on the raster once, with +pixel_seq_id' assert np.array_equal(on.row.values, p.row.values) and np.array_equal(on.col.values, p.col.values) # the land, in km², on the WGS84 ellipsoid as the release measures it (MERIT pixel areas by latitude) lat = 85 - (np.arange(r0, r0 + w.height) + 0.5) / 1200 A_, E2 = 6378137.0, 6.69437999014e-3 def band(phi): # area of the ellipsoid between the equator and latitude phi, per radian of longitude s = np.sin(np.radians(phi)); e = np.sqrt(E2) return A_ ** 2 * (1 - E2) / 2 * (s / (1 - E2 * s * s) + np.log((1 + e * s) / (1 - e * s)) / (2 * e)) pa_km2 = (band(lat + 1 / 2400) - band(lat - 1 / 2400)) * np.radians(1 / 1200) / 1e6 land = float((inb.sum(1) * pa_km2).sum()) # the basin row of the cut-out, in the basin table's layout, and the aliases the figure code reads b = pd.DataFrame([dict(basin_id=BASIN, flowdivide_level1_id=int(cb.flowdivide_level1_id), flowdivide_level2_id=int(cb.flowdivide_level2_id), flowdivide_level3_id=int(cb.flowdivide_level3_id), outlet_pixel_seq_id=LO, channel_pixel_count=N, upstream_area_km2=np.float32(m.upstream_area_km2), is_endorheic=np.int8(0), outlet_lon=float(mouth_r.downstream_end_lon), outlet_lat=float(mouth_r.downstream_end_lat), row_min=r0, row_max=int(mouth_r.upstream_catchment_row_max), col_min=c0, col_max=int(mouth_r.upstream_catchment_col_max), alias_outlet_pixel_id=LO, alias_upstream_pixel_id_max=HI)]) os.makedirs(DATD, exist_ok=True) pq.write_table(pa.Table.from_pandas(b, preserve_index=False), OUT % 'basin.parquet') pq.write_table(pa.Table.from_pandas(p, preserve_index=False), OUT % 'pixel_1km2.parquet') pq.write_table(pa.Table.from_pandas(r, preserve_index=False), OUT % 'reach_1km2.parquet') with rasterio.open(OUT % 'pixel_seq_id_1km2.tif', 'w', **prof) as dst: dst.write(v, 1) dst.update_tags(source='flownest_merit90m_global_20261113_195421 (code %s), basin_id %d, channel pixels %d-%d (the Little Blackfoot)' % (meta['code_version'], BASIN, LO, HI), numbering_sha256=str(meta.get('numbering_sha256'))) loc = lambda x: int(x) - C_LO + 1 J = dict(release='flownest_merit90m_global_20261113_195421', code_version=meta['code_version'], numbering_sha256=meta.get('numbering_sha256'), basin_id=BASIN, columbia_outlet_pixel_seq_id=C_LO, columbia_upstream_area_km2=float(cb.upstream_area_km2), mouth=dict(pixel_seq_id=LO, local=loc(LO), upstream_channel_pixel_count=N, last=HI, upstream_area_km2=float(m.upstream_area_km2), reach_seq_id=R_LO, path_seq_id=int(mouth_r.path_seq_id), path_level=int(mouth_r.path_level), next_down_pixel=below_mouth, next_down_reach_seq_id=int(mouth_r.next_down_reach_seq_id), downstream_end_lon=float(mouth_r.downstream_end_lon), downstream_end_lat=float(mouth_r.downstream_end_lat), reaches=len(r), paths=int(r.path_seq_id.nunique()), land_km2_from_raster=round(land, 2)), telegraph=dict(pixel_seq_id=TRIB_PIX, local=loc(TRIB_PIX), upstream_channel_pixel_count=int(t.upstream_channel_pixel_count), last=T_HI, upstream_area_km2=float(t.upstream_area_km2), reach_seq_id=int(tr.reach_seq_id), path_seq_id=int(tr.path_seq_id), path_level=int(tr.path_level), next_down_pixel=tj, next_down_reach_seq_id=int(tr.next_down_reach_seq_id), downstream_end_lon=float(tr.downstream_end_lon), downstream_end_lat=float(tr.downstream_end_lat), row=int(t.row), col=int(t.col)), window=dict(row_min=r0, row_max=int(mouth_r.upstream_catchment_row_max), col_min=c0, col_max=int(mouth_r.upstream_catchment_col_max))) json.dump(J, open(OUT.replace('_%s', '.json'), 'w'), indent=1) print('Little Blackfoot: pixel_seq_id %d-%d (%d channel pixels; local %d-%d), %.2f km² (raster land %.2f km²), %d reaches, %d paths' % (LO, HI, N, loc(LO), loc(HI), m.upstream_area_km2, land, len(r), r.path_seq_id.nunique())) print('Telegraph Creek: pixel %d (local %d), %d pixels, %.2f km², reach %d, path %d level %d, flows to pixel %d' % (TRIB_PIX, loc(TRIB_PIX), t.upstream_channel_pixel_count, t.upstream_area_km2, tr.reach_seq_id, tr.path_seq_id, tr.path_level, tj)) print('mouth flows to pixel %d (reach %d); window %d x %d' % (below_mouth, mouth_r.next_down_reach_seq_id, w.height, w.width)) print('written to', DATD)