"""How PixelGust makes its Topographic Wetness Index (TWI) layer.

Contains information from MERIT Hydro (https://global-hydrodynamics.github.io/MERIT_Hydro/),
which is made available here under the Open Database License (ODbL 1.0,
https://opendatacommons.org/licenses/odbl/1-0/). The TWI values PixelGust serves are derived
from MERIT Hydro and are licensed under the ODbL too. This file is the method of making them
(ODbL section 4.6 b), and https://pixelgust.com/docs#twi-data describes it in words. You may use,
copy and change this file freely.

Inputs, both free to download:
  upa        MERIT Hydro version 1.0.1, upstream drainage area in km2 on a 3 arc-second grid, in
             tiles of 5 degrees (Yamazaki et al. 2019). MERIT Hydro asks you to register first.
             A whole download is 57 tar files of 30 degrees holding 1,150 tiles of 6000 x 6000
             cells. Both are named by their lower-left corner, such as n30e005_upa.tif in
             upa_n30e000.tar. Count them, because a tar you lack reads just like open sea.
  elevation  USGS GMTED2010 breakline emphasis at 7.5 arc-seconds (be75, public domain), a zip of
             3,053,712,331 bytes:
             https://edcintl.cr.usgs.gov/downloads/sciweb1/shared/topo/downloads/GMTED/Grid_ZipFiles/be75_grd.zip

The grid. A cell of the layer is PIXEL_DEG degrees wide and high, about 250 m. Row 0 starts at NORTH
and rows count south, column 0 starts at WEST and columns count east, so that cell_lon() and
cell_lat() give the centre of any cell. The layer has ROWS rows and COLUMNS columns, held in four
files that share row 43200 and column 86399, and the header of each file states this grid to nine
decimals.

Each cell reads both sources at its own centre. Arrays are north-up. This file holds the arithmetic,
which needs numpy only. You supply the reading: a GeoTIFF and ArcGrid reader such as GDAL, and a
loop over tiles that calls upstream_area() only with centres inside the tile.
  1. Elevation. A cell takes the GMTED cell that holds its centre. That is always GMTED's row
     (row - GMTED_FIRST_ROW) and the same column, so the two grids pair up one to one.
  2. Slope. slope_deg() works on GMTED's own rows and columns and gives whole degrees. Before you
     call it, set GMTED's nodata, which is NO_VALUE, to NaN. At the 180 degree line a cell's
     neighbour is the first or last column, so add the last column before the first and the first
     after the last. Give it gmted_lat() of its rows, not cell_lat(), since the two can round a
     slope differently. TWI takes the rounded slope.
  3. Upstream area. upstream_area() takes the mean of each 2 x 2 block of upa cells, which gives
     6 arc-seconds, with blocks counted from the edge of the 5 degree tile, and a cell takes the
     block that holds its centre. The tile is the one that holds the centre too. The mean is kept
     as float32, as MERIT Hydro keeps upa.
  4. TWI. twi() combines them, and stored() is the value the layer holds: TWI x 10, rounded to a
     whole number. It takes pi as PI, as the script that built the layer wrote it.
  5. No value. A block of sea has no upa, and neither does a place MERIT Hydro has no tile for. A
     cell with no upa has no TWI, on sea and on land alike, whatever GMTED says there. A cell in a
     void of GMTED or beside one has no slope, and a cell north of 84 N or south of 56 S has no
     elevation, so neither has a TWI. A cell with upa where GMTED says 0 is land and has a TWI.
     A cell with no TWI holds NO_VALUE in the one-band copy of the layer made for publishing. In
     the four-band files the site reads it holds 0 on sea and where GMTED has no elevation, and
     NO_VALUE on the rest. The lowest TWI seen is 0.8, so 0 marks no value.
"""
import numpy as np

PIXEL_DEG = 0.0020833368743186295  # a cell of the layer, a little over 7.5 arc-seconds
WEST = -180.00013888888893  # the outer west edge of column 0
NORTH = 90.00195464602304  # the outer north edge of row 0
ROWS = 86401
COLUMNS = 172800
GMTED_FIRST_ROW = 2881  # the layer's row that holds GMTED's row 0
GMTED_NORTH = 83.99986111111106  # the outer north edge of GMTED's row 0, as its header states it
GMTED_CELL_DEG = 7.5 / 3600.0
UPA_CELL_DEG = 3.0 / 3600.0
BLOCK_DEG = 2 * UPA_CELL_DEG  # 2 x 2 cells of upa
CONTOUR_WIDTH_M = 250.0  # upstream area per metre of contour, at about the pixel size
SLOPE_FLOOR_RAD = 0.001  # so a flat cell does not divide by zero
PI = 3.14159  # true pi changes the stored value by 0.1 in about 1 cell of 200,000
METRES_PER_DEGREE = 111195.052  # a degree on a sphere of radius 6,371,007.2 m
NO_VALUE = -32768


def cell_lon(column):
    """The longitude of a cell's centre, from its column or an array of columns."""
    return WEST + (np.asarray(column, dtype=float) + 0.5) * PIXEL_DEG


def cell_lat(row):
    """The latitude of a cell's centre, from its row or an array of rows."""
    return NORTH - (np.asarray(row, dtype=float) + 0.5) * PIXEL_DEG


def gmted_lat(row):
    """The latitude of the centre of GMTED's row, from its row or an array of rows. GMTED's rows
    count south from GMTED_NORTH, so this is not cell_lat() of the layer's row."""
    return GMTED_NORTH - (np.asarray(row, dtype=float) + 0.5) * GMTED_CELL_DEG


def upstream_area(upa_km2, west, north, lons, lats):
    """upa of one tile at the cell centres lons x lats: an array of len(lats) rows and len(lons)
    columns. A centre outside the tile raises ValueError. west and north are the tile's outer
    edges, as its header states them: half a cell of upa west and south of the whole degrees of its
    name and size.
    Sea cells, which MERIT Hydro marks with -9999, stay out of the mean of a 2 x 2 block, and a
    block of sea has no value (NaN). The answer is float32, which decides the last digit of about
    1 cell in 3 million."""
    upa = np.asarray(upa_km2, dtype=float)
    h, w = upa.shape[0] // 2 * 2, upa.shape[1] // 2 * 2
    blocks = upa[:h, :w].reshape(h // 2, 2, w // 2, 2)
    land = blocks >= 0
    count = land.sum(axis=(1, 3))
    mean = np.where(land, blocks, 0.0).sum(axis=(1, 3)) / np.maximum(count, 1)
    mean = np.where(count > 0, mean, np.nan)
    i = np.floor((north - np.asarray(lats, dtype=float)) / BLOCK_DEG).astype(int)
    j = np.floor((np.asarray(lons, dtype=float) - west) / BLOCK_DEG).astype(int)
    if ((i < 0) | (i >= mean.shape[0])).any() or ((j < 0) | (j >= mean.shape[1])).any():
        raise ValueError("a cell centre lies outside this tile")
    return mean[np.ix_(i, j)].astype(np.float32)


def slope_deg(elevation_m, row_lat):
    """Slope in whole degrees from each cell's four neighbours, on GMTED's rows and columns, with
    its nodata set to NaN so that a void and the cells beside it have no value. row_lat holds
    gmted_lat() of each row, because a cell's east-west width shrinks with cos(lat). The first and
    last rows and columns of the array have no value, so read one more on every side. GMTED's own
    first and last rows have nothing beyond them, and so no slope."""
    z = np.asarray(elevation_m, dtype=float)
    dy = GMTED_CELL_DEG * METRES_PER_DEGREE
    dx = dy * np.cos(np.radians(np.asarray(row_lat, dtype=float)))[:, None]
    north_south, east_west = np.full(z.shape, np.nan), np.full(z.shape, np.nan)
    north_south[1:-1, :] = (z[:-2, :] - z[2:, :]) / (2.0 * dy)
    east_west[:, 1:-1] = (z[:, 2:] - z[:, :-2]) / (2.0 * dx)
    return np.rint(np.degrees(np.arctan(np.hypot(north_south, east_west))))


def twi(upa_km2, slope):
    """TWI = ln(a / tan(beta)), on arrays of the same shape, with slope in degrees. Where upa or
    slope is NaN, so is TWI."""
    a = np.asarray(upa_km2, dtype=float) * 1e6 / CONTOUR_WIDTH_M
    beta = np.maximum(np.asarray(slope, dtype=float) * (PI / 180.0), SLOPE_FLOOR_RAD)
    return np.log(a / np.tan(beta))


def stored(values):
    """TWI as the layer holds it: x 10, rounded to a whole number."""
    return np.rint(np.asarray(values) * 10)


if __name__ == "__main__":
    print(stored(twi([1.0, 50.0], [2.0, 0.0])))  # a slope of 2 degrees, then a flat valley floor
