# -*- coding: utf-8 -*- """The three small maps of Figure 5. globe_level1 at 0.2 degree (1-9 the level-1 groups, 10 the extra FullBasin groups, 11 land not numbered, 0 sea); l1_7 at 0.05 degree and l2_78 at 0.02 degree (basin_id; 0 small basin or not numbered; -1 sea or other group). Input: the global release (paths.GLOBAL). Output: three GeoTIFFs in ../Data (Data05c_*). Usage: python Data05c_flownest_coarse_maps_level1_group7.py """ import os, json import numpy as np, pandas as pd, rasterio from rasterio.enums import Resampling from rasterio.windows import Window import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import paths as PTH REL = PTH.GLOBAL HERE = os.path.dirname(os.path.abspath(__file__)) DATD = os.path.join(os.path.dirname(HERE), 'Data'); os.makedirs(DATD, exist_ok=True) OUT = os.path.join(DATD, 'Data05c_flownest_%s') GROUP = 7 WINDOWS = {'l1_7': ((26721, 95400), (50440, 152858), 60), 'l2_78': ((30105, 52665), (50440, 84304), 24)} meta = json.load(open(os.path.join(REL, 'metadata.json'))) assert meta['code_version'] == '10.61' and meta['numbering_sha256'][:12] == 'c485dec56c3a' G = pd.DataFrame(meta['flowdivide_level3_groups']).sort_values('first_pixel_seq_id').reset_index(drop=True) gf, gn = G.first_pixel_seq_id.values.astype('int64'), G.channel_pixel_count.values.astype('int64') assert gf[0] == 1 and (gf[1:] == gf[:-1] + gn[:-1]).all() and gf[-1] + gn[-1] - 1 == meta['channel_pixel_count'], 'the groups tile the numbers' l1 = G.flowdivide_level1_id.values.astype('int64') cls1 = np.where(l1 < 10, l1, 10).astype('uint8') # the class of each Level-3 group on the globe g7 = G[G.flowdivide_level1_id == GROUP]; assert (np.diff(g7.index) == 1).all(), 'group 7 is one range' P7 = (int(g7.first_pixel_seq_id.iloc[0]), int(g7.first_pixel_seq_id.iloc[-1] + g7.channel_pixel_count.iloc[-1])) # [first, end) B = pd.read_parquet(os.path.join(REL, 'flownest_merit90m_basin.parquet'), columns=['basin_id', 'flowdivide_level1_id', 'outlet_pixel_seq_id', 'channel_pixel_count']).sort_values('outlet_pixel_seq_id') bo, bn, bid = (B[c].values.astype('int64') for c in ('outlet_pixel_seq_id', 'channel_pixel_count', 'basin_id')) assert (bo[1:] >= bo[:-1] + bn[:-1]).all(), 'the basins of the table do not overlap' with rasterio.open(os.path.join(REL, 'flownest_merit90m_pixel_seq_id_1km2.tif')) as src: ND, crs = src.nodata, src.crs # ---- the globe f = 240 v = src.read(1, out_shape=(src.height // f, src.width // f), resampling=Resampling.nearest).astype('int64') tr = src.transform * src.transform.scale(src.width / v.shape[1], src.height / v.shape[0]) k = np.clip(np.searchsorted(gf, np.abs(v), side='right') - 1, 0, len(gf) - 1) g = np.where(v == ND, 0, np.where(v == 0, 11, cls1[k])).astype('uint8') with rasterio.open(OUT % 'globe_level1.tif', 'w', driver='GTiff', width=g.shape[1], height=g.shape[0], count=1, dtype='uint8', crs=crs, transform=tr, compress='deflate') as dst: dst.write(g, 1) print('globe %s: cells by class 0-11' % (g.shape,), np.bincount(g.ravel(), minlength=12).tolist()) # ---- Level-1 group 7 and Level-2 group 78: basin_id for name, ((r0, r1), (c0, c1), f) in WINDOWS.items(): w = Window(c0, r0, c1 - c0, r1 - r0) v = src.read(1, window=w, out_shape=(-(-(r1 - r0) // f), -(-(c1 - c0) // f)), resampling=Resampling.nearest).astype('int64') tr = src.window_transform(w) * src.window_transform(w).scale((c1 - c0) / v.shape[1], (r1 - r0) / v.shape[0]) a = np.abs(v); in7 = (v != ND) & (v != 0) & (a >= P7[0]) & (a < P7[1]) i = np.clip(np.searchsorted(bo, a, side='right') - 1, 0, len(bo) - 1) ok = in7 & (a >= bo[i]) & (a < bo[i] + bn[i]) assert (B.flowdivide_level1_id.values[i[ok]] == GROUP).all(), 'a basin of the range of group 7 is in group 7' m = np.where(ok, bid[i], np.where(in7 | (v == 0), 0, -1)).astype('int32') with rasterio.open(OUT % (name + '.tif'), 'w', driver='GTiff', width=m.shape[1], height=m.shape[0], count=1, dtype='int32', crs=crs, transform=tr, compress='deflate') as dst: dst.write(m, 1) print('%s: %s cells, %d basins seen, %d cells of land of group 7 in no basin of the table, rows %d-%d cols %d-%d' % (name, m.shape, len(np.unique(m[m > 0])), int((m == 0).sum()), r0, r1, c0, c1)) print('written to', DATD)