# -*- coding: utf-8 -*- """Figure 9: the GRDC gauges on the globe and the rows of the gauge crosswalk. Input: ../Data (Data06c, Data06e, Data19), the GRDC crosswalk (paths.GRDC_XW) and metadata.json of the global release (paths.GLOBAL). Output: ../Figures: png and pdf. Usage: python Fig09_global_gauges_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 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 gauge 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__)); PLOT = os.path.dirname(os.path.dirname(HERE)) DATD = os.path.join(os.path.dirname(HERE), 'Data'); FIGD = os.path.join(os.path.dirname(HERE), 'Figures') REL = os.path.join(PTH.GRDC_XW, 'flownest_merit90m_crosswalk_grdc_burek2023.parquet') # ================================================================ the files, and every number checked assert json.load(open(os.path.join(os.path.dirname(REL), 'metadata.json')))['code_version'] == '10.66' assert json.load(open(os.path.join(os.path.dirname(REL), 'metadata.json')))['release']['metadata_sha256'] == hashlib.sha256(open(os.path.join(PTH.GLOBAL, 'metadata.json'), 'rb').read()).hexdigest(), 'the package is made on _20261113_195421' R = pd.read_parquet(REL).sort_values('station_seq_id').reset_index(drop=True) assert len(R) == 10241 and (R.station_seq_id.values == np.arange(1, 10242)).all() T = pd.read_csv(os.path.join(DATD, 'Data06c_grdc_gauges.csv')).sort_values('station_seq_id').reset_index(drop=True) # The GRDC crosswalk (_20261113_195421) writes it so (checked next); Data06c writes 0 there (as the figure scripts read it), so the rule is applied to it here. assert (R.next_down_station_seq_id > 0).all() for D in (R, T): nd, sq = D.next_down_station_seq_id.values, D.station_seq_id.values end = (nd == 0) | (nd == sq) # 0 in Data06c, itself in the release assert (sq > 0).all() and end.sum() == 2392, end.sum() # 2,392 gauges with no gauge downstream D['next_down_station_seq_id'] = np.where(end, sq, nd) for c in ('grdc_station_id', 'pixel_seq_id', 'basin_id', 'next_down_station_seq_id', 'upstream_station_count'): assert (T[c].values == R[c].values).all(), c # the map data and the release agree LAST = R.station_seq_id + R.upstream_station_count - 1 # a gauge and the gauges upstream: station_seq_id to LAST dn = dict(zip(R.station_seq_id, R.next_down_station_seq_id)) inside = 0 for g in dn: # every gauge lies in the range of each gauge downstream of it c = g while dn[c] != c: # stop at a gauge that points to itself h = dn[c]; assert h < g <= LAST[h - 1]; inside += 1; c = h assert inside == 52341 with rasterio.open(os.path.join(DATD, 'Data06e_grdc_gauge_number_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) LAND = json.load(open(os.path.join(DATD, 'Data19_release_totals.json')))['land_km2'] NONE = 100 - 100 * T.own_area_km2.sum() / LAND # the land of all gauges, against all numbered land assert round(NONE, 1) == 42.9, NONE # ---- (a) the rivers named: outlet gauge (station_seq_id), GRDC station id, a point near the outlet gauge (lon, lat), and where the label goes NAMED = {'Mackenzie': (9775, 4208025, -126, 64), 'Columbia': (9374, 4115201, -147, 38), 'Mississippi': (8605, 4127930, -96, 39), 'Amazon': (7182, 3629001, -62, -5), 'Paraná': (7618, 3265601, -58, -27), 'Danube': (1878, 6742900, 22, 47), 'Nile': (1460, 1362100, 30, 21), 'Congo': (917, 1147013, 22, -2), 'Ob': (4431, 2912600, 70, 60), 'Lena': (5337, 2903430, 124, 63), 'Yangtze': (5807, 2181900, 106, 31), 'Murray': (6780, 5404271, 142, -29)} for name, (g, grdc, lx_, ly_) in NAMED.items(): r = R.iloc[g - 1] assert r.grdc_station_id == grdc and r.next_down_station_seq_id == g, name # an outlet gauge: no gauge downstream, points to itself print('ranges:', {n: (g, int(LAST[g - 1])) for n, (g, *_) in NAMED.items()}) # ---- (b) the rows shown, and the link to Figure 8 ROWS = [1, 2, 9374, 9375, 9423, 9424, 10240, 10241] c0 = R.iloc[9373]; c1 = R.iloc[9422] assert c0.basin_station_seq_id == 1 and c0.grdc_station_id == 4115201 and c0.upstream_station_count == 174 assert c1.basin_station_seq_id == 50 and c1.grdc_station_id == 4115348 and c1.upstream_station_count == 6 # gauge 50 of Figure 8, and 51-55 COLS = ['station_seq_id', 'basin_station_seq_id', 'grdc_station_id', 'pixel_seq_id', 'upstream_area_km2', 'basin_id', 'next_down_station_seq_id', 'upstream_station_count'] assert len(R.columns) == 19 and all(c in R.columns for c in COLS) print('all checks passed') # ================================================================ layout (inches from the top left) W = 7.48; ML = 0.08 AX0 = 0.62; AX1 = W - 0.10 # the map axes, room on the left for the latitudes MW = AX1 - AX0; MH = MW * 145 / 360 TA = 0.22; MY0 = TA + 0.12; TB = MY0 + MH + 0.70; TY0 = TB + 0.12 # ---- (b) the table: the column widths from the widest text, the header wrapped at underscores to fit 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 == 'upstream_area_km2': return '{:,.1f}'.format(v) if c == 'grdc_station_id': # an id of another dataset: written as GRDC writes it return '%d' % v return num(v) body = [] for k, g in enumerate(ROWS): if k and g - ROWS[k - 1] > 1: body.append(None) body.append([cell_text(c, R.iloc[g - 1][c]) for c in COLS]) TW = W - 2 * ML; EW = 0.30 # the last column: "…", more columns need = [max(text_inches(r[j], FS) for r in body if r) + 0.16 for j in range(len(COLS))] token = [max(text_inches(p + '_', FS, **BOLD) for p in c.split('_')) + 0.12 for c in COLS] base = [max(a, b) for a, b in zip(need, token)] CW = [b + (TW - EW - sum(base)) * b / sum(base) for b in base] # the spare width shared in proportion assert sum(base) <= TW - EW, sum(base) HEAD = [wrap(c, w) for c, w in zip(COLS, CW)] NL = max(len(h) for h in HEAD); RH = 0.215; HH = 0.10 + 0.19 * NL H = TY0 + HH + RH * len(body) + 0.10 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): # one line, bold; the rest is in the caption 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 gauge', 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 == 65534] = 0 # land not numbered: drawn as land with no gauge 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) & (V < 65535); rgb[g_] = PAL[(V[g_] * 37) % 100] # 37: consecutive numbers far apart on the colour wheel edge = np.zeros((NY, NX), bool) edge[:, :-1] |= V[:, :-1] != V[:, 1:]; edge[:-1, :] |= V[:-1, :] != V[1:, :] edge &= ~((V == 65535) & np.roll(V == 65535, -1, 1) & np.roll(V == 65535, -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')] for name, (g, grdc, lx_, ly_) in NAMED.items(): r = R.iloc[g - 1] ax.text(lx_, ly_, '%s\n%s–%s' % (name, num(g), num(LAST[g - 1])), fontsize=FS, color='white', ha='center', va='center', linespacing=1.0, path_effects=STROKE, zorder=6, **BOLD) if name == 'Columbia': # the basin of Figure 8 is small: the label lies in the Pacific ax.annotate('', (r.grdc_lon, r.grdc_lat), (lx_ + 9, ly_ + 3.5), arrowprops=dict(arrowstyle='-', color='black', lw=0.8), zorder=5) # the key, in the South Pacific kx, ky = -176, -38 ax.add_patch(Rectangle((kx, ky - 2.6), 9, 5.2, fc=NOG, ec='black', lw=0.4, zorder=6)) ax.text(kx + 12, ky, 'no gauge downstream', fontsize=FS, va='center', ha='left', zorder=6, linespacing=1.0, path_effects=[pe.withStroke(linewidth=2, foreground='white')]) # ================================================================ (b) the table title(ML, TB, '(b) GRDC crosswalk', W - 0.05) 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) X0 = [ML + sum(CW[:j]) for j in range(len(COLS) + 1)] for j, (c, lines) in enumerate(zip(COLS, HEAD)): cell(X0[j], TY0, CW[j], HH, '\n'.join(lines), HEAD_C, color='white', linespacing=1.25, **BOLD) cell(X0[-1], TY0, EW, HH, ELL, HEAD_C, color='white', **BOLD) for i, r in enumerate(body): y = TY0 + 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 == 0 cell(X0[j], y, CW[j], RH, s, fc, **(BOLD if bold else {})) cell(X0[-1], y, EW, RH, ELL, fc) 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, 'Fig09_global_gauges_and_crosswalk_table')