# -*- coding: utf-8 -*- """Colours, fonts, the Clark Fork window and small helpers shared by Figures A1-A4. """ import os os.environ.setdefault('OMP_NUM_THREADS', '1'); os.environ.setdefault('PROJ_NETWORK', 'OFF') import numpy as np, pandas as pd, geopandas as gpd, rasterio import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patheffects as pe from matplotlib.font_manager import FontProperties from matplotlib.textpath import text_to_path from affine import Affine from rasterio import features from shapely.geometry import shape, Point from shapely.ops import unary_union plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42, "font.family": "sans-serif", "font.sans-serif": ["Helvetica", "Arial"], "font.size": 8}) BOLD = dict(fontfamily='Arial', fontweight='bold') 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') C_MAIN, C_TRIB, C_OTHER, C_STRIP = '#0072B2', '#D55E00', '#9a9a9a', '#d0d0d0' T_MAIN, T_TRIB, T_DARK, T_GREY = '#005a8c', '#b34e00', '#1f1f1f', '#555555' F_TRIB, F_OTHER = '#f9dcc4', '#f0f0f0' KEYS = ('above', 'trib', 'below') ROLE = {'above': 'upstream', 'trib': 'tributary', 'below': 'downstream'} FILL = {'above': '#cfe4f2', 'trib': '#f6c8a3', 'below': '#8ebbd9'} INK = {'above': T_MAIN, 'trib': T_TRIB, 'below': T_MAIN} HALO = [pe.withStroke(linewidth=2.4, foreground='white')] ZOOM_LINE = dict(color='#777777', lw=0.5, linestyle=(0, (3, 2)), zorder=1) COL = {'main': C_MAIN, 'trib': C_TRIB, 'other': C_STRIP} EPSG = 32612; HALF = 1600.0 # UTM zone 12N (Montana, 112.4° W), so north is up; every junction window is 3.2 km wide, centred on the junction RIVER, TRIB_NAME = 'Clark Fork', 'Little Blackfoot River' num = lambda v: '{:,}'.format(int(v)) def runs(flags): i = np.nonzero(np.asarray(flags))[0] return int(1 + np.sum(np.diff(i) > 1)) if len(i) else 0 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 # ================================================================ the Little Blackfoot in the FlowNest release (flownest_merit90m_global_20261113_195421, code 10.61, numbering_version 0.2) BASIN = 32 # the Columbia, the basin that holds the Little Blackfoot TRIB_PIX, JUNC_PIX = 1088848706, 1088822414 D04 = os.path.join(DATD, 'DataA4_flownest_clarkfork_%s') _ALIAS = {'pixel_1km2': {'pixel_id': 'pixel_seq_id', 'reach_id': 'reach_seq_id', 'river_id': 'path_seq_id'}, 'reach_1km2': {'reach_id': 'reach_seq_id', 'outlet_pixel_id': 'downstream_end_pixel_seq_id', 'river_id': 'path_seq_id', 'river_level': 'path_level'}} def read04(kind): """A cut-out table with the alias_* columns read by the figures; each alias is checked against the release column(s) it comes from.""" d = pd.read_parquet(D04 % ('%s.parquet' % kind)) al = [c for c in d.columns if c.startswith('alias_')]; d = d.rename(columns={c: c[len('alias_'):] for c in al}) assert not d.columns.duplicated().any(), 'an alias name clashes with a release column' for a, b in _ALIAS.get(kind, {}).items(): assert (d[a].values == d[b].values).all(), (kind, a) if kind == 'pixel_1km2': assert (d.upstream_pixel_id_max == d.pixel_seq_id + d.upstream_channel_pixel_count - 1).all() if kind == 'reach_1km2': assert (d.upstream_end_pixel_id == d.downstream_end_pixel_seq_id + d.channel_pixel_count - 1).all() assert (d.upstream_pixel_id_max == d.downstream_end_pixel_seq_id + d.upstream_channel_pixel_count - 1).all() assert (d.upstream_reach_id_max == d.reach_seq_id + d.upstream_reach_count - 1).all() m = d.next_down_reach_id != 0; assert (~m).sum() == 1 and (d.next_down_reach_id[m] == d.next_down_reach_seq_id[m]).all() ue = dict(zip(d.reach_seq_id, d.upstream_end_pixel_id)) # README rule: the pixel below a reach is the upstream end of the next-down reach assert (d.next_down_pixel_id[m].values == np.array([ue[x] for x in d.next_down_reach_seq_id[m]])).all() and (d.next_down_pixel_id[~m] == 0).all() # 0 only at the mouth, which flows out of the cut-out return d BASIN_ROW = read04('basin').iloc[0] LO, HI = int(BASIN_ROW.outlet_pixel_id), int(BASIN_ROW.upstream_pixel_id_max) assert (LO, HI) == (1088820338, 1089010145) and int(BASIN_ROW.basin_id) == BASIN R0, C0 = int(BASIN_ROW.row_min), int(BASIN_ROW.col_min) # the first row and column of the cut-out raster in the whole grid with rasterio.open(D04 % 'pixel_seq_id_1km2.tif') as _r: PID, TR = _r.read(1).astype('int64'), _r.transform # Int64, so that abs() keeps nodata (-2**31) apart assert PID.shape == (int(BASIN_ROW.row_max) - R0, int(BASIN_ROW.col_max) - C0) # row_max and col_max are one past the last (half-open) GT = TR * Affine.translation(-C0, -R0) # row and column of the whole grid (from 0) to longitude and latitude def grid(r0, r1, c0, c1): """Rows r0..r1-1 and columns c0..c1-1 of the whole grid; beyond the cut-out raster, nodata.""" assert r0 < r1 and c0 < c1 out = np.full((r1 - r0, c1 - c0), -2**31, dtype=PID.dtype) a0, a1, b0, b1 = max(r0, R0), min(r1, R0 + PID.shape[0]), max(c0, C0), min(c1, C0 + PID.shape[1]) if a0 < a1 and b0 < b1: out[a0 - r0:a1 - r0, b0 - c0:b1 - c0] = PID[a0 - R0:a1 - R0, b0 - C0:b1 - C0] return out def polygon(mask, tr): return unary_union([shape(g) for g, _ in features.shapes(mask.astype('uint8'), mask=mask, transform=tr)]) _a = np.abs(PID) AREA = gpd.GeoDataFrame(geometry=[polygon((_a >= LO) & (_a <= HI), TR)], crs=4326).to_crs(EPSG) _j = read04('pixel_1km2')[['pixel_id', 'row', 'col']].set_index('pixel_id').loc[JUNC_PIX] JUNCTION = gpd.GeoSeries([Point(*(GT * (_j['col'] + 0.5, _j['row'] + 0.5)))], crs=4326).to_crs(EPSG).iloc[0] # ================================================================ rows of panel (c), the same for every method # A result is two numbers, 'elements' and 'ranges': the n elements of a river lie in k ranges of consecutive identifiers. def stat(cls, key): c = np.asarray(cls) == key; n, r = int(c.sum()), runs(c) return (num(n), num(r)) def order_row(group, l1, level, field, cls, ends, rng=None, cells=None): return dict(group=group, l1=l1, level=level, field=field, kind='order', cls=list(cls), ends=ends, cells=cells, res={k: stat(cls, k) + ((rng or {}).get(k, ''),) for k in ('trib', 'main')}) def none_row(group, l1, text): return dict(group=group, l1=l1, level='', field='', kind='none', text=text, res={'trib': ('', '–', ''), 'main': ('', '–', '')}) def arcset(down, keys): """The links of elements that stand in some order: down[i] is the place of the element that element i flows to (-1: none); keys gives the places of the three elements at the junction. Places are the centres of the cells of a strip.""" return dict(pairs=[(i + 0.5, j + 0.5) for i, j in enumerate(down) if j >= 0], hot={k: (keys[k] + 0.5, down[keys[k]] + 0.5) for k in ('above', 'trib')}, at={k: keys[k] + 0.5 for k in KEYS})