# -*- coding: utf-8 -*- """Figure 3: the pixel numbers on the test grid. (a) the number each pixel stores; (b) every object as one range of numbers; (c) the pixel table. Output: ../Figures: png and pdf. Usage: python Fig03_pixel_numbers_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_numbering import plt, Rectangle, down, number, grid, BOLD, F_OTHER, text_inches from toy_basin_reach_colors import color_of_reach, OUTLET_STUB FS, FT = 11, 12 REG = dict(fontfamily='Arial') LAND, F_UC, F_UP = F_OTHER, '#f2a65e', '#fde2c8' # the colours of Figures 1 and 2: land, unit catchment, upstream catchment INK = {1: '#0072B2', 2: '#007f5f'} # numbers of basin 1 blue, of basin 2 green (Figure 1) C_RIV, C_FRAME, C_BAR, C_TXT = '#333333', '#1f1f1f', '#6f6f6f', '#1f1f1f' QA, QB = 4, 13 # A and B by pixel_seq_id LINE_BY_REACH = False # ---------------------------------------------------------------- values, from the grid N = number(T.T_BASE) v, inv = N['v'], N['inv'] A, B = inv[QA], inv[QB] pos = lambda x: 'i%d' % (10 * x[0] + x[1]) assert pos(A) == 'i54' and pos(B) == 'i28' NPIX = len(N['n']); assert NPIX == 19 OUT_A = N['o'][A]; assert OUT_A == 13 # the largest number upstream of A count = {k: sum(abs(v[x]) == k for x in N['cells']) for k in range(1, NPIX + 1)} # pixels storing k or -k cum = {0: 0} for k in range(1, NPIX + 1): cum[k] = cum[k - 1] + count[k] assert cum[NPIX] == len(N['cells']) == 73 uc_A = {x for x in N['cells'] if abs(v[x]) == QA} up_A = {x for x in N['cells'] if QA <= abs(v[x]) <= OUT_A} assert up_A == {x for x in N['cells'] if T.is_up(x, A)} and len(up_A) == N['area'][A] == 36 assert (cum[OUT_A], cum[QA - 1]) == (46, 10) and cum[OUT_A] - cum[QA - 1] == 36 and count[10] == 1 # "none drains first to 10" for x in N['ch']: assert cum[N['o'][x]] - cum[N['n'][x] - 1] == N['area'][x], x # every channel pixel, not only A assert {v[x] for x in N['cells'] if N['reach'][N['first'][x]] == 7} == {10, 11, 12, 13, -11, -12, -13} # land of the reach of B 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] and N['basins'] == [(1, 17), (18, 19)] def runs(ks): # consecutive numbers as (first, last) out = [] for k in sorted(ks): if out and k == out[-1][1] + 1: out[-1] = (out[-1][0], k) else: out.append((k, k)) return out RUNS = T.flow_path_runs(N, QB) OBJ = ((('Main', 'stem'), runs(k for k in N['n'].values() if N['path'][inv[k]] == 1)), (('', 'Unit'), [(QA, QA)]), (('', 'Upstream'), runs(range(QA, OUT_A + 1))), (('Flow path', 'from B'), RUNS), (('Basin', '2'), [N['basins'][1]])) assert [r for _, r in OBJ] == [[(1, 8)], [(4, 4)], [(4, 13)], [(10, 13), (1, 4)], [(18, 19)]] # the ranges of Sections 3.2 and 3.3 SPAN = ('Catchment of A', 2, 3) assert {abs(v[x]) for x in uc_A} == {QA} and {abs(v[x]) for x in up_A} == set(range(QA, OUT_A + 1)) # a catchment: its numbers with either sign assert {abs(v[x]) for x in N['cells'] if BNO[T.basin_of(x)] == 2} == {18, 19} BY_ABS = (2, 3, 5) ABS_BARS = os.environ.get('FLOWNEST_FIG3_MARK', 'pm') == 'bars' assert {v[x] for x in uc_A} == {QA, -QA} and min(v[x] for x in up_A) == -OUT_A and len(uc_A) == 2 # A and one hillslope pixel def rlab(i, a, b): t = '%d\u2013%d' % (a, b) if a < b else '%d' % a # an en dash if i not in BY_ABS: return t return '|%s|' % t if ABS_BARS else '\u00b1(%s)' % t if a < b else '\u00b1' + t ink_px = lambda x: INK[BNO[T.basin_of(x)]] ink_k = lambda k: ink_px(inv[k]) shade = lambda k: F_UC if k == QA else F_UP if QA < k <= OUT_A else None # the pixel table (Table 2a), from the grid, and the two values a channel pixel takes from its reach (Section 3.4) def next_down(x): # the channel pixel it flows to; a basin outlet flows to itself d = down(x) return N['n'][d] if d in N['n'] else N['n'][x] for r in set(N['reach'].values()): # one largest upstream pixel number per reach: branches join only at its upstream end assert len({N['o'][x] for x in N['ch'] if N['reach'][x] == r}) == 1, r for x in N['ch']: # one less, except at the most downstream pixel of a reach k = N['n'][x] if k > 1 and N['reach'][inv[k - 1]] == N['reach'][x]: assert next_down(x) == k - 1, k # key, header lines (bottom aligned, long names broken after an underscore), stored in the pixel table def drains_to(y, x): # channel pixel y lies upstream of x, or is x (walked along D8) while y != x: y = down(y) if y not in N['n']: return False return True NCH = {x: sum(drains_to(y, x) for y in N['ch']) for x in N['ch']} assert all(NCH[x] == N['o'][x] - N['n'][x] + 1 for x in N['ch']) # the count gives the far end of the range PC = [('in', ('pixel_', 'seq_id'), 1), ('row', ('row',), 1), ('col', ('col',), 1), ('reach', ('reach_', 'seq_id'), 1), ('path', ('path_', 'seq_id'), 1), ('basin', ('basin_id',), 1), ('area', ('upstream_', 'area_km2'), 1), ('nch', ('upstream_', 'channel_', 'pixel_count'), 1)] PIX_KM2 = 1.00 PC = [c for c in PC if c[2]] + [c for c in PC if not c[2]] # stored columns first, then those from the reach table def prow(k): x = inv[k]; b = [j for j, (a, c) in enumerate(N['basins'], 1) if a <= k <= c] assert len(b) == 1 and x in N['ch'] val = dict(**{'in': k, 'nch': NCH[x], 'row': x[0], 'col': x[1], 'reach': N['reach'][x], 'path': N['path'][x], 'basin': b[0], 'area': N['area'][x], 'down': next_down(x)}) return tuple('%.2f' % (val[c[0]] * PIX_KM2) if c[0] == 'area' else '%d' % val[c[0]] for c in PC) PROWS = [1, 2, 3, 4, 5, None, 10, 11, 12, 13, None, 19] ck = lambda k: dict(zip([c[0] for c in PC], [int(float(t)) for t in prow(k)])) assert ck(QA) == dict(**{'in': 4, 'nch': 10, 'row': 5, 'col': 4, 'reach': 3, 'path': 1, 'basin': 1, 'area': 36}) assert ck(QB) == dict(**{'in': 13, 'nch': 1, 'row': 2, 'col': 8, 'reach': 7, 'path': 3, 'basin': 1, 'area': 4}) assert (ck(1)['nch'], ck(19)['nch'], ck(19)['basin']) == (17, 1, 2) and prow(1)[6] == '62.00' assert [c[1] for c in PC] == [('pixel_', 'seq_id'), ('row',), ('col',), ('reach_', 'seq_id'), ('path_', 'seq_id'), ('basin_id',), ('upstream_', 'area_km2'), ('upstream_', 'channel_', 'pixel_count')] # the 8 columns of the release assert down(inv[5]) == A and down(inv[10]) == A assert (ck(5)['area'], ck(5)['nch'], ck(10)['area'], ck(10)['nch']) == (22, 5, 12, 4) and 1 + 5 + 4 == ck(QA)['nch'] # larger first TAG = {QA: 'A', QB: 'B'} print('A %s = %d, B %s = %d; upstream of A %d-%d, %d pixels = %d - %d; pixels storing each number %s' % (pos(A), QA, pos(B), QB, QA, OUT_A, len(up_A), cum[OUT_A], cum[QA - 1], [count[k] for k in range(1, NPIX + 1)])) # ---------------------------------------------------------------- layout (inches from the top left) W, ML, MR, GAP = 7.48, 0.10, 0.06, 0.32 GW = 3.50; CELL = GW / 10 # (a): a pixel 0.35 in XB = ML + GW + GAP; BW = W - MR - XB # (b) TW = W - ML - MR # (c) across the page LH = FS / 72 * 1.25 YT = 0.06; Y0 = YT + 0.30 # titles of (a), (b); top of the map and of the header of (b) YB = Y0 + 2 * LH + 0.06 # top of row 1 of (b) RP = (Y0 + GW - YB) / NPIX # rows end level with the map assert RP >= 0.16, RP YT3 = YB + NPIX * RP + 0.34; Y3 = YT3 + 0.32 # title of (c); top of its header RHC, REC = 0.21, 0.15 # a row of (c), a row of dots NHL = max(len(c[1]) for c in PC); assert NHL == 3 Y3R = Y3 + NHL * LH + 0.06 # top of the first row of (c) H = Y3R + sum(REC if k is None else RHC for k in PROWS) + 0.10 fig = plt.figure(figsize=(W, H)); fy = lambda y: 1 - y / H; fx = lambda x: x / W tw = lambda t, bold: text_inches(t, FS, **(BOLD if bold else REG)) def text(x, y, t, bold=False, ha='left', va='top', color=C_TXT, **kw): fig.text(fx(x), fy(y), t, fontsize=FS, va=va, ha=ha, color=color, **{**(BOLD if bold else REG), **kw}) def rule(x0, x1, y, lw, color='#333333'): fig.add_artist(plt.Line2D([fx(x0), fx(x1)], [fy(y), fy(y)], color=color, lw=lw)) def box(x0, y0, w, h, **kw): fig.add_artist(Rectangle((fx(x0), fy(y0 + h)), w / W, h / H, **kw)) for x0, y0, t, w in ((ML, YT, '(a) The number each pixel stores', GW + GAP), (XB, YT, '(b) Ranges of pixel numbers', BW), (ML, YT3, '(c) The pixel table', TW)): assert tw(t, 1) * FT / FS < w, t fig.text(fx(x0), fy(y0), t, fontsize=FT, va='top', ha='left', **BOLD) # ---------------------------------------------------------------- (a) the signed raster ax = fig.add_axes([fx(ML), fy(Y0 + GW), GW / W, GW / H]) grid(ax, N, None, set()) col = lambda x: F_UC if x in uc_A else F_UP if x in up_A 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 = lambda x: '%d' % v[x] if v[x] > 0 else '\u2212%d' % -v[x] def from_text(p, mx, my): hw = tw(lab(p), p in N['ch']) / 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 N['ch']: y = down(x); cx = color_of_reach(N, N['reach'][x]) if LINE_BY_REACH else C_RIV if y is None: ax.plot(*zip(from_text(x, *OUTLET_STUB(x)), OUTLET_STUB(x)), color=cx, 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=cx, lw=2.6, solid_capstyle='butt', zorder=5) for x in N['cells']: ch = x in N['ch']; t = lab(x) assert tw(t, ch) < 0.88 * CELL, t ax.text(x[1] + 0.5, x[0] + 0.5, t, ha='center', va='center', fontsize=FS, color=ink_px(x), zorder=8, path_effects=[pe.withStroke(linewidth=2.5 if ch else 1.0, foreground=col(x))], **(BOLD if ch else REG)) for name, x, (dr, dc) in (('A', A, (1, -1)), ('B', B, (-1, 1))): # a frame, its letter on a corner no channel line crosses r, c = x nb = (r + dr, c + dc) assert down(x) != nb and not (nb in N['ch'] and down(nb) == x), name # only channel pixels carry a line ax.add_patch(Rectangle((c + 0.07, r + 0.07), 0.86, 0.86, fc='none', ec=C_FRAME, lw=2.0, zorder=6)) xm, ym = c + 0.5 + 0.43 * dc, r + 0.5 + 0.43 * dr ax.text(xm, ym, name, ha='center', va='center', fontsize=FS, color=C_FRAME, zorder=9, bbox=dict(boxstyle='square,pad=0.10', fc='white', ec=C_FRAME, lw=1.0), **BOLD) # ---------------------------------------------------------------- (b) each object is one range of numbers HDR = (('Channel', 'pixel'),) + tuple(h for h, _ in OBJ) assert [HDR[i] for i in SPAN[1:]] == [('', 'Unit'), ('', 'Upstream')] PADB = 0.06 if ABS_BARS else 0.05 # the plus-minus label of basin 2 is wider need = [max(tw(t, 0) for t in h) + PADB for h in HDR] for i, (_, rr) in enumerate(OBJ, 1): need[i] = max(need[i], max(tw(rlab(i, a, b), 0) for a, b in rr) + PADB) short = tw(SPAN[0], 0) + PADB - need[SPAN[1]] - need[SPAN[2]] # the shared header must fit over its two columns for i in SPAN[1:]: need[i] += max(short, 0) / 2 assert sum(need) <= BW, (sum(need), BW) cw = [w + (BW - sum(need)) / len(HDR) for w in need] xs = [XB] for w in cw: xs.append(xs[-1] + w) xc = lambda i: (xs[i] + xs[i + 1]) / 2 ytop = lambda k: YB + (k - 1) * RP for i, h in enumerate(HDR): for j, t in enumerate(h): text(xc(i), Y0 + j * LH, t, ha='center') YSP = Y0 + LH - 0.03 text((xs[SPAN[1]] + xs[SPAN[2] + 1]) / 2, Y0, SPAN[0], ha='center') rule(xs[SPAN[1]] + 0.05, xs[SPAN[2] + 1] - 0.05, YSP, 0.6) rule(XB, XB + BW, YB - 0.03, 0.6) for k in range(1, NPIX + 1): if shade(k): box(XB, ytop(k), BW, RP, fc=shade(k), ec='none', zorder=0) rule(XB, XB + BW, ytop(k) + RP, 0.4, '#e2e2e2') text(xc(0), ytop(k) + RP / 2, '%d' % k, bold=True, ha='center', va='center', color=ink_k(k)) if k in TAG: text(XB - 0.14, ytop(k) + RP / 2, TAG[k], bold=True, ha='center', va='center') # in the gap left of (b) BWD = 0.22 # width of a bar for i, (_, rr) in enumerate(OBJ, 1): for a, b in rr: box(xc(i) - BWD / 2, ytop(a) + 0.02, BWD, (b - a + 1) * RP - 0.04, fc=C_BAR, ec='none', zorder=3) for i, (_, rr) in enumerate(OBJ, 1): for a, b in rr: k = b + 1 if b < NPIX else a - 1 assert not any(c <= k <= d for c, d in rr), (i, k) text(xc(i), ytop(k) + RP / 2, rlab(i, a, b), ha='center', va='center') rule(XB, XB + BW, YB + NPIX * RP + 0.01, 1.0) for i, xv in enumerate(xs[1:-1], 1): fig.add_artist(plt.Line2D([fx(xv), fx(xv)], [fy(YSP if i == SPAN[2] else Y0 - 0.04), fy(YB + NPIX * RP)], color='#d0d0d0', lw=0.6, zorder=1)) # ---------------------------------------------------------------- (c) the pixel table as released C_FROM = '#6f6f6f' # headers of the values taken from the reach table need = [max(max(tw(t, 0) for t in c[1]), max(tw(prow(k)[i], i == 0) for k in PROWS if k)) for i, c in enumerate(PC)] assert all(c[2] for c in PC) XT = ML + 0.30 # a narrow margin on the left for A and B pad = (ML + TW - XT - sum(need)) / len(need) assert pad >= 0.20, pad # the headers must read apart pw = [w + pad for w in need] px = [XT] for w in pw: px.append(px[-1] + w) pxc = lambda i: (px[i] + px[i + 1]) / 2 for i, (_, hl, st) in enumerate(PC): for j, t in enumerate(hl): text(pxc(i), Y3 + (NHL - len(hl) + j) * LH, t, ha='center', color=C_TXT if st else C_FROM) rule(ML, ML + TW, Y3 - 0.04, 1.0); rule(ML, ML + TW, Y3R - 0.03, 0.6) y = Y3R for k in PROWS: if k is None: for i in range(len(PC)): text(pxc(i), y + REC / 2, '⋮', ha='center', va='center', fontfamily='DejaVu Sans') y += REC; continue if shade(k): box(ML, y, TW, RHC, fc=shade(k), ec='none', zorder=0) if k in TAG: text(ML + 0.15, y + RHC / 2, TAG[k], bold=True, ha='center', va='center') for i, t in enumerate(prow(k)): text(pxc(i), y + RHC / 2, t, bold=i == 0, ha='center', va='center', color=ink_k(k) if i == 0 else C_TXT) y += RHC rule(ML, ML + TW, y + 0.01, 1.0) FIGD = os.path.join(os.path.dirname(HERE), 'Figures'); stem = 'Fig03_pixel_numbers_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)); assert not os.path.exists(out), out fig.savefig(out, dpi=600); fig.savefig(out[:-4] + '.pdf'); print(out, '%.0f x %.0f mm' % (W * 25.4, H * 25.4), 'row %.3f in' % RP)