# -*- coding: utf-8 -*- """Figures A1-A4: the same variables of the Clark Fork in NHDPlus V2 (A1), HydroSHEDS v1 (A2), TDX-Hydro with MNSI (A3) and FlowNest (A4). Input: ../Data (DataA1-DataA4). Output: ../Figures: png, pdf and caption; with --draft DIR, a png and the caption in DIR. Usage: python FigA1toA4_variables_clarkfork.py [1 2 3 7] [--draft DIR] [--ver K] 1, 2, 3 and 7 draw Figures A1, A2, A3 and A4 (all four by default); 4-6 are FlowNest layouts not used in the paper. """ import os, sys, itertools os.environ.setdefault('OMP_NUM_THREADS', '1'); os.environ.setdefault('PROJ_NETWORK', 'OFF') import numpy as np, geopandas as gpd, shapely import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Rectangle, ConnectionPatch, Arc, FancyArrowPatch from affine import Affine from rasterio import features from shapely.geometry import box as sbox, shape, LineString from shapely.ops import unary_union import shapely.ops import matplotlib.patheffects as pe HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import FigA_loaders_clarkfork as J from FigA_common_clarkfork import (BOLD, FILL, INK, HALO, KEYS, C_MAIN, C_TRIB, C_OTHER, C_STRIP, T_MAIN, T_TRIB, T_DARK, T_GREY, num, text_inches, ROLE, F_TRIB, F_OTHER, ZOOM_LINE, AREA, COL, HALF, TRIB_NAME, runs, LO, HI, PID, TR, GT, R0, C0, EPSG, grid, order_row, TRIB_PIX, JUNC_PIX, read04, BASIN) FS, FT, LH = 10, 12, 0.165 # every text, every title (pt); a line of text (in) W = 7.48; ML = 0.10 # inches; the height follows the content LOCW, ZW = 1.00, 2.00 # the basin column and the junction window X_ZOOM = ML + LOCW + 0.08 XB = X_ZOOM + ZW + 0.12 # left edge of (b) in Figures 2-5 HALF_W = HALF; MPI = HALF / (ZW / 2) XS, XE = 1.68, W - 1.55; SW = XE - XS # the strips of (c) XN1, XN2 = W - 1.23, W - 0.45 SH, AH = 0.24, 0.42 # height of a strip, of its arcs Y0 = 0.70 # top of (a) and (b), from the top GROWS, GCOLS = (44235, 44241), (68224, 68233) # Figure 6a: rows and columns of the whole grid (the Matriotti junction at row 44239, column 68230) PRE = {'main': JUNC_PIX // 1000, 'trib': TRIB_PIX // 1000} # the digits before the last three, in the main stem and the tributary of Figure 6a CELL = (0.42, 0.525) # inches; widened only to fit full signed local labels at the unchanged 10 pt AW6 = 2.70 LAB6 = {'trib': (-12, -14), 'below': (4, 15), 'above': (10, 11)} # Figure 6a: (row, column) from the junction pixel of each label, outside the basin AWM = ZW LABM = {'trib': (-14, -2), 'below': (4, -12), 'above': (14, 6)} # Little Blackfoot): its labels, three lines each (role, field, value). The whole window lies in the region and grey rivers run all over it, so a label keeps # off the channel pixels of the main stem and of the tributary (a grey river under it is masked by the white halo). Each leader goes to a channel pixel of its # own reach (LABT, not the junction pixel itself, where a leader could belong to any of the three reaches); it leaves the label at its point nearest to the # pixel, is 140-700 m long and crosses no blue or orange channel pixel and no other label (the lowest-cost of all # compatible triples). The 1 km bar goes under the window. LABT = {'below': JUNC_PIX - 3, 'above': JUNC_PIX + 8, 'trib': TRIB_PIX + 7} # the pixel each leader of Figure A4a points to LOC6 = 'above' if '--above' in sys.argv else 'below' if '--below' in sys.argv else 'left' LOCH6, GAP6 = 1.20, 0.24 # the height of the whole basin and the gap between it and the window (in) STEM = {1: 'FigA1_variables_nhdplus_v2_clarkfork', 2: 'FigA2_variables_hydrosheds_v1_clarkfork', 3: 'FigA3_variables_tdx_mmw_clarkfork', 4: 'FigA4r_variables_flownest_reach_littleblackfoot', 5: 'FigA4p_variables_flownest_pixel_littleblackfoot', 6: 'FigA4m_variables_flownest_clarkfork', 7: 'FigA4_variables_flownest_clarkfork'} NAME = {1: 'NHDPlus V2', 2: 'HydroSHEDS v1', 3: 'TDX-Hydro + Model My Watershed', 4: 'FlowNest', 5: 'FlowNest', 6: 'FlowNest', 7: 'FlowNest'} TAGS = {1: ['reach level'], 2: ['reach level', 'sub-basin level'], 3: ['reach level'], 4: ['reach level'], 5: ['pixel level'], 6: ['reach level', 'pixel level'], 7: ['reach level']} UNIT = {1: 'flowline', 2: 'reach', 3: 'link', 4: 'reach', 5: 'pixel', 6: 'reach and pixel', 7: 'reach'} # The strips of (c): row of the loaded data, field, what it counts, arcs or not ROWS = {1: [(0, 'COMID', '{n} flowlines', 1), (1, 'HYDROSEQ', 'the same flowlines', 1), (2, 'REACHCODE', '{nv2:,} reach codes', 0)], 2: [(0, 'HYRIV_ID', '{n} reaches', 1), (1, 'PFAF_ID', '{n} sub-basins, level 12', 1)], # levels 10 to 12: the same three sub-basins 3: [(0, 'LINKNO', '{n} links', 1), (1, 'DISCOVER_TIME', 'the same links', 1)], 4: [(0, 'reach_seq_id', '{n} reaches', 1)], 5: [(0, 'pixel_seq_id', '{n} channel pixels', 1), (1, '|pixel_seq_id|', 'all {n} pixels', 0)], 6: [(0, 'reach_seq_id', '{n} reaches', 1), (1, 'pixel_seq_id', '{n} channel pixels', 1), (2, '|pixel_seq_id|', 'all {n} pixels', 0)], 7: [(0, 'reach_seq_id', '{n} reaches', 1)]} T3 = {} # the number of blocks of each strip, counted while drawing and used by the captions ARCS = {1: {0: 'cross', 1: 'cross'}, 2: {0: 'cross', 1: 'nest'}, 3: {0: 'cross', 1: 'nest'}, 4: {0: 'nest'}, 5: {0: 'nest'}, 6: {0: 'nest', 1: 'nest'}, 7: {0: 'nest'}} # as the captions say QUES = (('up- and', 'downstream?'), ('which', 'river?'), ('which', 'land?'), ('which', 'point?')) QUES_LEFT = (('up- and', 'down-', 'stream?'), ('which', 'river?'), ('which', 'land?'), ('which', 'point?')) PAD = 0.10 DRAFT = sys.argv[sys.argv.index('--draft') + 1] if '--draft' in sys.argv else None VER = int(sys.argv[sys.argv.index('--ver') + 1]) if '--ver' in sys.argv else 1 def arrow_marker(ang): """A narrow triangle pointing at angle ang + 90 degrees; an equilateral one turned 45 degrees reads as pointing sideways.""" t = np.radians(ang); c, s_ = np.cos(t), np.sin(t) return [(c * x - s_ * y, s_ * x + c * y) for x, y in ((0, 1), (-0.36, -0.7), (0.36, -0.7), (0, 1))] def save(fig, k, H, caption): stem = STEM[k] if DRAFT: os.makedirs(DRAFT, exist_ok=True) out = os.path.join(DRAFT, stem + '_draft.png'); fig.savefig(out, dpi=300); plt.close(fig) open(out[:-4] + '_caption.md', 'w', encoding='utf-8').write(caption + '\n') print(out, '%.0f x %.0f mm' % (W * 25.4, H * 25.4)); return figd = os.path.join(os.path.dirname(HERE), 'Figures') out = os.path.join(figd, '%s_v%d.png' % (stem, VER)) assert not any(os.path.exists(out[:-4] + suffix) for suffix in ('.png', '.pdf', '_caption.md')), out fig.savefig(out, dpi=300); fig.savefig(out[:-4] + '.pdf', dpi=600); plt.close(fig) open(out[:-4] + '_caption.md', 'w', encoding='utf-8').write(caption + '\n') print(out, 'and .pdf, _caption.md; %.0f x %.0f mm' % (W * 25.4, H * 25.4)) def split_note(sp): """Figure 3: a level-9 sub-basin over 250 km² is cut into pieces along its own river; two pieces with an even second digit stay on the main stem.""" assert all(s_['split'] == (s_['area_km2'] > 250) and s_['chain'] for s_ in sp), sp cut = [s_['pieces'] for s_ in sp if s_['split']]; mid = [q_ for s_ in sp if s_['split'] and s_['on_main_stem'] for q_ in s_['pieces'] if int(q_[1]) % 2 == 0] assert mid == ['32', '92'], mid g_ = '; '.join(', '.join(c_) if len(c_) == 2 else '%s to %s' % (c_[0], c_[-1]) for c_ in cut) return g_, mid # ================================================================ data def fn_tables(): """FlowNest from Data04: the reach and pixel tables, the three reaches at the junction.""" rb = read04('reach_1km2').sort_values('reach_id').reset_index(drop=True) p = read04('pixel_1km2').set_index('pixel_id') o_ = rb.outlet_pixel_id.values ridx = lambda px: int(np.searchsorted(o_, px, 'right')) - 1 junc = int(p.at[TRIB_PIX, 'next_down_pixel_id']); above = junc + 1; assert junc == JUNC_PIX R = {'trib': rb.iloc[ridx(TRIB_PIX)], 'below': rb.iloc[ridx(junc)], 'above': rb.iloc[ridx(above)]} t = R['trib'] # the tributary reach, as (b) of Figures 5 and 6 gives it assert int(t.river_id) == 33798307 and int(t.outlet_pixel_id) == TRIB_PIX and int(t.next_down_pixel_id) == junc and int(t.next_down_reach_id) == int(R['below'].reach_id) assert int(R['below'].upstream_end_pixel_id) == junc and int(R['above'].outlet_pixel_id) == above and int(R['above'].reach_id) == int(R['below'].reach_id) + 1 print('tributary reach', {c: int(t[c]) for c in ('reach_id', 'next_down_reach_id', 'upstream_reach_id_max', 'river_id', 'outlet_pixel_id', 'upstream_end_pixel_id', 'upstream_pixel_id_max', 'next_down_pixel_id')}) nd_ = dict(zip(rb.reach_id, rb.next_down_reach_id)); pv_ = dict(zip(rb.reach_id, rb.river_id)) # within a path a reach flows to the reach numbered one less assert all(nd_[r_] == r_ - 1 for r_ in rb.reach_id if nd_[r_] and pv_.get(nd_[r_]) == pv_[r_]) return rb, p, R, ridx def load(k): if k == 7: D = load(4) return D if k <= 3: D = {1: J.load_nhd, 2: J.load_hyd, 3: J.load_tdx}[k](); V = D['extra']['vals']; lb = D['zoom']['labels']['trib'] D['hot'] = {1: lambda: (lb[1].split()[-1], V['TOCOMID']), 2: lambda: (str(lb[2]), str(V['reach_NEXT_DOWN'])), 3: lambda: (str(lb[2]), V['DSLINKNO'])}[k]() assert D['hot'] == {1: ('24294294', '24293524'), 2: ('70376561', '70376560'), 3: ('720203780', '720170054')}[k], D['hot'] # DataA1-A3 (Clark Fork, Little Blackfoot) return D D = J.load_fn(); E = D['extra']; rb, p, R, ridx = fn_tables(); D['fn'] = (rb, p, R, ridx) (_, m0, m1, *_), (_, t0, t1, *_) = E['brackets'][:2]; main_last, b0, b1 = int(m1 - 0.5), int(t0 + 0.5), int(t1 - 0.5) assert D['zoom']['cls_n'](main_last) == 'main' and D['zoom']['cls_n'](main_last + 1) != 'main' and D['zoom']['cls_n'](b1) == 'trib' D['ends'] = (main_last, b0, b1) if k == 4: r0 = D['rows'][0]; D['rows'] = [r0]; E['arcsets'] = {0: E['arcsets'][0]} im = np.nonzero(np.array(r0['cls']) == 'main')[0]; it = np.nonzero(np.array(r0['cls']) == 'trib')[0] first = int(rb.reach_id.iloc[0]); mr = (first + im[0], first + im[-1]); trr = (first + it[0], first + it[-1]) t_ = R['trib']; assert trr == (int(t_.reach_id), int(t_.upstream_reach_id_max)) and len(it) == it[-1] - it[0] + 1 E['brackets'] = [(0, im[0], im[-1] + 1, 'the main stem, one path: [%s, %s)' % (num(mr[0]), num(mr[1] + 1)), T_MAIN, 'left'), (0, it[0], it[-1] + 1, '[%s, %s): %s with its tributaries' % (num(trr[0]), num(trr[1] + 1), TRIB_NAME), T_TRIB, 'left', 0.18)] D['hot'] = (num(R['trib'].reach_id), num(R['trib'].next_down_reach_id)) else: a = np.abs(PID); av = np.sort(a[(a >= LO) & (a <= HI)]) cls = np.where((av >= LO) & (av <= main_last), 'main', np.where((av >= b0) & (av <= b1), 'trib', 'other')) D['rows'] = [D['rows'][1], order_row(None, '%s raster pixels' % num(len(av)), 'pixel level', '|pixel_seq_id|', cls, (num(av[0]), num(av[-1])))] E['arcsets'] = {0: E['arcsets'][1]} E['brackets'] = [(0, LO - 0.5, main_last + 0.5, 'the main stem, one path: %s to %s' % (num(LO), num(main_last)), T_MAIN, 'left'), (0, b0 - 0.5, b1 + 0.5, '%s to %s: %s with its tributaries' % (num(b0), num(b1), TRIB_NAME), T_TRIB, 'left', 0.18)] D['hot'] = (num(TRIB_PIX), num(JUNC_PIX)) return D # ================================================================ (b): the four questions against the numberings def table(k, D): """Columns: (numbering, what it is, {question: lines}). A line is 'seg|seg'; a segment starting with * is bold, with ~ grey.""" E = D['extra']; V = E.get('vals', {}) if k == 1: assert (V['TOCOMID'], V['DNHYDROSEQ'], V['UPHYDROSEQ'], V['LEVELPATHI']) == ('24293524', '50010333', '50017557', '50017357'), V # DataA1 (Clark Fork, Little Blackfoot) return [('COMID', ['flowline ID'], {0: ['*TOCOMID', V['TOCOMID']], 2: ['*FEATUREID', '= COMID']}), ('HYDROSEQ', ['smaller is', 'downstream'], {0: ['*DNHYDROSEQ', V['DNHYDROSEQ'], '*UPHYDROSEQ', V['UPHYDROSEQ']], 1: ['*LEVELPATHI', V['LEVELPATHI']]}), ('REACHCODE', ['basin code', '+ reach number'], {3: ['*FROMMEAS', '*TOMEAS', '% along', 'the reach']})] if k == 2: V = {q: str(x) for q, x in V.items()} assert (V['reach_NEXT_DOWN'], V['unit_NEXT_DOWN'], V['HYBAS_L12']) == ('70376560', '7120370050', '7120370060'), V # DataA2 (Clark Fork): the Little Blackfoot reach lies in sub-basin 7120370060, PFAF_ID 782669601 return [('HYRIV_ID', ['reach ID'], {0: ['*NEXT_DOWN', V['reach_NEXT_DOWN']], 1: ['~*ORD_CLAS', '~an order,', '~not an ID'], 2: ['*HYBAS_L12', V['HYBAS_L12']]}), ('HYBAS_ID', ['sub-basin ID'], {0: ['*NEXT_DOWN', V['unit_NEXT_DOWN']], 2: ['the polygon', 'itself']}), ('PFAF_ID', ['Pfafstetter', 'code'], {0: ['from its digits:', '2 and 3', 'drain to 1'], 1: ['digit 7 is 6, even:', 'tributary basin', '*7826696', '~four largest only'], 2: ['the same', 'polygon']})] if k == 3: assert (V['DSLINKNO'], V['DISCOVER_TIME'], V['FINISH_TIME'], V['ROOT_ID'], V['LINKNO_region'], V['LINKNO_offset']) == \ ('720170054', '62913', '63050', '720207783', '203780', '720,000,000'), V # DataA3 (Clark Fork): it flows to the main-stem link below the junction return [('LINKNO', ['link ID'], {0: ['*DSLINKNO', V['DSLINKNO'], '*USLINKNO1, 2', '~the two links', '~upstream'], 2: ['*streamID', V['LINKNO_region'], '= LINKNO −', V['LINKNO_offset']]}), ('DISCOVER_TIME', ['depth-first', 'visit order'], {0: ['*DISCOVER_TIME| ' + V['DISCOVER_TIME'], '*FINISH_TIME| ' + V['FINISH_TIME'], '*ROOT_ID| ' + V['ROOT_ID']]})] rb, p, R, ridx = D['fn']; t = R['trib']; rule = ['depth first from the outlet,', 'larger drainage area first'] if k == 7: n_r = int(t.upstream_reach_id_max) - int(t.reach_id) + 1; n_c = int(t.upstream_end_pixel_id) - int(t.outlet_pixel_id) + 1 assert (n_r, n_c) == (512, 23), (n_r, n_c) return [('reach_seq_id', rule, {0: ['*next_down_reach_seq_id', num(t.next_down_reach_id), 'upstream, from its own:', '*upstream_reach_count| %d,' % n_r, '~here [%s, %s)' % (num(t.reach_id), num(t.upstream_reach_id_max + 1))], 1: ['*path_seq_id', num(t.river_id)], 2: ['*reach_seq_id| itself:', 'its unit-catchment polygon', 'and the reach raster'], 3: ['*downstream_end_pixel_seq_id| %s,' % num(t.outlet_pixel_id), '*channel_pixel_count| %d:' % n_c, '~pixel_seq_id [%s, %s)' % (num(t.outlet_pixel_id), num(t.upstream_end_pixel_id + 1))]})] def segs(line): out = [] for s_ in line.split('|'): g_ = s_.startswith('~'); s_ = s_[1:] if g_ else s_ b_ = s_.startswith('*'); s_ = s_[1:] if b_ else s_ out.append((s_, b_, g_)) return out seg_w = lambda line: sum(text_inches(s_, FS, **(BOLD if b_ else {})) for s_, b_, _ in segs(line)) def table_layout(cols, x0): """Widths of the question column and of each numbering column; heights of the heading and of each question row.""" qw = max(text_inches(t_, FS) for two in QUES for t_ in two) + 0.10 need = [max([text_inches(n_, FS, **BOLD)] + [text_inches(t_, FS) for t_ in what] + [seg_w(l_) for c_ in cells.values() for l_ in c_]) + PAD for n_, what, cells in cols] avail = W - 0.10 - x0 - qw; assert sum(need) <= avail + 1e-6, ('(b) is too wide', need, avail) cw = [n_ + (avail - sum(need)) / len(need) for n_ in need] if len(need) > 1 else [min(avail, max(need[0], 2.2))] hh = (1 + max(len(what) for _, what, _ in cols)) * LH + 0.10 rh = [max([len(QUES[q])] + [len(cells.get(q, ['–'])) for _, _, cells in cols]) * LH + 0.12 for q in range(4)] return qw, cw, hh, rh def draw_table(fig, T, cols, x0, y0, L): qw, cw, hh, rh = L; xc = [x0 + qw + sum(cw[:q]) for q in range(len(cw) + 1)]; H = fig.get_figheight(); fy = lambda y: 1 - y / H for q, (n_, what, _) in enumerate(cols): # the heading: the numbering, then what it is T(xc[q] + 0.06, y0 + 0.05 + LH / 2, n_, **BOLD) for m_, t_ in enumerate(what): T(xc[q] + 0.06, y0 + 0.05 + LH / 2 + LH * (m_ + 1), t_, color=T_GREY) y = y0 + hh; fig.add_artist(plt.Line2D([x0 / W, xc[-1] / W], [fy(y)] * 2, color='#888888', lw=0.7)) for q in range(4): if q: fig.add_artist(plt.Line2D([x0 / W, xc[-1] / W], [fy(y)] * 2, color='#dddddd', lw=0.6)) yc = y + rh[q] / 2 for m_, t_ in enumerate(QUES[q]): T(x0, yc + (m_ - (len(QUES[q]) - 1) / 2) * LH, t_) for c, (_, _, cells) in enumerate(cols): lines = cells.get(q) if not lines: T(xc[c] + 0.06, yc, '–', color=T_GREY); continue if not all(g_ for l_ in lines for _, _, g_ in segs(l_)): fig.add_artist(Rectangle(((xc[c] + 0.02) / W, fy(y + rh[q] - 0.03)), (cw[c] - 0.04) / W, (rh[q] - 0.06) / H, transform=fig.transFigure, fc='#ececec', ec='none', zorder=0.5)) for m_, l_ in enumerate(lines): x_ = xc[c] + 0.06; assert x_ + seg_w(l_) <= xc[c] + cw[c] - 0.02, l_ for s_, b_, g_ in segs(l_): T(x_, yc + (m_ - (len(lines) - 1) / 2) * LH, s_, color=T_GREY if g_ else T_DARK, **(BOLD if b_ else {})); x_ += text_inches(s_, FS, **(BOLD if b_ else {})) y += rh[q] return y # ================================================================ (a): the window, labels placed by a search def fn_window(D, WB): """Figure 5a: unit catchments (polygons from the signed raster) and channel lines of the reaches around the junction, with roles.""" rb, p, R, ridx = D['fn']; Z = D['zoom']; o_ = rb.outlet_pixel_id.values rj, cj = int(p.at[JUNC_PIX, 'row']), int(p.at[JUNC_PIX, 'col']) hy, hx = int(np.ceil((WB[3] - WB[1]) / 2 / Z['my'])) + 4, int(np.ceil((WB[2] - WB[0]) / 2 / Z['mx'])) + 4 r0, c0 = rj - hy, cj - hx; v = grid(r0, rj + hy + 1, c0, cj + hx + 1); a = np.abs(v); inb = (a >= LO) & (a <= HI) idx = np.where(inb, np.searchsorted(o_, a, 'right') - 1, -1) role = {ridx(JUNC_PIX): 'below', ridx(JUNC_PIX + 1): 'above', ridx(TRIB_PIX): 'trib'} tr = TR * Affine.translation(c0 - C0, r0 - R0); g = {} for geom, val in features.shapes((idx + 1).astype('int32'), mask=inb, transform=tr): g.setdefault(int(val) - 1, []).append(shape(geom)) poly = gpd.GeoDataFrame({'role': [role.get(i_) for i_ in g]}, geometry=[unary_union(s_) for s_ in g.values()], crs=4326).to_crs(EPSG) q = p[(p.row >= r0 - 2) & (p.row <= rj + hy + 2) & (p.col >= c0 - 2) & (p.col <= cj + hx + 2)] xy = lambda n_: GT * (p.at[n_, 'col'] + 0.5, p.at[n_, 'row'] + 0.5) cls_n = Z['cls_n']; rng = Z['rng'] rl = lambda n_: next((k_ for k_, (a0, a1) in rng.items() if a0 <= n_ <= a1), None) seg = [(int(n_), LineString([xy(n_), xy(int(d_))])) for n_, d_ in zip(q.index, q.next_down_pixel_id) if d_ and int(d_) in p.index] line = gpd.GeoDataFrame({'main': [cls_n(n_) == 'main' for n_, _ in seg], 'trib': [cls_n(n_) == 'trib' for n_, _ in seg], 'role': [rl(n_) for n_, _ in seg]}, geometry=[s_ for _, s_ in seg], crs=4326).to_crs(EPSG) return poly, line def place(Z, WB, labels, sizes): """Centres of the labels (metres): inside the window, clear of the main stem, the tributary, the bar and each other; each near its own line and over its own polygon. Returns the centres and the box of the scale bar.""" win = sbox(*WB); L = Z['line'][Z['line'].intersects(win)]; thick = L[L.main | L.trib]; thin = L[~(L.main | L.trib)] hard = unary_union(list(thick.geometry)).buffer(70).intersection(win) soft = unary_union(list(thin.geometry)).intersection(win) if len(thin) else None m_ = 40.0; bw, bh = 1000 + 2 * m_, (0.20 + 0.06) * MPI bar = None for cx_, cy_ in ((0, 1), (0, 0), (1, 1), (1, 0)): # the 1 km bar: the first corner clear of both rivers, top left first (the same corner in Figures 2-5) x0_ = WB[0] + m_ if cx_ == 0 else WB[2] - m_ - bw; y0_ = WB[1] + m_ if cy_ == 0 else WB[3] - m_ - bh b_ = sbox(x0_, y0_, x0_ + bw, y0_ + bh) if not b_.intersects(hard): bar = b_; break assert bar is not None, 'no corner for the scale bar' P = Z['poly']; C = {} for kk in KEYS: # the candidates of each label and their cost; the order of placing is chosen below w_, h_ = sizes[kk]; w_ += 2 * m_; h_ += 2 * m_ xs = np.arange(WB[0] + w_ / 2 + 20, WB[2] - w_ / 2 - 20, 40.0); ys = np.arange(WB[1] + h_ / 2 + 20, WB[3] - h_ / 2 - 20, 40.0) X, Y = [g_.ravel() for g_ in np.meshgrid(xs, ys)] bx = shapely.box(X - w_ / 2, Y - h_ / 2, X + w_ / 2, Y + h_ / 2) own = unary_union(list(thick[thick.role == kk].geometry)); assert not own.is_empty, kk cost = shapely.distance(shapely.points(X, Y), own) if kk != 'trib': # each main-stem label nearer its own piece than the other piece oth = unary_union(list(thick[thick.role == ('below' if kk == 'above' else 'above')].geometry)) if not oth.is_empty: # clearly nearer its own piece, and not at the junction where both pieces meet d_own, d_oth = shapely.distance(bx, own), shapely.distance(bx, oth) cost = cost + 5000 * (d_oth < 2 * d_own + 150) + 3000 * (shapely.distance(bx, Z.get('junction', Z.get('centre'))) < 400) mine = P[P.role == kk] if len(P) else P if len(mine): cost = cost + (1 - shapely.area(shapely.intersection(bx, unary_union(list(mine.geometry)))) / (w_ * h_)) * 800 oth_p = P[P.role.notna() & (P.role != kk)] if len(mine) else P.iloc[:0] if len(oth_p): cost = cost + shapely.area(shapely.intersection(bx, unary_union(list(oth_p.geometry)))) / (w_ * h_) * 1500 if soft is not None and not soft.is_empty: cost = cost + 300 * shapely.intersects(bx, soft) C[kk] = (X, Y, bx, np.where(shapely.intersects(bx, hard), np.inf, cost)) best = (np.inf, None) for order in itertools.permutations(KEYS): taken = [bar.buffer(m_)]; at = {}; tot = 0.0 for kk in order: X, Y, bx, cost = C[kk]; c_ = np.where(shapely.intersects(bx, unary_union(taken)), np.inf, cost); i_ = int(np.argmin(c_)) tot += c_[i_]; at[kk] = (X[i_], Y[i_]); taken.append(bx[i_]) if tot < best[0]: best = (tot, at) assert np.isfinite(best[0]), 'no place for the three labels' at = best[1] return at, bar def draw_window(fig, D, k, yt, ZH): """Figures 2-5: the basin (left) and the window at the junction (right), ZH inches tall.""" H = fig.get_figheight(); fy = lambda y: 1 - y / H Z = dict(D['zoom']); j = Z.get('junction', Z.get('centre')); hh = ZH / 2 * MPI WB = (j.x - HALF_W, j.y - hh, j.x + HALF_W, j.y + hh) ax_l = fig.add_axes([ML / W, fy(yt + ZH), LOCW / W, ZH / H]); ax_l.set_axis_off() lp, ll = D['loc_poly'], D['loc_line'] if len(lp): lp.plot(ax=ax_l, color=[F_TRIB if b else F_OTHER for b in lp.trib], edgecolor='white', linewidth=0.2, aspect=None, rasterized=True) for sel, col, lw in ((~ll.main & ~ll.trib, C_OTHER, 0.25), (ll.trib, C_TRIB, 0.45), (ll.main, C_MAIN, 1.0)): if sel.any(): ll[sel].plot(ax=ax_l, color=col, linewidth=lw, aspect=None, rasterized=True) e = AREA.total_bounds; cx = 0.5 * (e[0] + e[2]); hw = 0.5 * (e[2] - e[0]) + 600; s_ = 2 * hw / LOCW # metres per inch hb = (e[3] - e[1]) / s_ + 0.36; assert hb <= ZH, 'the basin and its bar do not fit the column' top_ = e[3] + 0.5 * (ZH - hb) * s_; ax_l.set_aspect('equal'); ax_l.set_xlim(cx - hw, cx + hw); ax_l.set_ylim(top_ - ZH * s_, top_) ax_l.add_patch(Rectangle((WB[0], WB[1]), WB[2] - WB[0], WB[3] - WB[1], fill=False, ec='black', lw=0.8, zorder=8)) yb = e[1] - 0.24 * s_; xb = cx - hw + 0.04 * s_ ax_l.plot([xb, xb + 50000], [yb, yb], color='black', lw=1.2, solid_capstyle='butt', clip_on=False) ax_l.text(xb + 50000 + 0.06 * s_, yb, '50 km', ha='left', va='center', fontsize=FS, clip_on=False, path_effects=HALO, zorder=10) assert 0.04 + 50000 / s_ + 0.06 + text_inches('50 km', FS) <= LOCW + 0.06, 'the 50 km label leaves the column' ax_w = fig.add_axes([X_ZOOM / W, fy(yt + ZH), ZW / W, ZH / H]); ax_w.set_xticks([]); ax_w.set_yticks([]) for sp in ax_w.spines.values(): sp.set_lw(0.8) for ya, yf in ((WB[3], 1.0), (WB[1], 0.0)): ax_l.add_artist(ConnectionPatch(xyA=(WB[2], ya), coordsA=ax_l.transData, xyB=(0.0, yf), coordsB=ax_w.transAxes, clip_on=False, **{**ZOOM_LINE, 'zorder': 0.5})) if k == 4: Z['poly'], Z['line'] = fn_window(D, WB) win = sbox(*WB); ax_w.set_facecolor(F_OTHER) pg = Z['poly'][Z['poly'].intersects(win)] if len(Z['poly']) else Z['poly'] if len(pg): pg.plot(ax=ax_w, color=[FILL[r] if isinstance(r, str) else F_OTHER for r in pg.role], edgecolor='white', linewidth=0.8, aspect=None) for _, l in Z['line'][Z['line'].intersects(win)].iterrows(): col = C_TRIB if l.trib else C_MAIN if l.main else C_OTHER for part in (l.geometry.geoms if l.geometry.geom_type.startswith('Multi') else [l.geometry]): q = np.asarray(part.coords)[:, :2] ax_w.plot(q[:, 0], q[:, 1], color=col, lw=2.2 if l.role in KEYS else 1.0 if (l.main or l.trib) else 0.7, solid_capstyle='round', zorder=3) # the labels: role, then each field over its value ids = {1: lambda kk: [ROLE[kk], 'COMID', Z['labels'][kk][1].split()[-1]], 2: lambda kk: [ROLE[kk]] + Z['labels'][kk][1:3], 3: lambda kk: [ROLE[kk]] + Z['labels'][kk][1:], 4: lambda kk: [ROLE[kk], num(D['fn'][2][kk].reach_id)]}[k] # Figure 5: the field is the heading of (b) lab = {kk: ids(kk) for kk in KEYS} sty = lambda q_: (BOLD, None) if q_ == 0 else ({}, T_GREY) if (q_ % 2 == 1 and k != 4) else ({}, None) sizes = {kk: (max(text_inches(t_, FS, **sty(q_)[0]) for q_, t_ in enumerate(lab[kk])) * MPI, len(lab[kk]) * LH * MPI) for kk in KEYS} at, bar = place(Z, WB, lab, sizes) D['leaders'] = [] LW_ = Z['line'][Z['line'].intersects(win)] for kk in KEYS: mine = Z['poly'][Z['poly'].role == kk] if len(Z['poly']) else Z['poly'] own = unary_union(list(mine.geometry)).intersection(win) if len(mine) else None; assert own is None or not own.is_empty, kk n_ = len(lab[kk]); txt = unary_union([sbox(at[kk][0] - w_ / 2, y_ - LH * MPI / 2, at[kk][0] + w_ / 2, y_ + LH * MPI / 2) for q_, t_ in enumerate(lab[kk]) for w_, y_ in [(text_inches(t_, FS, **sty(q_)[0]) * MPI, at[kk][1] + ((n_ - 1) / 2 - q_) * LH * MPI)]]) lin = unary_union(list(LW_[(LW_.role == kk) & (LW_.main | LW_.trib)].geometry)).intersection(win) small = own is not None and own.area < 0.25 * sizes[kk][0] * sizes[kk][1] off = own is not None and txt.intersection(own).area < 0.3 * txt.area far = txt.distance(lin) > 600 # that of the shade under it, so a line joins it to its own; one far from its reach print('Figure %d: %s label %.0f%% over its own unit catchment, %.0f m from its reach' % (k + 1, kk, 100 * txt.intersection(own).area / txt.area if own is not None else -1, txt.distance(lin))) # (A2a: 1.5 km) gets a line to the middle of the reach, in its own catchment if not (small or off or far): continue if not far: # to the point of its unit catchment nearest the centre of the label, 80 m inside its core = next((c_ for c_ in (own.buffer(-80), own.buffer(-40)) if not c_.is_empty), own) # edge (40 m if too small): the centre of the catchment made the tgt = shapely.ops.nearest_points(core, shapely.Point(at[kk]))[0] # line of A1a cross the main stem else: seg_ = shapely.ops.linemerge(lin) if lin.geom_type == 'MultiLineString' else lin # the middle of the part in the window: the point nearest to the seg_ = max(getattr(seg_, 'geoms', [seg_]), key=lambda g_: g_.length) # label was the junction itself, where the line could belong to any reach tgt = seg_.interpolate(0.5, normalized=True) ray = LineString([at[kk], (tgt.x, tgt.y)]).difference(txt.buffer(0.03 * MPI)) # from the centre of the label towards the target, outside the text s0 = shapely.Point(min(getattr(ray, 'geoms', [ray]), key=lambda g_: g_.distance(tgt)).coords[0]) assert s0.distance(tgt) >= 0.08 * MPI, ('leader too short', kk) ax_w.plot([s0.x, tgt.x], [s0.y, tgt.y], color=INK[kk], lw=0.9, solid_capstyle='round', zorder=6, path_effects=[pe.withStroke(linewidth=2.4, foreground='white')]) D['leaders'].append(kk); D.setdefault('leader_to', {})[kk] = 'reach' if far else 'catchment' for kk in KEYS: n_ = len(lab[kk]) for q_, t_ in enumerate(lab[kk]): kw_, c_ = sty(q_) ax_w.text(at[kk][0], at[kk][1] + ((n_ - 1) / 2 - q_) * LH * MPI, t_, fontsize=FS, color=c_ or INK[kk], ha='center', va='center', path_effects=HALO, zorder=7, **kw_) bx0, by0, bx1, by1 = bar.bounds ax_w.plot([bx0 + 40, bx0 + 1040], [by0 + 60] * 2, color='black', lw=1.2, solid_capstyle='butt', zorder=8) ax_w.text(bx0 + 540, by0 + 60 + 0.05 * MPI, '1 km', fontsize=FS, ha='center', va='bottom', zorder=8, path_effects=HALO) ax_w.set_aspect('equal'); ax_w.set_xlim(WB[0], WB[2]); ax_w.set_ylim(WB[1], WB[3]) D['labels_drawn'] = lab def draw_pixels(fig, D, T, yt, k=5): """Panel (a) of Figure A4: a window of 3.2 km x 4.8 km centred on the junction, one square per pixel of the raster; channel pixels dark, hillslope pixels light in the shade of their unit catchment, outside the basin white; the three channel pixels that meet at the junction labelled with their pixel_seq_id.""" H = fig.get_figheight(); fy = lambda y: 1 - y / H; rb, p, R, ridx = D['fn']; Z = D['zoom'] reach_only = k == 7; k = 6 if k == 7 else k AW_ = AWM if k == 6 else AW6; LAB_ = LABM if k == 6 else LAB6 mx, my = Z['mx'], Z['my']; HX, HY = HALF_W, 1.5 * HALF_W; AH = AW_ * HY / HX; mpi = 2 * HX / AW_ rj, cj = int(p.at[JUNC_PIX, 'row']), int(p.at[JUNC_PIX, 'col']) hx, hy = int(np.ceil(HX / mx)) + 1, int(np.ceil(HY / my)) + 1 v = grid(rj - hy, rj + hy + 1, cj - hx, cj + hx + 1); a = np.abs(v); inb = (a >= LO) & (a <= HI) chp = inb & (v > 0) # every pixel of the window is in the basin; labels and the bar keep off its channel pixels chp_mt = np.vectorize(lambda n_: bool(n_ > 0) and Z['cls_n'](int(n_)) in ('main', 'trib'))(v) & inb rl = lambda n_: next((k_ for k_, (a0, a1) in Z['rng'].items() if a0 <= n_ <= a1), None) rgb = np.ones(v.shape + (3,)); to_rgb = matplotlib.colors.to_rgb for r_, c_ in zip(*np.nonzero(inb)): n_ = int(v[r_, c_]) rgb[r_, c_] = to_rgb({'main': C_MAIN, 'trib': C_TRIB, 'other': C_OTHER}[Z['cls_n'](n_)] if n_ > 0 else FILL.get(rl(-n_), F_OTHER)) ya = yt + (LOCH6 + GAP6 if k == 6 and LOC6 == 'above' else 0) # top of the window xw = X_ZOOM if k == 6 and LOC6 == 'left' else ML ax = fig.add_axes([xw / W, fy(ya + AH), AW_ / W, AH / H]); ax.set_xticks([]); ax.set_yticks([]) for sp in ax.spines.values(): sp.set_lw(0.8) ax.imshow(rgb, extent=(-(hx + 0.5) * mx, (hx + 0.5) * mx, -(hy + 0.5) * my, (hy + 0.5) * my), aspect='auto', interpolation='nearest', zorder=1) for q in range(-hx, hx + 2): ax.axvline((q - 0.5) * mx, color='white', lw=0.3, zorder=2) for q in range(-hy, hy + 2): ax.axhline((q - 0.5) * my, color='white', lw=0.3, zorder=2) pix = LABT if reach_only else {'below': JUNC_PIX, 'above': JUNC_PIX + 1, 'trib': TRIB_PIX} for kk in KEYS: # role over number, a leader from the label to the centre of its pixel n_ = pix[kk] if reach_only: assert int(R[kk].outlet_pixel_id) <= n_ <= int(R[kk].upstream_end_pixel_id), ('the leader goes to a pixel of another reach', kk) r_, c_ = int(p.at[n_, 'row']) - rj, int(p.at[n_, 'col']) - cj; assert int(v[hy + r_, hx + c_]) == n_, kk lab = [(ROLE[kk], BOLD), ('reach_seq_id', dict(color=T_GREY)), (num(R[kk].reach_id), {})] if reach_only else [(ROLE[kk], BOLD), (num(n_), {})] if k != 6 else [(ROLE[kk], BOLD), ('reach ' + num(R[kk].reach_id), {}), ('pixel ' + num(n_), {})] # the merged figure: both numbers xl, yl = LAB_[kk][1] * mx, -LAB_[kk][0] * my; xp, yp = c_ * mx, -r_ * my pad_ = 15 if reach_only else 30; tx_ = lambda kw_: {q: w for q, w in kw_.items() if q != 'color'} hw = max(text_inches(t_, FS, **tx_(kw_)) for t_, kw_ in lab) / 2 * mpi + pad_; hh = len(lab) / 2 * LH * mpi + pad_ qr, qc = np.arange(-hy, hy + 1), np.arange(-hx, hx + 1) # no label text over a channel pixel (k = 7: of the main stem or the tributary) box = np.ix_(np.abs(-qr * my - yl) <= hh + my / 2, np.abs(qc * mx - xl) <= hw + mx / 2) clear_ = chp_mt if reach_only else chp assert not clear_[box].any(), ('label over a channel pixel', kk, int(clear_[box].sum())) assert abs(xl) + hw <= HX and abs(yl) + hh <= HY, ('label outside the window', kk) dx, dy = xp - xl, yp - yl; s_ = min(hw / abs(dx) if dx else np.inf, hh / abs(dy) if dy else np.inf) x0_, y0_ = (min(max(xp, xl - hw), xl + hw), min(max(yp, yl - hh), yl + hh)) if k == 6 else (xl + s_ * dx, yl + s_ * dy) ax.plot([x0_, xp], [y0_, yp], color=INK[kk], lw=0.9, solid_capstyle='round', zorder=6, path_effects=[pe.withStroke(linewidth=2.4, foreground='white')]) for q_, (t_, kw_) in enumerate(lab): ax.text(xl, yl + ((len(lab) - 1) / 2 - q_) * LH * mpi, t_, fontsize=FS, ha='center', va='center', path_effects=HALO, zorder=7, **{**dict(color=INK[kk]), **kw_}) if k == 6: yb = -HY - 0.14 * mpi ax.plot([HX - 1000, HX], [yb, yb], color='black', lw=1.2, solid_capstyle='butt', zorder=8, clip_on=False) ax.text(HX - 1000 - 0.06 * mpi, yb, '1 km', fontsize=FS, ha='right', va='center', zorder=8, clip_on=False) xb1 = HX - 0.12 * mpi; yb = -HY + 0.22 * mpi # the 1 km bar, bottom right, outside the basin if k != 6: bx_ = np.ix_(np.abs(-qr * my - (yb + 0.05 * mpi + LH / 2 * mpi)) <= (LH / 2 + 0.05) * mpi + my / 2, (qc * mx >= xb1 - 1000 - mx) & (qc * mx <= xb1 + mx)) assert not chp[bx_].any(), 'the 1 km bar over a channel pixel' ax.plot([xb1 - 1000, xb1], [yb, yb], color='black', lw=1.2, solid_capstyle='butt', zorder=8) ax.text(xb1 - 500, yb + 0.05 * mpi, '1 km', fontsize=FS, ha='center', va='bottom', zorder=8, path_effects=HALO) ax.set_xlim(-HX, HX); ax.set_ylim(-HY, HY) D['window6'] = (v.shape, int(inb.sum())) def sw(x_, y_, fc_): fig.add_artist(Rectangle((x_ / W, fy(y_ + 0.07)), 0.13 / W, 0.14 / H, transform=fig.transFigure, fc=fc_, ec='none')) KEY = (((C_MAIN, C_TRIB, C_OTHER), 'channel pixel'), ((FILL['below'], FILL['above'], FILL['trib'], F_OTHER), 'hillslope pixel')) if k == 6 and LOC6 == 'left': draw_basin_left(fig, D, T, yt, AH, ax, KEY, sw); return AH if k == 6: # the merged figure: the whole basin under (or over) the window, the key beside it yl = yt if LOC6 == 'above' else ya + AH + GAP6 CW = max(AW_, text_inches('(a) The %s junction' % TRIB_NAME, FT, **BOLD)) # the column of (a), as wide as its title bw, s6 = draw_basin6(fig, D, yl, CW, ax) x0 = ML + bw + 0.14 if LOC6 == 'below': # key and 10 km bar at the right of the basin, under the dashed lines y = yl + 0.10 + LH / 2 for fcs, t_ in KEY: # the swatches over their name: "hillslope pixel" with four swatches is wider than the room for q_, fc_ in enumerate(fcs): sw(x0 + 0.15 * q_, y, fc_) T(x0, y + LH, t_); assert x0 + text_inches(t_, FS) <= ML + CW, t_ y += 2 * LH + 0.06 bar10(fig, x0, yl + LOCH6 - 0.10, ML + CW, s6) if LOC6 == 'below': return AH + GAP6 + LOCH6 y = ya + AH + 0.08 + LH / 2 # the basin over the window: the key under the window else: y = yt + AH + 0.08 + LH / 2 # the key under the window for fcs, t_ in KEY: for q_, fc_ in enumerate(fcs): sw(ML + 0.15 * q_, y, fc_) x = ML + 0.15 * 4 + 0.04; T(x, y, t_); assert x + text_inches(t_, FS) <= ML + AW_, t_ y += LH return ya - yt + AH + 0.08 + 2 * LH def draw_basin_left(fig, D, T, yt, ZH, ax_w, KEY, sw): """The whole region and its 10 km bar in the left column, as draw_window draws them in Figures A1-A3, centred in the room above the key; the window as a rectangle, dashed lines from its right side to the left side of the pixel window ax_w; the key at the bottom of the column.""" H = fig.get_figheight(); fy = lambda y: 1 - y / H j = D['zoom'].get('junction', D['zoom'].get('centre')); WB = (j.x - HALF_W, j.y - 1.5 * HALF_W, j.x + HALF_W, j.y + 1.5 * HALF_W) KH = 2 * (2 * LH + 0.06); ZB = ZH - KH # the key: two entries, the swatches over the name ax_l = fig.add_axes([ML / W, fy(yt + ZB), LOCW / W, ZB / H]); ax_l.set_axis_off() lp, ll = D['loc_poly'], D['loc_line'] if len(lp): lp.plot(ax=ax_l, color=[F_TRIB if b else F_OTHER for b in lp.trib], edgecolor='white', linewidth=0.2, aspect=None, rasterized=True) for sel, col, lw in ((~ll.main & ~ll.trib, C_OTHER, 0.25), (ll.trib, C_TRIB, 0.45), (ll.main, C_MAIN, 1.0)): if sel.any(): ll[sel].plot(ax=ax_l, color=col, linewidth=lw, aspect=None, rasterized=True) e = AREA.total_bounds; cx = 0.5 * (e[0] + e[2]); hw = 0.5 * (e[2] - e[0]) + 600; s_ = 2 * hw / LOCW # metres per inch, as in Figures 2-4 hb = (e[3] - e[1]) / s_ + 0.36; assert hb <= ZB, ('the basin, its bar and the key do not fit the column', hb, ZB) top_ = e[3] + 0.5 * (ZB - hb) * s_; ax_l.set_aspect('equal'); ax_l.set_xlim(cx - hw, cx + hw); ax_l.set_ylim(top_ - ZB * s_, top_) ax_l.add_patch(Rectangle((WB[0], WB[1]), WB[2] - WB[0], WB[3] - WB[1], fill=False, ec='black', lw=0.8, zorder=8)) yb = e[1] - 0.24 * s_; xb = cx - hw + 0.04 * s_ ax_l.plot([xb, xb + 50000], [yb, yb], color='black', lw=1.2, solid_capstyle='butt', clip_on=False) ax_l.text(xb + 50000 + 0.06 * s_, yb, '50 km', ha='left', va='center', fontsize=FS, clip_on=False, path_effects=HALO, zorder=10) assert 0.04 + 50000 / s_ + 0.06 + text_inches('50 km', FS) <= LOCW + 0.06, 'the 50 km label leaves the column' for ya_, yf in ((WB[3], 1.0), (WB[1], 0.0)): ax_l.add_artist(ConnectionPatch(xyA=(WB[2], ya_), coordsA=ax_l.transData, xyB=(0.0, yf), coordsB=ax_w.transAxes, clip_on=False, **{**ZOOM_LINE, 'zorder': 0.5})) y = yt + ZB + 0.06 + LH / 2 for fcs, t_ in KEY: for q_, fc_ in enumerate(fcs): sw(ML + 0.15 * q_, y, fc_) T(ML, y + LH, t_, path_effects=HALO); assert text_inches(t_, FS) <= LOCW + 0.06, t_ y += 2 * LH + 0.06 assert y - LH / 2 - 0.06 <= yt + ZH + 1e-9, 'the key leaves (a)' def bar10(fig, x0, y, xmax, s_): """The 10 km bar of the whole basin, its left end at x0 (in), at height y (in from the top), as in Figures 2-4.""" H = fig.get_figheight(); fy = lambda y_: 1 - y_ / H # s_: metres per inch of the basin fig.add_artist(matplotlib.lines.Line2D([x0 / W, (x0 + 50000 / s_) / W], [fy(y), fy(y)], color='black', lw=1.2, solid_capstyle='butt', transform=fig.transFigure)) fig.text((x0 + 50000 / s_ + 0.06) / W, fy(y), '50 km', fontsize=FS, color=T_DARK, ha='left', va='center') assert x0 + 50000 / s_ + 0.06 + text_inches('50 km', FS) <= xmax, 'the 50 km label leaves the column' def draw_basin6(fig, D, yl, CW, ax_w): """The merged figure: the whole basin, LOCH6 tall at the left of the column of (a), top at yl (in from the top); the window as a rectangle, dashed lines from it to the corners of the pixel window ax_w (drawn under the basin). Returns the width of the basin (in) and its metres per inch.""" H = fig.get_figheight(); fy = lambda y: 1 - y / H j = D['zoom'].get('junction', D['zoom'].get('centre')); WB = (j.x - HALF_W, j.y - 1.5 * HALF_W, j.x + HALF_W, j.y + 1.5 * HALF_W) e = AREA.total_bounds; s_ = (e[3] - e[1]) / (LOCH6 - 0.04); bw = (e[2] - e[0]) / s_ # metres per inch ax_l = fig.add_axes([ML / W, fy(yl + LOCH6), CW / W, LOCH6 / H]); ax_l.set_axis_off() lp, ll = D['loc_poly'], D['loc_line'] if len(lp): lp.plot(ax=ax_l, color=[F_TRIB if b else F_OTHER for b in lp.trib], edgecolor='white', linewidth=0.2, aspect=None, rasterized=True, zorder=1) for sel, col, lw in ((~ll.main & ~ll.trib, C_OTHER, 0.25), (ll.trib, C_TRIB, 0.45), (ll.main, C_MAIN, 1.0)): if sel.any(): ll[sel].plot(ax=ax_l, color=col, linewidth=lw, aspect=None, rasterized=True, zorder=2) x0, y1 = e[0] - 0.02 * s_, e[3] + 0.02 * s_ ax_l.set_aspect('equal'); ax_l.set_xlim(x0, x0 + CW * s_); ax_l.set_ylim(y1 - LOCH6 * s_, y1) ax_l.add_patch(Rectangle((WB[0], WB[1]), WB[2] - WB[0], WB[3] - WB[1], fill=False, ec='black', lw=0.8, zorder=8)) ya_, yf = (WB[1], 1.0) if LOC6 == 'above' else (WB[3], 0.0) for xa, xf in ((WB[0], 0.0), (WB[2], 1.0)): ax_l.add_artist(ConnectionPatch(xyA=(xa, ya_), coordsA=ax_l.transData, xyB=(xf, yf), coordsB=ax_w.transAxes, clip_on=False, **{**ZOOM_LINE, 'zorder': 0.5})) return bw, s_ # ================================================================ (c) def blocks(r): c = np.asarray(r['cls']) if r['kind'] == 'order' else np.array([r['cls_n'](int(q)) for q in r['present']]) return runs(c == 'main'), runs(c == 'trib') def strips_height(k, E): rows = ROWS[k]; h = 0.22 + 0.24 + 0.14 for i, (ri, _, _, wa) in enumerate(rows): h += (0.20 if wa and (i == 0 or k == 6) else 0) + (AH if wa else 0) + (0.12 if i and not wa else 0) + SH + 0.14 bs = [b for b in E['brackets'] if b[0] == ri] if bs: h += 0.24 + max([b[6] for b in bs if len(b) > 6] or [0]) return h + 0.30 def draw_strips(fig, D, k, y, T): H = fig.get_figheight(); fy = lambda y_: 1 - y_ / H; E = D['extra']; rows = ROWS[k] fig.add_artist(plt.Line2D([ML / W, (W - 0.10) / W], [fy(y)] * 2, color='#bbbbbb', lw=0.6)); y += 0.22 tc_, hb_ = '(c) Sorted by each number: is each color one block?', 'blocks' assert ML + text_inches(tc_, FT, **BOLD) + 0.15 <= XN1 - 0.5 * text_inches('main stem', FS, **BOLD), tc_ T(ML, y, tc_, fontsize=FT, **BOLD); T(0.5 * (XN1 + XN2), y, hb_, color=T_GREY, ha='center') x, yl = ML, y + 0.24 for lab, col in (('main stem', C_MAIN), ('%s with its tributaries' % TRIB_NAME, C_TRIB), ('other', C_STRIP)): fig.add_artist(plt.Line2D([x / W, (x + 0.24) / W], [fy(yl)] * 2, color=col, lw=4, solid_capstyle='butt')); T(x + 0.29, yl, lab); x += 0.45 + text_inches(lab, FS) fig.add_artist(Arc(((x + 0.12) / W, fy(yl + 0.05)), 0.24 / W, 0.24 / H, theta1=0, theta2=180, transform=fig.transFigure, color='#8a8a8a', lw=1.0)) fig.add_artist(plt.Line2D([(x + 0.24) / W], [fy(yl + 0.035)], marker='v', ms=4.2, mfc='#8a8a8a', mec='none', transform=fig.transFigure)) T(x + 0.30, yl, 'flows to'); x += 0.30 + text_inches('flows to', FS) assert x <= XN1 - 0.5 * text_inches('main stem', FS, **BOLD) - 0.08, 'the legend runs into the column heads: %.2f in' % x wm_, wt_ = text_inches('main stem', FS, **BOLD), text_inches('tributary', FS, **BOLD) assert XN2 - wt_ / 2 - (XN1 + wm_ / 2) >= 0.08 and XN2 + wt_ / 2 <= W - 0.05, (XN1, XN2, wm_, wt_) T(XN1, yl, 'main stem', color=T_MAIN, ha='center', **BOLD); T(XN2, yl, 'tributary', color=T_TRIB, ha='center', **BOLD) y = yl + 0.14 fmt = dict(zip(('kept', 'nv2', 'new'), D.get('codes', ()))) for i, (ri, field, what, wa) in enumerate(rows): r = D['rows'][ri] if wa: if i == 0 or k == 6: ylab = y + 0.08; y += 0.20 # the merged figure: each strip with arcs names its tributary arc ya = y; y += AH if i and not wa: y += 0.12 # room for the two-line label of a strip without arcs ys = y a = fig.add_axes([XS / W, fy(ys + SH), SW / W, SH / H]); a.set_axis_off(); a.set_ylim(0, 1) if r['kind'] == 'order': cl = r['cls']; n = len(cl); a.set_xlim(0, n) if r.get('cells'): w = r.get('w') or [1] * n; x0 = np.concatenate([[0], np.cumsum(w)]); a.set_xlim(0, x0[-1]) for q, c in enumerate(cl): a.add_patch(Rectangle((x0[q], 0), w[q], 1, fc=COL[c], ec='white', lw=1.0)) assert text_inches(r['cells'][q], FS, **BOLD) <= SW * w[q] / x0[-1] - 0.02, r['cells'][q] a.text(x0[q] + 0.5 * w[q], 0.47, r['cells'][q], fontsize=FS, color='white', ha='center', va='center', **BOLD) else: q = 0 while q < n: m = q while m + 1 < n and cl[m + 1] == cl[q]: m += 1 a.add_patch(Rectangle((q, 0), m - q + 1, 1, fc=COL[cl[q]], ec='none')); q = m + 1 else: pr = r['present'] if k == 1: # REACHCODE: its own axis, the codes present cl = [r['cls_n'](int(p_)) for p_ in pr]; n = len(cl); a.set_xlim(0, n); a.add_patch(Rectangle((0, 0), n, 1, fc=COL['other'], ec='none')) for pass_ in ('trib', 'main'): q = 0 while q < n: m = q while m + 1 < n and cl[m + 1] == cl[q]: m += 1 if cl[q] == pass_: a.add_patch(Rectangle((q, 0), m - q + 1, 1, fc=COL[pass_], ec=COL[pass_], lw=0.4)) q = m + 1 else: a.set_xlim(r['lo'] - 0.5, r['hi'] + 0.5); a.add_patch(Rectangle((r['lo'] - 0.5, 0), r['hi'] - r['lo'] + 1, 1, fc='#f4f4f4', ec='none')); q = 0 while q < len(pr): m = q; c = r['cls_n'](int(pr[q])) while m + 1 < len(pr) and pr[m + 1] == pr[m] + 1 and r['cls_n'](int(pr[m + 1])) == c: m += 1 a.add_patch(Rectangle((pr[q] - 0.5, 0), pr[m] - pr[q] + 1, 1, fc=COL[c], ec='none')); q = m + 1 if wa: A = E['arcsets'][ri] b = fig.add_axes([XS / W, fy(ya + AH), SW / W, AH / H]); b.set_axis_off(); b.set_ylim(0, 1) x0_, x1_ = (0, len(r['cls'])) if r['kind'] == 'order' else (r['lo'] - 0.5, r['hi'] + 0.5); b.set_xlim(x0_, x1_) def one(f_, t_, **kw): b.add_patch(Arc((0.5 * (f_ + t_), 0), abs(f_ - t_), 1.92 * np.sqrt(abs(f_ - t_) / float(x1_ - x0_)), theta1=0, theta2=180, **kw)) cl_of = (lambda p_: r['cls'][int(p_)]) if r['kind'] == 'order' else (lambda p_: r['cls_n'](int(p_))) pr_ = {'main': [], 'trib': [], 'other': []} for f_, t_ in A['pairs']: pr_[cl_of(f_)].append((f_, t_)) dr_ = [tuple(sorted(p_)) for p_ in pr_['main'] + pr_['trib']] nx_ = sum(1 for a0, a1 in dr_ for b0, b1 in dr_ if a0 < b0 < a1 < b1) print('crossing arc pairs, Figure %s row %d (%s): %d' % ({1: 'A1', 2: 'A2', 3: 'A3', 7: 'A4'}.get(k, '6'), ri, field, nx_)) for f_, t_ in pr_['main']: one(f_, t_, lw=0.6, color=C_MAIN, alpha=0.9) for f_, t_ in pr_['trib']: one(f_, t_, lw=0.6, color=C_TRIB, alpha=0.9) f_, t_ = A['hot']['trib'] if t_ >= 0: # a unit that drains to no unit has no arc one(f_, t_, lw=3.6, color='white', zorder=4.9); one(f_, t_, lw=1.8, color=C_TRIB, zorder=5) b.plot([t_], [0.035], marker='v', ms=5.5, mfc=C_TRIB, mec='white', mew=0.5, zorder=6, clip_on=False) else: assert i > 0, 'the first row must have the tributary arc' if i == 0 or k == 6: # the arc of the tributary element, named once (in the merged figure once per strip) span = abs(f_ - t_) / float(x1_ - x0_) xa_ = XS + SW * (0.5 * (f_ + t_) - x0_) / (x1_ - x0_); ya_ = ya + AH - AH * 0.96 * np.sqrt(span) t1, t2 = D['hot_rows'][ri] if k == 6 else D['hot'] sg = ((t1, T_TRIB), (' flows to ', T_GREY), (t2, T_MAIN)); tw = sum(text_inches(q_, FS) for q_, _ in sg) xt = min(max(xa_ - tw / 2, XS), W - 0.10 - tw) for q_, c_ in sg: T(xt, ylab, q_, color=c_); xt += text_inches(q_, FS) fig.add_artist(plt.Line2D([xa_ / W] * 2, [fy(ylab + 0.08), fy(ya_)], color=T_DARK, lw=0.6, zorder=20)) fmt2 = dict(fmt, n='{:,}'.format(int(next(s_ for s_ in (r['l1'].split(' ')[0], D['rows'][0]['l1'].split(' ')[0]) if s_.replace(',', '').isdigit()).replace(',', '')))) lab = what.format(**fmt2) assert text_inches(lab, FS) <= XS - ML - 0.04 and text_inches(field, FS, **BOLD) <= XS - ML - 0.04, lab T(ML, ys + SH / 2 - 0.085, field, **BOLD); T(ML, ys + SH / 2 + 0.095, lab, color=T_GREY) bk = blocks(r); T3.setdefault(k, {})[i] = bk; print('Table 3: Figure %d, %s: %d main-stem and %d tributary blocks' % (k + 1, field, bk[0], bk[1])) T(XN1, ys + SH / 2, str(bk[0]), fontsize=FT, color=T_MAIN, ha='center', **BOLD) T(XN2, ys + SH / 2, str(bk[1]) if bk[1] else '–', fontsize=FT, color=T_TRIB, ha='center', **BOLD) # a dash: no element of its own y = ys + SH; dmax = 0.0 for bi, x0b, x1b, words, col, ha, *dyw in E['brackets']: if bi != ri: continue dyw = dyw[0] if dyw else 0.0; dmax = max(dmax, dyw) xf = lambda v_: XS + SW * (v_ / len(r['cls']) if r['kind'] == 'order' else (v_ - (r['lo'] - 0.5)) / (r['hi'] - r['lo'] + 1)) xa, xb = xf(x0b), xf(x1b); yk = y + 0.05 fig.add_artist(plt.Line2D([xa / W, xa / W, xb / W, xb / W], [fy(yk - 0.035), fy(yk), fy(yk), fy(yk - 0.035)], color=col, lw=1.0)) tw = text_inches(words, FS); xl = {'left': xa, 'center': 0.5 * (xa + xb) - tw / 2}[ha] xl = max(XS, min(xl, W - 0.10 - tw)) T(xl, yk + 0.11 + dyw, words, color=col) if any(b[0] == ri for b in E['brackets']): y += 0.24 + dmax y += 0.14 T(XS, y + 0.02, 'smaller number', color=T_GREY); T(XE, y + 0.02, 'larger number', color=T_GREY, ha='right') xm = XS + text_inches('smaller number', FS) + 0.10; xm2 = XE - text_inches('larger number', FS) - 0.10 fig.add_artist(FancyArrowPatch((xm / W, fy(y + 0.02)), (xm2 / W, fy(y + 0.02)), transform=fig.transFigure, arrowstyle='-|>', mutation_scale=10, lw=0.8, color='#777777', shrinkA=0, shrinkB=0)) assert set(ARCS[k]) == {ri for ri, _, _, wa in rows if wa} return y + 0.16 # ================================================================ captions def caption(k, D): E = D['extra']; nrow = lambda i: '{:,}'.format(int(D['rows'][i]['l1'].split(' ')[0].replace(',', ''))) REG = ('the Clark Fork upstream of gauge 50 (Clark Fork below Missoula, GRDC 4115348; 23,306 km²), the region of Figures 8 and 10 and part of the ' 'Columbia River basin') if k == 1: lm, lt = E['lp'] # the leaders drawn are listed in D['leaders']; the paper's caption is written in the manuscript (a short one) assert set((D.get('leader_to') or {}).values()) <= {'catchment'}, D.get('leader_to') ld_ = [ROLE[q] for q in (D.get('leaders') or [])]; ld_ = ('' if not ld_ else ', and a line joins the label of the %s flowline to its unit catchment' % ld_[0] if len(ld_) == 1 else ', and lines join the labels of the %s flowlines to their unit catchments' % ' and '.join(ld_)) assert (lm, lt) == (1, 176), (lm, lt) # DataA1: LEVELPATHI values on the Clark Fork, on the Little Blackfoot with its tributaries return ('Figure A1. How NHDPlus V2 identifies the river network where the Little Blackfoot River joins the Clark Fork at Garrison, Montana (USA), in %s. ' '(a) The region, with the Clark Fork (the main stem) in blue and the Little Blackfoot River with its tributaries in orange, and a window of 3.2 km × 4.8 km ' 'centered on the junction (north up; the same window in Figures A2a–A4a) ' 'with the COMID and the unit catchment of each of the three flowlines that meet there (FEATUREID = COMID). The three flowlines are drawn thick and the ' 'other flowlines of the two rivers thin; their unit catchments are shaded medium blue (downstream), light blue (upstream) and orange (tributary)%s. ' '(b) The four design questions (rows) against the numberings of the product (columns): how the tree is stored (up- and downstream?), which branch ' 'continues the river (which river?), how land is attached to the network (which land?) and whether an identifier can name a point on a reach, such as a gauge ' '(which point?). A grey entry gives, in bold, the field that answers the question for the tributary flowline, with its value; a dash means that the numbering ' 'does not answer it. TOCOMID, in PlusFlow.dbf, is the COMID of the flowline downstream. HYDROSEQ, in PlusFlowlineVAA.dbf, is smaller downstream at every link; ' 'DNHYDROSEQ and UPHYDROSEQ hold the HYDROSEQ of the flowlines downstream and upstream on the main path. LEVELPATHI identifies a river by the HYDROSEQ of its most ' 'downstream flowline and is shared by every flowline of that river: one value on the main stem and %d on the Little Blackfoot River with its tributaries. ' 'REACHCODE, the code of a basin (HUC8) followed by a reach number, addresses a point together with a measure; FROMMEAS and TOMEAS give the measures, in percent ' 'along the reach, at the two ends of a flowline. FEATUREID, the identifier of a unit catchment in Catchment.shp, equals the COMID of its flowline in NHDFlowline.shp. ' '(c) The %s flowlines of the region in the order of COMID and of HYDROSEQ, and its %s reach codes in the order of REACHCODE, smaller numbers at left, colored as ' 'in (a) and grey otherwise. A set can be selected by two numbers only if its color forms one block; the columns at right give the number of blocks. Arcs join ' 'each flowline of the main stem and of the Little Blackfoot River with its tributaries to the flowline it flows to (arc height grows with span), and the thick ' 'arc is the link from the tributary flowline to the main stem. Crossing arcs mean that the numbers jump between branches. REACHCODE stores no downstream code, ' 'so its strip has no arcs.' % (REG, ld_, lt, nrow(0), '{:,}'.format(D['codes'][1]))) if k == 2: n12 = nrow(1); bm_, bt_ = T3[2][1]; ex_ = E['pfaf_example']; c7 = E['pfaf_trib'] assert set((D.get('leader_to') or {}).values()) <= {'reach'}, D.get('leader_to') ld2 = [ROLE[q] for q in (D.get('leaders') or [])]; ld2 = ('' if not ld2 else '; a line joins the label of the %s reach to it' % ld2[0] if len(ld2) == 1 else '; lines join the labels of the %s reaches to them' % ' and '.join(ld2)) assert (E['pfaf_prefix'], c7, ex_, E['n_trib_units'], bt_) == ('78266', '7826696', '782669601000', 9, 1), (E['pfaf_prefix'], c7, ex_, E['n_trib_units'], bt_) # DataA2 (Clark Fork) return ('Figure A2. As Figure A1, for HydroSHEDS v1. HYRIV_ID identifies a reach of HydroRIVERS and HYBAS_ID a sub-basin of HydroBASINS, whose PFAF_ID is its ' 'Pfafstetter code, with one digit per level: from level 4 on, the parts of a basin are numbered from the outlet up, with odd digits for the parts ' 'along its main stem and even digits for its four largest tributary basins, so 2 and 3 drain to 1, and a 0 marks a level at which a basin is not divided. (a) The HYRIV_ID of the three reaches at the ' 'junction, and, shaded, the level-12 sub-basin each lies in%s. (b) A reach stores the next reach downstream (NEXT_DOWN) and, in HYBAS_L12, the HYBAS_ID of the ' 'level-12 sub-basin it lies in, whose record gives the PFAF_ID. ORD_CLAS, the classical river order, shows which branch continues at a junction, but all rivers ' 'of an order share its value, so it does not identify a river. PFAF_ID tells, here, the tributary basin a reach lies in, but not the river it is on: the ' 'tributary reach lies in sub-basin %s, whose seventh digit, 6, is even, so it lies in the tributary basin %s, that of the Little Blackfoot River, ' 'as does a reach of any of its tributaries. This holds only because the Little Blackfoot is one of the four largest ' 'tributaries of basin %s; a tributary that is never among the four largest lies in a sub-basin with an odd digit, together with the main stem. A sub-basin ' 'stores the next sub-basin downstream in its own NEXT_DOWN. The reaches are in HydroRIVERS_*.shp and the sub-basins in hybas_*_lev12_*.shp; an asterisk in a ' 'file name, here and in Figure A3, stands for the part that varies with region, version or threshold. (c) The %s reaches of the region in the order ' 'of HYRIV_ID, and its %s level-12 sub-basins in the order of PFAF_ID, with the links between them (NEXT_DOWN of HydroBASINS). Every PFAF_ID of the region ' 'begins with %s, a level-5 basin, and the sub-basin at gauge 50 lies only partly in the region. The %d sub-basins of the Little Blackfoot all begin with %s ' 'and form one block. The main stem forms %d blocks: at every level the tributary basins are numbered between the parts of the main stem. HYRIV_ID arcs ' 'cross and PFAF_ID arcs only nest.' % (ld2, ex_, c7, c7[:-1], nrow(0), n12, E['pfaf_prefix'], E['n_trib_units'], c7, bm_)) if k == 3: ft, jn, nl = E['walk']; V = E['vals']; d0, f0 = int(V['DISCOVER_TIME']), int(V['FINISH_TIME']) lo_, do_, fo_ = E['outlet_link']; assert fo_ - do_ == nl and V['LINKNO_offset'] == '720,000,000' assert T3[3][1] == (ft + 1, 1), (T3[3][1], ft) # the main stem breaks at each junction where the search enters the tributary first print('TDX walk', E['walk'], 'blocks', T3[3][1], 'DISCOVER_TIME of the Little Blackfoot', d0, 'outlet link', E['outlet_link']) return ('Figure A3. As Figure A1, for TDX-Hydro with the nested set index of Haag and Shokoufandeh (2019) that Model My Watershed adds to it. LINKNO numbers a link, ' 'the reach of TDX-Hydro. Model My Watershed adds 72 × 10⁷, the header number of this region, to every LINKNO to make it unique worldwide, and LINKNO is shown ' 'with this addition. (a) The links at the junction with their LINKNO; unit-catchment polygons are not drawn. (b) A link stores the next link downstream ' '(DSLINKNO) and the two links that meet at its upstream end (USLINKNO1 and USLINKNO2), in TDX_streamnet_*.gpkg. Each unit-catchment polygon of TDX-Hydro, in ' 'TDX_streamreach_basins_*.gpkg, carries streamID, which equals the LINKNO of its link before the addition. DISCOVER_TIME, in TDX_streamreach_basins_*.parquet of ' 'Model My Watershed, is the time at which a depth-first search from the outlet link of a tree (ROOT_ID) reaches a link, and the link and the links upstream of it ' 'are those of the same ROOT_ID whose discovery time t satisfies DISCOVER_TIME ≤ t < FINISH_TIME. (c) The %s links of the region in the ' 'order of LINKNO and of DISCOVER_TIME. The region is not a tree of its own in TDX-Hydro: its links belong to the tree of the Columbia (ROOT_ID %s) and are ' 'the links upstream of its outlet link %s, DISCOVER_TIME [%s, %s). At every junction the search enters USLINKNO2 first, and USLINKNO2 never has the higher ' 'stream order. On the main stem USLINKNO2 is the tributary at %d of %d junctions, so the main stem breaks there into %d blocks; at the junction of the Little ' 'Blackfoot it is the Little Blackfoot, so this river is visited before the main stem above it and is one range, DISCOVER_TIME [%s, %s). LINKNO arcs cross; ' 'DISCOVER_TIME arcs only nest, as in any depth-first numbering.' % (num(nl), num(V['ROOT_ID']), num(lo_), num(do_), num(fo_), ft, jn, ft + 1, num(d0), num(f0))) rb, p, R, ridx = D['fn']; t = R['trib'] if k == 7: n_r = int(t.upstream_reach_id_max) - int(t.reach_id) + 1 assert n_r == 512 return ('Figure A4. As Figure A1, for the reaches of FlowNest on MERIT Hydro (3″, about 90 m; channel pixels at 1 km²). reach_seq_id numbers the reaches depth ' 'first from the basin outlet, the branch with the larger drainage area first. In FlowNest the region is not a basin of its own but part of the Columbia ' 'River basin (basin_id %s); the numbers are those of the global release. (a) At left, the region with the window as a rectangle; at right, the window of ' 'Figures A1a–A3a drawn pixel by pixel, each pixel about %.0f m wide and %.0f m tall. Channel pixels are dark (the main stem blue, the Little Blackfoot River ' 'with its tributaries orange, other rivers grey). Hillslope pixels are light, in the shade of the unit catchment they belong to (of the downstream, upstream ' 'and tributary reach, or of another reach); every pixel of the window lies in the region. The labels give the reach_seq_id of the three reaches that meet at ' 'the junction, and a line points to a channel pixel of each. (b) A reach stores the reach downstream (next_down_reach_seq_id) and the number of reaches ' 'upstream of it, itself included (upstream_reach_count, here %s), so the reaches upstream of it are that many consecutive numbers from its own reach_seq_id; ' 'the path it belongs to (path_seq_id, here the Little Blackfoot River); and its first channel pixel (downstream_end_pixel_seq_id) and the number of its ' 'channel pixels (channel_pixel_count), which are consecutive in pixel_seq_id. These are columns of the reach table (flownest_merit90m_reach_1km2.parquet); ' 'the polygons of the unit catchments (flownest_merit90m_unit_catchment_1km2.geo.parquet) and the reach raster (flownest_merit90m_reach_seq_id_1km2.tif) ' 'store reach_seq_id, the raster on channel pixels and its negative on hillslope pixels. In the file names, 1km2 stands for the channel threshold. ' '(c) The %s reaches of the region in the order of reach_seq_id. Within a path each reach flows to the reach numbered one less, which gives the short arcs; ' 'longer arcs appear only where one path joins another, and they only nest. One block for each set follows from how the numbers are made; it is not a ' 'measure of hydrological accuracy.' % ('{:,}'.format(BASIN), D['zoom']['mx'], D['zoom']['my'], num(n_r), num(len(rb)))) # ================================================================ the figure def draw(D, k): E = D['extra'] if k <= 4: cols = table(k, D); L = table_layout(cols, XB); ZH = 3.0 # every window 3.0 in tall: 4.8 km, as Figure 1c top_h = max(ZH, L[2] + sum(L[3])) else: k6 = 6 if k == 7 else k AW_ = AWM if k6 == 6 else AW6 cols = table(k, D); XB6 = max(ML + AW_, ML + text_inches('(a) The %s junction' % TRIB_NAME, FT, **BOLD)) + 0.18 if k6 == 6 and LOC6 == 'left': global QUES, PAD; XB6, QUES, PAD = XB, QUES_LEFT, 0.08 L = table_layout(cols, XB6) left_h = 1.5 * AW_ if k6 == 6 and LOC6 == 'left' else (1.5 * AW_ + GAP6 + LOCH6 + (0.08 + 2 * LH if LOC6 == 'above' else 0)) if k6 == 6 else 1.5 * AW_ + 0.08 + 2 * LH # (a): window, key (and the whole basin) top_h = max(left_h, L[2] + sum(L[3])) H = Y0 + top_h + 0.16 + strips_height(k, E) fig = plt.figure(figsize=(W, H)); fy = lambda y: 1 - y / H T = lambda x, y, s, **kw: fig.text(x / W, fy(y), s, **{**dict(fontsize=FS, color=T_DARK, ha='left', va='center'), **kw}) # ---- title: the product and the level of its numbers T(ML, 0.24, NAME[k], fontsize=13, va='baseline', **BOLD); x = ML + text_inches(NAME[k], 13, **BOLD) + 0.16 for tag in TAGS[k]: w_ = text_inches(tag, FS, **BOLD) + 0.16 fig.add_artist(Rectangle((x / W, fy(0.285)), w_ / W, 0.21 / H, transform=fig.transFigure, fc='#4a4a4a', ec='none')) T(x + w_ / 2, 0.18, tag, color='white', ha='center', **BOLD); x += w_ + 0.08 assert x <= W - 0.10 # ---- (a) xb_ = XB if k <= 4 else XB6 ta = '(a) The %s junction' % TRIB_NAME; assert ML + text_inches(ta, FT, **BOLD) <= xb_ - 0.10, ta T(ML, 0.56, ta, fontsize=FT, va='baseline', **BOLD) if k <= 4: draw_window(fig, D, k, Y0, ZH) else: h_a = draw_pixels(fig, D, T, Y0, k); assert abs(h_a - left_h) < 1e-9, (h_a, left_h) # ---- (b) tb = next(t_ for t_ in ('(b) Four questions for the tributary %s' % UNIT[k], '(b) The tributary %s: four questions' % UNIT[k], '(b) Four questions') if xb_ + text_inches(t_, FT, **BOLD) <= W - 0.10) T(xb_, 0.56, tb, fontsize=FT, va='baseline', **BOLD) draw_table(fig, T, cols, xb_, Y0 - 0.04, L) # ---- (c) y_end = draw_strips(fig, D, k, Y0 + top_h + 0.16, T); assert abs(y_end - H) < 0.35, (y_end, H) if k <= 4: print('Figure %d: leaders to' % (k + 1), D.get('leaders')) save(fig, k, H, caption(k, D)) if __name__ == '__main__': for k in [int(a) for i, a in enumerate(sys.argv[1:], 1) if a.isdigit() and len(a) == 1 and sys.argv[i - 1] not in ('--ver', '--draft')] or [1, 2, 3, 7]: assert k in (1, 2, 3, 7), 'k = 1, 2, 3, 7 are Figures A1-A4' draw(load(k), k)