# -*- coding: utf-8 -*- """Figure 2: four ways to store a tree (Karwin, 2010), on the 10 reaches of the test grid. (a) the reaches; (b) the reaches in depth-first order; (c) what each model stores for each reach. Output: ../Figures: png and pdf. Usage: python Fig02_four_tree_models_toy_basin.py [reach|basin] """ 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 SQ, color_of_reach, OUTLET_STUB FS, FT = 11, 12 REG = dict(fontfamily='Arial') Q = 4 # the reach asked about: reach 4, pixels i34 and i44 (Figure 1d) LAND, F_UC, F_UP = F_OTHER, '#f2a65e', '#fde2c8' # the colours of Figure 1: land, unit catchment, upstream catchment C_RIV, INK = '#333333', {1: '#0072B2', 2: '#007f5f'} LABEL_DX = {'i54': -0.26, 'i34': 0.74}; NUMBER_INK = (sys.argv[1:] or ['reach'])[0]; assert NUMBER_INK in ('reach', 'basin') # ---------------------------------------------------------------- the reaches and the four models, from the grid N = number(T.T_BASE) pos = lambda x: 'i%d' % (10 * x[0] + x[1]) reach_of = {x: N['reach'][N['first'][x]] for x in N['ch']} R = {} for k, r in enumerate(N['R'], 1): a, b = r[:2]; out = N['inv'][a]; y = down(out) R[k] = dict(px=[N['inv'][n] for n in range(a, b + 1)], dn=reach_of[y] if y is not None else 0) def route(k): # from the outlet up to reach k p = [k] while R[p[-1]]['dn']: p.append(R[p[-1]]['dn']) return p[::-1] K = sorted(R) UP = {k: [j for j in K if k in route(j)] for k in K} # reaches upstream of k, itself included for k in K: # px runs from the reach's outlet up to its upstream end assert all(down(R[k]['px'][i + 1]) == R[k]['px'][i] for i in range(len(R[k]['px']) - 1)), k HEAD = {k: R[k]['px'][-1] for k in K} NAME = {k: i for i, k in enumerate(sorted(K, key=HEAD.get), 1)} # numbered as a row-by-row scan meets the upstream ends assert NAME == {5: 1, 6: 2, 7: 3, 4: 4, 3: 5, 8: 6, 9: 7, 2: 8, 1: 9, 10: 10}, NAME NM = lambda k: str(NAME[k]) # a reach's identifier; k is its FlowNest (depth-first) rank ROWS = sorted(K, key=NAME.get) # rows of (c) by identifier ADJ = {k: NM(R[k]['dn'] or k) for k in K} # an outlet's downstream reach is itself assert ADJ[1] == NM(1) and ADJ[10] == NM(10) and K == list(range(1, len(K) + 1)) PATH = {k: '/'.join(map(NM, route(k))) for k in K} NEST = {k: '%d, %d' % (k, max(UP[k])) for k in K} # ranks, not identifiers CLOS = {k: ', '.join(str(n) for n in sorted(NAME[j] for j in UP[k])) for k in K} for k in K: # the nested set is the closure table with each row one run of ranks assert UP[k] == list(range(k, max(UP[k]) + 1)), k ans = UP[Q] assert ans == [4, 5, 6] and [j for j in K if PATH[j] == PATH[Q] or PATH[j].startswith(PATH[Q] + '/')] == ans assert {pos(x) for x in R[Q]['px']} == {'i34', 'i44'} n_adj, n_path, n_nest, n_clos = len(K), sum(len(route(k)) for k in K), 2 * len(K), sum(len(UP[k]) for k in K) print('reaches %d; numbers stored: adjacency %d, path %d, nested %d, closure %d rows (%d numbers)' % (len(K), n_adj, n_path, n_nest, n_clos, 2 * n_clos)) for k in ROWS: print(NM(k), 'rank', k, [pos(x) for x in R[k]['px']], ADJ[k], PATH[k], NEST[k], CLOS[k]) # rounds of the adjacency list: reaches whose downstream reach was found in the round before rounds, front = [], [Q] while front: nxt = [j for j in K if R[j]['dn'] in front]; rounds.append((front, nxt)); front = nxt assert len(rounds) == 2 and rounds[0][1] == [5, 6] and rounds[1][1] == [] def n_rounds(k): # queries the adjacency list needs for the reaches upstream of k; the last finds none n, front = 0, [k] while front: front = [j for j in K if R[j]['dn'] in front]; n += 1 return n MAXQ = max(n_rounds(k) for k in K) # at most: from an outlet, one query a reach on the longest route assert MAXQ == max(len(route(k)) for k in K) == 5 and n_rounds(Q) == 2 # ---------------------------------------------------------------- the tables COLS = ('Reach', 'Adjacency list', 'Path enumeration', 'Nested set', 'Closure table') SUB = ((), ('reach', 'downstream'), ('route from', 'the outlet'), ('rank and largest', 'rank upstream'), ('reaches upstream,', 'a row each')) CELL = lambda k: (NM(k), ADJ[k], PATH[k], NEST[k], CLOS[k]) # are bold too, as in the path enumeration, since their ranks 5 and 6 are what lie in 4 to 6 BOLDS = {(j, 1) for j in rounds[0][1]} | {(j, 2) for j in ans} | {(j, 3) for j in ans} | {(Q, 4)} STORED = ('Stored', '%d numbers' % n_adj, '%d numbers' % n_path, '%d numbers' % n_nest, '%d numbers' % (2 * n_clos)) assert STORED[1:] == ('10 numbers', '30 numbers', '20 numbers', '60 numbers') QUERIES = ('Queries', 'up to %d' % MAXQ, '1', '1', '1') FOOT = (STORED, QUERIES) PAD = 0.14 SQG = SQ + 0.05 DIG = 0.21 * FS / 72 / 2 # digits sit this much above the centre of a text box with va='center' tw = lambda t, bold: text_inches(t, FS, **(BOLD if bold else REG)) W, ML, MR, GAP = 7.48, 0.10, 0.06, 0.30 TW = W - ML - MR # (c) across the page CW = [max([tw(COLS[c], 1)] + [tw(f[c], c == 0) for f in FOOT] + [tw(t, 0) for t in SUB[c]] + [tw(CELL(k)[c], (k, c) in BOLDS or c == 0) + (SQG if c == 0 else 0) for k in K]) + PAD for c in range(5)] assert sum(CW) <= TW, (sum(CW), CW) CW = [w + (TW - sum(CW)) * (0 if c == 0 else 0.25) for c, w in enumerate(CW)] # spare width to the four models GWA = 2.50 # (a): a pixel 0.25 in XB = ML + GWA + GAP; BW = W - MR - XB # (b) LH = FS / 72 * 1.32 # one line RH = LH + 0.03 # one row of (c) YT = 0.06; Y0 = YT + 0.30 # titles of (a), (b); top of the map and of (b) YT2 = Y0 + GWA + 0.26; Y2 = YT2 + 0.30 # title of (c); top of its header YH = Y2 + 3 * LH + 0.06 # the rule under the header of (c) YR = lambda i: YH + 0.03 + i * RH # top of row i of (c) YS = YR(len(K)) + 0.05 # top of the rows of numbers stored and of queries H = YS + len(FOOT) * RH + 0.12 fig = plt.figure(figsize=(W, H)); fy = lambda y: 1 - y / H; fx = lambda x: x / W def text(x, y, t, bold=False, ha='left', va='top'): fig.text(fx(x), fy(y), t, fontsize=FS, va=va, ha=ha, **(BOLD if bold else REG)) def rule(x0, x1, y, lw): fig.add_artist(plt.Line2D([fx(x0), fx(x1)], [fy(y), fy(y)], color='#333333', lw=lw)) def box(x0, y0, w, h, **kw): # a rectangle in inches from the top left of the page fig.add_artist(Rectangle((fx(x0), fy(y0 + h)), w / W, h / H, **kw)) for x0, y0, t, w in ((ML, YT, '(a) The reaches of Figure 1', GWA + GAP), (XB, YT, '(b) Reaches upstream, in depth-first order', BW), (ML, YT2, '(c) The same reaches in four models', TW)): assert tw(t, 1) * FT / FS < w, t fig.text(fx(x0), fy(y0), t, fontsize=FT, va='top', ha='left', **BOLD) # (b): columns, the reaches in depth-first rank; row, a bar over the reaches upstream of that reach, itself included LWB = max(tw('Reach', 1), tw('Rank', 0)) + PAD XC = XB + LWB; CWB = (BW - LWB) / len(K) # one column a reach YB = Y0 + 2 * LH + 0.06 # top of the first row RHB = (Y0 + GWA - YB) / len(K) # rows end level with the map text(XB + PAD / 2, Y0, 'Rank') text(XB + PAD / 2, Y0 + LH, 'Reach', bold=True) assert ans[0] == Q and PAD / 2 + SQG + tw('10', 1) < LWB box(XC + (Q - 1) * CWB, YB, CWB, len(K) * RHB, fc=F_UC, ec='none', zorder=0) box(XC + Q * CWB, YB, (len(ans) - 1) * CWB, len(K) * RHB, fc=F_UP, ec='none', zorder=0) # the reaches upstream light orange for j in range(len(K) + 1): fig.add_artist(plt.Line2D([fx(XC + j * CWB)] * 2, [fy(YB), fy(YB + len(K) * RHB)], color='#d0d0d0', lw=0.6, zorder=1)) rule(XB, XB + BW, YB - 0.03, 0.6) for i, k in enumerate(K): text(XC + (i + 0.5) * CWB, Y0, str(k), ha='center') text(XC + (i + 0.5) * CWB, Y0 + LH, NM(k), bold=True, ha='center') box(XB + PAD / 2, YB + (i + 0.5) * RHB - DIG - SQ / 2, SQ, SQ, fc=color_of_reach(N, k), ec='none', zorder=4) text(XB + PAD / 2 + SQG, YB + (i + 0.5) * RHB, NM(k), bold=True, va='center') box(XC + (k - 1) * CWB + 0.05, YB + i * RHB + 0.045, (max(UP[k]) - k + 1) * CWB - 0.10, RHB - 0.09, fc='#6f6f6f', ec='none', zorder=3) rule(XB, XB + BW, YB + len(K) * RHB + 0.01, 1.0) # (c): one row a reach, by identifier; shaded, the reaches upstream of the reach asked about; last, the numbers stored and the queries for i, k in enumerate(ROWS): if k in ans: box(ML, YR(i), TW, RH, fc=F_UC if k == Q else F_UP, ec='none', zorder=0) rule(ML, ML + TW, Y2 - 0.04, 1.0); rule(ML, ML + TW, YH, 0.6); rule(ML, ML + TW, YR(len(K)) + 0.03, 0.6); rule(ML, ML + TW, YS + len(FOOT) * RH + 0.03, 1.0) x = ML for c in range(5): text(x + PAD / 2, Y2, COLS[c], bold=True) for j, t in enumerate(SUB[c]): text(x + PAD / 2, Y2 + (j + 1) * LH, t) for i, k in enumerate(ROWS): if c == 0: box(x + PAD / 2, YR(i) + 0.03, SQ, SQ, fc=color_of_reach(N, k), ec='none', zorder=4) text(x + PAD / 2 + (SQG if c == 0 else 0), YR(i) + 0.03, CELL(k)[c], bold=(k, c) in BOLDS or c == 0) for j, f in enumerate(FOOT): text(x + PAD / 2, YS + j * RH + 0.03, f[c], bold=c == 0) x += CW[c] ax = fig.add_axes([fx(ML), fy(Y0 + GWA), GWA / W, GWA / H]) up_px = {x for x in N['cells'] if T.is_up(x, R[Q]['px'][0])} uc_px = {x for x in N['cells'] if reach_of[N['first'][x]] == Q} grid(ax, N, None, set()) for x in N['cells']: ax.add_patch(Rectangle((x[1], x[0]), 1, 1, fc=F_UC if x in uc_px else F_UP if x in up_px else LAND, ec='white', lw=0.8)) CELLW = GWA / 10 # inches a pixel 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] centred = {HEAD[k]: NM(k) for k in K if pos(HEAD[k]) not in LABEL_DX} def from_text(p, mx, my): if p not in centred: return p[1] + 0.5, p[0] + 0.5 hw = text_inches(centred[p], FS, **BOLD) / CELLW / 2 + 0.05; hh = 0.716 * FS / 72 / CELLW / 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, (pos(p), s) return p[1] + 0.5 + s * dx, p[0] + 0.5 + s * dy for x in N['ch']: # in each channel pixel, from its centre to the edge it drains through and back y = down(x); cx = color_of_reach(N, reach_of[x]) 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 R[Q]['px']: ax.add_patch(Rectangle((x[1] + 0.07, x[0] + 0.07), 0.86, 0.86, fc='none', ec='#1f1f1f', lw=1.6, zorder=6)) byname = {pos(x): x for x in N['ch']} for k in K: # read row by row, the numbers run 1 to 10 x = HEAD[k]; assert reach_of[x] == k, k bg = F_UC if x in uc_px else F_UP if x in up_px else LAND ax.text(x[1] + 0.5 + LABEL_DX.get(pos(x), 0), x[0] + 0.5, NM(k), ha='center', va='center', fontsize=FS, color=color_of_reach(N, k) if NUMBER_INK == 'reach' else INK[BNO[T.basin_of(x)]], zorder=8, path_effects=[pe.withStroke(linewidth=3.0, foreground=bg)], **BOLD) FIGD = os.path.join(os.path.dirname(HERE), 'Figures'); stem = 'Fig02_four_tree_models_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), 'map %.2f in' % GWA, 'cols', ['%.2f' % c for c in CW])