# -*- coding: utf-8 -*- """Figure 7: subbasins of the Little Blackfoot at 25, 5 and 1 km2 (a-c) and the window at the mouth of Telegraph Creek (d-f). Input: the global release (paths.GLOBAL) and the coarser thresholds (paths.COARSER). Output: with --final, ../Figures: png and pdf; otherwise ../Drafts: one png. Usage: python Fig07_subbasins_three_thresholds_littleblackfoot.py [--final] """ import os, re, glob, sys import numpy as np, rasterio, geopandas as gpd, pyarrow.parquet as pq from rasterio.windows import Window import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Patch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42, "font.family": "sans-serif", "font.sans-serif": ["Helvetica", "Arial", "DejaVu Sans"]}) RELEASE, COARSER = PTH.GLOBAL, PTH.COARSER R, RC = RELEASE + '/flownest_merit90m_', COARSER + '/flownest_merit90m_' import json _m, _c = (json.load(open(os.path.join(x, 'metadata.json'))) for x in (RELEASE, COARSER)) import hashlib, shapely assert _m['code_version'] == '10.61' and _c['code_version'] == '10.66' and _m['numbering_sha256'][:12] == 'c485dec56c3a' assert _c['release']['metadata_sha256'] == hashlib.sha256(open(os.path.join(RELEASE, 'metadata.json'), 'rb').read()).hexdigest(), 'made on _20261113_195421' from flownest import Release # noqa: E402 REL_PY = Release(RELEASE, COARSER) SRC = {1: R, 5: RC, 25: RC} # the files of each threshold FINAL = '--final' in sys.argv HERE = os.path.dirname(os.path.abspath(__file__)); FIGD = os.path.join(os.path.dirname(HERE), 'Figures' if FINAL else 'Drafts') BID = 32; A0, NR = 65454196, 512; TRIB = 65454317; TRIB_NAME = 'Telegraph Creek' # the Columbia; the reaches of the Little Blackfoot; the 1 km2 reach at the mouth of Telegraph Creek P_MOUTH, P_TRIB = 1088848706, 1088850437 # downstream end pixels of the Little Blackfoot and of Telegraph Creek FS, FT = 10, 12; C_RIV = '#0072B2'; RED = '#D55E00'; AMBER = '#E69F00'; UNIT_L = '#fbd3b0'; LAND = '#ececec'; C_REACH = '#6A3D9A' # purple: not the orange of the Telegraph Creek outline num = lambda v: f'{int(v):,}' FLT = [('reach_seq_id', '>=', A0), ('reach_seq_id', '<', A0 + NR)] d = pq.read_table(R + 'reach_1km2.parquet', columns=['reach_seq_id', 'next_down_reach_seq_id', 'break_threshold_km2', 'upstream_area_km2', 'unit_catchment_area_km2'], filters=FLT).to_pandas().sort_values('reach_seq_id').reset_index(drop=True) LOC = pq.read_table(R + 'reach_location_1km2.parquet', columns=['reach_seq_id', 'downstream_end_lat', 'unit_catchment_row_min', 'unit_catchment_row_max', 'unit_catchment_col_min', 'unit_catchment_col_max'], filters=FLT).to_pandas().sort_values('reach_seq_id').reset_index(drop=True) assert (LOC.reach_seq_id.values == d.reach_seq_id.values).all(); d = d.join(LOC.drop(columns='reach_seq_id')) # same rows in both tables a = int(d.reach_seq_id[0]); n = len(d) assert a == A0 and n == NR and (d.reach_seq_id.values == np.arange(a, a + n)).all() and not (a <= d.next_down_reach_seq_id[0] < a + n) # contiguous; the mouth flows out of the range down = d.next_down_reach_seq_id.values - a; down[0] = 0; brk = d.break_threshold_km2.values.astype(np.float64) assert ((down[1:] >= 0) & (down[1:] < n)).all(), 'a reach of the Little Blackfoot flows out of the range' assert (down[1:] < np.arange(1, n)).all() area = d.unit_catchment_area_km2.values.astype(np.float64) assert abs(area.sum() / d.upstream_area_km2[0] - 1) < 0.003 # unit catchments are summed on pixel areas (known ~0.2%) blk = {1: np.arange(n)} for T in (5, 25): b = np.empty(n, np.int64) for r in range(n): b[r] = r if (r == 0 or brk[r] >= T) else b[down[r]] blk[T] = b r0, r1 = d.unit_catchment_row_min.min() - 4, d.unit_catchment_row_max.max() + 4 c0, c1 = d.unit_catchment_col_min.min() - 4, d.unit_catchment_col_max.max() + 4 with rasterio.open(R + 'reach_seq_id_1km2.tif') as src: g = np.abs(src.read(1, window=Window(c0, r0, c1 - c0 + 1, r1 - r0 + 1)).astype(np.int64)); tr = src.transform ins = (g >= a) & (g < a + n); loc = np.where(ins, g - a, 0) lab = {T: np.where(ins, blk[T][loc], -1) for T in (1, 5, 25)} N = {T: len(np.unique(blk[T])) for T in (1, 5, 25)} AREA = {T: np.bincount(blk[T], weights=area, minlength=n)[np.unique(blk[T])] for T in (1, 5, 25)} for T in (1, 5, 25): assert len(np.unique(lab[T][ins])) == N[T], T # every subbasin is on the raster for f, c in ((1, 5), (5, 25)): # nesting: each finer subbasin lies in one coarser assert len(np.unique(np.c_[lab[f][ins], lab[c][ins]], axis=0)) == N[f], (f, c) t = TRIB - a; assert blk[25][t] == t mem = blk[25] == t; MB = lab[25] == t print('subbasins', N, 'medians', {T: round(float(np.median(AREA[T])), 1) for T in N}, '%s at 25 km2: %.1f km2 (upstream %.1f), %d subbasins at 5, %d at 1' % (TRIB_NAME, area[mem].sum(), d.upstream_area_km2[t], len(np.unique(blk[5][mem])), mem.sum())) lines = gpd.read_parquet(R + 'reach_line_1km2.geo.parquet', columns=['reach_seq_id', 'geometry'], filters=[('reach_seq_id', '>=', A0), ('reach_seq_id', '<', A0 + NR)]) assert len(lines) == n upa = dict(zip(d.reach_seq_id, d.upstream_area_km2)) ASP = 1 / np.cos(np.radians(d.downstream_end_lat.mean())) # a pixel is ASP times as tall as wide on the ground # ---- (d-f): each threshold from its own released files ---- RCOLS = ['reach_seq_id', 'downstream_end_pixel_seq_id', 'path_seq_id', 'upstream_reach_count', 'upstream_area_km2'] def reach_at_pixel(T, p): """the reach of threshold T whose downstream end is pixel p (one row of that threshold's reach table).""" t_ = pq.read_table(SRC[T] + 'reach_%dkm2.parquet' % T, columns=RCOLS, filters=[('downstream_end_pixel_seq_id', '=', p)]).to_pandas() assert len(t_) == 1, (T, p); return t_.iloc[0] ID, NET, LIN = {}, {}, {} for T in (25, 5, 1): m = reach_at_pixel(T, P_MOUTH); k = reach_at_pixel(T, P_TRIB) m0, mn = int(m.reach_seq_id), int(m.upstream_reach_count) assert mn == N[T], (T, mn) # the same 27, 121, 512 reaches as (a-c) ID[T] = dict(reach=int(k.reach_seq_id), path=int(k.path_seq_id), pixel=int(k.downstream_end_pixel_seq_id)) assert m0 <= ID[T]['reach'] < m0 + mn # Telegraph Creek lies in the range of the Little Blackfoot NET[T] = pq.read_table(SRC[T] + 'reach_%dkm2.parquet' % T, columns=RCOLS, filters=[('reach_seq_id', '>=', m0), ('reach_seq_id', '<', m0 + mn)] ).to_pandas().sort_values('reach_seq_id').reset_index(drop=True) LIN[T] = gpd.read_parquet(SRC[T] + 'reach_line_%dkm2.geo.parquet' % T, columns=['reach_seq_id', 'geometry'], filters=[('reach_seq_id', '>=', m0), ('reach_seq_id', '<', m0 + mn)]) assert len(NET[T]) == len(LIN[T]) == mn ID[T]['range'] = (m0, mn) print({T: ID[T] for T in ID}) ON = {T: set(map(tuple, shapely.get_coordinates(LIN[T].geometry.values))) for T in (5, 25)} # the vertices (pixel centres) of each threshold's lines def on_channel(geom, T): """the part of a 1 km² reach line on the lines of threshold T (a reach that crosses T loses its head); None if under two vertices.""" if T == 1: return geom c = shapely.get_coordinates(geom); i = np.nonzero([tuple(x) in ON[T] for x in c])[0] assert (np.diff(i) == 1).all(), 'the part on the channel is one piece' return shapely.LineString(c[i]) if len(i) >= 2 else None segs = lambda gs: {frozenset((tuple(p), tuple(q))) for g in gs for p, q in zip(shapely.get_coordinates(g)[:-1], shapely.get_coordinates(g)[1:])} for T in (5, 25): drawn = [on_channel(g_, T) for k_, g_ in zip(lines.reach_seq_id, lines.geometry) if upa[k_] >= T] assert segs([g_ for g_ in drawn if g_ is not None]) == segs(LIN[T].geometry), T # (a, b) draw exactly the lines of 5 and 25 km² assert ID[1]['reach'] == TRIB and len({ID[T]['pixel'] for T in ID}) == 1 and len({ID[T]['reach'] for T in ID}) == 3 and len({ID[T]['path'] for T in ID}) == 3 TL = pq.read_table(R + 'reach_location_1km2.parquet', filters=[('reach_seq_id', '=', TRIB)]).to_pandas().iloc[0] PX = pq.read_table(R + 'pixel_1km2.parquet', columns=['pixel_seq_id', 'row', 'col'], filters=[('pixel_seq_id', '=', P_TRIB)]).to_pandas().iloc[0] MT, ML_, MO = 12, 10, 4 # margins in pixels: more on the north and west, where the main stem runs br0, br1 = int(TL.upstream_catchment_row_min) - MT, int(TL.upstream_catchment_row_max) + MO bc0, bc1 = int(TL.upstream_catchment_col_min) - ML_, int(TL.upstream_catchment_col_max) + MO WB = Window(bc0, br0, bc1 - bc0, br1 - br0) gb, gp = {}, {} with rasterio.open(R + 'reach_seq_id_1km2.tif') as s: gb[1] = s.read(1, window=WB).astype(np.int64) with rasterio.open(R + 'pixel_seq_id_1km2.tif') as s: gp[1] = s.read(1, window=WB).astype(np.int64) for T in (5, 25): # no raster in step 9's package: made from the 1 km2 raster gb[T] = REL_PY.window_at(T, br0, br1, bc0, bc1); gp[T] = gp[1] assert (REL_PY.window_at(1, br0, br1, bc0, bc1) == gb[1]).all() pr, pc = int(PX.row) - br0, int(PX.col) - bc0 for T in (1, 5, 25): # the claim of (d-f), read from the rasters at the pixel assert gb[T][pr, pc] == ID[T]['reach'] and gp[T][pr, pc] == P_TRIB, (T, gb[T][pr, pc], gp[T][pr, pc]) insB = {T: (np.abs(gb[T]) >= ID[T]['range'][0]) & (np.abs(gb[T]) < sum(ID[T]['range'])) for T in (1, 5, 25)} assert (insB[1] == insB[5]).all() and (insB[1] == insB[25]).all() insB = insB[1]; TC = np.abs(gb[25]) == ID[25]['reach'] # Telegraph Creek = its one subbasin at 25 km2 Hb, Wb = insB.shape print('window (d-f) rows', br0, br1, 'cols', bc0, bc1, 'outlet pixel at', pr, pc) def edges(img, m): e = np.zeros(img.shape, bool) e[:-1] |= (img[:-1] != img[1:]) & (m[:-1] | m[1:]); e[:, :-1] |= (img[:, :-1] != img[:, 1:]) & (m[:, :-1] | m[:, 1:]) return e def thick(e): return e | np.roll(e, 1, 0) | np.roll(e, 1, 1) def draw_lines(ax, geoms, cc0, rr0, **kw): for geom in geoms: for gg in getattr(geom, 'geoms', [geom]): x, y = np.asarray(gg.xy); cc, rr = ~tr * (x, y) ax.plot(cc - cc0 - .5, rr - rr0 - .5, solid_capstyle='round', solid_joinstyle='round', **kw) rng = np.random.default_rng(3); PAL = plt.get_cmap('tab20') H, Wd = g.shape # two rows of three panels; every size in inches W, ML, GAP = 7.48, 0.05, 0.12; PW = (W - 2 * ML - 2 * GAP) / 3; PH = PW * H * ASP / Wd; PHb = PW * Hb * ASP / Wb TOP, MID, TXT, LEGH = 0.52, 0.42, 0.80, 0.30; FH = TOP + PH + MID + PHb + TXT + LEGH yb = LEGH + TXT; yt = yb + PHb + MID # bottoms of the two rows of maps fig = plt.figure(figsize=(W, FH)) def text_w(s, size, **kw): # width of a text in inches t_ = fig.text(0, 0, s, fontsize=size, **kw); fig.canvas.draw(); w = t_.get_window_extent().width / fig.dpi; t_.remove(); return w def title(x0, ytop, s): fig.text(x0 / W, 1 - ytop / FH, s, fontsize=FT, fontfamily='Arial', fontweight='bold', va='baseline') # Helvetica here has no bold face coarser = {25: None, 5: 25, 1: 5} for j, T in enumerate((25, 5, 1)): x0 = ML + j * (PW + GAP) # ---- top row ---- ax = fig.add_axes([x0 / W, yt / FH, PW / W, PH / FH]) u, inv = np.unique(lab[T][ins], return_inverse=True) col = np.array([PAL(q)[:3] for q in rng.integers(0, 20, len(u))]) * .40 + .60 pic = np.ones(g.shape + (3,)); pic[ins] = col[inv] pic[edges(lab[T], ins)] = .55 if coarser[T]: pic[thick(edges(lab[coarser[T]], ins)) & ins] = 0 ax.imshow(pic, interpolation='nearest', aspect='auto') # the axes box already has the ground shape of the pixels for k, geom in zip(lines.reach_seq_id, lines.geometry): A = upa[k] part = on_channel(geom, T) if A >= T else None # only its part on the channel of threshold T if part is not None: draw_lines(ax, [part], c0, r0, color=C_RIV, lw=0.25 + 0.35 * np.log10(A)) # same river, same width in every panel ov = np.zeros(g.shape + (4,)); ov[thick(thick(edges(MB.astype(int), ins)))] = matplotlib.colors.to_rgba(RED) ax.imshow(ov, interpolation='nearest', aspect='auto', zorder=5) # orange outline on top of the rivers ax.set_xlim(-.5, Wd - .5); ax.set_ylim(H - .5, -.5); ax.axis('off') title(x0, 0.20, '(%s) %d km²' % ('abc'[j], T)) fig.text(x0 / W, 1 - 0.42 / FH, '%d subbasins, median %.1f km²' % (N[T], np.median(AREA[T])), fontsize=FS, va='baseline') assert text_w('%d subbasins, median %.1f km²' % (N[T], np.median(AREA[T])), FS) <= PW + GAP - 0.05 if j == 0: # the name of the tributary: the nearest place where its text covers no pixel of the river basin rr_, cc_ = np.nonzero(MB); yc, xc = rr_.mean(), cc_.mean() tw = text_w(TRIB_NAME, FS) * Wd / PW; th = 0.17 * H / PH # the text box in pixels best = None for ytx in np.arange(th, H - 1, 2.0): for xtx in np.arange(0, Wd - tw, 2.0): a_, b_ = int(ytx - th), int(ytx) + 1; c_, d_ = int(xtx), int(xtx + tw) + 1 if ins[max(a_ - 3, 0):b_ + 3, max(c_ - 3, 0):d_ + 3].any(): continue dd = np.hypot(xtx + tw / 2 - xc, (ytx - th / 2 - yc) * ASP) if dd > 0.25 * np.hypot(tw, th * ASP) and (best is None or dd < best[0]): best = (dd, xtx, ytx) assert best is not None _, xtx, ytx = best ax.annotate(TRIB_NAME, xy=(xc, yc), xytext=(xtx + tw / 2, ytx - th / 2), fontsize=FS, color=RED, ha='center', va='center', zorder=6, arrowprops=dict(arrowstyle='-|>', color=RED, lw=1.0, shrinkA=2, shrinkB=4)) # ---- bottom row: the same window at each threshold, from that threshold's files ---- axb = fig.add_axes([x0 / W, yb / FH, PW / W, PHb / FH]) lb = np.abs(gb[T]); me = lb == ID[T]['reach'] pic = np.ones(gb[T].shape + (3,)); pic[insB & ~TC] = matplotlib.colors.to_rgb(LAND) pic[me] = matplotlib.colors.to_rgb(UNIT_L) # the subbasin of the reach at the mouth pic[edges(lb, insB)] = .55 axb.imshow(pic, interpolation='nearest', aspect='auto') ov = np.zeros(gb[T].shape + (4,)); ov[thick(edges(TC.astype(int), insB))] = matplotlib.colors.to_rgba(RED) axb.imshow(ov, interpolation='nearest', aspect='auto', zorder=2) net = NET[T].set_index('reach_seq_id'); L = LIN[T].set_index('reach_seq_id') onp = net.index[net.path_seq_id == ID[T]['path']] draw_lines(axb, L.loc[onp].geometry, bc0, br0, color=AMBER, lw=6.5, alpha=.75, zorder=3) # the path, as a wide band for k_, geom in L.geometry.items(): A = net.upstream_area_km2[k_] draw_lines(axb, [geom], bc0, br0, color=C_RIV, lw=0.5 + 0.5 * np.log10(A), zorder=4) draw_lines(axb, [L.geometry[ID[T]['reach']]], bc0, br0, color=C_REACH, lw=2.6, zorder=5) # the reach at the mouth axb.plot(pc, pr, 'o', ms=6.5, mfc='k', mec='white', mew=1.0, zorder=7) # its downstream end pixel (catchment outlet) axb.set_xlim(-.5, Wb - .5); axb.set_ylim(Hb - .5, -.5); axb.axis('off') title(x0, TOP + PH + 0.30, '(%s) %d km²' % ('def'[j], T)) # the three numbers under the map: label at left, value right-aligned to the panel edge rows = [('reach_seq_id', num(ID[T]['reach']), 'normal', 'k'), ('path_seq_id', num(ID[T]['path']), 'normal', 'k'), ('pixel_seq_id at ●', num(ID[T]['pixel']), 'bold', 'k')] for i, (lab_, val, wt, cl) in enumerate(rows): yy = (LEGH + TXT - 0.22 - i * 0.20) / FH fig.text((x0 + 0.03) / W, yy, lab_, fontsize=FS, va='baseline', color='0.25') fig.text((x0 + PW - 0.03) / W, yy, val, fontsize=FS, va='baseline', ha='right', color=cl, **(dict(fontfamily='Arial', fontweight='bold') if wt == 'bold' else {})) assert text_w(lab_, FS) + text_w(val, FS, fontfamily='Arial', fontweight='bold') + 0.15 <= PW, lab_ # the orange Telegraph Creek outline (named in (a)) and the thick black boundaries in (b, c) are explained in the caption HD = [Line2D([], [], color=C_REACH, lw=2.6, label='reach at the mouth of %s' % TRIB_NAME), Patch(fc=UNIT_L, ec='.55', lw=0.8, label='its subbasin'), (Line2D([], [], color=AMBER, lw=6, alpha=.75), Line2D([], [], color=C_RIV, lw=1.0)), # as on the maps: band with the river in it Line2D([], [], color='none', marker='o', ms=6.5, mfc='k', mec='white', label='its downstream end pixel')] kw = dict(loc='lower center', borderaxespad=0, fontsize=FS, frameon=False, handlelength=1.6, handletextpad=0.5, columnspacing=1.2) from matplotlib.legend_handler import HandlerTuple l1 = fig.legend(handles=HD, labels=['reach at the mouth of %s' % TRIB_NAME, 'its subbasin', 'its path', 'its downstream end pixel'], ncol=4, bbox_to_anchor=(0.5, 0.04 / FH), handler_map={tuple: HandlerTuple(ndivide=1, pad=0)}, **kw) fig.canvas.draw() assert l1.get_window_extent().width / fig.dpi <= W - 0.1, l1.get_window_extent().width / fig.dpi os.makedirs(FIGD, exist_ok=True) stem = 'Fig07_subbasins_three_thresholds_littleblackfoot' if not FINAL: out = os.path.join(FIGD, stem + '_draft.png'); fig.savefig(out, dpi=200); print('draft', out); sys.exit() used = [int(re.search(r'_v(\d+)\.png$', p).group(1)) for p in glob.glob(os.path.join(FIGD, stem + '_v*.png'))] out = os.path.join(FIGD, '%s_v%d.png' % (stem, 1 + max(used or [0]))) fig.savefig(out, dpi=300); fig.savefig(out[:-4] + '.pdf'); print(out)