# -*- coding: utf-8 -*- """The 174 GRDC gauges of the Columbia for Figure 8. Output: ../Data/Data06j_columbia_owner_008.tif and ../Data/Data06j_columbia_clarkfork_owner_004.tif (int16, the gauge each cell drains to), ../Data/Data06j_columbia_gauges.csv, ../Data/Data06j_columbia_rivers.parquet (channels of at least 100 km2) and ../Data/Data06j_columbia_summary.json Input: the global release (paths.GLOBAL), ../Data/Data06c_grdc_gauges.csv and the GRDC station names (paths.GRDC_SUMMARY_CSV). Usage: python Data06j_columbia_gauges_nested.py """ import os, sys, json, csv import numpy as np, pandas as pd, rasterio import pyarrow.dataset as ds from affine import Affine from rasterio.windows import Window HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH from flownest import Release # noqa: E402 RELEASE = PTH.GLOBAL NAMES = PTH.GRDC_SUMMARY_CSV DATD = os.path.join(os.path.dirname(HERE), 'Data') GAUGES = os.path.join(DATD, 'Data06c_grdc_gauges.csv') OUT = os.path.join(DATD, 'Data06j_columbia_%s') MOUTH, CLARK = 4115201, 4115346 # GRDC numbers: the lowest gauge of the Columbia, of the Clark Fork MARGIN = 0.3 # degrees around a window RIVER_MIN = 100.0 # km², upstream area of the rivers kept rel = Release(RELEASE) ND = rel.nodata GT = Affine.from_gdal(*rel.geotransform) os.makedirs(DATD, exist_ok=True) A_WGS, F_WGS = 6378137.0, 1 / 298.257223563 # WGS84 area of a row of samples, as the release (metadata.json: earth_model) E2 = F_WGS * (2 - F_WGS); E1 = np.sqrt(E2) def _q(lat): s = np.sin(np.radians(lat)) return s / (1 - E2 * s * s) + np.log((1 + E1 * s) / (1 - E1 * s)) / (2 * E1) def row_km2(lat_top, lat_bottom, dlon): return A_WGS ** 2 * (1 - E2) / 2 * np.radians(dlon) * np.abs(_q(lat_top) - _q(lat_bottom)) / 1e6 assert abs(row_km2(90, -90, 360) / 510065621.7 - 1) < 1e-8 # ================================================================ 1. the Columbia and its gauges T = pd.read_csv(GAUGES) m = T[T.grdc_station_id == MOUTH].iloc[0] COL = int(m.basin_id) # the Columbia in the gauge table assert rel.meta['code_version'] == '10.61' and COL == 32, 'the Columbia is FullBasin 32' b = rel.basin(COL) blo = int(b['outlet_pixel_seq_id']); bhi = blo + int(b['channel_pixel_count']) - 1 A = T[T.basin_id == COL].reset_index(drop=True) A = pd.DataFrame(dict(k=A.basin_station_seq_id, grdc_station_id=A.grdc_station_id, lon=A.lon, lat=A.lat, pixel_seq_id=A.pixel_seq_id, upstream_channel_pixel_count=A.upstream_channel_pixel_count, upstream_area_km2=A.upstream_area_km2, own_area_km2=A.own_area_km2, n_all_up=A.upstream_station_count - 1, # the other gauges upstream (Data06c counts itself) station_seq_id=A.station_seq_id, next_down_station_seq_id=A.next_down_station_seq_id)) ns = len(A) PX_ = rel.rows_at('pixel_1km2.parquet', A.pixel_seq_id.values, ['pixel_seq_id', 'basin_id', 'upstream_area_km2', 'upstream_channel_pixel_count']) PX_ = pd.DataFrame(PX_) if isinstance(PX_, dict) else PX_ assert (PX_.pixel_seq_id.values == A.pixel_seq_id.values).all() and (PX_.basin_id.values == COL).all() assert (PX_.upstream_channel_pixel_count.values == A.upstream_channel_pixel_count.values).all() assert np.abs(PX_.upstream_area_km2.values / A.upstream_area_km2.values - 1).max() < 1e-6, 'the gauge pixels in the pixel table' assert ns == 174 and (A.k.values == np.arange(1, ns + 1)).all() and (A.pixel_seq_id.values >= blo).all() and (A.pixel_seq_id + A.upstream_channel_pixel_count - 1 <= bhi).all() assert int(m.basin_station_seq_id) == 1 and A.n_all_up[0] == ns - 1, 'gauge 1, at the mouth, holds every other gauge' alo = A.pixel_seq_id.values.astype('int64'); ahi = alo + A.upstream_channel_pixel_count.values.astype('int64') - 1 dk = np.zeros(ns, 'int64'); dep = np.zeros(ns, 'int64'); stack = [] for i in range(ns): # the gauges related again from their ranges alone while stack and ahi[stack[-1]] < alo[i]: stack.pop() if stack: assert ahi[i] <= ahi[stack[-1]], 'two ranges cross' dk[i], dep[i] = stack[-1] + 1, len(stack) stack.append(i) assert (np.where(A.next_down_station_seq_id > 0, A.next_down_station_seq_id - A.station_seq_id[0] + 1, 0) == dk).all(), 'the first gauge downstream in Data06c' assert (np.searchsorted(alo, ahi, side='right') - A.k.values == A.n_all_up.values).all(), 'the gauges upstream are the next numbers' A['next_down_k'] = dk; A['depth'] = dep A = A.drop(columns=['station_seq_id', 'next_down_station_seq_id']) second = np.r_[alo[1:] != alo[:-1], True] # the last gauge of its pixel holds the own land assert (A.own_area_km2.values[~second] == 0).all() rounds = np.ones(ns, 'int64') for i in range(ns - 1, -1, -1): # in decreasing number every gauge comes after the gauges upstream of it if dk[i]: rounds[dk[i] - 1] = max(rounds[dk[i] - 1], rounds[i] + 1) A['round'] = rounds ck = int(A.k[A.grdc_station_id == CLARK].iloc[0]) assert (ck, A.n_all_up[ck - 1], rounds[ck - 1]) == (47, 13, 6), 'gauge 47 with gauges 48 to 60 upstream, 6 rounds' print('1. the Columbia: basin %d, range %d-%d (%d pixels), %.0f km²; %d gauges on %d pixels, depth 0-%d, %d rounds; the Clark Fork: gauges %d-%d, %d rounds' % (COL, blo, bhi, bhi - blo + 1, b['upstream_area_km2'], ns, len(np.unique(alo)), A.depth.max(), rounds.max(), ck, ck + A.n_all_up[ck - 1], rounds[ck - 1])) print(' gauges per depth', A.depth.value_counts().sort_index().to_dict(), '; pixels with two gauges', int((~second).sum())) cut = np.unique(np.concatenate([alo[second], ahi[second] + 1])); owner = np.zeros(len(cut), 'int64'); stack = []; i = 0 glo, ghi, gk = alo[second], ahi[second], A.k.values[second] for j, c in enumerate(cut): while i < len(glo) and glo[i] <= c: stack.append(i); i += 1 while stack and ghi[stack[-1]] < c: stack.pop() owner[j] = gk[stack[-1]] if stack else 0 def owner_of(v): a = np.abs(np.asarray(v, 'int64')); j = np.searchsorted(cut, a, side='right') - 1 return np.where(j >= 0, owner[np.clip(j, 0, None)], 0) assert (owner_of(glo) == gk).all() and (owner_of(-ghi) == owner_of(ghi)).all() # ================================================================ 2. the owner of every sample of two windows P = rel.file('pixel_seq_id_1km2.tif') def owners(lon0, lon1, lat0, lat1, ovr, f, name): with rasterio.open(P) as s, rasterio.open(P, overview_level=ovr) as o: TO = s.transform * Affine.scale(f) # overview sample (i, j) is pixel (f i, f j): top-left sampling, checked below assert o.shape == (s.height // f, s.width // f), o.shape c0, r0 = [int(np.floor(t)) for t in ~TO * (lon0, lat1)] c1, r1 = [int(np.ceil(t)) for t in ~TO * (lon1, lat0)] W = Window(c0, r0, c1 - c0, r1 - r0); V = o.read(1, window=W).astype('int64') TW = TO * Affine.translation(c0, r0) i, j = V.shape[0] // 2, V.shape[1] // 2 # one block of the full raster against the overview full = s.read(1, window=Window((c0 + j) * f, (r0 + i) * f, 40 * f, 40 * f)) assert (full[::f, ::f] == V[i:i + 40, j:j + 40]).all(), 'the overview is not top-left sampling' inb = (V != ND) & (np.abs(V) >= blo) & (np.abs(V) <= bhi) R = np.where(inb, owner_of(V), np.where(V == ND, -2, -1)).astype('int16') lat = TW.f + TW.e * (np.arange(R.shape[0]) + 0.5) km2 = row_km2(lat - TW.e / 2, lat + TW.e / 2, TW.a)[:, None] * np.ones((1, R.shape[1])) area = np.bincount(R[inb].astype('int64'), weights=km2[inb], minlength=ns + 1) prof = dict(driver='GTiff', height=R.shape[0], width=R.shape[1], count=1, dtype='int16', crs='EPSG:4326', transform=TW, compress='deflate', nodata=-2) with rasterio.open(OUT % name, 'w', **prof) as d: d.write(R, 1) return R, TW, area assert b['col_min'] >= 0, 'not across 180 degrees' x0, y1 = GT * (b['col_min'], b['row_max']); x1, y0 = GT * (b['col_max'], b['row_min']) # the maxima are one past the last R, TW, area = owners(x0 - MARGIN, x1 + MARGIN, y1 - MARGIN, y0 + MARGIN, 2, 8, 'owner_008.tif') assert abs(area.sum() / b['upstream_area_km2'] - 1) < 0.01, area.sum() big = A.own_area_km2.values >= 5e3 err = area[1:][big] / A.own_area_km2.values[big] - 1 assert np.abs(err).max() < 0.05, err for k in A.k[big]: # every large own land holds its gauge c, r = [int(t) for t in ~TW * (A.lon[k - 1], A.lat[k - 1])] assert (R[max(r - 4, 0):r + 5, max(c - 4, 0):c + 5] == k).any(), k print('2. basin window %d x %d; %.0f km² sampled (table %.0f); %d own lands >= 5,000 km² within %.1f%%; no gauge downstream %.0f km²' % (R.shape[0], R.shape[1], area.sum(), b['upstream_area_km2'], big.sum(), 100 * np.abs(err).max(), area[0])) cs = A[(A.k >= ck) & (A.k <= ck + A.n_all_up[ck - 1])] rr, cc = np.nonzero(np.isin(R, cs.k.values)) # the Clark Fork upstream of gauge 47 on the basin window, with a margin lo_, hi_ = TW * (cc.min(), rr.max() + 1), TW * (cc.max() + 1, rr.min()) ck_box = tuple(round(v, 2) for v in (lo_[0] - 0.1, hi_[0] + 0.1, lo_[1] - 0.1, hi_[1] + 0.1)) R4, T4, a4 = owners(*ck_box, 1, 4, 'clarkfork_owner_004.tif') inside = np.isin(R4, cs.k.values) edge = np.concatenate([inside[0], inside[-1], inside[:, 0], inside[:, -1]]) assert not edge.any(), 'the Clark Fork reaches the edge of its window' ca = a4[cs.k.values].sum() assert abs(ca / A.upstream_area_km2[ck - 1] - 1) < 0.01, (ca, A.upstream_area_km2[ck - 1]) print(' Clark Fork window %d x %d; %.0f km² sampled (table %.0f)' % (R4.shape[0], R4.shape[1], ca, A.upstream_area_km2[ck - 1])) # ================================================================ 3. the rivers rf, rn = rel.reach_range(COL) # the reaches of the Columbia: one range; the lines carry only reach_seq_id RR = pd.DataFrame(rel.reaches(rf, rn, columns=['reach_seq_id', 'downstream_end_pixel_seq_id', 'basin_id', 'upstream_area_km2'])) assert (RR.basin_id == COL).all() and RR.reach_seq_id.iloc[0] == rf and len(RR) == rn RR = RR[RR.upstream_area_km2 >= RIVER_MIN].drop(columns='basin_id') L = ds.dataset(rel.file('reach_line_1km2.geo.parquet')).to_table( columns=['reach_seq_id', 'geometry'], filter=ds.field('reach_seq_id').isin(RR.reach_seq_id.values)).to_pandas() L = RR.merge(L, on='reach_seq_id', how='left', validate='1:1'); assert L.geometry.notna().all() assert len(L) and L.upstream_area_km2.max() <= b['upstream_area_km2'] * 1.001 L.to_parquet(OUT % 'rivers.parquet') print('3. %d river reaches >= %.0f km²' % (len(L), RIVER_MIN)) # ================================================================ 4. the names, and the files nm = {} for r in list(csv.reader(open(NAMES, encoding='latin-1')))[2:]: try: nm[int(r[14])] = (r[17].strip(), r[18].strip()) except (ValueError, IndexError): pass assert all(g in nm for g in A.grdc_station_id), 'a gauge without a name' A['river'] = [nm[g][0] for g in A.grdc_station_id]; A['station'] = [nm[g][1] for g in A.grdc_station_id] assert A.river[0] == 'COLUMBIA RIVER' and A.river[ck - 1] == 'CLARK FORK' A['pixel_local_first'] = alo - blo + 1 # pixel numbers counted from 1 at the outlet of the basin A['pixel_local_last'] = ahi - blo + 1 A['own_area_sampled_km2'] = area[1:].round(0) A.to_csv(OUT % 'gauges.csv', index=False) J = dict(basin_id=COL, first=blo, last=bhi, pixels=bhi - blo + 1, area_km2=float(b['upstream_area_km2']), outlet_lon=float(b['outlet_lon']), outlet_lat=float(b['outlet_lat']), gauges=ns, depth_max=int(A.depth.max()), rounds=int(rounds.max()), clark_gauge=ck, clark_gauges=int(A.n_all_up[ck - 1] + 1), clark_rounds=int(rounds[ck - 1]), clark_box=ck_box, no_gauge_km2=float(area[0]), step_deg=TW.a, clark_step_deg=T4.a) json.dump(J, open(OUT % 'summary.json', 'w'), indent=1) print('4. written:', ', '.join(os.path.basename(OUT % s) for s in ['owner_008.tif', 'clarkfork_owner_004.tif', 'gauges.csv', 'rivers.parquet', 'summary.json']))