# -*- coding: utf-8 -*- """The global map of Figure 9: which of the 10,241 GRDC gauges each 0.05-degree cell drains to. Output: ../Data/Data06e_grdc_gauge_number_globe_005deg.tif (uint16: the gauge, 0 no gauge downstream, 65534 land not numbered, 65535 sea). Input: the global release (paths.GLOBAL) and ../Data/Data06c_grdc_gauges.csv Usage: python Data06e_grdc_gauge_number_globe.py """ import os, sys import numpy as np, pandas as pd, rasterio from affine import Affine from rasterio.enums import Resampling 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 DATD = os.path.join(os.path.dirname(HERE), 'Data') F = 60 # 60 x 3″ = 0.05° rel = Release(RELEASE) assert rel.meta['code_version'] == '10.61' ND = rel.nodata T = pd.read_csv(os.path.join(DATD, 'Data06c_grdc_gauges.csv')) assert len(T) == 10241 and (T.station_seq_id.values == np.arange(1, 10242)).all() and (np.diff(T.pixel_seq_id.values) >= 0).all() G = T.sort_values(['pixel_seq_id', 'own_area_km2'], ascending=[True, False]).drop_duplicates('pixel_seq_id').sort_values('pixel_seq_id') assert len(G) == 10185 and abs(G.own_area_km2.sum() - T.own_area_km2.sum()) < 1e-3, 'the other gauge on a pixel owns nothing' lo, num = G.pixel_seq_id.values.astype('int64'), G.station_seq_id.values.astype('int64') hi = lo + G.upstream_channel_pixel_count.values.astype('int64') - 1 n = len(lo) cut = np.unique(np.concatenate([lo, hi + 1])); owner = np.zeros(len(cut), 'int64'); stack = []; i = 0 for k, x in enumerate(cut): while i < n and lo[i] <= x: stack.append(i); i += 1 while stack and hi[stack[-1]] < x: stack.pop() owner[k] = num[stack[-1]] if stack else 0 def owner_of(v): a = np.abs(np.asarray(v, 'int64')); k = np.searchsorted(cut, a, side='right') - 1 return np.where(k >= 0, owner[np.clip(k, 0, None)], 0) assert (owner_of(lo) == num).all() and (owner_of(-hi) == owner_of(hi)).all() with rasterio.open(rel.file('pixel_seq_id_1km2.tif'), OVERVIEW_LEVEL='NONE') as src: v = src.read(1, out_shape=(src.height // F, src.width // F), resampling=Resampling.nearest).astype('int64') tr = src.transform * Affine.scale(F) sea = v == ND; numbered = ~sea & (v != 0) out = np.where(sea, 65535, np.where(~numbered, 65534, owner_of(np.where(numbered, v, 0)))).astype('uint16') with rasterio.open(os.path.join(DATD, 'Data06e_grdc_gauge_number_globe_005deg.tif'), 'w', driver='GTiff', width=out.shape[1], height=out.shape[0], count=1, dtype='uint16', crs='EPSG:4326', transform=tr, compress='deflate') as d: d.write(out, 1) # the check: the area of each number in the picture against own_area_km2 of the table A_WGS, F_WGS = 6378137.0, 1 / 298.257223563 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) le = tr.f + tr.e * np.arange(out.shape[0] + 1) rk = A_WGS ** 2 * (1 - E2) / 2 * np.radians(abs(tr.a)) * np.abs(_q(le[:-1]) - _q(le[1:])) / 1e6 w = np.repeat(rk, out.shape[1]); m = out.ravel() < 65534 a = np.bincount(out.ravel()[m], weights=w[m], minlength=10242) own = np.zeros(10242); own[T.station_seq_id.values] = T.own_area_km2.values big = own >= 10000 no_sample = (a[1:] == 0) print('shape', out.shape, 'numbers in picture', int((a[1:] > 0).sum()), 'of 10241; no gauge %.2f %%' % (100 * a[0] / a.sum())) print('gauges with no sample: %d, of which own area 0 (the other gauge on a pixel): %d, the rest small gauges: %d (largest own area %.0f km²)' % (no_sample.sum(), np.sum(no_sample & (own[1:] == 0)), np.sum(no_sample & (own[1:] > 0)), own[1:][no_sample].max())) print('own >= 10,000 km²: %d gauges, largest error of area in picture %.1f %%; correlation %.5f' % (big.sum(), 100 * np.abs(a[big] / own[big] - 1).max(), np.corrcoef(a[big], own[big])[0, 1])) print('total gauged in picture %.1f M vs table %.1f M' % (a[1:].sum() / 1e6, own.sum() / 1e6))