# -*- coding: utf-8 -*- """The one-pass experiment of the paper: every catchment total on the globe in one pass. For every channel pixel, the sum of the pixel areas over its upstream range [p, p + n) is compared with the drainage area of MERIT Hydro (upa); the same pass gives the mean elevation upstream of every GRDC gauge. Input: ../Data/Data06c_grdc_gauges.csv, the global release (paths.GLOBAL) and MERIT Hydro elv and upa (paths.MERIT_HYDRO_DIR). Output: ../Data/Data14_one_pass_global.json and ../Data/Data14_grdc_upstream_elevation.csv (with level-3 IDs given, a pilot run: ../Data/_Data14_pilot.json). Usage: python Data14_one_pass_global.py [workers] [flowdivide_level3_id ...] """ import os, sys, json, time from concurrent.futures import ProcessPoolExecutor import numpy as np, pandas as pd, rasterio, pyarrow.parquet as pq from rasterio.windows import Window from numba import njit 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 from flownest.stats import pixel_areas_km2 # noqa: E402 RELEASE = PTH.GLOBAL MERIT = PTH.MERIT_HYDRO_DIR ELV, UPA = os.path.join(MERIT, 'elv', 'elv_global_90m.tif'), os.path.join(MERIT, 'upa', 'upa_global_90m.tif') DATD = os.path.join(os.path.dirname(HERE), 'Data') BLOCK = 512 * 8 # blocks on the raster's own tiling BINS = np.array([0, 1e-4, 1e-3, 1e-2, 1e-1, 1e30]) # classes of |area from the pass / MERIT's area - 1| @njit(nogil=True) def any_of_group(v, first, last): for r in range(v.shape[0]): for c in range(v.shape[1]): k = int(v[r, c]) if k != -2147483648 and first <= (k if k > 0 else -k) <= last: return True return False @njit(nogil=True) def scan(v, x, area, A, E, Ae, C, first, last): seen = 0 for r in range(v.shape[0]): a = area[r] for c in range(v.shape[1]): k = int(v[r, c]) if k == -2147483648 or k == 0: continue k = k if k > 0 else -k if k < first or k > last: continue i = k - first A[i] += a C[i] += 1 seen += 1 e = x[r, c] if e > -9000: E[i] += a * e Ae[i] += a return seen def blocks(r0, r1, c0, c1): """The window rows r0 .. r1 - 1, columns c0 .. c1 - 1, cut on the blocks of the grid.""" for r in range(r0 // BLOCK * BLOCK, r1, BLOCK): for c in range(c0 // BLOCK * BLOCK, c1, BLOCK): a, b, d, e = max(r, r0), min(r + BLOCK, r1), max(c, c0), min(c + BLOCK, c1) yield Window(d, a, e - d, b - a) def job(g): rel = Release(RELEASE) NR, NC = rel.nrow, rel.ncol first, n = int(g['first_pixel_seq_id']), int(g['channel_pixel_count']) last = first + n - 1 x0, dx, _, y0, _, dy = rel.geotransform area = pixel_areas_km2(y0, -dy, dx, NR)[:, 0] # the row's area from the grid's own edges A = np.zeros(n); E = np.zeros(n); Ae = np.zeros(n); C = np.zeros(n, np.int64) cmin, cmax = int(g['col_min']), int(g['col_max']) parts = [(cmin, cmax)] if cmin >= 0 else [(cmin + NC, NC), (0, cmax)] # a window across 180 degrees: its two parts t0 = time.time(); seen = 0; read = 0 with rasterio.open(rel.file('pixel_seq_id_1km2.tif')) as s, rasterio.open(ELV) as x: for c0, c1 in parts: for w in blocks(int(g['row_min']), int(g['row_max']), c0, c1): v = s.read(1, window=w); read += 1 if not any_of_group(v, first, last): continue e = x.read(1, window=w) seen += scan(v, e, area[w.row_off:w.row_off + w.height], A, E, Ae, C, first, last) t_scan = time.time() - t0 assert C.min() >= 1, 'every channel pixel counts itself' assert seen == int(g['unit_catchment_pixel_count']), 'the land pixels of the group, as metadata.json' t1 = time.time() for a in (A, E, Ae, C): np.cumsum(a, out=a) t_sum = time.time() - t1 assert C[-1] == seen # ---- every channel pixel, its upstream area from the running sum, against MERIT's area at its pixel t2 = time.time() P = rel.pixels(first, n, ['row', 'col', 'upstream_channel_pixel_count']) u = rel.values_at(P['row'], P['col'], raster=UPA).astype(np.float64) assert u.min() > 0, 'MERIT gives an area at every channel pixel' o = np.arange(n) + P['upstream_channel_pixel_count'].astype(np.int64) - 1 assert (o >= np.arange(n)).all() and o.max() < n, 'the upstream range stays in the group' before = lambda a: np.r_[0, a[:-1]] up = A[o] - before(A) vis = C[o] - before(C) ratio = up / u; r_ = np.abs(ratio - 1); big = u >= 100 j = int(np.argmax(r_)) r0, nr = int(g['first_reach_seq_id_1km2']), int(g['reach_count_1km2']) Rg = pq.read_table(rel.file('reach_1km2.parquet'), columns=['downstream_end_pixel_seq_id', 'channel_pixel_count', 'upstream_area_km2'], filters=[('reach_seq_id', '>=', r0), ('reach_seq_id', '<', r0 + nr)]).to_pandas() assert len(Rg) == nr sm = (Rg.upstream_area_km2.values < np.float32(1)) & (Rg.channel_pixel_count.values == 1) io = Rg.downstream_end_pixel_seq_id.values[sm].astype(np.int64) - first assert (o[io] == io).all(), 'a small basin is its outlet alone' t_check = time.time() - t2 # ---- the stations in this group T = pd.read_csv(os.path.join(DATD, 'Data06c_grdc_gauges.csv')) T = T[(T.pixel_seq_id >= first) & (T.pixel_seq_id <= last)].copy() i = T.pixel_seq_id.values.astype(np.int64) - first; q = i + T.upstream_channel_pixel_count.values.astype(np.int64) - 1 sub = lambda a: a[q] - np.where(i > 0, a[np.maximum(i - 1, 0)], 0) T['up_land_km2'] = sub(A); T['up_land_pixels'] = sub(C) with np.errstate(invalid='ignore', divide='ignore'): T['up_mean_elev_m'] = sub(E) / sub(Ae) out = dict(flowdivide_level3_id=int(g['flowdivide_level3_id']), first=first, numbers=n, land_pixels=int(seen), blocks_read=read, land_km2=float(A[-1]), small_basins=int(sm.sum()), land_small_basins_km2=float(up[io].sum()), seconds_scan=round(t_scan, 1), seconds_running_sum=round(t_sum, 2), seconds_check=round(t_check, 1), area_ratio_hist=np.histogram(r_, BINS)[0].tolist(), area_ratio_hist_small_basins=np.histogram(r_[io], BINS)[0].tolist(), area_ratio_hist_100km2=np.histogram(r_[big], BINS)[0].tolist(), worst=float(r_[j]), worst_pixel_seq_id=first + j, worst_100km2=float(r_[big].max()) if big.any() else 0.0, ratio_min=float(ratio.min()), ratio_max=float(ratio.max()), visits_every_catchment=int(vis.sum()), stations=len(T), visits_stations=int(T.up_land_pixels.sum()), stations_mean_ratio_q=[float(t) for t in np.quantile(T.up_land_km2 / T.upstream_area_km2, [0, .01, .5, .99, 1])] if len(T) else []) print('L3 %d: %d numbers, %d land pixels, %d blocks; %.0f + %.1f + %.0f s; ratio %.6f - %.6f' % (out['flowdivide_level3_id'], n, seen, read, t_scan, t_sum, t_check, out['ratio_min'], out['ratio_max']), flush=True) return out, T if __name__ == '__main__': args = sys.argv[1:] w = int(args[0]) if args else 4 pick = [int(a) for a in args[1:]] rel = Release(RELEASE) G = pd.DataFrame(rel.meta['flowdivide_level3_groups']) assert G.channel_pixel_count.sum() == rel.meta['channel_pixel_count'] == 1223005242 and len(G) == 313 assert (G.first_pixel_seq_id.values[1:] == (G.first_pixel_seq_id + G.channel_pixel_count).values[:-1]).all(), 'the groups tile the number axis' if pick: G = G[G.flowdivide_level3_id.isin(pick)] assert len(G) == len(pick), 'a flowdivide_level3_id that is not in metadata.json' G = G.sort_values('channel_pixel_count', ascending=False) # the longest first, so that no long group starts late t0 = time.time() with ProcessPoolExecutor(w) as ex: res = list(ex.map(job, [r._asdict() for r in G.itertuples(index=False)], chunksize=1)) wall = round(time.time() - t0) S = sorted((r[0] for r in res), key=lambda s: s['first']) J = dict(release=os.path.basename(RELEASE), workers=w, wall_seconds=wall, sets=S) Q = pd.concat([r[1] for r in res]).sort_values('station_seq_id') json.dump(J, open(os.path.join(DATD, 'Data14_one_pass_global.json' if not pick else '_Data14_pilot.json'), 'w'), indent=1) Q.to_csv(os.path.join(DATD, 'Data14_grdc_upstream_elevation.csv' if not pick else '_Data14_pilot.csv'), index=False) # ---- the sums over the groups, the figures' numbers CELLS = sum(s['land_pixels'] for s in S); NUMS = sum(s['numbers'] for s in S); ALL = sum(s['visits_every_catchment'] for s in S) GAUGES = sum(s['visits_stations'] for s in S); HIST = np.sum([s['area_ratio_hist'] for s in S], axis=0) H100 = np.sum([s['area_ratio_hist_100km2'] for s in S], axis=0); HSM = np.sum([s['area_ratio_hist_small_basins'] for s in S], axis=0) LAND = sum(s['land_km2'] for s in S); LSM = sum(s['land_small_basins_km2'] for s in S) print('%d workers, %d s; %d land pixels, %d numbers, %d stations' % (w, wall, CELLS, NUMS, sum(s['stations'] for s in S))) print('land %.0f km2, of it the %d basins of 0.05-1 km2 %.0f km2; without them %.0f km2' % (LAND, sum(s['small_basins'] for s in S), LSM, LAND - LSM)) print('visits: every catchment %.3e (%.0f x the land pixels), the stations %.3e (%.2f x)' % (ALL, ALL / CELLS, GAUGES, GAUGES / CELLS)) print('area ratio %.7f - %.7f; classes of |ratio - 1| %s; of the small basins %s; of the channels of at least 100 km2 %s, largest %.6f' % (min(s['ratio_min'] for s in S), max(s['ratio_max'] for s in S), HIST.tolist(), HSM.tolist(), H100.tolist(), max(s['worst_100km2'] for s in S))) print('seconds, sum over the groups: pass %.0f, running sum %.0f, check %.0f' % (sum(s['seconds_scan'] for s in S), sum(s['seconds_running_sum'] for s in S), sum(s['seconds_check'] for s in S))) if not pick: assert NUMS == 1223005242 and HIST.sum() == NUMS and sum(s['stations'] for s in S) == 10241 and sum(s['small_basins'] for s in S) == 2228923