# -*- coding: utf-8 -*- """Figure 4: a coarser threshold on the test grid. (a, b) the reach rasters at 4 and 8 pixels; (c) the reach tables at both thresholds. Output: ../Figures: png, pdf and caption; with --draft DIR, a png and the caption in DIR. Usage: python Fig04_coarser_threshold_toy_basin.py [--draft DIR] """ import os, sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Rectangle, FancyBboxPatch HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) from toy_basin_numbering import (FT, W, ML, MR, T_BASE, Q_UP, DRAFT, BOLD, T_DARK, T_GREY, number, grid, basin_of, text_inches) from toy_basin_numbering import is_up as F5_is_up, down, F_OTHER import matplotlib.patheffects as pe from toy_basin_reach_colors import SQ, OUTLET_COLOR, OUTLET_STUB FS, LH = 11, 11 / 72 * 1.25 GW = 3.50; CELL = GW / 10; XB = W - MR - GW REG = dict(fontfamily='Arial') INK = {1: '#0072B2', 2: '#007f5f'} F_UC, F_UP = '#f2a65e', '#fde2c8' T_COARSE = 8 LAND = F_OTHER C_RIV, C_FRAME = '#333333', '#1f1f1f' C_GONE = '#7d7d7d' RH, PAD, GAPC = 0.26, 0.04, 0.24 def coarse(N, M): """The reaches of M (threshold T_COARSE) in the numbers of N (base threshold), and their unit catchments as sets of |v|.""" kept = sorted(N['n'][x] for x in M['ch']) assert all(M['n'][x] == kept.index(N['n'][x]) + 1 for x in M['ch']) # the same order: only numbers are removed out = [] for j, (a8, b8, _, _) in enumerate(M['R'], 1): ks = [N['n'][M['inv'][k]] for k in range(a8, b8 + 1)] A, B = ks[0], ks[-1] assert ks == list(range(A, B + 1)), ks # a run of consecutive numbers fine = sorted({N['reach'][N['inv'][k]] for k in ks}) assert N['R'][fine[0] - 1][0] == A and all(N['R'][i - 1][1] <= B for i in fine[:-1]) cut = N['R'][fine[-1] - 1][1] > B # the most upstream one cut short ku = M['cup'][N['inv'][B]] # branches at 8 pixels joining at b oA = N['o'][N['inv'][A]] tail = set(range(N['o'][ku[-1]] + 1 if ku else B + 1, oA + 1)) land = {abs(N['v'][x]) for x in N['cells'] if M['reach'][M['first'][x]] == j} assert land == set(range(A, B + 1)) | tail, (j, sorted(land)) out.append(dict(A=A, B=B, fine=fine, cut=cut, land=sorted(land), tail=sorted(tail), joined=bool(ku))) assert [r['A'] for r in out] == sorted(r['A'] for r in out) # reach_seq_id = rank of the outlet pixel for i in range(1, len(N['R']) + 1): # nested in the unit catchments at 8 pixels assert len({M['reach'][M['first'][x]] for x in N['cells'] if N['reach'][N['first'][x]] == i}) == 1 xq = N['inv'][Q_UP] # the same two comparisons at 8 pixels assert {k for k in kept if Q_UP <= k <= N['o'][xq]} == {N['n'][q] for q in M['ch'] if F5_is_up(q, xq)} return kept, out def runs(ks): rr = [[ks[0], ks[0]]] for k in ks[1:]: if k == rr[-1][1] + 1: rr[-1][1] = k else: rr.append([k, k]) return [tuple(r) for r in rr] # ---------------------------------------------------------------- the reach tables at both thresholds def breaks(N): """break_threshold of each reach at the base threshold (pixels): its drainage area if it ends at a basin outlet, else the smaller of its drainage area and the largest drainage area of the other channel branches joining at the same confluence.""" out = [] for a, b, d, _ in N['R']: x = N['inv'][a]; y = down(x) if y is None: out.append(N['area'][x]); continue other = [N['area'][u] for u in N['ch'] if u != x and down(u) == y] assert other, a # every other reach starts at a confluence out.append(min(N['area'][x], max(other))) return out def tables(N, M, CR, kept): """r4: one row per reach at 4 pixels; r8: one per reach at 8 pixels, with the first and last reaches at 4 pixels it is made of.""" r4, r8 = [], [] for i, (a, b, _, _) in enumerate(N['R'], 1): x = N['inv'][a] j = M['reach'][M['first'][x]] # the reach at 8 pixels it belongs to or, if removed, drains into r4.append(dict(reach=i, outlet=a, end=b, out=N['o'][x], receiving=j, removed=not any(N['inv'][k] in M['ch'] for k in range(a, b + 1)), unit=sum(1 for y in N['cells'] if N['reach'][N['first'][y]] == i))) for j, r in enumerate(CR, 1): A, xa = r['A'], N['inv'][r['A']]; o = N['o'][xa] assert {k for k in kept if A <= k <= o} == {N['n'][q] for q in M['ch'] if F5_is_up(q, xa)} q = r4[r['fine'][0] - 1] assert q['outlet'] == A and q['out'] == o # the same outlet pixel, so the same largest upstream pixel number assert all(r4[i - 1]['receiving'] == j and not r4[i - 1]['removed'] for i in r['fine']) assert r['fine'] == list(range(r['fine'][0], r['fine'][-1] + 1)) # consecutive rows: one box r8.append(dict(reach=j, outlet=A, end=r['B'], out=o, first=r['fine'][0], last=r['fine'][-1], cut=r['cut'], unit=sum(1 for y in N['cells'] if M['reach'][M['first'][y]] == j))) assert {i for q in r8 for i in range(q['first'], q['last'] + 1)} == {r['reach'] for r in r4 if not r['removed']} # the network at T_COARSE from one column: reaches start on the rows with break_threshold >= T_COARSE; a kept reach belongs to # the nearest such row at or above it; a removed one drains, through the reaches downstream, into the first kept one brk = breaks(N) starts = [i for i, k in enumerate(brk, 1) if k >= T_COARSE] assert [r4[i - 1]['outlet'] for i in starts] == [q['outlet'] for q in r8], starts for q in r8 + r4: q['nch'] = q['end'] - q['outlet'] + 1; q['nup'] = q['out'] - q['outlet'] + 1 for q in r8: # the channel pixels of a reach at 8 pixels: those of its box, kept assert q['nch'] == sum(r4[i - 1]['nch'] for i in range(q['first'], q['last'] + 1)) - (r4[q['last'] - 1]['end'] - q['end']) assert q['nup'] == r4[q['first'] - 1]['nup'] for i, r in enumerate(r4, 1): r['brk'] = brk[i - 1] assert r['removed'] == (N['area'][N['inv'][r['outlet']]] < T_COARSE) j = i while r4[j - 1]['removed']: j = N['R'][j - 1][2] assert starts.index(max(s for s in starts if s <= j)) + 1 == r['receiving'], i return r4, r8 H4 = [('reach_', 'seq_id'), ('downstream_', 'end_', 'pixel_', 'seq_id'), ('channel_', 'pixel_', 'count'), ('upstream_', 'channel_', 'pixel_', 'count'), ('break_', 'threshold', '(pixels)'), ('reach_', 'seq_id', 'at %d' % T_COARSE, 'pixels')] # long names broken after a _ to fit the width H8 = H4[:4] def panel_map(ax, N, ch, reach_of, fr, uc, up, color_of, gone=()): """The reach raster at the threshold whose channel pixels are ch: a channel pixel stores the reach of its unit catchment (reach_of), bold, a hillslope pixel minus it, as Figure 3a; coloured by basin; orange, the unit catchment uc of one reach, light orange the rest of its upstream catchment up; the channel lines dark grey; framed, the channel pixels fr of that reach.""" grid(ax, N, None, set()) size = {} for x in N['cells']: size[basin_of(x)] = size.get(basin_of(x), 0) + 1 bno = {o: k for k, o in enumerate(sorted(size, key=lambda o: -size[o]), 1)} # basin 1 the larger col = lambda x: F_UC if x in uc else F_UP if x in up else LAND for x in N['cells']: ax.add_patch(Rectangle((x[1], x[0]), 1, 1, fc=col(x), ec='white', lw=0.8)) lab = {x: ('%d' if x in ch else '\u2212%d') % reach_of(x) for x in N['cells']} # hillslope negative, as Figure 3a def from_text(p, mx, my): # a line starts at the edge of the number of p, not between its digits hw = text_inches(lab[p], FS, **(BOLD if p in ch else REG)) / CELL / 2 + 0.05; hh = 0.716 * FS / 72 / CELL / 2 + 0.05 dx, dy = mx - p[1] - 0.5, my - p[0] - 0.5 s = min(hw / abs(dx) if dx else 9, hh / abs(dy) if dy else 9); assert s < 0.8, (p, s) return p[1] + 0.5 + s * dx, p[0] + 0.5 + s * dy for x in ch: # in each channel pixel, from its number to the edge it drains through y = down(x) if y is None: ax.plot(*zip(from_text(x, *OUTLET_STUB(x)), OUTLET_STUB(x)), color=color_of(x), lw=2.6, solid_capstyle='butt', zorder=5) continue mx, my = (x[1] + y[1]) / 2 + 0.5, (x[0] + y[0]) / 2 + 0.5 for p in (x, y): ax.plot(*zip(from_text(p, mx, my), (mx, my)), color=color_of(x), lw=2.6, solid_capstyle='butt', zorder=5) for x in gone: y = down(x); assert y is not None and x not in ch, x # grey line from its number to the number it drains to mx, my = (x[1] + y[1]) / 2 + 0.5, (x[0] + y[0]) / 2 + 0.5 ax.plot(*zip(from_text(x, mx, my), from_text(y, mx, my)), color=C_GONE, lw=1.5, ls=(0, (2.4, 1.6)), dash_capstyle='butt', zorder=4) for (r, c) in fr: ax.add_patch(Rectangle((c + 0.07, r + 0.07), 0.86, 0.86, fc='none', ec=C_FRAME, lw=2.0, zorder=6)) for x in N['cells']: c = x in ch; t = lab[x] assert text_inches(t, FS, **(BOLD if c else REG)) < 0.88 * CELL, t ax.text(x[1] + 0.5, x[0] + 0.5, t, ha='center', va='center', fontsize=FS, color=INK[bno[basin_of(x)]], zorder=8, path_effects=[pe.withStroke(linewidth=2.5 if c else 1.0, foreground=col(x))], **(BOLD if c else REG)) def panel_c(fig, H, y0, r4, r8): colw = lambda heads: [max(text_inches(t, FS) for t in h) + PAD for h in heads] w4, w8 = colw(H4), colw(H8) wd = W - ML - MR extra = (wd - sum(w4) - GAPC - sum(w8)) / (len(w4) + len(w8)); assert extra >= 0, (sum(w4) + GAPC + sum(w8), wd) x4 = [ML]; [x4.append(x4[-1] + w + extra) for w in w4] x8 = [x4[-1] + GAPC]; [x8.append(x8[-1] + w + extra) for w in w8] nl = max(len(h) for h in H4 + H8) TOP = RH; HDR = TOP + nl * LH + 0.08; hd = HDR + len(r4) * RH ax = fig.add_axes([0, 1 - (y0 + hd) / H, 1, hd / H]); ax.set_xlim(0, W); ax.set_ylim(hd, 0); ax.axis('off') yr = lambda j: HDR + j * RH # top of row j (row 0: reach 1 at 4 pixels) for xs, t in ((x4, 'At %d pixels' % T_BASE), (x8, 'At %d pixels' % T_COARSE)): ax.text((xs[0] + xs[-1]) / 2, TOP / 2, t, ha='center', va='center', fontsize=FS, color=T_DARK, **BOLD) for y, lw in ((TOP, 0.6), (HDR, 0.6), (hd, 1.0)): ax.plot([xs[0], xs[-1]], [y, y], color=T_DARK, lw=lw) for j in range(1, len(r4)): ax.plot([x4[0], x4[-1]], [yr(j)] * 2, color='#e4e4e4', lw=0.5, zorder=0) for xs, heads in ((x4, H4), (x8, H8)): for i, h in enumerate(heads): for k, t in enumerate(h): ax.text((xs[i] + xs[i + 1]) / 2, HDR - 0.05 - (len(h) - 1 - k) * LH, t, ha='center', va='bottom', fontsize=FS, color=T_DARK, **(BOLD if i == 1 else {})) def cell(xs, i, y, t, bold=False, sq=None): xc = (xs[i] + xs[i + 1]) / 2 if sq: w = text_inches(t, FS, **(BOLD if bold else {})); g = SQ + 0.05 + w; assert g < xs[i + 1] - xs[i] - 0.04, t ax.add_patch(Rectangle((xc - g / 2, y - 0.21 * FS / 72 / 2 - SQ / 2), SQ, SQ, fc=sq, ec='none', zorder=4)) xc += (SQ + 0.05) / 2 # digits sit 0.105 em above the centre of a box with va='center' ax.text(xc, y, t, ha='center', va='center', fontsize=FS, color=T_DARK, **(BOLD if bold else {})) for j, r in enumerate(r4): yc = yr(j) + RH / 2 for i, (k, b) in enumerate((('reach', True), ('outlet', True), ('nch', False), ('nup', False), ('brk', r['brk'] >= T_COARSE), ('receiving', False))): # bold: starts a reach at T_COARSE cell(x4, i, yc, '%d' % r[k], b, sq=OUTLET_COLOR[r['outlet']] if k == 'reach' else None) if r['removed']: ax.text((x8[0] + x8[-1]) / 2, yc, 'removed', ha='center', va='center', fontsize=FS, color=T_GREY, fontstyle='italic') for q in r8: # one box per reach at 8 pixels, over the reaches at 4 pixels it is made of j0, j1 = q['first'] - 1, q['last'] ax.add_patch(FancyBboxPatch((x8[0] + 0.05, yr(j0) + 0.02), x8[-1] - x8[0] - 0.10, yr(j1) - yr(j0) - 0.04, boxstyle='round,pad=0,rounding_size=0.05', fc='none', ec=T_DARK, lw=1.0, zorder=3)) cell(x8, 0, (yr(j0) + yr(j1)) / 2, '%d' % q['reach'], True, sq=OUTLET_COLOR[q['outlet']]) # the reach, across its rows cell(x8, 1, yr(j0) + RH / 2, '%d' % q['outlet'], True) # its outlet pixel and upstream_channel_pixels: on the row cell(x8, 3, yr(j0) + RH / 2, '%d' % q['nup']) # of the reach at 4 pixels with the same outlet pixel cell(x8, 2, (yr(j0) + yr(j1)) / 2, '%d' % q['nch']) # its channel pixels: across its rows return hd def draw(): N, M = number(T_BASE), number(T_COARSE) kept, CR = coarse(N, M) r4, r8 = tables(N, M, CR, kept) removed = sorted(N['n'][x] for x in N['ch'] - M['ch']) print('threshold %d pixels: kept %s, removed channel pixels %s' % (T_COARSE, kept, removed)) for r in r4: print(' at %d: reach %d %d-%d out %d break %d -> %d%s, unit %d' % (T_BASE, r['reach'], r['outlet'], r['end'], r['out'], r['brk'], r['receiving'], ' removed' if r['removed'] else '', r['unit'])) for q in r8: print(' at %d: reach %d %d-%d out %d, made of %d-%d%s, unit %d %s' % (T_COARSE, q['reach'], q['outlet'], q['end'], q['out'], q['first'], q['last'], ' (last cut short)' if q['cut'] else '', q['unit'], runs(CR[q['reach'] - 1]['land']))) yt1, yg1 = 0.06, 0.34 yt2 = yg1 + GW + 0.22; yg2 = yt2 + 0.30 H = yg2 + RH + max(len(h) for h in H4 + H8) * LH + 0.08 + len(r4) * RH + 0.04 fig = plt.figure(figsize=(W, H)); fy = lambda y: 1 - y / H q2 = r8[1] # reach 2: its unit catchment grows, its upstream catchment stays up2 = {x for x in N['cells'] if q2['outlet'] <= abs(N['v'][x]) <= q2['out']} rch4, rch8 = (lambda x: N['reach'][N['first'][x]]), (lambda x: M['reach'][M['first'][x]]) o2 = N['inv'][q2['outlet']] uc4 = {x for x in N['cells'] if rch4(x) == rch4(o2)}; uc8 = {x for x in N['cells'] if rch8(x) == rch8(o2)} fr4 = {x for x in N['ch'] if rch4(x) == rch4(o2)}; fr8 = {x for x in M['ch'] if rch8(x) == rch8(o2)} assert (len(fr4), len(fr8)) == (1, 3), (len(fr4), len(fr8)) print('reach 2: unit catchment %d -> %d pixels, upstream catchment %d' % (len(uc4), len(uc8), len(up2))) col4 = lambda x: OUTLET_COLOR[N['R'][rch4(x) - 1][0]] col8 = lambda x: OUTLET_COLOR[r8[rch8(x) - 1]['outlet']] # a reach at 8 pixels, that of the 4-pixel reach with its outlet pixel assert all(r8[j - 1]['outlet'] == N['n'][M['inv'][M['R'][j - 1][0]]] for j in range(1, len(r8) + 1)) panel_map(fig.add_axes([ML / W, fy(yg1 + GW), GW / W, GW / H]), N, N['ch'], rch4, fr4, uc4, up2, col4) panel_map(fig.add_axes([XB / W, fy(yg1 + GW), GW / W, GW / H]), N, M['ch'], rch8, fr8, uc8, up2, col8, gone=N['ch'] - M['ch']) panel_c(fig, H, yg2, r4, r8) for x0, y0, t in ((ML, yt1, '(a) Reach raster at %d pixels: %d reaches' % (T_BASE, len(r4))), (XB, yt1, '(b) Reach raster at %d pixels: %d reaches' % (T_COARSE, len(r8))), (ML, yt2, '(c) The reaches at %d pixels, made of reaches at %d pixels' % (T_COARSE, T_BASE))): fig.text(x0 / W, fy(y0), t, fontsize=FT, va='top', ha='left', **BOLD) info = dict(N=N, M=M, r4=r4, r8=r8, removed=removed, q2=q2, uc4=uc4, uc8=uc8, up2=up2, rch8=rch8, fr4=fr4, fr8=fr8) return fig, H, info def caption(I): """Every number from the grid and the tables; the asserts tie the words to them.""" N, M, r4, q2 = I['N'], I['M'], I['r4'], I['q2'] lst = lambda ks: ', '.join('%s' % k for k in ks[:-1]) + ' and %s' % ks[-1] gone = [r for r in r4 if r['removed']] for r in gone: # a removed reach: all its pixels store minus its receiving reach px = [x for x in N['cells'] if N['reach'][N['first'][x]] == r['reach']] assert all(x not in M['ch'] and I['rch8'](x) == r['receiving'] for x in px), r['reach'] last = r4[-1]; assert basin_of(N['inv'][last['outlet']]) != basin_of(N['inv'][1]) # the second basin: one reach at both thresholds assert [r['reach'] for r in r4 if basin_of(N['inv'][r['outlet']]) == basin_of(N['inv'][last['outlet']])] == [last['reach']] k2 = q2['reach']; assert r4[q2['first'] - 1]['reach'] == k2 # reach 2 keeps its number nums = sorted({abs(N['v'][x]) for x in I['uc8']}) on3a = ' or '.join('%d' % a if a == b else '%d to %d' % (a, b) for a, b in runs(nums)) assert on3a == '2 to 4 or 14', on3a # as Section 3.5 says assert len(I['up2']) == N['area'][N['inv'][q2['outlet']]] # the upstream catchment: one range of |v|, at both thresholds assert len(I['uc4']) == r4[k2 - 1]['unit'] and len(I['uc8']) == q2['unit'] T4, T8 = T_BASE, T_COARSE; assert len(I['fr4']) == 1 ends = [q['outlet'] for q in I['r8']] assert ends == [r4[q['first'] - 1]['outlet'] for q in I['r8']] q5 = next(q for q in I['r8'] if q['reach'] != r4[q['first'] - 1]['reach']) same = (' A reach thus keeps its downstream_end_pixel_seq_id at both thresholds (%s; bold), while its reach_seq_id, counted afresh at each threshold, may change: the reach ' 'whose downstream end is pixel %d is reach %d at %d pixels and reach %d at %d pixels.' % (lst(ends), q5['outlet'], r4[q5['first'] - 1]['reach'], T4, q5['reach'], T8)) return ('Figure 4. A coarser threshold removes channel pixels and merges reaches; no pixel is renumbered. ' '(a) The reach raster of the test grid of Figure 3 at %d pixels: a channel pixel stores the reach_seq_id of its reach ' '(bold), a hillslope pixel minus that of the reach of the first channel pixel it drains to; numbers of one basin blue and ' 'of the other green; each reach a line in its own colour, as in Figure 1d; framed, the channel pixel of reach %d. Orange, the unit ' 'catchment of reach %d (pixels storing %d or \u2212%d); light orange, the rest of its upstream catchment. ' '(b) The same raster at %d pixels, not stored but read from (a): each number, without sign, is replaced by the ' 'reach at the coarser threshold given for that reach in the last column of (c), with a minus sign on the pixels that are not channel pixels at %d pixels; ' 'a reach keeps the colour of the %d-pixel reach with the same downstream-end pixel. ' 'The channel pixels %s of Figure 3a become hillslope pixels (dashed grey lines, each to the pixel it drains to); reaches %s are removed, and their pixels store %s; reach %d, ' 'the second basin, becomes reach %d. Reach %d now has %d channel pixels (framed); its unit catchment grows from %d to %d pixels, the pixels storing %s, ' 'with either sign, in Figure 3a; its upstream catchment, %d pixels, does not change. ' '(c) The reach tables at both thresholds, with upstream_channel_pixel_count counted on the channel pixels at %d pixels; a square before a ' 'reach_seq_id gives the colour of its line in (a) and (b). Each ' 'reach at %d pixels (a box) starts on a row of the %d-pixel table with break_threshold \u2265 %d (bold) ' 'and keeps that row\u2019s upstream_channel_pixel_count; its channel_pixel_count counts ' 'only the channel pixels kept at %d pixels. The last column gives, for each reach at %d pixels, its reach at %d pixels.' % (T4, k2, k2, k2, k2, T8, T8, T4, lst(I['removed']), lst([r['reach'] for r in gone]), lst(['\u2212%d' % r['receiving'] for r in gone]), last['reach'], last['receiving'], k2, len(I['fr8']), len(I['uc4']), len(I['uc8']), on3a, len(I['up2']), T4, T8, T4, T8, T8, T4, T8)) + same if __name__ == '__main__': fig, H, I = draw() cap = caption(I) if DRAFT: os.makedirs(DRAFT, exist_ok=True) out = os.path.join(DRAFT, 'Fig04_coarser_threshold_toy_basin_draft.png'); fig.savefig(out, dpi=300) open(out[:-4] + '_caption.md', 'w', encoding='utf-8').write(cap + '\n') else: import re, glob FIGD = os.path.join(os.path.dirname(HERE), 'Figures'); stem = 'Fig04_coarser_threshold_toy_basin' used = [int(m.group(1)) for m in (re.search(r'_v(\d+)\.png$', f) for f in glob.glob(os.path.join(FIGD, stem + '_v*.png'))) if m] out = os.path.join(FIGD, '%s_v%d.png' % (stem, max([0] + used) + 1)) assert not any(os.path.exists(out[:-4] + s) for s in ('.png', '.pdf', '_caption.md')), out fig.savefig(out, dpi=600); fig.savefig(out[:-4] + '.pdf') open(out[:-4] + '_caption.md', 'w', encoding='utf-8').write(cap + '\n') print(out, '%.0f x %.0f mm' % (W * 25.4, H * 25.4))