# -*- coding: utf-8 -*- """Figure 11: the SWORD reaches on the globe (a) and the rows of the reach and node crosswalks. Input: ../Data (Data06m), the SWORD crosswalk (paths.SWORD_XW) and metadata.json of the global release (paths.GLOBAL). Output: ../Figures: png and pdf. Usage: python Fig11_global_sword_reaches_and_crosswalk_table.py """ import os, re, glob, json, hashlib os.environ.setdefault('OMP_NUM_THREADS', '1') import numpy as np, pandas as pd, rasterio, pyarrow.parquet as pq import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patheffects as pe import matplotlib.colors as mcolors from matplotlib.patches import Rectangle from matplotlib.font_manager import FontProperties from matplotlib.textpath import text_to_path import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH FS, FT = 10, 12 plt.rcParams.update({'pdf.fonttype': 42, 'ps.fonttype': 42, 'font.family': 'sans-serif', 'font.sans-serif': ['Helvetica', 'Arial'], 'font.size': FS, 'mathtext.default': 'regular'}) BOLD = dict(fontfamily='Arial', fontweight='bold') T_DARK, T_GREY = '#1f1f1f', '#555555' NOG = np.array(mcolors.to_rgb('#d9d9d9')) # land with no SWORD reach downstream HEAD_C, ALT = '#1F4E79', '#f7f7f7'; ELL = '…' def text_inches(text, fontsize, **kw): return text_to_path.get_text_width_height_descent(text, FontProperties(family=kw.get('fontfamily'), weight=kw.get('fontweight'), size=fontsize), False)[0] / 72 num = lambda v: '{:,}'.format(int(round(v))) HERE = os.path.dirname(os.path.abspath(__file__)); DATD = os.path.join(os.path.dirname(HERE), 'Data'); FIGD = os.path.join(os.path.dirname(HERE), 'Figures') XWD = PTH.SWORD_XW # ================================================================ the files, and every number checked R = pd.read_parquet(os.path.join(XWD, 'flownest_merit90m_crosswalk_sword_v17c_reach.parquet')) FN_META = os.path.join(PTH.GLOBAL, 'metadata.json') assert json.load(open(os.path.join(XWD, 'metadata.json')))['code_version'] == '10.66' assert json.load(open(os.path.join(XWD, 'metadata.json')))['release']['metadata_sha256'] == hashlib.sha256(open(FN_META, 'rb').read()).hexdigest() NREACH, NCOL = len(R), len(R.columns) assert NREACH == 248673 NUMB = R[R.sword_reach_seq_id > 0].sort_values('sword_reach_seq_id').reset_index(drop=True) assert len(NUMB) == 240111 and (NUMB.sword_reach_seq_id.values == np.arange(1, 240112)).all() assert (R.sword_reach_seq_id == 0).sum() == 8562 and (R[R.sword_reach_seq_id == 0].nodes_placed == 0).all() assert (R.matched_at_step != 'not_matched').sum() == 236613 LAST = NUMB.sword_reach_seq_id + NUMB.upstream_sword_reach_count - 1 J = json.load(open(os.path.join(DATD, 'Data06m_sword_reach_land_summary.json'))) assert J['release'] == PTH.SWORD_XW_NAME and J['reaches_numbered'] == 240111 OUTER = np.r_[True, NUMB.sword_reach_seq_id.values[1:] > np.maximum.accumulate(LAST.values)[:-1]] # in no range of a reach numbered before it with rasterio.open(os.path.join(DATD, 'Data06m_sword_reach_land_globe_005deg.tif')) as r_: GN, TG = r_.read(1), r_.transform assert GN.shape == (2900, 7200) and np.allclose((TG.a, TG.c, TG.e, TG.f), (0.05, -180.0, -0.05, 85.0), atol=1e-9) assert GN.max() <= 240111 and GN.min() == -2 # the share of land with no SWORD reach downstream, again from the raster (cell areas on the WGS84 ellipsoid, as Data06m) A_WGS, F_WGS = 6378137.0, 1 / 298.257223563; E2 = F_WGS * (2 - F_WGS); E1 = np.sqrt(E2) _q = lambda la: np.sin(np.radians(la)) / (1 - E2 * np.sin(np.radians(la)) ** 2) + np.log((1 + E1 * np.sin(np.radians(la))) / (1 - E1 * np.sin(np.radians(la)))) / (2 * E1) le = 85 - 0.05 * np.arange(2901); rk = A_WGS ** 2 * (1 - E2) / 2 * np.radians(0.05) * np.abs(_q(le[:-1]) - _q(le[1:])) / 1e6 AREA = np.repeat(rk[:, None], 7200, axis=1) OWN = 100 * AREA[GN > 0].sum() / AREA[GN >= 0].sum() assert round(OWN, 2) == J['share_of_land_pct'] == 70.68, OWN NONE = 100 - OWN # ---- (a) the river systems named: outlet SWORD reach, its expected position (lon, lat), and where the label goes (as in Figure 9) NAMED = {'Mackenzie': (82100700035, (-136.1, 68.9), -125, 66), 'Columbia': (78210000025, (-123.3, 46.2), -150, 30), 'Mississippi': (74300100016, (-89.4, 29.0), -88, 40), 'Amazon': (62305000175, (-50.8, -0.5), -62, -5), 'Paraná': (64300000016, (-58.4, -34.0), -58, -28), 'Danube': (22609000016, (29.7, 45.2), 18, 48), 'Nile': (17300000296, (30.4, 31.4), 30, 20), 'Congo': (13211000016, (12.6, -6.0), 22, -4), 'Ob': (31310000045, (69.8, 66.5), 73, 60), 'Lena': (34100000025, (129.0, 72.0), 127, 67), 'Yangtze': (43309000105, (121.1, 31.8), 105, 30), 'Murray': (56510000016, (138.9, -35.5), 143, -28)} NODE = pq.read_table(os.path.join(XWD, 'flownest_merit90m_crosswalk_sword_v17c_node.parquet'), columns=['sword_reach_id', 'sword_lon', 'sword_lat'], filters=[('sword_reach_id', 'in', [v[0] for v in NAMED.values()])]).to_pandas() RNG = {} for name, (rid, (x_, y_), lx_, ly_) in NAMED.items(): r = R[R.sword_reach_id == rid].iloc[0]; d = NODE[NODE.sword_reach_id == rid] assert abs(d.sword_lon.mean() - x_) < 0.3 and abs(d.sword_lat.mean() - y_) < 0.3, (name, d.sword_lon.mean(), d.sword_lat.mean()) first, last = int(r.sword_reach_seq_id), int(r.sword_reach_seq_id + r.upstream_sword_reach_count - 1) assert OUTER[first - 1], name # an outermost range: no SWORD reach downstream RNG[name] = (first, last) print('ranges:', RNG) # ---- (b) the rows shown, and the link to Figure 10 ROWS = [1, 226283, 226682, 226683] S = NUMB.set_index('sword_reach_seq_id', drop=False) assert S.loc[226283].sword_reach_id == 78210000025 and S.loc[226283].upstream_sword_reach_count == 1067 and S.loc[226283].basin_id == 32 # the Columbia outlet reach assert S.loc[226682].sword_reach_id == 78266700011 and S.loc[226682].upstream_sword_reach_count == 32 # the Clark Fork reach at gauge 50 (Figures 8, 10) UNN = R[R.sword_reach_id == 11544000051].iloc[0]; assert UNN.sword_reach_seq_id == 0 and UNN.matched_at_step == 'not_matched' and UNN.nodes_placed == 0 COLS = ['sword_reach_id', 'sword_reach_seq_id', 'upstream_sword_reach_count', 'basin_id', 'path_seq_id_1km2', 'most_downstream_pixel_seq_id', 'nodes_placed'] assert all(c in R.columns for c in COLS) assert S.loc[226683].sword_reach_id == 78266700021 and S.loc[226683].upstream_sword_reach_count == 25 # the reach of Figure 10c # ---- (c) the node crosswalk: the rows shown, chosen as in (b) NCOLS = ['sword_node_id', 'sword_node_seq_id', 'upstream_sword_node_count', 'sword_reach_id', 'pixel_seq_id', 'distance_to_pixel_m', 'placed_by'] ND = pq.read_table(os.path.join(XWD, 'flownest_merit90m_crosswalk_sword_v17c_node.parquet'), columns=NCOLS).to_pandas() NNODE = int((ND.sword_node_seq_id > 0).sum()) assert len(ND) == 11112454 and NNODE == 10729230 assert (np.sort(ND.sword_node_seq_id.values[ND.sword_node_seq_id.values > 0]) == np.arange(1, NNODE + 1)).all() # 1..N without gaps NS = ND[ND.sword_node_seq_id > 0].set_index('sword_node_seq_id', drop=False) NROWS = [1, 10089242, 10106889, 10106890] q = NS.loc[10089242] # the most downstream node of the Columbia: on reach 226,283 assert q.sword_reach_id == 78210000025 and q.upstream_sword_node_count == 48029 and q.placed_by == 'continued_from_neighbor' assert NS.loc[10089241].sword_reach_id != 78210000025 and NS.loc[10089241].sword_node_seq_id + NS.loc[10089241].upstream_sword_node_count <= 10089242 q = NS.loc[10106889]; assert q.sword_node_id == 78266700020721 and q.sword_reach_id == 78266700021 and q.upstream_sword_node_count == 972 q = NS.loc[10106890]; assert q.sword_node_id == 78266900090011 and q.sword_reach_id == 78266900091 and q.upstream_sword_node_count == 365 UNP = ND[ND.sword_reach_id == UNN.sword_reach_id].sort_values('sword_node_id') assert len(UNP) == 33 and (UNP.sword_node_seq_id == 0).all() and (UNP.pixel_seq_id == 0).all() and UNP.distance_to_pixel_m.isna().all() UNP = UNP.iloc[0]; assert UNP.sword_node_id == 11544000050011 and UNP.placed_by == '' print('all checks passed; %d columns in the release' % NCOL) # ================================================================ layout (inches from the top left) W = 7.48; ML = 0.08 AX0 = 0.62; AX1 = W - 0.10 MW = AX1 - AX0; MH = MW * 145 / 360 TA = 0.22; MY0 = TA + 0.12; TB = MY0 + MH + 0.70; TY0 = TB + 0.12 RH = 0.205; TW = W - 2 * ML; EW = 0.22 def wrap(name, width): parts = name.split('_'); lines = [parts[0]] for p in parts[1:]: if text_inches(lines[-1] + '_' + p, FS, **BOLD) + 0.10 <= width: lines[-1] += '_' + p else: lines[-1] += '_'; lines.append(p) return lines def cell_text(c, v): if c in ('sword_reach_id', 'sword_node_id'): # an id of another dataset: written as SWORD writes it return '%d' % v if c == 'distance_to_pixel_m': return '' if pd.isna(v) else '%.1f' % v # empty in the file for a node not placed if c in ('matched_at_step', 'placed_by'): return str(v) return num(v) def rows_body(rows, D, cols, last): # "…" between rows that do not follow each other, and before the last row body = [] for k, g in enumerate(rows): if k and g - rows[k - 1] > 1: body.append(None) body.append([cell_text(c, D.loc[g][c]) for c in cols]) return body + [None, [cell_text(c, last[c]) for c in cols]] def min_width(c, maxl): w = max(text_inches(p + '_', FS, **BOLD) for p in c.split('_')) + 0.10 while len(wrap(c, w)) > maxl: w += 0.01 return w def widths(cols, body): need = [max(text_inches(r[j], FS) if r[j] else 0 for r in body if r) + 0.06 for j in range(len(cols))] # the columns are then widened to the full width token = [min_width(c, 2) for c in cols] base = [max(a, b) for a, b in zip(need, token)] assert sum(base) <= TW - EW, sum(base) CW = [b + (TW - EW - sum(base)) * b / sum(base) for b in base] HEAD = [wrap(c, w) for c, w in zip(cols, CW)] return CW, HEAD, 0.10 + 0.19 * max(len(h) for h in HEAD) BODY_R = rows_body(ROWS, S, COLS, UNN); CW_R, HEAD_R, HH_R = widths(COLS, BODY_R) NSHOW = [c for c in NCOLS if c != 'placed_by'] BODY_N = rows_body(NROWS, NS, NSHOW, UNP); CW_N, HEAD_N, HH_N = widths(NSHOW, BODY_N) TC = TY0 + HH_R + RH * len(BODY_R) + 0.42; TZ0 = TC + 0.12 # (c): title and table H = TZ0 + HH_N + RH * len(BODY_N) + 0.10 assert H * 25.4 <= 230, H * 25.4 fig = plt.figure(figsize=(W, H)) A = fig.add_axes([0, 0, 1, 1]); A.set_xlim(0, W); A.set_ylim(H, 0); A.set_axis_off(); A.set_zorder(5) T_ = lambda x, y, s, **kw: A.text(x, y, s, **{**dict(fontsize=FS, color=T_DARK, ha='left', va='baseline'), **kw}) def title(x, y, a, limit): assert x + text_inches(a, FT, **BOLD) <= limit, a T_(x, y, a, fontsize=FT, **BOLD) # ================================================================ (a) the globe, sampled at the pixels of the printed map title(ML, TA, '(a) Unit catchment of each SWORD reach', W - 0.05) NX, NY = int(round(MW * 300)), int(round(MH * 300)) lon = -180 + (np.arange(NX) + .5) * 360 / NX; lat = 85 - (np.arange(NY) + .5) * 145 / NY col = np.floor((lon + 180) / 0.05).astype(int); row = np.floor((85 - lat) / 0.05).astype(int) V = GN[row[:, None], col[None, :]].astype(np.int64) V[V == -1] = 0 # land not numbered: drawn as land with no SWORD reach downstream PAL = mcolors.hsv_to_rgb(np.stack([np.linspace(0, 1, 100, endpoint=False), np.full(100, .65), np.full(100, .85)], 1)) # FullBasin: distinct_colors(100) rgb = np.ones((NY, NX, 3)); rgb[V == 0] = NOG g_ = V > 0; rgb[g_] = PAL[(V[g_] * 37) % 100] # 37: consecutive numbers far apart on the colour wheel # between reaches, so the colours stay visible; a sample's system is the outermost range holding its reach number SYS0 = NUMB.sword_reach_seq_id.values[OUTER] SYS = np.where(V > 0, SYS0[np.searchsorted(SYS0, np.clip(V, 1, None), side='right') - 1], V) edge = np.zeros((NY, NX), bool) edge[:, :-1] |= SYS[:, :-1] != SYS[:, 1:]; edge[:-1, :] |= SYS[:-1, :] != SYS[1:, :] edge &= ~((V == -2) & np.roll(V == -2, -1, 1) & np.roll(V == -2, -1, 0)) # no lines in the sea rgb[edge] = 0.0 ax = fig.add_axes([AX0 / W, 1 - (MY0 + MH) / H, MW / W, MH / H]) ax.imshow(rgb, extent=(-180, 180, -60, 85), interpolation='none', aspect='auto') ax.set_xlim(-180, 180); ax.set_ylim(-60, 85) ax.set_xticks(np.arange(-180, 181, 60)); ax.set_yticks(np.arange(-60, 86, 30)) ax.set_xticks(np.arange(-180, 181, 30), minor=True); ax.set_yticks(np.arange(-60, 86, 15), minor=True) ax.grid(which='major', linestyle='--', linewidth=0.4, alpha=0.6, color='#555555'); ax.grid(which='minor', linestyle=':', linewidth=0.3, alpha=0.5, color='#555555') ax.tick_params(axis='both', which='major', labelsize=FS, length=4, width=0.8); ax.tick_params(axis='both', which='minor', length=2, width=0.6) ax.set_xticklabels(['%d°%s' % (abs(v), 'W' if v < 0 else ('E' if v > 0 else '')) for v in range(-180, 181, 60)]) ax.get_xticklabels()[0].set_ha('left'); ax.get_xticklabels()[-1].set_ha('right') ax.set_yticklabels(['%d°%s' % (abs(v), 'S' if v < 0 else ('N' if v > 0 else '')) for v in range(-60, 86, 30)]) ax.set_xlabel('Longitude', fontsize=FS, **BOLD, labelpad=2); ax.set_ylabel('Latitude', fontsize=FS, **BOLD, labelpad=2) for s_ in ax.spines.values(): s_.set_linewidth(0.8) STROKE = [pe.withStroke(linewidth=2.2, foreground='black')] LAB = [] for name, (rid, (x_, y_), lx_, ly_) in NAMED.items(): a, b = RNG[name] LAB.append(ax.text(lx_, ly_, '%s\n%s–%s' % (name, num(a), num(b)), fontsize=FS, color='white', ha='center', va='center', linespacing=1.0, path_effects=STROKE, zorder=6, **BOLD)) if name == 'Columbia': # the basin of Figure 10 is small: the label lies in the Pacific ax.annotate('', (x_, y_), (lx_ + 20, ly_ + 8.5), arrowprops=dict(arrowstyle='-', color='black', lw=0.8), zorder=5) kx, ky = -176, -34 ax.add_patch(Rectangle((kx, ky - 2.6), 9, 5.2, fc=NOG, ec='black', lw=0.4, zorder=6)) LAB.append(ax.text(kx + 12, ky, 'no SWORD reach\ndownstream', fontsize=FS, va='center', ha='left', zorder=6, linespacing=1.0, path_effects=[pe.withStroke(linewidth=2, foreground='white')])) fig.canvas.draw(); rd = fig.canvas.get_renderer() BB = [t.get_window_extent(rd) for t in LAB] for i in range(len(BB)): # no two labels overlap, and all lie inside the map assert ax.get_window_extent(rd).contains(BB[i].x0, BB[i].y0) and ax.get_window_extent(rd).contains(BB[i].x1, BB[i].y1), LAB[i].get_text() for j in range(i): assert not BB[i].overlaps(BB[j]), (LAB[i].get_text(), LAB[j].get_text()) # ================================================================ (b) and (c) the tables def cell(x, y, w, h, s, fc, **kw): A.add_patch(Rectangle((x, y), w, h, fc=fc, ec='black', lw=0.6, zorder=2)) if s: T_(x + w / 2, y + h / 2, s, ha='center', va='center', zorder=3, **kw) def table(ty, cols, CW, HEAD, HH, body): # bold: the new number (second column) X0 = [ML + sum(CW[:j]) for j in range(len(cols) + 1)] for j, (c, lines) in enumerate(zip(cols, HEAD)): cell(X0[j], ty, CW[j], HH, '\n'.join(lines), HEAD_C, color='white', linespacing=1.25, **BOLD) cell(X0[-1], ty, EW, HH, ELL, HEAD_C, color='white', **BOLD) for i, r in enumerate(body): y = ty + HH + RH * i; fc = ALT if i % 2 else 'white' for j in range(len(cols)): s = ELL if r is None else r[j] bold = r is not None and j == 1 cell(X0[j], y, CW[j], RH, s, fc, **(BOLD if bold else {})) cell(X0[-1], y, EW, RH, ELL, fc) title(ML, TB, '(b) SWORD reach crosswalk', W - 0.05) table(TY0, COLS, CW_R, HEAD_R, HH_R, BODY_R) title(ML, TC, '(c) SWORD node crosswalk', W - 0.05) table(TZ0, NSHOW, CW_N, HEAD_N, HH_N, BODY_N) def save(fig, stem): used = [int(m.group(1)) for m in (re.search(r'_v(\d+)\.(png|pdf)$', f) for f in glob.glob(os.path.join(FIGD, stem + '_v*'))) if m] out = os.path.join(FIGD, '%s_v%d.png' % (stem, 1 + max(used or [0]))) fig.savefig(out, dpi=300, facecolor='white'); fig.savefig(out[:-4] + '.pdf', facecolor='white', dpi=300); plt.close(fig) print(out, 'and .pdf; %.0f x %.0f mm' % (W * 25.4, H * 25.4)) save(fig, 'Fig11_global_sword_reaches_and_crosswalk_table')