# -*- coding: utf-8 -*- """Figure 1: the terms, on the 10 x 10 test grid. (a) D8 flow directions; (b) drainage area; (c) the pixel level; (d) the reach level. Output: ../Figures: png and pdf. Usage: python Fig01_terms_toy_basin.py """ import os, sys, re, glob import matplotlib.patheffects as pe HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import toy_basin_numbering as T from toy_basin_reach_colors import OUTLET_COLOR, OUTLET_STUB from toy_basin_numbering import (plt, Rectangle, MSK, DIR, down, number, grid, W, ML, GW, XB, BOLD, C_MAIN, C_TRIB, F_OTHER, text_inches) FS, FT = 12, 14 REACH = 4 # the reach of (d): main stem, channel pixels 5 to 6 LAND = F_OTHER # a pixel of a basin: light grey land, as in Figures 9 and 10; outside the basins white INK = {1: '#0072B2', 2: '#007f5f'} F_UC, F_UP = '#f2a65e', '#fde2c8' C_SUB = '#b85c00' C_RIV, C_FRAME = '#333333', '#1f1f1f' # (b), (c): the channel a black line; a pixel of (c), (d) a black frame def arrows(ax, N): """As the arrows of toy_basin_numbering.py, but an east or west arrow, which runs below the numbers, ends at the side edge instead of 0.22 past it. Past the edge its head met the head of a diagonal arrow into the same pixel (i22 and i32 into i23, i28 and i38 into i27, i29 and i39 into i28) and the two looked like one double arrow.""" from matplotlib.patches import FancyArrowPatch for x in N['cells']: y = down(x) if y is None: continue r, c = x; dr, dc = y[0] - r, y[1] - c t0, t1, lift = (0.08, 0.50, 0.30) if dr == 0 else (0.30, 0.72, 0.0) ax.add_patch(FancyArrowPatch((c + 0.5 + t0 * dc, r + 0.5 + t0 * dr + lift), (c + 0.5 + t1 * dc, r + 0.5 + t1 * dr + lift), arrowstyle='-|>', mutation_scale=8, lw=1.0, color='black', zorder=5, shrinkA=0, shrinkB=0)) N = number(T.T_BASE) basin_first = {b0 for b0, _ in N['basins']} main_path = {j for j, (a, _) in enumerate(N['paths'], 1) if a in basin_first} # a path that reaches an outlet is a main stem path_color = lambda x: C_MAIN if N['path'][x] in main_path else C_TRIB conf = [x for x in N['ch'] if len(N['cup'][x]) >= 2 and down(x) is not None] # an outlet keeps only its ▼ a, b = N['R'][REACH - 1][:2]; out_px = N['inv'][a] up_px = {x for x in N['cells'] if T.is_up(x, out_px)} uc_px = {x for x in N['cells'] if N['reach'][N['first'][x]] == REACH} px_uc = {x for x in N['cells'] if N['first'][x] == out_px} # (c): unit catchment of the outlet pixel of the reach assert len(up_px) == N['area'][out_px] and px_uc < uc_px and out_px == (4, 4) # pixel i44 assert uc_px < up_px and {N['n'][x] for x in N['ch'] & uc_px} == set(range(a, b + 1)) assert len(main_path) == len(N['basins']) == 2 print('channel pixels %d, reaches %d, paths %d (main stems %s), confluences %d; reach %d: channel pixels %d-%d, ' 'unit catchment %d pixels (%d channel + %d hillslope), upstream catchment of its outlet pixel %d pixels' % (len(N['ch']), len(N['R']), len(N['paths']), sorted(main_path), len(conf), REACH, a, b, len(uc_px), len(uc_px & N['ch']), len(uc_px - N['ch']), len(up_px))) size = {} for x in N['cells']: size[T.basin_of(x)] = size.get(T.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 (62 pixels), basin 2 (11) assert sorted(size.values()) == [11, 62] ink = lambda x: INK[BNO[T.basin_of(x)]] if MSK[x] else '#b5b5b5' def frames(ax, S): # a pixel: a black frame set a little inside it for (r, c) in S: ax.add_patch(Rectangle((c + 0.07, r + 0.07), 0.86, 0.86, fc='none', ec=C_FRAME, lw=2.0, zorder=6)) def river(ax, text_of, lw=3.0, color_of=lambda p: C_RIV): # the channel: in each channel pixel, from its label to the edge it drains through def from_text(p, mx, my): hw = text_inches(text_of(p), FS, **BOLD) / T.CELL / 2 + 0.05; hh = 0.716 * FS / 72 / T.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, 0.85) # labels i27 and i65 nearly fill a pixel: keep a stub return p[1] + 0.5 + s * dx, p[0] + 0.5 + s * dy for x in N['ch']: y = down(x) if y is None: ax.plot(*zip(from_text(x, *OUTLET_STUB(x)), OUTLET_STUB(x)), color=color_of(x), lw=lw, 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=lw, solid_capstyle='butt', zorder=5) def fill(ax, color_of): grid(ax, N, None, set()) for x in N['cells']: ax.add_patch(Rectangle((x[1], x[0]), 1, 1, fc=color_of(x), ec='white', lw=0.8)) def p_a(ax): # D8 codes and arrows; an outlet is the pixel coded 0 fill(ax, base); arrows(ax, N) labels(ax, lambda x: '%d' % DIR[x] if MSK[x] else None, base, bold_of=lambda x: DIR[x] == 0) base = lambda x: LAND # every pixel of a basin light grey land def labels(ax, text_of, color_of, bold_of=lambda x: x in N['ch'], ink_of=lambda x: ink(x)): """One label per pixel in the colour of its basin; bold on channel pixels; a halo of the pixel colour keeps a line under it clear.""" for r in range(10): for c in range(10): x = (r, c); inside = MSK[x]; bold = inside and bold_of(x); t = text_of(x) if t is None: continue assert text_inches(t, FS, **(BOLD if bold else {})) < 0.88 * T.CELL, t bg = color_of(x) if inside else 'white' ax.text(c + 0.5, r + 0.5, t, ha='center', va='center', fontsize=FS, color=ink_of(x), zorder=8, path_effects=[pe.withStroke(linewidth=1.0, foreground=bg)], **(BOLD if bold else {})) pos = lambda x: 'i%d' % (10 * x[0] + x[1]) # pixel position, row by row def p_b(ax): # drainage area; a black line through the channel pixels (>= base threshold) fill(ax, base); river(ax, lambda x: '%d' % N['area'][x]) labels(ax, lambda x: '%d' % N['area'][x] if MSK[x] else None, base) def p_c(ax): # pixel level: pixel i44, its unit catchment, its upstream catchment col = lambda x: F_UC if x in px_uc else F_UP if x in up_px else base(x) fill(ax, col); river(ax, pos); frames(ax, {out_px}) labels(ax, pos, col) def p_d(ax): # reach level: the reach of i34 and i44 (framed), its unit and upstream catchments col = lambda x: F_UC if x in uc_px else F_UP if x in up_px else base(x) fill(ax, col); river(ax, pos, color_of=reach_color); frames(ax, uc_px & N['ch']) labels(ax, pos, col) for (r, c) in uc_px: for dr, dc, seg in ((0, 1, ((c + 1, r), (c + 1, r + 1))), (1, 0, ((c, r + 1), (c + 1, r + 1))), (0, -1, ((c, r), (c, r + 1))), (-1, 0, ((c, r), (c + 1, r)))): if (r + dr, c + dc) not in uc_px: ax.plot(*zip(*seg), color=C_SUB, lw=2.6, solid_capstyle='round', zorder=7, clip_on=False) top = min(uc_px) # its uppermost pixel (i7, on the upper edge of the grid): the label sits above it ax.text(top[1] + 0.5, top[0] - 0.14, 'subbasin', ha='center', va='bottom', fontsize=FS, color=C_SUB, clip_on=False, **BOLD) reach_color = lambda x: OUTLET_COLOR[N['R'][N['reach'][x] - 1][0]] assert len({OUTLET_COLOR[r[0]] for r in N['R']}) == len(N['R']) == 10 YT1 = 0.06; YG1 = 0.34; YT2 = YG1 + GW + 0.24; YG2 = YT2 + 0.28 H = YG2 + GW + 0.06 fig = plt.figure(figsize=(W, H)); fy = lambda y: 1 - y / H for x0, y0, t in ((ML, YT1, '(a) D8 flow directions'), (XB, YT1, '(b) Drainage area (pixels)'), (ML, YT2, '(c) Pixel level'), (XB, YT2, '(d) Reach level')): assert text_inches(t, FT, **BOLD) < GW + 0.05, t fig.text(x0 / W, fy(y0), t, fontsize=FT, va='top', ha='left', **BOLD) for x0, y0, f in ((ML, YG1, p_a), (XB, YG1, p_b), (ML, YG2, p_c), (XB, YG2, p_d)): f(fig.add_axes([x0 / W, fy(y0 + GW), GW / W, GW / H])) FIGD = os.path.join(os.path.dirname(HERE), 'Figures'); stem = 'Fig01_terms_toy_basin' 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, max([0] + used) + 1)) fig.savefig(out, dpi=300); fig.savefig(out[:-4] + '.pdf'); print(out, '%.0f x %.0f mm' % (W * 25.4, H * 25.4))