#!/usr/bin/env python3
"""Experiment X3: how much land did the sea take back when the ice melted?

    python3 pipeline/experiments/drowned-land.py

Reads NOAA ETOPO 2022 (surface elevation, 60 arc-seconds, public domain) over OPeNDAP at a
4-arc-minute stride, and measures, on a spherical Earth of radius 6371.0088 km:
  - land today: cells above 0 m
  - land the sea has taken back: cells between 0 m and a lower sea level, tested at 120 m and at
    134 m below today (the book cites Lambeck and colleagues, 2014: about 134 m at the Last
    Glacial Maximum), so the answer is shown with its sensitivity, not as one number
  - the same for four named shelves (boxes stated below)
Inland basins below sea level (the Caspian, the Dead Sea) are excluded by box, and the result says
so. Not modelled: isostatic rebound, erosion and sediment since then, so this is today's sea floor
read as if it were the old land surface. Writes results to experiments/drowned-land.json.
"""
import json, math, os, subprocess
import numpy as np

URL = ('https://www.ngdc.noaa.gov/thredds/dodsC/global/ETOPO2022/60s/60s_surface_elev_netcdf/'
       'ETOPO_2022_v1_60s_N90W180_surface.nc')
STEP = 4                          # arc-minutes
NI, NJ = 10800, 21600             # 60 arc-second grid, rows south to north
HERE = os.path.dirname(os.path.abspath(__file__))
CACHE = os.path.join(HERE, '.cache-etopo-4min.npy')
R = 6371.0088

def fetch():
    if os.path.exists(CACHE):
        return np.load(CACHE)
    parts = []
    for ja in range(0, NJ, 1200):
        jb = min(ja + 1200 - STEP, NJ - 1)
        url = f'{URL}.dods?z%5B0:{STEP}:{NI-1}%5D%5B{ja}:{STEP}:{jb}%5D'
        raw = subprocess.run(['curl', '-s', '--max-time', '900', url], capture_output=True).stdout
        k = raw.find(b'\nData:\n')
        assert k >= 0, f'no Data section at column {ja}'
        body = raw[k + 7:]
        n = int.from_bytes(body[:4], 'big')
        v = np.frombuffer(body[8:8 + 4 * n], dtype='>f4').astype(np.float32)
        rows = len(range(0, NI, STEP)); cols = len(range(ja, jb + 1, STEP))
        assert v.size == rows * cols, (ja, v.size, rows, cols)
        parts.append(v.reshape(rows, cols))
        print('  columns', ja, 'to', jb)
    a = np.hstack(parts)
    np.save(CACHE, a)
    return a

z = fetch()
rows, cols = z.shape
lat = -90 + (np.arange(rows) * STEP + 0.5) / 60.0
lon = -180 + (np.arange(cols) * STEP + 0.5) / 60.0
d = math.radians(STEP / 60.0)
cell = R * R * d * (np.sin(np.radians(lat) + d / 2) - np.sin(np.radians(lat) - d / 2))   # km2 per cell by row
A = np.repeat(cell[:, None], cols, axis=1)
LAT, LON = np.meshgrid(lat, lon, indexing='ij')

inland = ((LAT > 36) & (LAT < 48) & (LON > 46) & (LON < 56)) | ((LAT > 29) & (LAT < 34) & (LON > 34) & (LON < 37))
land = (z > 0) & ~inland

def taken(level, box=None):
    m = (z <= 0) & (z > -level) & ~inland
    if box:
        s, n, w, e = box
        m &= (LAT >= s) & (LAT <= n) & (LON >= w) & (LON <= e)
    return float(A[m].sum())

SHELVES = {  # south, north, west, east (degrees)
    'Sunda Shelf (South East Asia)': (-9, 12, 95, 120),
    'Sahul Shelf (Australia and New Guinea)': (-20, 0, 120, 150),
    'The North Sea and Doggerland': (50, 62, -5, 10),
    'Beringia (between Siberia and Alaska)': (60, 72, 165, -155 + 360),
}
res = dict(source='NOAA ETOPO 2022, surface elevation, 60 arc-second grid read at 4 arc-minutes',
           licence='Public domain (NOAA NCEI), doi:10.25921/fd45-gt74',
           earth_radius_km=R, land_today_km2=round(float(A[land].sum())))
for level in (120, 134):
    t = taken(level)
    res[f'taken_at_{level}m_km2'] = round(t)
    res[f'taken_at_{level}m_pct_of_land_today'] = round(100 * t / res['land_today_km2'], 1)
# Beringia crosses the antimeridian: measure it in two boxes.
for level in (120, 134):
    sh = {}
    for name, box in SHELVES.items():
        if name.startswith('Beringia'):
            sh[name] = round(taken(level, (60, 72, 165, 180)) + taken(level, (60, 72, -180, -155)))
        else:
            sh[name] = round(taken(level, box))
    res[f'shelves_at_{level}m_km2'] = sh
res['boxes'] = SHELVES
res['not_modelled'] = 'isostatic rebound, erosion and sediment since the Last Glacial Maximum; inland basins below sea level excluded by box'
json.dump(res, open(os.path.join(HERE, 'drowned-land.json'), 'w'), indent=1)
print(json.dumps(res, indent=1))
