#!/usr/bin/env python3 """ Extract a regular-grid, time-varying 2D surface velocity field from the SUNTANS internal-tide harmonic atlas (NW Australian shelf / Timor Sea). This reproduces the physics of `iwatlas/uvdriver.py::extract_hc_uv_spatial` + `sshdriver.predict_scalar` without depending on the `iwatlas` / `sfoda` stack (whose requirements.txt pins dead `git+git://` URLs). Pipeline -------- 1. Read the unstructured cell-centre SSH harmonic amplitudes SSH_BC_Aa (real) and SSH_BC_Ba (imaginary), shape (Ntide, Nc). 2. Restrict to a rectangular sub-region (+ margin) in the projected coords, build a single Delaunay triangulation, and reuse it to interpolate all Ntide x 2 amplitude fields onto a fine regular grid. 3. Take spatial gradients (eta_x, eta_y) with np.gradient on the fine grid, in TRUE metres. 4. Apply the linear polarization relations (calc_u_complex / calc_v_complex, copied verbatim from uvdriver.py, including the u/v `den` asymmetry) to get complex u, v amplitudes per constituent. 5. Reconstruct the time series and subsample onto the final 21x21 grid. Output (written next to this script): suntans_fields.npy -- (501, 441, 2) float64, u/v in m/s, flattened as index = ix*21 + iy suntans_meta.json -- grid coords, lon/lat bounds, time axis, stats Projection ---------- xv/yv are projected metres. Inverting them as Web Mercator (EPSG:3857) lands the mesh in 107.7-142.4 E, 4.2-23.8 S, which matches the documented dataset extent (NW Australian shelf / Timor Sea), so EPSG:3857 is confirmed. Note on Web Mercator scale: Web Mercator metres are inflated by 1/cos(lat) relative to true ground distance. np.gradient is therefore taken with respect to TRUE metres (dx_true = dx_mercator * cos(lat)), otherwise the gradients -- and hence the velocities -- would be ~4.5% too small at this latitude. """ import json import os import numpy as np import xarray as xr from scipy.interpolate import LinearNDInterpolator from scipy.spatial import Delaunay # ---------------------------------------------------------------------------- # Configuration # ---------------------------------------------------------------------------- HERE = os.path.dirname(os.path.abspath(__file__)) ATLAS = os.path.join(HERE, "suntans_atlas.nc") R_EARTH = 6378137.0 # Web Mercator sphere radius [m] # Region centre, in projected (Web Mercator) metres. Selected by scanning the # Australian NW shelf band (112-126 E, 11-20 S) for the box with the largest mean # SSH_BC_var subject to: dense mesh coverage, full containment in the mesh hull, # and no cell shallower than 150 m. # # That last constraint matters. The single most energetic box (~118.8 E, 17.2 S) # straddles the coastline/islands, where neighbouring cell depths jump abruptly # (e.g. 55 m -> 395 m over ~2 km, with some 10-15 m coastal cells). SSH_BC # amplitude steps across those bathymetry discontinuities, so np.gradient there # returns huge, largely spurious gradients -- that box produced ~10 isolated # grid points spiking to 1-3.7 m/s against a 0.1-0.5 m/s background. Restricting # to depths > 150 m keeps the shelf-break generation zone while excluding those # near-land steps, and every point then lands in the physical range. # # Chosen: Rowley Shelf break / continental slope, ~lon 118.1 E, lat 17.3 S, # depth range ~240-5200 m. X_CENTRE = 13147867.0 Y_CENTRE = -1952977.0 # Half-width chosen to match the paper's *dimensionless* advection regime rather # than an arbitrary box size. BALLAST's benefit comes from drifters being # advected across/out of the region, so what must match is # (typical speed x horizon) / domain width. # The paper's stated SUNTANS hyperparameters imply velocity sd # sqrt((20/5^2 + 0.01/4^2)*15) = 3.47 units/time over a horizon T=5 on a 21-point # grid, i.e. a ratio of ~0.87. This field's drifters travel ~34 km in the 5 M2 # periods, so a ~40 km box reproduces that ratio (~0.85); the original 150 km box # gave only 0.24, where drifters barely move and the look-ahead is moot. # 40 km over 21 points is also ~2 km spacing, i.e. the SUNTANS mesh's native # resolution -- so this box resolves the model rather than super-resolving it. HALF_WIDTH = 21e3 # half-width of the target box, in projected metres MARGIN = 30e3 # extra halo fed to the triangulation, projected metres MIN_DEPTH = 150.0 # reject the region if any cell is shallower than this [m] N_OUT = 21 # final grid is N_OUT x N_OUT SUBSAMPLE = 4 # fine grid is (N_OUT-1)*SUBSAMPLE + 1 = 161 points/side N_FINE = (N_OUT - 1) * SUBSAMPLE + 1 N_TIMES = 501 N_PERIODS = 5 # total span = N_PERIODS * M2 period GRAV = 9.81 # ---------------------------------------------------------------------------- # Projection helpers (inverse Web Mercator, EPSG:3857) # ---------------------------------------------------------------------------- def merc_to_lonlat(x, y): """Inverse Web Mercator: projected metres -> (lon, lat) in degrees.""" lon = np.degrees(x / R_EARTH) lat = np.degrees(2.0 * np.arctan(np.exp(y / R_EARTH)) - np.pi / 2.0) return lon, lat # ---------------------------------------------------------------------------- # Physics -- copied EXACTLY from iwatlas/uvdriver.py # ---------------------------------------------------------------------------- def calc_coriolis(latdeg): omega = 2 * np.pi / 86400.0 degrad = np.pi / 180.0 return 2 * omega * np.sin(latdeg * degrad) def calc_u_complex(eta_x, eta_y, omega, f, g=GRAV, tau=1e6): omegaT = omega + 1j / tau num = -1j * omegaT * g * eta_x + f * g * eta_y den = omegaT ** 2.0 - f ** 2.0 return num / den def calc_v_complex(eta_x, eta_y, omega, f, g=GRAV, tau=1e6): omegaT = omega + 1j / tau num = -1j * omegaT * g * eta_y - f * g * eta_x # NOTE: `omega` here, not `omegaT` -- this u/v asymmetry is present in the # original iwatlas source and is preserved deliberately. den = omega ** 2.0 - f ** 2.0 return num / den # ---------------------------------------------------------------------------- # Main # ---------------------------------------------------------------------------- def main(): ds = xr.open_dataset(ATLAS) xv = ds["xv"].values yv = ds["yv"].values omega = ds["omega"].values ntide = omega.shape[0] lon_all, lat_all = merc_to_lonlat(xv, yv) print(f"Mesh extent: lon {lon_all.min():.2f} to {lon_all.max():.2f} E, " f"lat {lat_all.min():.2f} to {lat_all.max():.2f}") # --- Restrict to sub-region + margin so the triangulation stays small ---- half = HALF_WIDTH + MARGIN sel = (np.abs(xv - X_CENTRE) < half) & (np.abs(yv - Y_CENTRE) < half) n_sel = int(sel.sum()) print(f"Cells in sub-region (+{MARGIN/1e3:.0f} km margin): {n_sel}") if n_sel < 100: raise RuntimeError("Too few cells in sub-region for interpolation") # Guard the depth constraint the region was chosen to satisfy (see above): # shallow cells neighbour abrupt bathymetry steps that corrupt the gradients. # This applies to the TARGET box only -- the margin is just triangulation # support outside the output grid, so shallow cells there are harmless. box = ((np.abs(xv - X_CENTRE) < HALF_WIDTH) & (np.abs(yv - Y_CENTRE) < HALF_WIDTH)) dv_box = ds["dv"].values[box] print(f"Depth in target box: min {dv_box.min():.0f} m, " f"mean {dv_box.mean():.0f} m, max {dv_box.max():.0f} m") if dv_box.min() < MIN_DEPTH: raise RuntimeError( f"Target box contains cells shallower than {MIN_DEPTH} m " f"(min {dv_box.min():.0f} m); expect spurious gradient spikes." ) pts = np.column_stack([xv[sel], yv[sel]]) # --- Build the Delaunay triangulation ONCE and reuse for all 35 x 2 fields print("Building Delaunay triangulation ...") tri = Delaunay(pts) # --- Fine regular grid, in projected metres ------------------------------ gx_fine = np.linspace(X_CENTRE - HALF_WIDTH, X_CENTRE + HALF_WIDTH, N_FINE) gy_fine = np.linspace(Y_CENTRE - HALF_WIDTH, Y_CENTRE + HALF_WIDTH, N_FINE) GX, GY = np.meshgrid(gx_fine, gy_fine, indexing="ij") # (N_FINE, N_FINE) # Every fine grid point must fall inside the triangulation, else NaNs. outside = tri.find_simplex(np.column_stack([GX.ravel(), GY.ravel()])) < 0 if outside.any(): raise RuntimeError(f"{outside.sum()} fine-grid points outside mesh hull") _, GLAT = merc_to_lonlat(GX, GY) f_cor = calc_coriolis(GLAT) # (N_FINE, N_FINE) # --- Grid spacing in TRUE metres ---------------------------------------- # Web Mercator metres are inflated by 1/cos(lat); undo that. dx_merc = gx_fine[1] - gx_fine[0] dy_merc = gy_fine[1] - gy_fine[0] coslat = np.cos(np.radians(GLAT)) print(f"Fine grid: {N_FINE}x{N_FINE}, spacing {dx_merc:.0f} m (Mercator) " f"~ {dx_merc*coslat.mean():.0f} m (true)") # --- Interpolate the SSH harmonic amplitudes onto the fine grid ---------- eta_re_all = ds["SSH_BC_Aa"][...].values[:, sel] # (ntide, n_sel) eta_im_all = ds["SSH_BC_Ba"][...].values[:, sel] u_c = np.zeros((ntide, N_FINE, N_FINE), np.complex128) v_c = np.zeros((ntide, N_FINE, N_FINE), np.complex128) amp_mean = np.zeros(ntide) print(f"Interpolating and applying polarization relations for {ntide} " f"constituents ...") for ii in range(ntide): # Reuse `tri` -- LinearNDInterpolator accepts a prebuilt Delaunay. eta_re = LinearNDInterpolator(tri, eta_re_all[ii, :])(GX, GY) eta_im = LinearNDInterpolator(tri, eta_im_all[ii, :])(GX, GY) amp_mean[ii] = np.mean(np.abs(eta_re + 1j * eta_im)) # np.gradient along axis 0 = x, axis 1 = y. Spacing in TRUE metres. eta_re_dx, eta_re_dy = np.gradient(eta_re, dx_merc, dy_merc) eta_im_dx, eta_im_dy = np.gradient(eta_im, dx_merc, dy_merc) eta_re_dx, eta_im_dx = eta_re_dx / coslat, eta_im_dx / coslat eta_re_dy, eta_im_dy = eta_re_dy / coslat, eta_im_dy / coslat eta_x = eta_re_dx + 1j * eta_im_dx eta_y = eta_re_dy + 1j * eta_im_dy u_c[ii] = calc_u_complex(eta_x, eta_y, omega[ii], f_cor) v_c[ii] = calc_v_complex(eta_x, eta_y, omega[ii], f_cor) # --- Subsample to the final 21x21 grid ---------------------------------- sl = slice(None, None, SUBSAMPLE) x_coords = gx_fine[sl] y_coords = gy_fine[sl] assert x_coords.size == N_OUT and y_coords.size == N_OUT u_c = u_c[:, sl, sl] # (ntide, 21, 21) v_c = v_c[:, sl, sl] # --- Time axis: 5 M2 periods, 501 steps --------------------------------- # M2 = the constituent with the largest mean SSH amplitude in this region. i_m2 = int(np.argmax(amp_mean)) omega_m2 = float(omega[i_m2]) period_m2 = 2 * np.pi / omega_m2 print(f"Dominant constituent: index {i_m2}, omega={omega_m2:.6e} rad/s, " f"period={period_m2/3600:.3f} h") times = np.linspace(0.0, N_PERIODS * period_m2, N_TIMES) # seconds # --- Reconstruct the time series ---------------------------------------- # u(t) = sum_ii [ Re(u_ii)*cos(omega_ii*t) + Im(u_ii)*sin(omega_ii*t) ] # (matches sshdriver.predict_scalar; mean amplitude a0 = 0 for velocity) cos_t = np.cos(omega[None, :] * times[:, None]) # (nt, ntide) sin_t = np.sin(omega[None, :] * times[:, None]) u_t = (np.einsum("tk,kxy->txy", cos_t, u_c.real) + np.einsum("tk,kxy->txy", sin_t, u_c.imag)) v_t = (np.einsum("tk,kxy->txy", cos_t, v_c.real) + np.einsum("tk,kxy->txy", sin_t, v_c.imag)) # --- Flatten as index = ix*21 + iy (x-major, y-minor) ------------------- # u_t is (nt, ix, iy); C-order ravel of the last two axes gives ix*21+iy. fields = np.stack([u_t.reshape(N_TIMES, N_OUT * N_OUT), v_t.reshape(N_TIMES, N_OUT * N_OUT)], axis=-1) fields = np.ascontiguousarray(fields, dtype=np.float64) # --- Verify -------------------------------------------------------------- assert fields.shape == (N_TIMES, N_OUT * N_OUT, 2), fields.shape assert np.isfinite(fields).all(), "NaN/Inf in output" # Explicitly confirm the ix*21+iy ordering round-trips. _chk = fields[:, :, 0].reshape(N_TIMES, N_OUT, N_OUT) assert np.allclose(_chk, u_t) for ix in (0, 7, 20): for iy in (0, 13, 20): assert fields[3, ix * N_OUT + iy, 0] == u_t[3, ix, iy] print("Ordering check passed: index = ix*21 + iy") speed = np.hypot(fields[..., 0], fields[..., 1]) stats = { "mean_speed": float(speed.mean()), "max_speed": float(speed.max()), "std_u": float(fields[..., 0].std()), "std_v": float(fields[..., 1].std()), } time_var = fields.std(axis=0).mean() space_var = fields.std(axis=1).mean() print(f"Shape: {fields.shape}") print(f"mean_speed={stats['mean_speed']:.4f} m/s " f"max_speed={stats['max_speed']:.4f} m/s") print(f"std_u={stats['std_u']:.4f} std_v={stats['std_v']:.4f} m/s") print(f"Variation over time (mean std over t): {time_var:.4f} m/s") print(f"Variation over space (mean std over x): {space_var:.4f} m/s") assert time_var > 0, "field does not vary in time" assert space_var > 0, "field does not vary in space" lon_c, lat_c = merc_to_lonlat(np.array([x_coords[0], x_coords[-1]]), np.array([y_coords[0], y_coords[-1]])) meta = { "x_coords": [float(v) for v in x_coords], "y_coords": [float(v) for v in y_coords], "lon_bounds": [float(lon_c[0]), float(lon_c[1])], "lat_bounds": [float(lat_c[0]), float(lat_c[1])], "times_seconds": [float(t) for t in times], "omega_M2": omega_m2, "region_note": ( "Australian NW shelf: Rowley Shelf break / continental slope " "internal-tide generation zone. Centre ~118.1 E, 17.3 S; box " "150 km x 150 km in EPSG:3857 (Web Mercator) metres, ~143 km true. " "Depth range ~240-5200 m. Selected as the highest mean SSH_BC_var " "box within 112-126 E, 11-20 S subject to dense mesh coverage, full " "containment in the mesh hull, and no cell shallower than 150 m " "(shallow/coastal cells sit next to abrupt bathymetry steps that " "make np.gradient return spurious gradients). Coordinates " "x_coords/y_coords are projected EPSG:3857 metres. Fields are " "flattened as index = ix*21 + iy." ), "velocity_stats": stats, "projection": "EPSG:3857 (Web Mercator)", "n_constituents": int(ntide), "dominant_constituent_index": i_m2, "m2_period_seconds": float(period_m2), } np.save(os.path.join(HERE, "suntans_fields.npy"), fields) with open(os.path.join(HERE, "suntans_meta.json"), "w") as fh: json.dump(meta, fh, indent=2) print(f"lon bounds: {meta['lon_bounds']}") print(f"lat bounds: {meta['lat_bounds']}") print("Wrote suntans_fields.npy and suntans_meta.json") if __name__ == "__main__": main()