| |
| """ |
| 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 |
|
|
| |
| |
| |
|
|
| HERE = os.path.dirname(os.path.abspath(__file__)) |
| ATLAS = os.path.join(HERE, "suntans_atlas.nc") |
|
|
| R_EARTH = 6378137.0 |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| X_CENTRE = 13147867.0 |
| Y_CENTRE = -1952977.0 |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| HALF_WIDTH = 21e3 |
| MARGIN = 30e3 |
| MIN_DEPTH = 150.0 |
|
|
| N_OUT = 21 |
| SUBSAMPLE = 4 |
| N_FINE = (N_OUT - 1) * SUBSAMPLE + 1 |
|
|
| N_TIMES = 501 |
| N_PERIODS = 5 |
|
|
| GRAV = 9.81 |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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 |
| |
| |
| den = omega ** 2.0 - f ** 2.0 |
| return num / den |
|
|
|
|
| |
| |
| |
|
|
| 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}") |
|
|
| |
| 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") |
|
|
| |
| |
| |
| |
| 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]]) |
|
|
| |
| print("Building Delaunay triangulation ...") |
| tri = Delaunay(pts) |
|
|
| |
| 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") |
|
|
| |
| 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) |
|
|
| |
| |
| 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)") |
|
|
| |
| eta_re_all = ds["SSH_BC_Aa"][...].values[:, 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): |
| |
| 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)) |
|
|
| |
| 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) |
|
|
| |
| 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] |
| v_c = v_c[:, sl, sl] |
|
|
| |
| |
| 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) |
|
|
| |
| |
| |
| cos_t = np.cos(omega[None, :] * times[:, None]) |
| 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)) |
|
|
| |
| |
| 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) |
|
|
| |
| assert fields.shape == (N_TIMES, N_OUT * N_OUT, 2), fields.shape |
| assert np.isfinite(fields).all(), "NaN/Inf in output" |
|
|
| |
| _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() |
|
|