# -*- coding: utf-8 -*- """Figure 5: the objects of FlowNest, from the globe to one pixel, each one range of numbers. (a) the eight objects as rows; (b) the zoom chain of Data05 on maps. Input: ../Data (Data04, Data05, Data05c, Data06j) and the global release (paths.GLOBAL). Output: with --final, ../Figures: png and pdf; otherwise ../Drafts: one png. Usage: python Fig05_objects_chain_littleblackfoot.py [--final] """ import os, re, sys, glob, json import numpy as np, pandas as pd, geopandas as gpd, rasterio from affine import Affine from rasterio.warp import calculate_default_transform, reproject, Resampling from shapely.geometry import Point, LineString HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import paths as PTH # the common module of this folder: the Little Blackfoot cut-out Data04 and Figure 8's Data06j, both in ../Data from Fig05_common_littleblackfoot import (BOLD, DATD as D09, BASIN as BASIN_COMMON, C_MAIN, C_TRIB, C_OTHER, T_DARK, T_GREY, T_MAIN, T_TRIB, F_OTHER, ZOOM_LINE, EPSG, num, text_inches, PID, TR, GT, R0, C0, LO, HI, polygon, read04, TRIB_PIX, JUNC_PIX, AREA) BASIN = 32 # the Columbia: FullBasin basin 32 DATD = os.path.join(os.path.dirname(HERE), 'Data') assert BASIN_COMMON == BASIN and D09 == DATD import matplotlib.pyplot as plt, matplotlib.patheffects as pe from matplotlib.patches import Rectangle, Polygon as Poly, FancyArrowPatch from matplotlib.colors import ListedColormap, to_rgb FINAL = '--final' in sys.argv FS, FT, LH = 10, 12, 0.165 # points of the text and of the panel titles (as Figures 1-6); a line, inches W = 7.48; ML = 0.08 # inches MW, MH = 0.80, 0.58 # the map of a row, at ML TX = ML + MW + 0.12 # the words of a row; their width TW and the bar BX0..BX1 follow from the words PITCH, BT, BH = 0.70, 0.32, 0.18 G = ['#bdbdbd', '#d4d4d4', '#a8a8a8']; LAND = '#ececec'; AMBER = '#E69F00'; AMBER_L = '#F1CA73'; WARM = ['#d9cfc4', '#c9bcae'] UP, UNIT = '#fde2c8', '#f2a65e' # the upstream catchment and the unit catchment, as in Figures 1 and 6 FIGD = os.path.join(os.path.dirname(HERE), 'Figures' if FINAL else 'Drafts'); os.makedirs(FIGD, exist_ok=True) REL = PTH.GLOBAL RIVER_MAP_KM2 = 10000.0 # the rivers on the map of the Columbia: reach lines with at least this upstream area # ================================================================ the files, and every number checked J = json.load(open(os.path.join(DATD, 'Data05_flownest_littleblackfoot_zoom_chain.json'))) assert J['source'].startswith('flownest_merit90m_global_20261113_195421 (code 10.61') META = json.load(open(os.path.join(REL, 'metadata.json'))); assert META['code_version'] == '10.61' D05 = os.path.join(DATD, 'Data05c_flownest_%s') GL, L1, L2, L3, BA, CO, LB, TG, RH, PX = (J[k] for k in ('globe', 'level1', 'level2', 'level3', 'basin', 'columbia', 'littleblackfoot', 'telegraph', 'reach', 'pixel')) RV, HO = TG['main_stem'], CO['holder'] # the path of Telegraph Creek; the tributary network of the Columbia that holds the Little Blackfoot P = PX['pixel_seq_id'] # the basins of Level-1 group 7 in the basin table (at least 1 km²), in the order of their pixel numbers B = (pd.read_parquet(os.path.join(REL, 'flownest_merit90m_basin.parquet')).query('flowdivide_level1_id == 7').sort_values('outlet_pixel_seq_id').reset_index(drop=True)) assert len(B) == 46711 BIX = pd.Index(B.basin_id.values) # basin_id -> its row in B X = read04('pixel_1km2').set_index('pixel_id') # the 8,442 channel pixels of the Little Blackfoot RC = pd.read_parquet(os.path.join(DATD, 'Data05_flownest_telegraph_path_reach_1km2.parquet')).sort_values('reach_seq_id').reset_index(drop=True) fl = lambda d: (int(d['first']), int(d['last'])) def tiles(parts, lo, hi): """The runs (first, last) cover lo..hi one after another.""" f, l = [int(a) for a, _ in parts], [int(b) for _, b in parts] return f[0] == lo and l[-1] == hi and all(f[k + 1] == l[k] + 1 for k in range(len(f) - 1)) allr = GL['parts'] + L1['parts'] + L2['parts'] + L3['parts'] + [GL, L1, L2, L3, BA, CO['main_stem'], HO, HO['main_stem'], LB, LB['main_stem'], TG, RV, RH, PX] assert all(d['count'] == d['last'] - d['first'] + 1 for d in allr) L1S = [d['code'] for d in GL['parts'] if d['code'] >= 100000] assert len(GL['parts']) == 34 and tiles([fl(d) for d in GL['parts']], 1, GL['last']) and [d['code'] for d in GL['parts'][:9]] == list(range(1, 10)) assert L1S == [100001, 100002] + list(range(200001, 200024)) and fl(GL['parts'][6]) == fl(L1) assert tiles([fl(d) for d in L1['parts']], *fl(L1)) and [d['code'] for d in L1['parts']] == list(range(71, 79)) and fl(L1['parts'][7]) == fl(L2) assert tiles([fl(d) for d in L2['parts']], *fl(L2)) and [d['code'] for d in L2['parts']] == [781, 782, 783] and fl(L2['parts'][1]) == fl(L3) assert tiles([fl(d) for d in L3['parts']], *fl(L3)) and len(L3['parts']) == L3['basins']['count'] == 121 and L3['basins']['in_basin_table'] == 27 SB = BA['rank_in_l3'] - 1 # the Columbia among the basins of 782 (the first: the largest) assert SB == 0 and L3['parts'][SB]['code'] == BA['basin_id'] == BASIN and fl(L3['parts'][SB]) == fl(BA) # the Columbia: its main stem, then its 2,004 tributary networks; the Little Blackfoot lies inside one of them (the Pend Oreille-Clark Fork) HI_ = CO['holder_index'] assert tiles([fl(CO['main_stem'])] + CO['tributaries'], *fl(BA)) and tuple(CO['tributaries'][HI_]) == fl(HO) assert HO['first'] < LO and HI <= HO['last'] and HO['main_stem']['first'] == HO['first'] and HO['main_stem']['path_level'] == 2 assert J['flow_path'][2][0] == HO['first'] and J['flow_path_paths'][2]['path_seq_id'] == HO['main_stem']['path_seq_id'] # the Little Blackfoot: its main stem, then its 63 tributary networks; Telegraph Creek one of them ST = TG['index_among_tributaries'] + 1 # Telegraph Creek among the parts of the Little Blackfoot bar (the main stem first) assert fl(LB) == (LO, HI) and tiles([fl(LB['main_stem'])] + LB['tributaries'], LO, HI) and tuple(LB['tributaries'][ST - 1]) == fl(TG) and TG['first'] == TRIB_PIX assert tiles([fl(RV)] + TG['tributaries'], *fl(TG)) and RV['first'] == TG['first'] == RH['first'] and RH['last'] <= RV['last'] assert RH['first'] <= P <= RH['last'] and P - RH['first'] + 1 == 5 and RH['next_down_pixel'] == JUNC_PIX # every code is the run of its Level-3 groups in metadata.json, and holds the basins of at least 1 km² of that code (the one-pixel # basins under 1 km² are not in the basin table; each code starts with its largest basin) GM = pd.DataFrame(META['flowdivide_level3_groups']).sort_values('first_pixel_seq_id').reset_index(drop=True) for key, parts in (('flowdivide_level2_id', L1['parts']), ('flowdivide_level3_id', L2['parts'])): for d in parts: g_ = GM[GM[key] == d['code']]; assert (np.diff(g_.index) == 1).all() assert (int(g_.first_pixel_seq_id.iloc[0]), int(g_.first_pixel_seq_id.iloc[-1] + g_.channel_pixel_count.iloc[-1] - 1)) == fl(d) and g_.channel_pixel_count.sum() == d['count'] s = B[B[key] == d['code']] assert int(s.outlet_pixel_seq_id.min()) == d['first'] and int((s.outlet_pixel_seq_id + s.channel_pixel_count).max() - 1) <= d['last'] and s.channel_pixel_count.sum() <= d['count'] s = B[B.flowdivide_level3_id == 782] # the 27 basins of code 782 in the basin table, largest area first P3 = {d['first']: d for d in L3['parts']} assert all(P3[int(o)]['code'] == int(b) and P3[int(o)]['count'] == int(n) and P3[int(o)]['in_basin_table'] for b, o, n in zip(s.basin_id, s.outlet_pixel_seq_id, s.channel_pixel_count)) assert len(s) == sum(d['in_basin_table'] for d in L3['parts']) == 27 and all(d['count'] == 1 for d in L3['parts'] if not d['in_basin_table']) assert (np.diff(s.upstream_area_km2.values.astype('float64')) <= 2e-6).all() assert abs(float(B.loc[B.basin_id == BASIN, 'upstream_area_km2'].iloc[0]) - BA['area_km2']) < 1e-3 assert BA['area_km2'] / L3['area_km2'] > 0.95 and s.upstream_area_km2.iloc[1:].max() < 0.03 * BA['area_km2'] # 'the Columbia and 120 other basins' ("small basins" are those of 0.05-1 km² in the text, Table 3) NAME = {BASIN: ('Columbia', -123.256, 46.152)} # name: the outlet of the basin for b_, (n_, lon_, lat_) in NAME.items(): r_ = B[B.basin_id == b_].iloc[0]; assert abs(r_.outlet_lon - lon_) < 0.002 and abs(r_.outlet_lat - lat_) < 0.002, n_ # the names of paths: the Pend Oreille-Clark Fork from Butte (Montana) to the Columbia just north of 49° N; the Little Blackfoot joins the # Clark Fork at Garrison (Montana); Telegraph Creek joins the Little Blackfoot near Elliston assert abs(HO['outlet']['lon'] + 117.62) < 0.01 and abs(HO['outlet']['lat'] - 49.004) < 0.01 and abs(HO['source']['lon'] + 112.52) < 0.01 and abs(HO['source']['lat'] - 45.82) < 0.01 assert abs(J['flow_path_paths'][1]['downstream_end_lon'] + 112.796) < 0.01 and abs(J['flow_path_paths'][1]['downstream_end_lat'] - 46.514) < 0.01 assert abs(J['flow_path_paths'][0]['downstream_end_lon'] + 112.395) < 0.01 and abs(J['flow_path_paths'][0]['downstream_end_lat'] - 46.529) < 0.01 RANGE = {78: (42, 59)} # where the outlets are (latitude, ° N); the words below say where, not where it drains for c_, k_ in ((78, 'flowdivide_level2_id'),): s = B[B[k_] == c_]; assert (round(s.outlet_lat.min()), round(s.outlet_lat.max())) == RANGE[c_] and s.outlet_lon.max() < -112, c_ # the reaches of the path of Telegraph Creek at 1 km²: the reach of p first assert tiles(list(zip(RC.downstream_end_pixel_seq_id, RC.last_pixel)), *fl(RV)) and list(RC.reach_seq_id) == list(range(RV['reaches']['first'], RV['reaches']['last'] + 1)) assert int(RC.reach_seq_id.iloc[0]) == RH['reach_seq_id'] and (int(RC.downstream_end_pixel_seq_id.iloc[0]), int(RC.last_pixel.iloc[0])) == fl(RH) assert abs(RC.length_km.sum() - RV['length_km']) < 1e-3 and abs(float(RC.length_km.iloc[0]) - RH['length_km']) < 1e-4 assert (X.index[0], X.index[-1], len(X)) == (LO, HI, HI - LO + 1) and (int(X.at[P, 'row']), int(X.at[P, 'col'])) == (PX['grid_row'], PX['grid_col']) assert int(X.at[P, 'reach_id']) == RH['reach_seq_id'] nd = X.next_down_pixel_id # (b) one step up and one step down: every number RCH, PTH, GRP = RH['reach_seq_id'], RV['path_seq_id'], 782 NR = RV['reaches']['count'] LADDER = [('Channel pixel p', num(P), 'white'), ('Reach', num(RCH), C_TRIB), ('Path', num(PTH), AMBER), ('Basin', '%s (Columbia)' % num(BASIN), '#e4e4e4'), ('Level-3 group', num(GRP), '#e4e4e4')] # the last step: a Level-3 group is one range of path numbers (the basin_id of its basins, FullBasin's global numbers, are not one range) STEPS = [('reach_seq_id', '%d pixels' % RH['count'], RH['first'], RH['last']), ('path_seq_id', '%d reaches' % NR, RCH, RV['reaches']['last']), ('basin_id', '%s paths' % num(CO['paths']['count']), CO['paths']['first'], CO['paths']['last']), ('flowdivide_level3_id', '%s paths' % num(L3['paths']['count']), L3['paths']['first'], L3['paths']['last'])] assert (L3['paths']['first'], L3['paths']['last']) == (33777623, 33943153) == (CO['paths']['first'], 33943153) # the Columbia's paths come first # the ranges of reach_seq_id (1 km²) of every row: the group rows from the Level-3 groups of metadata.json, which follow one another in # both numbers; each group row must also give the pixel range of the files above G3 = GM assert (G3.first_pixel_seq_id.values[1:] == (G3.first_pixel_seq_id + G3.channel_pixel_count).values[:-1]).all() and G3.first_pixel_seq_id.iloc[0] == 1 assert (G3.first_reach_seq_id_1km2.values[1:] == (G3.first_reach_seq_id_1km2 + G3.reach_count_1km2).values[:-1]).all() and G3.first_reach_seq_id_1km2.iloc[0] == 1 def runs_of(s): """The pixel and reach ranges (first, last) of consecutive Level-3 groups.""" assert (np.diff(s.index) == 1).all() return ((int(s.first_pixel_seq_id.iloc[0]), int(s.first_pixel_seq_id.iloc[-1] + s.channel_pixel_count.iloc[-1] - 1)), (int(s.first_reach_seq_id_1km2.iloc[0]), int(s.first_reach_seq_id_1km2.iloc[-1] + s.reach_count_1km2.iloc[-1] - 1))) RCH_RANGE = [] for s, d in ((G3, GL), (G3[G3.flowdivide_level1_id == 7], L1), (G3[G3.flowdivide_level2_id == 78], L2), (G3[G3.flowdivide_level3_id == 782], L3)): px, rc = runs_of(s); assert px == fl(d), (px, fl(d)); RCH_RANGE.append(rc) assert RCH_RANGE[3] == fl(L3['reaches']) and RCH_RANGE[0] == (1, 70883935) assert CO['reaches']['first'] == L3['reaches']['first'] == CO['main_stem']['reaches']['first'] # the Columbia is the first basin of 782 assert fl(LB['reaches']) == (LB['local_offsets']['reach'] + 1, LB['local_offsets']['reach'] + 512) and LB['local_offsets']['pixel'] == LO - 1 assert fl(TG['reaches'])[0] == RCH and TG['reaches']['count'] == RH['upstream_reach_count'] == 29 RCH_RANGE += [fl(CO['reaches']), fl(LB['reaches']), fl(TG['reaches']), (RCH, RCH)] print('all checks passed') # ================================================================ the rows of (a), and the layout from the widths of their words C78 = {781: (2, G[0]), 782: (5, C_TRIB), 783: (4, G[2])} # the codes of 78: class on the map, colour on the bar TAIL = (GL['parts'][9]['first'], GL['last']); assert (TAIL[1] - TAIL[0] + 1) / GL['last'] < 0.0011 # the 25 other groups: 0.10 % COL_PARTS = [(*fl(CO['main_stem']), C_MAIN, None, None)] # the Columbia: the Pend Oreille-Clark Fork network split around the Little Blackfoot. # Its main stem is 0.45 % of the bar and the Little Blackfoot starts at 13 %: their words above the bar would meet, so only the # Little Blackfoot (the part the next row enlarges) is named here; the next row names its main stem, blue as here for k, (a, b) in enumerate(CO['tributaries']): COL_PARTS += [(a, LO - 1, G[k % 3], None, None), (LO, HI, C_TRIB, 'Little Blackfoot', None), (HI + 1, b, G[k % 3], None, None)] if k == HI_ else [(a, b, G[k % 3], None, None)] SC = [k for k, d in enumerate(COL_PARTS) if d[:2] == (LO, HI)]; assert len(SC) == 1; SC = SC[0] assert tiles([d[:2] for d in COL_PARTS], *fl(BA)) ROWS = [dict(title='Globe', lines=['9 continental', 'Level-1 groups'], lo=1, hi=GL['last'], sel=6, parts=[(d['first'], d['last'], C_TRIB if k == 6 else G[k % 3], str(d['code']), None) for k, d in enumerate(GL['parts'][:9])] + [(*TAIL, G[0], None, None)]), dict(title='Level-1 group 7', lines=['North and Central America'], lo=L1['first'], hi=L1['last'], sel=7, parts=[(d['first'], d['last'], C_TRIB if d['code'] == 78 else G[k % 3], str(d['code']), None) for k, d in enumerate(L1['parts'])]), dict(title='Level-2 group 78', lines=['Pacific Northwest'], lo=L2['first'], hi=L2['last'], sel=1, parts=[(d['first'], d['last'], C78[d['code']][1], '%d · Columbia' % d['code'] if d['code'] == 782 else str(d['code']), str(d['code'])) for d in L2['parts']]), dict(title='Level-3 group 782', lines=['the Columbia and', '%d other basins' % (len(L3['parts']) - 1)], lo=L3['first'], hi=L3['last'], sel=SB, parts=[(d['first'], d['last'], C_TRIB if d['code'] == BASIN else G[k % 3], NAME.get(d['code'], ('',))[0], None) for k, d in enumerate(L3['parts'])]), dict(title='Columbia River basin', lines=['basin_id %s' % num(BASIN), '%s km²' % num(round(BA['area_km2']))], lo=BA['first'], hi=BA['last'], sel=SC, parts=COL_PARTS), dict(title='Little Blackfoot network', lines=['%s km²' % num(round(LB['area_km2'])), 'joins the Clark Fork'], lo=LO, hi=HI, sel=ST, parts=[(*fl(LB['main_stem']), C_MAIN, 'main stem', None)] + [(a, b, C_TRIB if k == ST - 1 else G[k % 3], 'Telegraph Creek' if k == ST - 1 else None, None) for k, (a, b) in enumerate(LB['tributaries'])]), dict(title='Telegraph Creek network', lines=['%.1f km²' % TG['area_km2']], lo=TG['first'], hi=TG['last'], sel=0, parts=[(a, b, C_TRIB if a == RH['first'] else (AMBER_L, AMBER)[k % 2], None, None) for k, (a, b) in enumerate(zip(RC.downstream_end_pixel_seq_id, RC.last_pixel))] + [(a, b, WARM[k % 2], None, None) for k, (a, b) in enumerate(TG['tributaries'])]), dict(title='Reach %s' % num(RCH), lines=['%.1f km' % RH['length_km']], lo=RH['first'], hi=RH['last'], sep='white', parts=[(q, q, C_TRIB, None, None) for q in range(RH['first'], RH['last'] + 1)])] assert len(ROWS) == len(RCH_RANGE) == 8 for R, (a, b) in zip(ROWS, RCH_RANGE): R['rlo'], R['rhi'] = a, b SUB = ['Bar: the pixel_seq_id of a unit, increasing to the right; its width is its number of channel pixels (1 km²).', 'Thin line: its reach_seq_id. Each range is written a + 1 … + n: without the offset a, every unit counts from 1 to n.'] TA = '(a) From the globe to one reach: each row enlarges the outlined orange part above' TB = '(b) Small to large is one field; large to small is one range of identifiers' assert all(ML + text_inches(s, FS) <= W - 0.05 for s in SUB) and ML + text_inches(TA, FT, **BOLD) <= W - 0.05 and ML + text_inches(TB, FT, **BOLD) <= W - 0.05 Y0 = 0.28 + 0.28 YL = BT + BH + 0.075 # the thin line of reach_seq_id in its row, under the bar YP = YL + 0.20 # the words p = a + 5 under the last row YB = Y0 + PITCH * (len(ROWS) - 1) + YP + 0.40 # the title of (b): below the words under the last bar YR = YB + 0.38 + 0.42 + 0.17 + 2 * LH + 0.12 # (b): the line of the last orange arrow, under the three lines below the boxes H = YR + 0.20 + 0.08 # the height of the figure: then the one line of words under that arrow # ================================================================ drawing 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() # inches from the top left T_ = lambda x, y, s, **kw: A.text(x, y, s, **{**dict(fontsize=FS, color=T_DARK, ha='left', va='baseline'), **kw}) def label(x, y, pieces, ha, draw=True): """Words made of pieces (text, bold): the offset a grey, the numbers counted from 1 bold. Returns its width.""" w = [text_inches(t, FS, **(BOLD if b else {})) for t, b in pieces] x = x - sum(w) if ha == 'right' else x for (t, b), w_ in zip(pieces, w if draw else []): A.text(x, y, t, fontsize=FS, ha='left', va='center_baseline', color=T_DARK if b else T_GREY, **(BOLD if b else {})); x += w_ return sum(w) LEFT = lambda lo: [(num(lo - 1), False), (' + 1', True)] # the range lo..hi is a + 1 .. a + n, with a = lo - 1 RIGHT = lambda lo, hi: [('+ ' + num(hi - lo + 1), True)] TW = max([text_inches(R['title'], FS, **BOLD) for R in ROWS] + [text_inches(s, FS) for R in ROWS for s in R['lines']]) BX0 = TX + TW + 0.10 + max(label(0, 0, LEFT(lo), 'right', False) for R in ROWS for lo in (R['lo'], R['rlo'])) + 0.04 BX1 = W - 0.05 - max(label(0, 0, RIGHT(lo, hi), 'left', False) for R in ROWS for lo, hi in ((R['lo'], R['hi']), (R['rlo'], R['rhi']))) - 0.04 BW = BX1 - BX0; print('bar width %.2f in' % BW) assert BW > 2.4, BW def fits(s, x0, x1): # words inside a part of a bar keep a margin; a single digit a smaller one return text_inches(s, FS) <= x1 - x0 - (0.015 if len(s) == 1 else 0.05) def bar(y, lo, hi, parts, sel=None, sep=None): """A bar of pixel_seq_id lo..hi; parts are (first, last, colour, words, shorter words). Returns x of an id.""" n = hi - lo + 1; xa = lambda v: BX0 + BW * (v - lo) / n; yt = y + BT for k, (a, b, fc, w1, w2) in enumerate(parts): x0, x1 = xa(a), xa(b + 1) A.add_patch(Rectangle((x0, yt), x1 - x0, BH, fc=fc, ec=sep or 'none', lw=0.4 if sep else 0, zorder=2)) for s in (w1, w2): if s and fits(s, x0, x1): A.text((x0 + x1) / 2, yt + BH / 2, s, fontsize=FS, ha='center', va='center_baseline', zorder=3, color='white' if fc in (C_TRIB, C_MAIN) else T_DARK); break if sel is not None: a, b = parts[sel][:2]; A.add_patch(Rectangle((xa(a), yt), xa(b + 1) - xa(a), BH, fill=False, ec=T_DARK, lw=0.5, zorder=4)) return xa def ends(y, R): """The two ranges of a row, a + 1 .. n: pixel_seq_id at the bar, reach_seq_id at the thin line under it.""" for yy, lo, hi, tag in ((y + BT + BH / 2, R['lo'], R['hi'], 'pixel_seq_id'), (y + YL, R['rlo'], R['rhi'], 'reach_seq_id')): w = label(BX0 - 0.04, yy, LEFT(lo), 'right'); label(BX1 + 0.04, yy, RIGHT(lo, hi), 'left') if R is ROWS[0]: # the first row names its two lines, in the space its short offsets leave xt = BX0 - 0.04 - w - 0.12; T_(xt, yy, tag, ha='right', va='center_baseline') assert xt - text_inches(tag, FS) >= TX + max([text_inches(R['title'], FS, **BOLD)] + [text_inches(s, FS) for s in R['lines']]) + 0.10 A.plot([BX0, BX1], [y + YL] * 2, color=T_DARK, lw=1.0, solid_capstyle='butt', zorder=3) for xx in (BX0, BX1): A.plot([xx, xx], [y + YL - 0.035, y + YL + 0.035], color=T_DARK, lw=0.8, zorder=3) def zoom(y, x0, x1): """From the orange part of the bar of the row at y to the whole bar of the next row.""" yb, yn = y + BT + BH, y + PITCH + BT A.add_patch(Poly([(x0, yb), (x1, yb), (BX1, yn), (BX0, yn)], closed=True, fc='#f3f3f3', ec='none', zorder=0.5)) for xa, xb in ((x0, BX0), (x1, BX1)): A.plot([xa, xb], [yb, yn], **ZOOM_LINE) def words(y, title, lines): T_(TX, y + 0.16, title, **BOLD) for k, s in enumerate(lines): T_(TX, y + 0.16 + LH * (k + 1), s, color=T_GREY) assert 0.16 + LH * len(lines) + 0.04 <= PITCH def mapax(y): a = fig.add_axes([ML / W, 1 - (y + 0.04 + MH) / H, MW / W, MH / H]); a.set_axis_off(); return a def frame(a, x0, x1, y0, y1, pad=0.06): """The limits of a map: the box x0..x1, y0..y1 with a margin, widened to the shape of the map.""" cx, cy, hw, hh = (x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 2 * (1 + pad), (y1 - y0) / 2 * (1 + pad) if hw / hh < MW / MH: hw = hh * MW / MH else: hh = hw * MH / MW a.set_xlim(cx - hw, cx + hw); a.set_ylim(cy - hh, cy + hh); a.set_aspect('auto') # ---- the maps of the four upper rows: the coarse pictures of Data05 (nearest samples), projected CM = ListedColormap(['white', LAND, G[0], G[1], G[2], C_TRIB]) # 0 sea; 1 other land; 2-4 the greys of the bar; 5 orange assert all(CM.colors[k] == c for k, c in C78.values()) def warp(name, crs, grid_=None, long_=700): with rasterio.open(D05 % name) as r_: a, tr = r_.read(1), r_.transform fill = 255 if a.dtype == np.uint8 else -9; assert not (a == fill).any() if grid_ is None: h, w = a.shape; l, b, r, t = rasterio.transform.array_bounds(h, w, tr) dtr, dw, dh = calculate_default_transform('EPSG:4326', crs, w, h, l, b, r, t); k = max(dw, dh) / long_ grid_ = (dtr * Affine.scale(k), int(np.ceil(dh / k)), int(np.ceil(dw / k))) out = np.full(grid_[1:], fill, a.dtype) reproject(a, out, src_transform=tr, src_crs='EPSG:4326', src_nodata=fill, dst_transform=grid_[0], dst_crs=crs, dst_nodata=fill, resampling=Resampling.nearest) return out, grid_ def show(a, cls, grid_, sel): tr, h, w = grid_ a.imshow(cls, cmap=CM, vmin=-0.5, vmax=5.5, interpolation='nearest', extent=(tr.c, tr.c + w * tr.a, tr.f + h * tr.e, tr.f)) r_, c_ = np.nonzero(sel) frame(a, tr.c + tr.a * c_.min(), tr.c + tr.a * (c_.max() + 1), tr.f + tr.e * (r_.max() + 1), tr.f + tr.e * r_.min()) def paint(name, cls): """A regional map: class cls[the row of basin_id in B] on each basin of the picture; around the picture, the land of group 7 at 0.05° and of the globe at 0.2°, so that the land does not end at the edge of the picture.""" crs = 'EPSG:%d' % EPSG; v, gg = warp(name, crs); c = np.zeros(v.shape, np.uint8) g, _ = warp('globe_level1.tif', crs, gg); s, _ = warp('l1_7.tif', crs, gg) other = (g >= 1) & (g <= 11) & (g != 7) # the land of another group (-1 is that or the sea) c[(v == -9) & (((s == -9) & (g >= 1) & (g <= 11)) | (s >= 0) | ((s == -1) & other))] = 1 c[(v == 0) | ((v == -1) & other)] = 1 ok = v >= 1; i_ = BIX.get_indexer(v[ok]); assert (i_ >= 0).all(); c[ok] = cls[i_] return c, gg, c >= 2 EQE = 'EPSG:8857' # Equal Earth g, gg = warp('globe_level1.tif', EQE) lut = np.zeros(256, np.uint8); lut[1:11] = [5 if k == 6 else 2 + k % 3 for k in range(10)]; lut[11] = 1 RK3 = {d['code']: k for k, d in enumerate(L3['parts'])} # the place of a basin among the 121 of group 782 (as the bar) rk = np.array([RK3.get(int(b), 0) for b in B.basin_id.values]) MAP = {0: (lut[g], gg, g >= 1), 1: paint('l1_7.tif', np.array([5 if x == 78 else 2 + (x - 71) % 3 for x in B.flowdivide_level2_id.values], np.uint8)), 2: paint('l2_78.tif', np.array([C78[x][0] if x in C78 else 1 for x in B.flowdivide_level3_id.values], np.uint8)), 3: paint('l2_78.tif', np.where(B.flowdivide_level3_id.values == 782, np.where(B.basin_id.values == BASIN, 5, 2 + rk % 3), 1).astype(np.uint8))} assert (MAP[3][0] == 5).sum() > 0.9 * (MAP[3][0] >= 2).sum() # the Columbia fills its group on the map, as on the bar # ---- the map of the Columbia (Figure 8's land and rivers): its land light, its main stem blue, the larger rivers grey, the Little Blackfoot orange with rasterio.open(os.path.join(D09, 'Data06j_columbia_owner_008.tif')) as r_: own, otr = r_.read(1), r_.transform COLAND = gpd.GeoDataFrame(geometry=[polygon(own >= 0, otr)], crs=4326).to_crs(EPSG) COLAND['geometry'] = COLAND.simplify(400) RIV = pd.read_parquet(os.path.join(D09, 'Data06j_columbia_rivers.parquet')) RIV = gpd.GeoDataFrame(RIV, geometry=gpd.GeoSeries.from_wkb(RIV.geometry), crs=4326) ms_r = CO['main_stem']['reaches']; ho_r = HO['main_stem']['reaches'] RIV['role'] = np.where(RIV.reach_seq_id.between(ms_r['first'], ms_r['last']), 'main', 'other') assert (RIV.role == 'main').sum() > 0.9 * ms_r['count'], 'the main stem of the Columbia is not in the rivers of Figure 8' # its head, under 100 km², is not assert RIV.reach_seq_id.between(ho_r['first'], ho_r['last']).sum() > 0.9 * ho_r['count'] # the Pend Oreille-Clark Fork is among the rivers kept RIV = RIV[(RIV.role == 'main') | (RIV.upstream_area_km2 >= RIVER_MAP_KM2)].to_crs(EPSG) LBC = AREA.geometry.iloc[0].centroid # ---- the maps of the Little Blackfoot rows: the channel pixels as lines to the pixel they flow to (as in Figure 6) a_ = np.abs(PID) in_si, in_rk, in_rh = ((a_ >= lo) & (a_ <= hi) for lo, hi in ((LO, HI), fl(TG), fl(RH))) poly = gpd.GeoDataFrame({'fc': [F_OTHER, UP]}, geometry=[polygon(in_si & ~in_rk, TR), polygon(in_rk, TR)], crs=4326).to_crs(EPSG) lon, lat = GT * (X['col'].values + 0.5, X['row'].values + 0.5); xy = dict(zip(X.index, zip(lon, lat))) q_ = [q for q in X.index if nd[q] and nd[q] != q] seg = gpd.GeoDataFrame({'q': q_}, geometry=[LineString([xy[q], xy[int(nd[q])]]) for q in q_], crs=4326).to_crs(EPSG) MS = LB['main_stem']['last'] role = lambda q: ('reach' if RH['first'] <= q <= RH['last'] else 'river' if q <= RV['last'] else 'net') if TG['first'] <= q <= TG['last'] else \ 'main' if q <= MS else 'other' seg['role'] = [role(q) for q in seg.q] PXY = gpd.GeoSeries([Point(*xy[P])], crs=4326).to_crs(EPSG).iloc[0] def lines(a, style): for r_, (col, lw) in style.items(): s = seg[seg.role.isin(r_.split())] if len(s): s.plot(ax=a, color=col, linewidth=lw, aspect=None) def pmark(a, x, y, ms): a.plot([x], [y], 'D', ms=ms, mfc='white', mec=T_DARK, mew=0.8, zorder=9) # ================================================================ the header and (a) T_(ML, 0.28, TA, fontsize=FT, **BOLD) def above_at(x0, x1, s): """Where words over a part of a bar too narrow for them go: centred on the part, kept within the bar.""" w = text_inches(s, FS); xc = min(max((x0 + x1) / 2, BX0 + w / 2), BX1 - w / 2) return xc - w / 2, xc + w / 2 def above(xl, y, s, i, **kw): """The words, from xl; below row 1 they lie on the grey of the zoom. Words that reach left of the bar (where there is no zoom) get a halo of that grey instead of a box of it.""" out = xl < BX0 - 1e-9 and i > 0 T_(xl, y + BT - 0.05, s, ha='left', zorder=3, **(dict(path_effects=[pe.withStroke(linewidth=2.4, foreground='#f3f3f3')]) if out else dict(bbox=dict(fc='white' if i == 0 else '#f3f3f3', ec='none', pad=0.8))), **kw) for i, R in enumerate(ROWS): y = Y0 + PITCH * i xa = bar(y, R['lo'], R['hi'], R['parts'], R.get('sel'), R.get('sep')); ends(y, R) words(y, R['title'], R['lines']) if R.get('sel') is not None and i + 1 < len(ROWS): a, b = R['parts'][R['sel']][:2]; zoom(y, xa(a), xa(b + 1)) ax = mapax(y) if i < 4: show(ax, *MAP[i]) elif i == 4: # the Columbia: the Little Blackfoot is a few samples on its map, a ring shows where COLAND.plot(ax=ax, color=F_OTHER, edgecolor='#c8c8c8', linewidth=0.3, aspect=None) RIV[RIV.role == 'other'].plot(ax=ax, color=C_OTHER, linewidth=0.35, aspect=None) RIV[RIV.role == 'main'].plot(ax=ax, color=C_MAIN, linewidth=0.8, aspect=None) AREA.plot(ax=ax, color=C_TRIB, edgecolor=C_TRIB, linewidth=0.4, aspect=None) b_ = COLAND.total_bounds; frame(ax, b_[0], b_[2], b_[1], b_[3], 0.04) ax.plot([LBC.x], [LBC.y], 'o', ms=7.5, mfc='none', mec=T_DARK, mew=0.8, zorder=6, clip_on=False) elif i == 5: # the Little Blackfoot: the land of Telegraph Creek orange, the main stem blue poly.plot(ax=ax, color=poly.fc, edgecolor='white', linewidth=0.2, aspect=None) lines(ax, {'other': (C_OTHER, 0.2), 'net river reach': (C_TRIB, 0.35), 'main': (C_MAIN, 0.7)}) b_ = poly.total_bounds; frame(ax, b_[0], b_[2], b_[1], b_[3], 0.04); pmark(ax, PXY.x, PXY.y, 2.6) elif i == 6: # Telegraph Creek: its path amber, the reach of p orange poly.plot(ax=ax, color=poly.fc, edgecolor='white', linewidth=0.2, aspect=None) lines(ax, {'other': (C_OTHER, 0.3), 'main': (C_MAIN, 1.0), 'net': ('#b3a596', 0.45), 'river': (AMBER, 0.9), 'reach': (C_TRIB, 1.4)}) b_ = poly.geometry.iloc[1].bounds; frame(ax, b_[0], b_[2], b_[1], b_[3], 0.08); pmark(ax, PXY.x, PXY.y, 3.6) else: # the reach: its channel pixels and its land, on the grid of 3″ pixels r_, c_ = np.nonzero(in_rh); r0, r1, c0, c1 = r_.min() - 4, r_.max() + 5, c_.min() - 4, c_.max() + 5 mx, my = 111320 * np.cos(np.radians(PX['lat'])) * GT.a, 110950 * abs(GT.e) nx, ny = c1 - c0, r1 - r0 if nx * mx / (ny * my) < MW / MH: d = int(np.ceil((ny * my * MW / MH / mx - nx) / 2)); c0, c1 = c0 - d, c1 + d else: d = int(np.ceil((nx * mx * MH / MW / my - ny) / 2)); r0, r1 = r0 - d, r1 + d assert r0 >= 0 and c0 >= 0 and r1 <= PID.shape[0] and c1 <= PID.shape[1] v = PID[r0:r1, c0:c1]; q = np.abs(v); rgb = np.ones(v.shape + (3,)) for m, col in (((v < 0) & in_si[r0:r1, c0:c1], F_OTHER), ((v < 0) & in_rk[r0:r1, c0:c1], UP), ((v < 0) & in_rh[r0:r1, c0:c1], UNIT), (v > 0, C_OTHER), ((v > 0) & (q >= TG['first']) & (q <= TG['last']), '#b3a596'), ((v > 0) & (q >= RV['first']) & (q <= RV['last']), AMBER), ((v > 0) & (q >= LO) & (q <= MS), C_MAIN), ((v > 0) & in_rh[r0:r1, c0:c1], C_TRIB)): rgb[m] = to_rgb(col) ax.imshow(rgb, extent=(0, (c1 - c0) * mx, 0, (r1 - r0) * my), interpolation='nearest') pr, pc = int(X.at[P, 'row']) - R0 - r0, int(X.at[P, 'col']) - C0 - c0; assert v[pr, pc] == P frame(ax, 0, (c1 - c0) * mx, 0, (r1 - r0) * my, 0); pmark(ax, (pc + 0.5) * mx, (r1 - r0 - pr - 0.5) * my, 4.2) # a part too narrow for its words gets them above the bar: the groups of the first three rows, the part that the next row # enlarges, and the main stem # (in the Little Blackfoot row the main stem and Telegraph Creek are 0.24 in apart: two such words that would meet are set # apart about the middle of the gap between their parts, the left ones ending there, the right ones starting there) todo = [] for k, (a, b, fc, w1, w2) in enumerate(R['parts']): if w1 and not any(s_ and fits(s_, xa(a), xa(b + 1)) for s_ in (w1, w2)) and (i <= 2 or k == R.get('sel') or w1 == 'main stem'): todo.append([xa(a), xa(b + 1), w1, *above_at(xa(a), xa(b + 1), w1)]); print('row %d: %s above the bar' % (i, w1)) todo.sort(key=lambda t: t[3]) for t, u in zip(todo, todo[1:]): if t[4] + 0.06 > u[3]: assert t[1] < u[0], (i, t, u); m = (t[1] + u[0]) / 2; wt, wu = t[4] - t[3], u[4] - u[3] t[3:5] = m - 0.04 - wt, m - 0.04; u[3:5] = m + 0.04, m + 0.04 + wu assert t[3] >= TX + TW + 0.10 and u[4] <= BX1, (i, t, u); print('row %d: %s and %s set apart' % (i, t[2], u[2])) assert all(t[4] + 0.06 <= u[3] for t, u in zip(todo, todo[1:])), (i, todo) for x0, x1, w1, xl, xr in todo: above(xl, y, w1, i, color={'main stem': T_MAIN, 'Telegraph Creek': T_TRIB, 'Little Blackfoot': T_TRIB}.get(w1, T_DARK)) if i == 6: # what the parts of Telegraph Creek are: its path, then its tributary networks; yk = y + BT - 0.03 # the words of the path, longer than its part, a line higher and joined to its bracket for a, b, s, col, up in ((RV['first'], RV['last'], 'path %s · %d reaches' % (num(PTH), NR), '#8a5a00', True), (RV['last'] + 1, TG['last'], '%d tributary networks' % len(TG['tributaries']), T_DARK, False)): x0, x1 = xa(a), xa(b + 1); ws = text_inches(s, FS) A.plot([x0, x0, x1, x1], [yk + 0.025, yk, yk, yk + 0.025], color=col, lw=0.7, zorder=3) yl = yk - 0.045 - (LH if up else 0); xl = x0 + 0.05 if up else (x0 + x1 - ws) / 2 if up: A.plot([x0, x0], [yk, yl - 0.035], color=col, lw=0.7, zorder=3) else: assert x0 <= xl and xl + ws <= x1, s T_(xl, yl, s, color=col, zorder=3, bbox=dict(fc='#f3f3f3', ec='none', pad=0.8)); assert xl + ws <= BX1, s if i == 7: # p in its reach xp = (xa(P) + xa(P + 1)) / 2; A.plot([xp], [y + BT + BH / 2], 'D', ms=5, mfc='white', mec=T_DARK, mew=0.8, zorder=6) s = 'p = %s = %s + %d' % (num(P), num(RH['first'] - 1), P - RH['first'] + 1); assert xp - text_inches(s, FS) / 2 >= TX + TW + 0.10 T_(xp, y + YP, s, ha='center') # ================================================================ (b) one step up, one step down T_(ML, YB, TB, fontsize=FT, **BOLD) BWS = [max(text_inches(t1, FS, **BOLD), text_inches(t2, FS)) + 0.14 for t1, t2, fc in LADDER] GP = (W - 0.10 - sum(BWS)) / 4; assert GP >= 0.45, GP # the gaps between the boxes hold the two arrows XB = [0.05 + sum(BWS[:k]) + GP * k for k in range(5)] yt, hb = YB + 0.38, 0.42 for (t1, t2, fc), x, bw in zip(LADDER, XB, BWS): dark = fc == C_TRIB A.add_patch(Rectangle((x, yt), bw, hb, fc=fc, ec=T_DARK if fc == 'white' else 'none', lw=0.5, zorder=2)) A.text(x + bw / 2, yt + 0.155, t1, fontsize=FS, ha='center', va='center_baseline', color='white' if dark else T_DARK, zorder=3, **BOLD) A.text(x + bw / 2, yt + 0.315, t2, fontsize=FS, ha='center', va='center_baseline', color='white' if dark else T_DARK, zorder=3) XM, WS = [], [] for k, (fld, n_, a_, b_) in enumerate(STEPS): # above the gap the field (small to large), below it the count and the range (large to small) x0, x1 = XB[k] + BWS[k], XB[k + 1]; xm = (x0 + x1) / 2 last = k == len(STEPS) - 1 # a Level-3 group down: drawn below, from the group into the Path box A.add_patch(FancyArrowPatch((x0 + 0.03, yt + 0.14), (x1 - 0.03, yt + 0.14), arrowstyle='-|>', mutation_scale=7, color=T_GREY, lw=0.8, shrinkA=0, shrinkB=0, zorder=3)) if not last: A.add_patch(FancyArrowPatch((x1 - 0.03, yt + 0.29), (x0 + 0.03, yt + 0.29), arrowstyle='-|>', mutation_scale=7, color=C_TRIB, lw=0.8, shrinkA=0, shrinkB=0, zorder=3)) rows_ = [(fld, yt - 0.07, T_DARK, {})] + ([] if last else [(n_, yt + hb + 0.17, T_TRIB, BOLD), (num(a_), yt + hb + 0.17 + LH, T_GREY, {}), ('to ' + num(b_), yt + hb + 0.17 + 2 * LH, T_GREY, {})]) for s, yy, col, kw in rows_: T_(xm, yy, s, ha='center', color=col, **kw) XM.append(xm); WS.append([text_inches(s, FS, **kw) for s, yy, col, kw in rows_]) assert all(XM[k + 1] - XM[k] >= (WS[k][j] + WS[k + 1][j]) / 2 + 0.10 for k in range(3) for j in range(min(len(WS[k]), len(WS[k + 1])))) # the words of two gaps do not meet assert XM[0] - WS[0][0] / 2 >= 0.03 and XM[-1] + max(WS[-1]) / 2 <= W - 0.03 # area), but the group's paths are; so its orange arrow leaves the group, runs under the Basin box and the words of the gaps, and rises # into the Path box between the words of the second and third gaps, with the count and the range of paths under it fld, n_, a_, b_ = STEPS[-1] x2, x4 = XB[2] + BWS[2] / 2, XB[4] + BWS[4] / 2 assert XM[1] + max(WS[1]) / 2 + 0.06 <= x2 <= XM[2] - max(WS[2]) / 2 - 0.06 # it rises clear of the words of both gaps A.plot([x4, x4, x2, x2], [yt + hb + 0.03, YR, YR, yt + hb + 0.15], color=C_TRIB, lw=0.8, solid_joinstyle='miter', solid_capstyle='butt', zorder=3) A.add_patch(FancyArrowPatch((x2, yt + hb + 0.18), (x2, yt + hb + 0.03), arrowstyle='-|>', mutation_scale=7, color=C_TRIB, lw=0.8, shrinkA=0, shrinkB=0, zorder=3)) s1, s2 = n_, '%s to %s' % (num(a_), num(b_)) w1, w2 = text_inches(s1, FS, **BOLD), text_inches(s2, FS); xs = (x2 + x4) / 2 - (w1 + 0.08 + w2) / 2 T_(xs, YR + 0.20, s1, color=T_TRIB, **BOLD); T_(xs + w1 + 0.08, YR + 0.20, s2, color=T_GREY) assert x2 <= xs and xs + w1 + 0.08 + w2 <= x4 def save(fig, stem): if not FINAL: out = os.path.join(FIGD, stem + '_draft.png'); fig.savefig(out, dpi=200); plt.close(fig); print('draft', out); return 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*')) + glob.glob(os.path.join(FIGD, '_rejected', stem + '_v*'))) if m] out = os.path.join(FIGD, '%s_v%d.png' % (stem, 1 + max(used or [0]))) fig.savefig(out, dpi=300); fig.savefig(out[:-4] + '.pdf'); plt.close(fig) print(out, 'and .pdf; %.0f x %.0f mm' % (W * 25.4, H * 25.4)) save(fig, 'Fig05_objects_chain_littleblackfoot')