"""Figure 6: how to use the files. (a) the files of the release by format; (b) the raster route and the vector route to the catchment of reach 65,454,196 (the Little Blackfoot). Input: the global release (paths.GLOBAL). Output: ../Figures (with --final) or ../Drafts: png and pdf. Usage: python Fig06_how_to_use_the_files_littleblackfoot.py [--final] [--ver K] """ import os, sys import numpy as np, rasterio, geopandas as gpd, pyarrow.parquet as pq from rasterio.windows import Window from scipy.ndimage import binary_dilation import shapely import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Rectangle, FancyBboxPatch, Polygon, FancyArrow from matplotlib.colors import ListedColormap sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42, "font.family": "sans-serif", "font.sans-serif": ["Helvetica", "Arial", "DejaVu Sans"]}) REL = PTH.GLOBAL R = os.path.join(REL, 'flownest_merit90m_') import json _m = json.load(open(os.path.join(REL, 'metadata.json'))) assert _m['code_version'] == '10.61' and _m['numbering_sha256'][:12] == 'c485dec56c3a' FINAL = '--final' in sys.argv VER = int(sys.argv[sys.argv.index('--ver') + 1]) if '--ver' in sys.argv else 1 HERE = os.path.dirname(os.path.abspath(__file__)); FIGD = os.path.join(os.path.dirname(HERE), 'Figures' if FINAL else 'Drafts') A0 = 65454196 # the reach at the mouth of the Little Blackfoot River (Figure 5) num = lambda v: f'{int(v):,}' # ---------------------------------------------------------------- data def row_of(path, col, i): """value of column col on row i (counted from 0) of a parquet file, reading one row group""" f = pq.ParquetFile(path); k = 0 for g in range(f.num_row_groups): m = f.metadata.row_group(g).num_rows if i < k + m: return f.read_row_group(g, columns=[col]).column(0)[i - k].as_py() k += m raise IndexError(i) for fn, col in (('reach_1km2.parquet', 'reach_seq_id'), ('reach_location_1km2.parquet', 'reach_seq_id'), ('unit_catchment_1km2.geo.parquet', 'reach_seq_id'), ('reach_line_1km2.geo.parquet', 'reach_seq_id')): assert row_of(R + fn, col, A0 - 1) == A0, fn # number n is on row n - 1 in every table and vector file assert row_of(R + 'basin.parquet', 'basin_id', 0) == 1 t = pq.read_table(R + 'reach_1km2.parquet', filters=[('reach_seq_id', '=', A0)]).to_pandas().iloc[0] NUP = int(t.upstream_reach_count); A1 = A0 + NUP # [A0, A1): the reach and the reaches upstream of it assert NUP == 512, NUP AREA = float(t.upstream_area_km2); assert round(AREA) == 1066 P0 = int(t.downstream_end_pixel_seq_id); NCH = int(t.upstream_channel_pixel_count); P1 = P0 + NCH assert (P0, P1, NCH) == (1088848706, 1088857148, 8442) L = pq.read_table(R + 'reach_location_1km2.parquet', filters=[('reach_seq_id', '=', A0)]).to_pandas().iloc[0] r0, r1 = int(L.upstream_catchment_row_min), int(L.upstream_catchment_row_max) # half-open: row_max = last row + 1 c0, c1 = int(L.upstream_catchment_col_min), int(L.upstream_catchment_col_max) assert (r0, r1, c0, c1) == (45874, 46405, 80645, 81249), (r0, r1, c0, c1) WIN = Window(c0, r0, c1 - c0, r1 - r0) with rasterio.open(R + 'reach_seq_id_1km2.tif') as s: g = s.read(1, window=WIN).astype(np.int64); tr = s.window_transform(WIN) with rasterio.open(R + 'pixel_seq_id_1km2.tif') as s: gp = s.read(1, window=WIN).astype(np.int64) ins = (np.abs(g) >= A0) & (np.abs(g) < A1) chan = ins & (g > 0) NPIX = int(ins.sum()); assert NPIX == 180446, NPIX assert (((np.abs(gp) >= P0) & (np.abs(gp) < P1)) == ins).all() # the pixel_seq_id raster gives the same pixels assert int(((gp >= P0) & (gp < P1)).sum()) == NCH # of which 8,442 channel pixels assert ins[0].any() and ins[-1].any() and ins[:, 0].any() and ins[:, -1].any() # the window is tight uc = gpd.read_parquet(R + 'unit_catchment_1km2.geo.parquet', filters=[('reach_seq_id', '>=', A0), ('reach_seq_id', '<', A1)]) ln = gpd.read_parquet(R + 'reach_line_1km2.geo.parquet', columns=['reach_seq_id', 'geometry'], filters=[('reach_seq_id', '>=', A0), ('reach_seq_id', '<', A1)]) assert len(uc) == NUP and len(ln) == NUP poly = shapely.union_all(shapely.set_precision(uc.geometry.values, 1e-6)) assert round(poly.area / abs(tr.a * tr.e)) == 180446, poly.area / abs(tr.a * tr.e) # the dissolved unit catchments cover the same 180,446 pixels # (two parts: one pixel joins the rest only at a corner, a diagonal D8 link) bw, bs, be, bn = rasterio.transform.array_bounds(r1 - r0, c1 - c0, tr) # (west, south, east, north) pb = poly.bounds assert max(abs(pb[0] - bw), abs(pb[1] - bs), abs(pb[2] - be), abs(pb[3] - bn)) < 1e-6, (pb, (bw, bs, be, bn)) # raster window = bounding box of the polygon LAT = (bs + bn) / 2; ASP = 1 / np.cos(np.radians(LAT)) print('reach table row %s: [%s, %s), %d reaches, %.1f km2; window rows [%s, %s) cols [%s, %s); %s pixels; channel [%s, %s) %s' % (num(A0 - 1), num(A0), num(A1), NUP, AREA, num(r0), num(r1), num(c0), num(c1), num(NPIX), num(P0), num(P1), num(NCH))) # ---------------------------------------------------------------- drawing helpers (figure in mm; y up) WMM, HMM = 190, 206 fig = plt.figure(figsize=(WMM / 25.4, HMM / 25.4)) ax = fig.add_axes([0, 0, 1, 1]); ax.set_xlim(0, WMM); ax.set_ylim(0, HMM); ax.axis('off') FS, FT = 10, 12 DARK, GREY, BLUE = '#222222', '#666666', '#1F6FB5' C_RAS, C_TAB, C_VEC = '#7B4A9C', '#4A6788', '#2E8455' # format colours: raster, table, vector HILL, HILL_E, OUTW = '#FBD9A8', '#E8892B', '#E6E6E6' ROWBG = {'nav': '#FCF8E6', 'pix': '#F6F6F6', 'rch': '#F1F4F8'} def T(x, y, s, **k): if k.pop('weight', None) == 'bold': k.update(fontfamily='Arial', fontweight='bold') # Helvetica.ttc has no bold face here return ax.text(x, y, s, fontsize=k.pop('fs', FS), color=k.pop('c', DARK), **k) def icon(x, y, kind, fmt, w=6.2, h=8.0): """a file icon, lower-left at (x, y): page with folded corner, a band in the format colour, a glyph of what it holds""" f = 1.8 ax.add_patch(Polygon([(x, y), (x + w, y), (x + w, y + h - f), (x + w - f, y + h), (x, y + h)], closed=True, fc='white', ec=DARK, lw=0.6, zorder=3)) ax.plot([x + w - f, x + w - f, x + w], [y + h, y + h - f, y + h - f], color=DARK, lw=0.6, zorder=3) ax.add_patch(Rectangle((x, y), w, 1.3, fc={'r': C_RAS, 't': C_TAB, 'v': C_VEC}[fmt], ec='none', zorder=4)) gx, gy = x + 0.8, y + 1.9 if kind == 'grid': cols = [[HILL, BLUE, HILL], [HILL, BLUE, BLUE], [BLUE, HILL, HILL]] for i in range(3): for j in range(3): ax.add_patch(Rectangle((gx + j * 1.35, gy + i * 1.35), 1.15, 1.15, fc=cols[i][j], ec='none', zorder=4)) elif kind in ('rows', 'window'): for i in range(4): ax.add_patch(Rectangle((gx, gy + i * 1.15), w - 1.8, 0.75, fc='#DDE3EA', ec='none', zorder=4)) ax.add_patch(Rectangle((gx, gy + i * 1.15), 0.8, 0.75, fc=BLUE if kind == 'rows' else '#8899AA', ec='none', zorder=4)) if kind == 'window': ax.add_patch(Rectangle((gx + 1.6, gy + 3.2), 1.6, 1.4, fc='none', ec=DARK, lw=0.6, ls=(0, (1.5, 1)), zorder=5)) elif kind == 'poly': cx, cy = x + w / 2, y + 4.4 pts = [(cx + 2.1 * np.cos(a), cy + 2.1 * np.sin(a)) for a in np.radians([90, 162, 234, 306, 18])] ax.add_patch(Polygon(pts, closed=True, fc=HILL, ec=HILL_E, lw=0.9, zorder=4)) ax.plot([cx - 0.7, cx + 0.2, cx + 0.8], [cy - 1.2, cy - 0.1, cy + 1.2], color=BLUE, lw=0.9, zorder=5) elif kind == 'line': cx, cy = x + w / 2, y + 4.2 ax.plot([cx - 2.2, cx + 0.2], [cy - 1.6, cy - 0.1], color=BLUE, lw=1.1, zorder=5) ax.plot([cx + 0.2, cx + 2.2], [cy - 0.1, cy + 0.8], color=BLUE, lw=1.1, zorder=5) ax.plot([cx + 0.2, cx - 0.2], [cy - 0.1, cy + 2.0], color=BLUE, lw=1.1, zorder=5) def cellbox(x0, x1, y0, y1, bg): ax.add_patch(FancyBboxPatch((x0, y0), x1 - x0, y1 - y0, boxstyle='round,pad=0,rounding_size=1.2', fc=bg, ec='#C9C9C9', lw=0.7, zorder=1)) def entry(x, ytop, kind, fmt, name, lines): icon(x, ytop - 8.6, kind, fmt) T(x + 7.6, ytop - 0.6, name, weight='bold', va='top', linespacing=1.15) T(x + 7.6, ytop - 4.9 - 4.06 * name.count('\n'), '\n'.join(lines), va='top', linespacing=1.15) # a two-line name pushes the text down one line # ---------------------------------------------------------------- (a) the files XC = [(29, 81), (84, 136), (139, 189)] # raster, table, vector columns T(1.5, HMM - 3, '(a) The files of each level', fs=FT, weight='bold', va='top') for (x0, x1), name, fmt, use, c in zip(XC, ('Raster', 'Table', 'Vector'), ('GeoTIFF', 'Parquet', 'GeoParquet'), ('for overlay with other grids', 'for lookup by number', 'for maps and web display'), (C_RAS, C_TAB, C_VEC)): xm = (x0 + x1) / 2 T(xm, HMM - 10.5, name, fs=FT, weight='bold', ha='center', va='top') T(xm, HMM - 15.6, fmt, c=GREY, ha='center', va='top') T(xm, HMM - 20.0, use, c=c, weight='bold', ha='center', va='top') ROWS = [('nav', 'Navigation', ['basins ≥ 1 km²']), ('pix', 'Pixel level', ['≥ 1 km²,', 'all thresholds']), ('rch', 'Reach level', ['1 km², base of', 'coarser reaches'])] RH, RG, YTOP = 16.0, 2.0, HMM - 26.0 for i, (key, name, sub) in enumerate(ROWS): yt = YTOP - i * (RH + RG); yb = yt - RH T(1.5, yt - 1.6, name, fs=11, weight='bold', va='top') T(1.5, yt - 6.4, '\n'.join(sub), c=GREY, va='top', linespacing=1.1) if key == 'nav': cellbox(*XC[0], yb, yt, ROWBG[key]); entry(XC[0][0] + 1.5, yt - 2.6, 'grid', 'r', 'FullBasin', ['basin ID on each', 'pixel of a basin']) cellbox(*XC[1], yb, yt, ROWBG[key]); entry(XC[1][0] + 1.5, yt - 2.6, 'rows', 't', 'basin', ['Level-1 to 3 groups,', 'number ranges']) cellbox(*XC[2], yb, yt, ROWBG[key]); entry(XC[2][0] + 1.5, yt - 2.6, 'poly', 'v', 'basin', ['polygons']) elif key == 'pix': cellbox(*XC[0], yb, yt, ROWBG[key]); entry(XC[0][0] + 1.5, yt - 2.6, 'grid', 'r', 'pixel_seq_id', ['+ number: channel', '− number: hillslope']) cellbox(*XC[1], yb, yt, ROWBG[key]); entry(XC[1][0] + 1.5, yt - 2.6, 'rows', 't', 'pixel', ['row, col, reach,', 'basin']) else: cellbox(*XC[0], yb, yt, ROWBG[key]); entry(XC[0][0] + 1.5, yt - 2.6, 'grid', 'r', 'reach_seq_id', ['+ number: channel', '− number: hillslope']) cellbox(*XC[1], yb, yt, ROWBG[key]); entry(XC[1][0] + 1.0, yt - 2.6, 'rows', 't', 'reach', ['ranges,', 'attributes']) entry(XC[1][0] + 27.0, yt - 2.6, 'window', 't', 'location', ['windows']) cellbox(*XC[2], yb, yt, ROWBG[key]); entry(XC[2][0] + 1.0, yt - 2.6, 'line', 'v', 'line', ['channel']) entry(XC[2][0] + 23.0, yt - 2.6, 'poly', 'v', 'unit\ncatchment', ['polygons']) # the file name, unit catchment, kept whole # ---------------------------------------------------------------- (b) the example YB = YTOP - 3 * (RH + RG) - 1.0 # top of (b) ax.add_patch(FancyBboxPatch((0.8, 26.5), WMM - 1.6, YB - 26.5, boxstyle='round,pad=0,rounding_size=1.8', fc='#F4F7FB', ec='#B7C6D8', lw=0.8, zorder=0)) T(2.5, YB - 2.0, '(b) The Little Blackfoot River (Figure 5): the upstream catchment of reach %s' % num(A0), fs=FT, weight='bold', va='top') yr = YB - 10.5 for (x0, x1), name, c, items in ((XC[0], 'Raster route', C_RAS, [('rows', 't', 'reach table'), ('window', 't', 'location table'), ('grid', 'r', 'reach_seq_id raster')]), (XC[2], 'Vector route', C_VEC, [('rows', 't', 'reach table'), ('poly', 'v', 'unit catchment file'), ('line', 'v', 'line file')])): xm = (x0 + x1) / 2 T(xm, yr, name, fs=FT, weight='bold', c=c, ha='center', va='top') for k, (kind, fmt, lab) in enumerate(items): yy = yr - 6.5 - k * 7.0 icon(x0 + 9, yy - 5.2, kind, fmt, w=5.0, h=6.4) if k: T(x0 + 5.0, yy - 2.0, '+', fs=11, weight='bold', ha='center', va='center') T(x0 + 16, yy - 2.0, lab, weight='bold' if k == 0 else 'normal', c=BLUE if k == 0 else DARK, va='center') # the centre box: one row of the reach table bx0, bx1, by1 = XC[1][0] + 1, XC[1][1] - 1, yr + 1.0; by0 = by1 - 24 ax.add_patch(FancyBboxPatch((bx0, by0), bx1 - bx0, by1 - by0, boxstyle='round,pad=0,rounding_size=1.5', fc='white', ec=BLUE, lw=1.4, zorder=2)) xm = (bx0 + bx1) / 2 T(xm, by1 - 2.2, 'reach table, row %s' % num(A0 - 1), weight='bold', ha='center', va='top') T(xm, by1 - 7.0, 'the reach and its %d\nupstream reaches:' % (NUP - 1), ha='center', va='top', linespacing=1.1) T(xm, by1 - 16.4, '[%s, %s)' % (num(A0), num(A1)), fs=FT, weight='bold', c=BLUE, ha='center', va='top') for xs, dx in ((bx0 - 0.5, -6.0), (bx1 + 0.5, 6.0)): ax.add_patch(FancyArrow(xs, (by0 + by1) / 2, dx, 0, width=1.6, head_width=4.6, head_length=3.2, length_includes_head=True, fc='#444444', ec='none', zorder=3)) # maps MT, MB_ = yr - 29.5, 37.0 # top and bottom of the maps (mm) hmm = MT - MB_; wmm = hmm * (c1 - c0) / ((r1 - r0) * ASP) def map_axes(xm): return fig.add_axes([(xm - wmm / 2) / WMM, MB_ / HMM, wmm / WMM, hmm / HMM]) # raster route xmR = (XC[0][0] + XC[0][1]) / 2 a1 = map_axes(xmR) img = np.where(ins, 1, 0); img = np.where(binary_dilation(chan, iterations=1) & ins, 2, img) # channel pixels widened by one pixel on each side (drawn three pixels wide) a1.imshow(img, cmap=ListedColormap([OUTW, HILL, BLUE]), vmin=0, vmax=2, interpolation='nearest', extent=(bw, be, bs, bn), aspect=ASP) # vector route xmV = (XC[2][0] + XC[2][1]) / 2 a2 = map_axes(xmV) gpd.GeoSeries([poly]).plot(ax=a2, fc=HILL, ec=HILL_E, lw=1.0) ln.plot(ax=a2, color=BLUE, lw=0.45) for a in (a1, a2): a.set_xlim(bw, be); a.set_ylim(bs, bn); a.set_aspect(ASP); a.set_xticks([]); a.set_yticks([]) for sp in a.spines.values(): sp.set_linestyle((0, (3, 2))); sp.set_linewidth(1.0); sp.set_color(DARK) T(xmR, MB_ - 2.0, '%s pixels, %s km²' % (num(NPIX), num(round(AREA))), ha='center', va='top') T(xmV, MB_ - 2.0, 'the same %s pixels' % num(NPIX), ha='center', va='top') # centre: the block of rows tx0, tx1 = XC[1][0] + 10, XC[1][1] - 10; NRW = 15; rh = hmm / NRW; hb0, hb1 = 4, 10 for k in range(NRW): yy = MT - (k + 1) * rh ax.add_patch(Rectangle((tx0, yy), tx1 - tx0, rh, fc='#CFE0F2' if hb0 <= k < hb1 else 'white', ec='#BBBBBB', lw=0.5, zorder=2)) ax.add_patch(Rectangle((tx0, MT - hb1 * rh), tx1 - tx0, (hb1 - hb0) * rh, fc='none', ec=BLUE, lw=1.5, zorder=3)) T((tx0 + tx1) / 2, MT - (hb0 + hb1) / 2 * rh, '%d rows' % NUP, fs=FT, weight='bold', c=BLUE, ha='center', va='center', zorder=4) T((tx0 + tx1) / 2, MB_ - 2.0, 'one block of rows, no search', ha='center', va='top') # the rule and the key ax.add_patch(FancyBboxPatch((32, 17.0), 126, 6.4, boxstyle='round,pad=0,rounding_size=3.2', fc='white', ec=BLUE, lw=1.2)) T(95, 20.2, 'In every table and vector file, number n is on row n − 1 (first row: 0)', weight='bold', c=BLUE, ha='center', va='center') def key(x, y, patch_kw, lab): ax.add_patch(Rectangle((x, y - 1.6), 4.2, 3.2, **patch_kw)); return T(x + 5.6, y, lab, va='center') key(20, 10.0, dict(fc=BLUE, ec='none'), 'channel pixel') key(62, 10.0, dict(fc=HILL, ec='none'), 'hillslope pixel') key(104, 10.0, dict(fc=OUTW, ec='none'), 'other pixels of the window') key(20, 4.0, dict(fc='none', ec=DARK, lw=0.9, ls=(0, (2, 1.5))), 'raster window: the bounding box of the polygon, from the location table') # ---------------------------------------------------------------- checks: font sizes, overlaps, inside the page fig.canvas.draw(); rd = fig.canvas.get_renderer() txt = [t_ for t_ in ax.texts if t_.get_text().strip()] assert min(t_.get_fontsize() for t_ in txt) >= 10 bbs = [(t_.get_text()[:30], t_.get_window_extent(rd)) for t_ in txt] W_, H_ = fig.bbox.width, fig.bbox.height bad = [s for s, b in bbs if b.x0 < 0 or b.y0 < 0 or b.x1 > W_ or b.y1 > H_] ov = [(s1, s2) for i, (s1, b1) in enumerate(bbs) for s2, b2 in bbs[i + 1:] if b1.overlaps(b2)] print('labels:', 'ok' if not bad and not ov else ('outside %s overlaps %s' % (bad, ov))) os.makedirs(FIGD, exist_ok=True) out = os.path.join(FIGD, 'Fig06_how_to_use_the_files_littleblackfoot_v%d' % VER) fig.savefig(out + '.png', dpi=300); fig.savefig(out + '.pdf') print(out)