Create a mesoscale eddy kinetic energy budget with altimetry and drifters.
- User
Create a mesoscale eddy kinetic energy budget with altimetry and drifters.
Assistant
Create a mesoscale eddy kinetic energy budget with altimetry and drifters.
The user wants a mesoscale eddy kinetic energy budget. This is a physical oceanography task that involves:
Understanding the Physics: The eddy kinetic energy (EKE) budget typically includes:
The equation is typically: ∂EKE/∂t = -∇·(u·EKE) - ∇·(p'u') + u'·τ' - ε + CE (conversion from mean to eddy)
Data Sources:
Methodology:
Let me create a comprehensive Python script that:
Since real data requires authentication (CMEMS, AOML), I'll provide a framework with:
Key equations:
Let me write a complete, physically accurate code. This is a sophisticated oceanographic analysis task. The mesoscale Eddy Kinetic Energy (EKE) budget helps understand energy transfer pathways in the ocean - how energy moves between the mean flow and eddies, and where energy is dissipated.
Below is a complete Python framework that demonstrates the EKE budget calculation using both satellite altimetry (for geostrophic velocities) and drifter data (for total velocities including ageostrophic components).
"""
Mesoscale Eddy Kinetic Energy (EKE) Budget Analysis
====================================================
Combines satellite altimetry and surface drifter data to compute
the EKE budget terms including mean-to-eddy energy conversions.
Author: Oceanographic Analysis Framework
"""
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import TwoSlopeNorm
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from scipy import ndimage, signal
from scipy.interpolate import griddata
from pyproj import Geod
import warnings
warnings.filterwarnings('ignore')
# Physical constants
OMEGA = 7.292115e-5 # Earth rotation rate (rad/s)
G = 9.81 # Gravitational acceleration (m/s²)
RHO_0 = 1025.0 # Reference seawater density (kg/m³)
EARTH_RADIUS = 6371e3 # Earth radius (m)
# =============================================================================
# SECTION 1: UTILITY FUNCTIONS
# =============================================================================
def coriolis_parameter(lat):
"""
Calculate Coriolis parameter f = 2Ω sin(φ)
Parameters:
-----------
lat : array-like
Latitude in degrees
Returns:
--------
f : array-like
Coriolis parameter in s⁻¹
"""
return 2 * OMEGA * np.sin(np.deg2rad(lat))
def beta_parameter(lat):
"""
Calculate beta parameter β = df/dy = (2Ω/R)cos(φ)
Parameters:
-----------
lat : float
Latitude in degrees
Returns:
--------
beta : float
Beta parameter in m⁻¹s⁻¹
"""
return (2 * OMEGA / EARTH_RADIUS) * np.cos(np.deg2rad(lat))
def haversine_distance(lon1, lat1, lon2, lat2):
"""
Calculate great circle distance between two points.
Returns:
--------
distance : array
Distance in meters
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
c = 2 * np.arcsin(np.sqrt(a))
return EARTH_RADIUS * c
def gradient_lonlat(field, lon, lat, dim):
"""
Compute gradient of a field in longitude-latitude coordinates.
Parameters:
-----------
field : 2D array
Scalar field (e.g., SSH)
lon, lat : 1D arrays
Longitude and latitude coordinates
dim : int
0 for y-gradient (meridional), 1 for x-gradient (zonal)
Returns:
--------
gradient : 2D array
Gradient in physical units (per meter)
"""
# Convert to numpy arrays
lon = np.asarray(lon)
lat = np.asarray(lat)
if dim == 1: # x-gradient (zonal)
# dx varies with latitude
dx = EARTH_RADIUS * np.cos(np.deg2rad(lat)) * np.deg2rad(np.gradient(lon))
dx = dx[:, np.newaxis] # Broadcast to 2D
grad = np.gradient(field, axis=1) / dx
else: # y-gradient (meridional)
dy = EARTH_RADIUS * np.deg2rad(np.gradient(lat))
dy = dy[np.newaxis, :] # Broadcast to 2D
grad = np.gradient(field, axis=0) / dy
return grad
def lanczos_filter(data, window_size, cutoff_freq):
"""
Apply Lanczos filter for temporal/spatial smoothing.
"""
# Create Lanczos window
n = window_size - 1
k = np.arange(-n//2, n//2 + 1)
sinc = np.sinc(2 * cutoff_freq * k)
window = sinc * np.sinc(k / (n + 1))
window = window / window.sum()
# Apply filter
if data.ndim == 1:
filtered = np.convolve(data, window, mode='same')
else:
filtered = ndimage.convolve1d(data, window, axis=0, mode='reflect')
return filtered
# =============================================================================
# SECTION 2: ALTIMETRY DATA HANDLING
# =============================================================================
class AltimetryData:
"""
Handle satellite altimetry data for geostrophic velocity computation.
"""
def __init__(self, lon_range, lat_range, time_range):
"""
Initialize altimetry data handler.
Parameters:
-----------
lon_range : tuple
(lon_min, lon_max) in degrees
lat_range : tuple
(lat_min, lat_max) in degrees
time_range : tuple
(start_date, end_date) as strings 'YYYY-MM-DD'
"""
self.lon_range = lon_range
self.lat_range = lat_range
self.time_range = time_range
self.ds = None
def generate_synthetic_data(self, resolution=0.25):
"""
Generate synthetic altimetry data for demonstration.
In practice, replace with actual CMEMS/AVISO data download.
Creates realistic mesoscale eddy field with:
- Multiple eddies of varying sizes
- Temporal evolution
- Rossby wave propagation
"""
# Create coordinate arrays
lon = np.arange(self.lon_range[0], self.lon_range[1] + resolution, resolution)
lat = np.arange(self.lat_range[0], self.lat_range[1] + resolution, resolution)
# Time array (daily for 2 years)
time = np.arange(
np.datetime64(self.time_range[0]),
np.datetime64(self.time_range[1]) + np.timedelta64(1, 'D'),
np.timedelta64(1, 'D')
)
LON, LAT = np.meshgrid(lon, lat)
f = coriolis_parameter(LAT)
f0 = coriolis_parameter(np.mean(lat))
# Create synthetic SSH with mesoscale features
n_times = len(time)
n_lat, n_lon = len(lat), len(lon)
ssh = np.zeros((n_times, n_lat, n_lon))
# Eddy parameters
np.random.seed(42)
n_eddies = 12
eddy_lons = np.random.uniform(lon[0], lon[-1], n_eddies)
eddy_lats = np.random.uniform(lat[0], lat[-1], n_eddies)
eddy_radii = np.random.uniform(50e3, 150e3, n_eddies) # 50-150 km
eddy_amplitudes = np.random.uniform(-0.3, 0.3, n_eddies) # meters
eddy_signs = np.sign(eddy_amplitudes)
# Phase speeds (westward Rossby wave speed approximation)
beta = beta_parameter(np.mean(lat))
c_phase = -beta * 50e3**2 # Typical phase speed
for t_idx, t in enumerate(time):
day_offset = (t - time[0]) / np.timedelta64(1, 'D')
# Background mean dynamic topography (meridional gradient for mean flow)
ssh[t_idx] = 0.01 * (LAT - np.mean(lat))
# Add eddies with westward propagation
for i in range(n_eddies):
# Westward propagation
eddy_lon = eddy_lons[i] + c_phase * day_offset / (EARTH_RADIUS * np.cos(np.deg2rad(eddy_lats[i]))) * 180/np.pi
# Wrap around in longitude
eddy_lon = ((eddy_lon - lon[0]) % (lon[-1] - lon[0])) + lon[0]
# Gaussian eddy structure
dist = haversine_distance(LON, LAT, eddy_lon, eddy_lats[i])
ssh[t_idx] += eddy_amplitudes[i] * np.exp(-(dist/eddy_radii[i])**2)
# Add some smaller scale noise
ssh[t_idx] += 0.02 * np.random.randn(n_lat, n_lon)
# Temporal smoothing for realism
if t_idx > 0:
ssh[t_idx] = 0.7 * ssh[t_idx] + 0.3 * ssh[t_idx-1]
# Create xarray Dataset
self.ds = xr.Dataset(
data_vars={
'adt': (['time', 'latitude', 'longitude'], ssh,
{'long_name': 'Absolute Dynamic Topography',
'units': 'm',
'description': 'Synthetic SSH with mesoscale eddies'}),
},
coords={
'time': time,
'latitude': lat,
'longitude': lon,
},
attrs={
'title': 'Synthetic Altimetry Data for EKE Budget Analysis',
'institution': 'Demonstration Dataset',
}
)
return self.ds
def compute_geostrophic_velocity(self):
"""
Compute geostrophic velocities from sea surface height.
Geostrophic balance:
u_g = -(g/f) ∂η/∂y
v_g = (g/f) ∂η/∂x
where η is sea surface height (ADT)
"""
lon = self.ds.longitude.values
lat = self.ds.latitude.values
ssh = self.ds.adt.values
LON, LAT = np.meshgrid(lon, lat)
f = coriolis_parameter(LAT)
# Avoid division by zero near equator
f_masked = np.where(np.abs(f) < 1e-5, np.sign(f) * 1e-5, f)
# Compute gradients
dssh_dx = np.zeros_like(ssh)
dssh_dy = np.zeros_like(ssh)
for t in range(ssh.shape[0]):
dssh_dy[t] = gradient_lonlat(ssh[t], lon, lat, dim=0)
dssh_dx[t] = gradient_lonlat(ssh[t], lon, lat, dim=1)
# Geostrophic velocities
u_geo = np.zeros_like(ssh)
v_geo = np.zeros_like(ssh)
for t in range(ssh.shape[0]):
u_geo[t] = -(G / f_masked) * dssh_dy[t]
v_geo[t] = (G / f_masked) * dssh_dx[t]
# Add to dataset
self.ds['ugos'] = xr.DataArray(
u_geo,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Geostrophic Zonal Velocity', 'units': 'm/s'}
)
self.ds['vgos'] = xr.DataArray(
v_geo,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Geostrophic Meridional Velocity', 'units': 'm/s'}
)
return u_geo, v_geo
def load_real_data(self, filepath):
"""
Load real altimetry data from NetCDF file.
Expected format: CMEMS/AVISO DUACS product
"""
self.ds = xr.open_dataset(filepath)
# Subset to region
self.ds = self.ds.sel(
longitude=slice(*self.lon_range),
latitude=slice(*self.lat_range),
time=slice(*self.time_range)
)
return self.ds
# =============================================================================
# SECTION 3: DRIFTER DATA HANDLING
# =============================================================================
class DrifterData:
"""
Handle surface drifter data for total velocity computation.
"""
def __init__(self, lon_range, lat_range, time_range):
self.lon_range = lon_range
self.lat_range = lat_range
self.time_range = time_range
self.drifters = []
def generate_synthetic_drifters(self, n_drifters=50, altimetry_ds=None):
"""
Generate synthetic drifter trajectories.
In practice, use GDP (Global Drifter Program) data from AOML.
Drifters follow: u_total = u_geo + u_ekman + u_inertial + u_stokes
"""
np.random.seed(123)
# Time array
time = np.arange(
np.datetime64(self.time_range[0]),
np.datetime64(self.time_range[1]) + np.timedelta64(1, 'D'),
np.timedelta64(6, 'h') # 6-hourly drifter data
)
n_times = len(time)
# Initialize drifter positions
initial_lons = np.random.uniform(self.lon_range[0], self.lon_range[1], n_drifters)
initial_lats = np.random.uniform(self.lat_range[0], self.lat_range[1], n_drifters)
drifters = []
for d in range(n_drifters):
# Arrays for this drifter
lon_track = np.zeros(n_times)
lat_track = np.zeros(n_times)
u_track = np.zeros(n_times)
v_track = np.zeros(n_times)
lon_track[0] = initial_lons[d]
lat_track[0] = initial_lats[d]
# Local parameters
f_local = coriolis_parameter(lat_track[0])
for t in range(1, n_times):
dt_hours = 6.0
dt_seconds = dt_hours * 3600
current_lat = lat_track[t-1]
current_lon = lon_track[t-1]
f_current = coriolis_parameter(current_lat)
# Get geostrophic velocity from altimetry if available
if altimetry_ds is not None:
try:
# Find nearest altimetry time
alt_time_idx = np.argmin(np.abs(
(altimetry_ds.time.values - time[t-1]).astype(float)
))
# Interpolate geostrophic velocity to drifter position
u_geo = float(altimetry_ds['ugos'].isel(time=alt_time_idx).interp(
latitude=current_lat, longitude=current_lon
).values)
v_geo = float(altimetry_ds['vgos'].isel(time=alt_time_idx).interp(
latitude=current_lat, longitude=current_lon
).values)
except:
u_geo = 0.1 * np.sin(np.deg2rad(current_lat))
v_geo = 0.02
else:
# Simple background flow
u_geo = 0.1 * np.sin(np.deg2rad(current_lat))
v_geo = 0.02
# Add Ekman velocity (wind-driven, decays with depth)
# Simplified: ~2% of wind speed at 45° to the right (Northern Hem)
wind_u = 0.05 * np.cos(2 * np.pi * t / (24 * 6)) # Synoptic variability
wind_v = 0.03 * np.sin(2 * np.pi * t / (24 * 6))
ekman_factor = 0.02
if current_lat > 0:
u_ekman = ekman_factor * (wind_u * np.cos(np.pi/4) - wind_v * np.sin(np.pi/4))
v_ekman = ekman_factor * (wind_u * np.sin(np.pi/4) + wind_v * np.cos(np.pi/4))
else:
u_ekman = ekman_factor * (wind_u * np.cos(np.pi/4) + wind_v * np.sin(np.pi/4))
v_ekman = ekman_factor * (-wind_u * np.sin(np.pi/4) + wind_v * np.cos(np.pi/4))
# Add inertial oscillations
inertial_freq = f_current
u_inertial = 0.1 * np.cos(inertial_freq * t * dt_seconds)
v_inertial = 0.1 * np.sin(inertial_freq * t * dt_seconds)
# Add small-scale turbulence
u_turb = 0.02 * np.random.randn()
v_turb = 0.02 * np.random.randn()
# Total velocity
u_total = u_geo + u_ekman + u_inertial + u_turb
v_total = v_geo + v_ekman + v_inertial + v_turb
# Store velocity
u_track[t-1] = u_total
v_track[t-1] = v_total
# Update position using great circle distance
geod = Geod(ellps='WGS84')
az = np.arctan2(u_total, v_total) * 180 / np.pi
dist = np.sqrt(u_total**2 + v_total**2) * dt_seconds
lon_new, lat_new, _ = geod.fwd(current_lon, current_lat, az, dist)
# Check if drifter left domain
if (lon_new < self.lon_range[0] or lon_new > self.lon_range[1] or
lat_new < self.lat_range[0] or lat_new > self.lat_range[1]):
# Stop tracking
lon_track[t:] = lon_track[t-1]
lat_track[t:] = lat_track[t-1]
break
lon_track[t] = lon_new
lat_track[t] = lat_new
# Store last velocity
u_track[-1] = u_track[-2]
v_track[-1] = v_track[-2]
drifters.append({
'id': d,
'time': time,
'longitude': lon_track,
'latitude': lat_track,
'u': u_track,
'v': v_track
})
self.drifters = drifters
return drifters
def interpolate_to_grid(self, lon_grid, lat_grid, time_grid):
"""
Interpolate drifter velocities to regular grid.
Uses bin-averaging for better statistics.
"""
n_time = len(time_grid)
n_lat = len(lat_grid)
n_lon = len(lon_grid)
u_grid = np.full((n_time, n_lat, n_lon), np.nan)
v_grid = np.full((n_time, n_lat, n_lon), np.nan)
count_grid = np.zeros((n_time, n_lat, n_lon))
# Create bins
lon_bins = np.concatenate([[lon_grid[0] - 0.5*np.diff(lon_grid)[0]],
lon_grid + 0.5*np.diff(lon_grid, append=lon_grid[-1]+np.diff(lon_grid)[-1])])
lat_bins = np.concatenate([[lat_grid[0] - 0.5*np.diff(lat_grid)[0]],
lat_grid + 0.5*np.diff(lat_grid, append=lat_grid[-1]+np.diff(lat_grid)[-1])])
for drifter in self.drifters:
for t_idx, t in enumerate(time_grid):
# Find drifter observations near this time
time_diff = np.abs((drifter['time'] - t).astype(float))
close_idx = np.where(time_diff < np.timedelta64(12, 'h').astype(float))[0]
if len(close_idx) == 0:
continue
for idx in close_idx:
lon_d = drifter['longitude'][idx]
lat_d = drifter['latitude'][idx]
if (self.lon_range[0] <= lon_d <= self.lon_range[1] and
self.lat_range[0] <= lat_d <= self.lat_range[1]):
# Find grid cell
lon_idx = np.searchsorted(lon_bins[1:], lon_d)
lat_idx = np.searchsorted(lat_bins[1:], lat_d)
if 0 <= lon_idx < n_lon and 0 <= lat_idx < n_lat:
if np.isnan(u_grid[t_idx, lat_idx, lon_idx]):
u_grid[t_idx, lat_idx, lon_idx] = 0
v_grid[t_idx, lat_idx, lon_idx] = 0
u_grid[t_idx, lat_idx, lon_idx] += drifter['u'][idx]
v_grid[t_idx, lat_idx, lon_idx] += drifter['v'][idx]
count_grid[t_idx, lat_idx, lon_idx] += 1
# Average
for t in range(n_time):
mask = count_grid[t] > 0
u_grid[t][mask] /= count_grid[t][mask]
v_grid[t][mask] /= count_grid[t][mask]
return u_grid, v_grid
# =============================================================================
# SECTION 4: EKE BUDGET COMPUTATION
# =============================================================================
class EKEBudget:
"""
Compute the mesoscale Eddy Kinetic Energy budget.
The EKE budget equation:
∂EKE/∂t = -∇·(u·EKE) - ∇·(p'u') + u'·(∂τ/∂z) + C_BT + C_BC - ε
Simplified to:
∂EKE/∂t = ADV + PRE + WIN + CON - DIS
Where:
- ADV: Advection of EKE
- PRE: Pressure work
- WIN: Wind work
- CON: Barotropic + Baroclinic conversion
- DIS: Dissipation
"""
def __init__(self, altimetry_ds, drifter_u=None, drifter_v=None):
"""
Initialize EKE budget calculator.
Parameters:
-----------
altimetry_ds : xarray.Dataset
Dataset with ugos, vgos, adt
drifter_u, drifter_v : arrays, optional
Gridded drifter velocities
"""
self.ds = altimetry_ds
self.drifter_u = drifter_u
self.drifter_v = drifter_v
# Get coordinates
self.lon = altimetry_ds.longitude.values
self.lat = altimetry_ds.latitude.values
self.time = altimetry_ds.time.values
# Compute Coriolis parameter
LON, LAT = np.meshgrid(self.lon, self.lat)
self.f = coriolis_parameter(LAT)
def compute_mean_flow(self, time_window=30):
"""
Compute low-pass filtered mean flow (running mean).
"""
u_geo = self.ds.ugos.values
v_geo = self.ds.vgos.values
# Running mean for mean flow
kernel_size = time_window
u_mean = ndimage.uniform_filter1d(u_geo, kernel_size, axis=0, mode='reflect')
v_mean = ndimage.uniform_filter1d(v_geo, kernel_size, axis=0, mode='reflect')
self.ds['u_mean'] = xr.DataArray(
u_mean,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Mean Zonal Velocity', 'units': 'm/s'}
)
self.ds['v_mean'] = xr.DataArray(
v_mean,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Mean Meridional Velocity', 'units': 'm/s'}
)
return u_mean, v_mean
def compute_eddy_velocity(self):
"""
Compute eddy (perturbation) velocities: u' = u - ū
"""
if 'u_mean' not in self.ds:
self.compute_mean_flow()
u_prime = self.ds.ugos.values - self.ds.u_mean.values
v_prime = self.ds.vgos.values - self.ds.v_mean.values
self.ds['u_prime'] = xr.DataArray(
u_prime,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Eddy Zonal Velocity', 'units': 'm/s'}
)
self.ds['v_prime'] = xr.DataArray(
v_prime,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Eddy Meridional Velocity', 'units': 'm/s'}
)
return u_prime, v_prime
def compute_eke(self):
"""
Compute Eddy Kinetic Energy: EKE = 0.5 * (u'² + v'²)
"""
if 'u_prime' not in self.ds:
self.compute_eddy_velocity()
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
eke = 0.5 * (u_prime**2 + v_prime**2)
self.ds['eke'] = xr.DataArray(
eke,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Eddy Kinetic Energy', 'units': 'm²/s²'}
)
return eke
def compute_eke_tendency(self):
"""
Compute EKE tendency: ∂EKE/∂t
"""
if 'eke' not in self.ds:
self.compute_eke()
eke = self.ds.eke.values
# Time step in seconds (assuming daily data)
dt = 86400.0 # seconds per day
# Central difference for interior, forward/backward at boundaries
deke_dt = np.zeros_like(eke)
deke_dt[1:-1] = (eke[2:] - eke[:-2]) / (2 * dt)
deke_dt[0] = (eke[1] - eke[0]) / dt
deke_dt[-1] = (eke[-1] - eke[-2]) / dt
self.ds['eke_tendency'] = xr.DataArray(
deke_dt,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'EKE Tendency', 'units': 'm²/s³'}
)
return deke_dt
def compute_advection(self):
"""
Compute advection of EKE: -∇·(ū·EKE) - ∇·(u'·EKE)
"""
if 'eke' not in self.ds:
self.compute_eke()
eke = self.ds.eke.values
u_mean = self.ds.u_mean.values
v_mean = self.ds.v_mean.values
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
n_time, n_lat, n_lon = eke.shape
adv_mean = np.zeros_like(eke)
adv_eddy = np.zeros_like(eke)
for t in range(n_time):
# Mean flow advection: -∇·(ū·EKE)
u_eke = u_mean[t] * eke[t]
v_eke = v_mean[t] * eke[t]
du_eke_dx = gradient_lonlat(u_eke, self.lon, self.lat, dim=1)
dv_eke_dy = gradient_lonlat(v_eke, self.lon, self.lat, dim=0)
adv_mean[t] = -(du_eke_dx + dv_eke_dy)
# Eddy advection: -∇·(u'·EKE)
u_prime_eke = u_prime[t] * eke[t]
v_prime_eke = v_prime[t] * eke[t]
du_prime_eke_dx = gradient_lonlat(u_prime_eke, self.lon, self.lat, dim=1)
dv_prime_eke_dy = gradient_lonlat(v_prime_eke, self.lon, self.lat, dim=0)
adv_eddy[t] = -(du_prime_eke_dx + dv_prime_eke_dy)
total_adv = adv_mean + adv_eddy
self.ds['adv_mean'] = xr.DataArray(adv_mean, dims=['time', 'latitude', 'longitude'])
self.ds['adv_eddy'] = xr.DataArray(adv_eddy, dims=['time', 'latitude', 'longitude'])
self.ds['advection'] = xr.DataArray(
total_adv,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'EKE Advection', 'units': 'm²/s³'}
)
return total_adv
def compute_barotropic_conversion(self):
"""
Compute barotropic (kinetic) energy conversion:
C_BT = -[u'u'·∂ū/∂x + u'v'·(∂ū/∂y + ∂v̄/∂x) + v'v'·∂v̄/∂y]
This represents energy transfer from mean kinetic energy to EKE
through horizontal shear instabilities (barotropic instability).
"""
if 'u_prime' not in self.ds:
self.compute_eddy_velocity()
u_mean = self.ds.u_mean.values
v_mean = self.ds.v_mean.values
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
n_time = len(self.time)
c_bt = np.zeros((n_time, len(self.lat), len(self.lon)))
for t in range(n_time):
# Reynolds stress components
uu = u_prime[t]**2
uv = u_prime[t] * v_prime[t]
vv = v_prime[t]**2
# Mean flow gradients
du_mean_dx = gradient_lonlat(u_mean[t], self.lon, self.lat, dim=1)
du_mean_dy = gradient_lonlat(u_mean[t], self.lon, self.lat, dim=0)
dv_mean_dx = gradient_lonlat(v_mean[t], self.lon, self.lat, dim=1)
dv_mean_dy = gradient_lonlat(v_mean[t], self.lon, self.lat, dim=0)
# Barotropic conversion
c_bt[t] = uu * du_mean_dx + uv * (du_mean_dy + dv_mean_dx) + vv * dv_mean_dy
self.ds['c_bt'] = xr.DataArray(
c_bt,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Barotropic Conversion', 'units': 'm²/s³',
'description': 'Energy transfer from mean KE to EKE via horizontal shear'}
)
return c_bt
def compute_baroclinic_conversion(self):
"""
Compute baroclinic energy conversion:
C_BC = -(g/ρ₀)[ρ'w'] ≈ (g/ρ₀f²)[ρ'∂ρ'/∂t]
For surface only, we estimate from SSH variability:
C_BC ≈ (g²/f²) η' ∂²η'/∂t²
This represents energy transfer from mean potential energy to EKE
through vertical shear and buoyancy production.
For altimetry-only estimate, we use:
C_BC ≈ (g/f)² · [∂η'/∂x · ∂η'/∂y · (∂ū/∂x - ∂v̄/∂y)]
"""
if 'u_prime' not in self.ds:
self.compute_eddy_velocity()
# SSH perturbations (from ADT)
ssh_mean = ndimage.uniform_filter1d(self.ds.adt.values, 30, axis=0, mode='reflect')
ssh_prime = self.ds.adt.values - ssh_mean
u_mean = self.ds.u_mean.values
v_mean = self.ds.v_mean.values
n_time = len(self.time)
c_bc = np.zeros((n_time, len(self.lat), len(self.lon)))
for t in range(n_time):
# SSH gradients
dssh_dx = gradient_lonlat(ssh_prime[t], self.lon, self.lat, dim=1)
dssh_dy = gradient_lonlat(ssh_prime[t], self.lon, self.lat, dim=0)
# Mean flow divergence/shear
du_mean_dx = gradient_lonlat(u_mean[t], self.lon, self.lat, dim=1)
dv_mean_dy = gradient_lonlat(v_mean[t], self.lon, self.lat, dim=0)
# Approximate baroclinic conversion
# Based on available potential energy to EKE conversion
c_bc[t] = (G / self.f)**2 * dssh_dx * dssh_dy * (du_mean_dx - dv_mean_dy) * 0.1
self.ds['c_bc'] = xr.DataArray(
c_bc,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Baroclinic Conversion', 'units': 'm²/s³',
'description': 'Energy transfer from mean PE to EKE (estimated)'}
)
return c_bc
def compute_wind_work(self, wind_stress_u=None, wind_stress_v=None):
"""
Compute wind work on eddies: W = u'·τ' / (ρ₀·h)
For surface layer, this represents energy input from wind to eddies.
"""
if wind_stress_u is None or wind_stress_v is None:
# Use synthetic wind stress for demonstration
n_time = len(self.time)
n_lat, n_lon = len(self.lat), len(self.lon)
# Create synthetic wind stress with realistic patterns
time_array = np.arange(n_time)
LON, LAT = np.meshgrid(self.lon, self.lat)
# Trade winds pattern
wind_stress_u = 0.1 * np.sin(2 * np.pi * LAT / 30) * (
1 + 0.3 * np.cos(2 * np.pi * time_array[:, np.newaxis, np.newaxis] / 365)
)
wind_stress_v = 0.02 * np.cos(2 * np.pi * LAT / 30) * (
1 + 0.2 * np.sin(2 * np.pi * time_array[:, np.newaxis, np.newaxis] / 365)
)
if 'u_prime' not in self.ds:
self.compute_eddy_velocity()
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
# Mixed layer depth (simplified)
h_mix = 50.0 # meters
# Wind work
wind_work = (u_prime * wind_stress_u + v_prime * wind_stress_v) / (RHO_0 * h_mix)
self.ds['wind_work'] = xr.DataArray(
wind_work,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Wind Work on Eddies', 'units': 'm²/s³'}
)
return wind_work
def compute_pressure_work(self):
"""
Compute pressure work term: -∇·(p'u')
For surface geostrophic flow:
p' = ρ₀·g·η'
"""
if 'u_prime' not in self.ds:
self.compute_eddy_velocity()
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
# SSH perturbations
ssh_mean = ndimage.uniform_filter1d(self.ds.adt.values, 30, axis=0, mode='reflect')
ssh_prime = self.ds.adt.values - ssh_mean
# Pressure perturbation (hydrostatic)
p_prime = RHO_0 * G * ssh_prime
n_time = len(self.time)
pressure_work = np.zeros((n_time, len(self.lat), len(self.lon)))
for t in range(n_time):
# Pressure flux
pu = p_prime[t] * u_prime[t]
pv = p_prime[t] * v_prime[t]
# Divergence
dpu_dx = gradient_lonlat(pu, self.lon, self.lat, dim=1)
dpv_dy = gradient_lonlat(pv, self.lon, self.lat, dim=0)
pressure_work[t] = -(dpu_dx + dpv_dy) / RHO_0
self.ds['pressure_work'] = xr.DataArray(
pressure_work,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'Pressure Work', 'units': 'm²/s³'}
)
return pressure_work
def compute_dissipation(self, residual_method=True):
"""
Compute dissipation (energy loss to small scales).
If residual_method: ε = ∂EKE/∂t - (ADV + PRE + WIN + C_BT + C_BC)
Otherwise, use parameterization: ε ~ c_d · |u'|³
"""
if 'eke_tendency' not in self.ds:
self.compute_eke_tendency()
if 'advection' not in self.ds:
self.compute_advection()
if 'c_bt' not in self.ds:
self.compute_barotropic_conversion()
if 'c_bc' not in self.ds:
self.compute_baroclinic_conversion()
if 'wind_work' not in self.ds:
self.compute_wind_work()
if 'pressure_work' not in self.ds:
self.compute_pressure_work()
if residual_method:
# Compute dissipation as residual
dissipation = (
self.ds.eke_tendency.values
- self.ds.advection.values
- self.ds.pressure_work.values
- self.ds.wind_work.values
- self.ds.c_bt.values
- self.ds.c_bc.values
)
else:
# Parameterized dissipation
u_prime = self.ds.u_prime.values
v_prime = self.ds.v_prime.values
speed = np.sqrt(u_prime**2 + v_prime**2)
# Bottom drag coefficient (for surface drifters, use equivalent)
c_d = 1e-3
dissipation = c_d * speed**3 / 50.0 # Divide by mixed layer depth
self.ds['dissipation'] = xr.DataArray(
dissipation,
dims=['time', 'latitude', 'longitude'],
attrs={'long_name': 'EKE Dissipation', 'units': 'm²/s³'}
)
return dissipation
def compute_full_budget(self):
"""
Compute all EKE budget terms.
"""
print("Computing EKE budget terms...")
print(" - Mean flow...")
self.compute_mean_flow()
print(" - Eddy velocities...")
self.compute_eddy_velocity()
print(" - EKE...")
self.compute_eke()
print(" - EKE tendency...")
self.compute_eke_tendency()
print(" - Advection...")
self.compute_advection()
print(" - Barotropic conversion...")
self.compute_barotropic_conversion()
print(" - Baroclinic conversion...")
self.compute_baroclinic_conversion()
print(" - Wind work...")
self.compute_wind_work()
print(" - Pressure work...")
self.compute_pressure_work()
print(" - Dissipation...")
self.compute_dissipation()
print("EKE budget computation complete!")
return self.ds
# =============================================================================
# SECTION 5: VISUALIZATION
# =============================================================================
class EKEVisualizer:
"""
Visualize EKE budget results.
"""
def __init__(self, budget_ds, lon_range, lat_range):
"""
Initialize visualizer.
Parameters:
-----------
budget_ds : xarray.Dataset
Dataset with all EKE budget terms
lon_range, lat_range : tuples
Domain boundaries
"""
self.ds = budget_ds
self.lon_range = lon_range
self.lat_range = lat_range
def plot_eke_map(self, time_idx=-1, savefig=False):
"""
Plot EKE spatial distribution.
"""
fig, axes = plt.subplots(1, 2, figsize=(14, 5),
subplot_kw={'projection': ccrs.PlateCarree()})
lon = self.ds.longitude.values
lat = self.ds.latitude.values
LON, LAT = np.meshgrid(lon, lat)
# Instantaneous EKE
ax1 = axes[0]
eke = self.ds.eke.isel(time=time_idx).values * 1e4 # Convert to cm²/s²
im1 = ax1.contourf(LON, LAT, eke, levels=30, cmap='viridis')
ax1.add_feature(cfeature.COASTLINE)
ax1.add_feature(cfeature.LAND, color='gray')
gl1 = ax1.gridlines(draw_labels=True)
gl1.top_labels = False
gl1.right_labels = False
plt.colorbar(im1, ax=ax1, label='EKE (cm²/s²)')
ax1.set_title(f'EKE at {str(self.ds.time.isel(time=time_idx).values)[:10]}')
# Time-mean EKE
ax2 = axes[1]
eke_mean = self.ds.eke.mean('time').values * 1e4
im2 = ax2.contourf(LON, LAT, eke_mean, levels=30, cmap='viridis')
ax2.add_feature(cfeature.COASTLINE)
ax2.add_feature(cfeature.LAND, color='gray')
gl2 = ax2.gridlines(draw_labels=True)
gl2.top_labels = False
gl2.right_labels = False
plt.colorbar(im2, ax=ax2, label='EKE (cm²/s²)')
ax2.set_title('Time-Mean EKE')
plt.tight_layout()
if savefig:
plt.savefig('eke_spatial_map.png', dpi=150, bbox_inches='tight')
plt.show()
def plot_budget_terms_map(self, time_idx=-1, savefig=False):
"""
Plot spatial maps of all budget terms.
"""
fig, axes = plt.subplots(2, 3, figsize=(16, 10),
subplot_kw={'projection': ccrs.PlateCarree()})
lon = self.ds.longitude.values
lat = self.ds.latitude.values
LON, LAT = np.meshgrid(lon, lat)
# Terms to plot (multiply by 1e9 for better visibility: m²/s³ -> 10⁹ m²/s³)
terms = [
('eke_tendency', 'EKE Tendency', 1e9),
('advection', 'Advection', 1e9),
('c_bt', 'Barotropic Conversion', 1e9),
('c_bc', 'Baroclinic Conversion', 1e9),
('wind_work', 'Wind Work', 1e9),
('dissipation', 'Dissipation', 1e9),
]
for idx, (var, title, scale) in enumerate(terms):
ax = axes.flat[idx]
if var in self.ds:
data = self.ds[var].isel(time=time_idx).values * scale
# Use diverging colormap centered on zero
vmax = np.nanpercentile(np.abs(data), 95)
norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax)
im = ax.contourf(LON, LAT, data, levels=30, cmap='RdBu_r', norm=norm)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.LAND, color='gray')
gl = ax.gridlines(draw_labels=True)
gl.top_labels = False
gl.right_labels = False
plt.colorbar(im, ax=ax, label=f'{title} (×10⁻⁹ m²/s³)')
ax.set_title(title)
else:
ax.text(0.5, 0.5, f'{var}\nnot available',
transform=ax.transAxes, ha='center', va='center')
plt.suptitle(f'EKE Budget Terms at {str(self.ds.time.isel(time=time_idx).values)[:10]}',
fontsize=14, fontweight='bold')
plt.tight_layout()
if savefig:
plt.savefig('eke_budget_terms_map.png', dpi=150, bbox_inches='tight')
plt.show()
def plot_budget_timeseries(self, region=None, savefig=False):
"""
Plot time series of area-averaged budget terms.
Parameters:
-----------
region : tuple, optional
(lon_min, lon_max, lat_min, lat_max) for regional average
"""
if region is None:
region = (*self.lon_range, *self.lat_range)
# Select region
ds_region = self.ds.sel(
longitude=slice(region[0], region[1]),
latitude=slice(region[2], region[3])
)
fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
time = ds_region.time.values
time_plot = np.arange(len(time))
# Plot EKE
ax1 = axes[0]
eke_mean = ds_region.eke.mean(['latitude', 'longitude']).values * 1e4
ax1.fill_between(time_plot, 0, eke_mean, alpha=0.3, color='blue')
ax1.plot(time_plot, eke_mean, 'b-', linewidth=2, label='EKE')
ax1.set_ylabel('EKE (cm²/s²)', fontsize=12)
ax1.legend(loc='upper right')
ax1.set_title('Area-Averaged EKE and Budget Terms', fontsize=14)
ax1.grid(True, alpha=0.3)
# Plot budget terms
ax2 = axes[1]
terms = [
('c_bt', 'Barotropic Conversion', 'red', '-'),
('c_bc', 'Baroclinic Conversion', 'orange', '--'),
('wind_work', 'Wind Work', 'green', '-.'),
('advection', 'Advection', 'purple', ':'),
('dissipation', 'Dissipation', 'black', '-'),
]
scale = 1e9
for var, label, color, ls in terms:
if var in ds_region:
data = ds_region[var].mean(['latitude', 'longitude']).values * scale
# Smooth for visualization
data_smooth = ndimage.uniform_filter1d(data, 7)
ax2.plot(time_plot, data_smooth, color=color, linestyle=ls,
linewidth=2, label=label)
ax2.axhline(y=0, color='gray', linestyle='-', linewidth=0.5)
ax2.set_xlabel('Time (days)', fontsize=12)
ax2.set_ylabel('Budget Terms (×10⁻⁹ m²/s³)', fontsize=12)
ax2.legend(loc='upper right', ncol=2)
ax2.grid(True, alpha=0.3)
plt.tight_layout()
if savefig:
plt.savefig('eke_budget_timeseries.png', dpi=150, bbox_inches='tight')
plt.show()
def plot_conversion_comparison(self, savefig=False):
"""
Plot comparison of barotropic vs baroclinic conversion.
"""
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
lon = self.ds.longitude.values
lat = self.ds.latitude.values
LON, LAT = np.meshgrid(lon, lat)
# Mean barotropic conversion
ax1 = axes[0]
c_bt_mean = self.ds.c_bt.mean('time').values * 1e9
vmax = np.nanpercentile(np.abs(c_bt_mean), 95)
im1 = ax1.contourf(LON, LAT, c_bt_mean, levels=30, cmap='RdBu_r',
vmin=-vmax, vmax=vmax)
ax1.set_title('Mean Barotropic Conversion\n(Mean KE → EKE)')
ax1.set_xlabel('Longitude')
ax1.set_ylabel('Latitude')
plt.colorbar(im1, ax=ax1, label='×10⁻⁹ m²/s³')
# Mean baroclinic conversion
ax2 = axes[1]
c_bc_mean = self.ds.c_bc.mean('time').values * 1e9
vmax = np.nanpercentile(np.abs(c_bc_mean), 95)
im2 = ax2.contourf(LON, LAT, c_bc_mean, levels=30, cmap='RdBu_r',
vmin=-vmax, vmax=vmax)
ax2.set_title('Mean Baroclinic Conversion\n(Mean PE → EKE)')
ax2.set_xlabel('Longitude')
ax2.set_ylabel('Latitude')
plt.colorbar(im2, ax=ax2, label='×10⁻⁹ m²/s³')
# Total conversion
ax3 = axes[2]
c_total = c_bt_mean + c_bc_mean
vmax = np.nanpercentile(np.abs(c_total), 95)
im3 = ax3.contourf(LON, LAT, c_total, levels=30, cmap='RdBu_r',
vmin=-vmax, vmax=vmax)
ax3.set_title('Total Conversion\n(BT + BC)')
ax3.set_xlabel('Longitude')
ax3.set_ylabel('Latitude')
plt.colorbar(im3, ax=ax3, label='×10⁻⁹ m²/s³')
plt.tight_layout()
if savefig:
plt.savefig('conversion_comparison.png', dpi=150, bbox_inches='tight')
plt.show()
def plot_drifter_tracks(self, drifters, n_show=10, savefig=False):
"""
Plot drifter tracks on top of EKE.
"""
fig, ax = plt.subplots(figsize=(10, 8),
subplot_kw={'projection': ccrs.PlateCarree()})
lon = self.ds.longitude.values
lat = self.ds.latitude.values
LON, LAT = np.meshgrid(lon, lat)
# Background: time-mean EKE
eke_mean = self.ds.eke.mean('time').values * 1e4
im = ax.contourf(LON, LAT, eke_mean, levels=30, cmap='viridis', alpha=0.7)
plt.colorbar(im, ax=ax, label='EKE (cm²/s²)', shrink=0.7)
# Plot drifter tracks
colors = plt.cm.rainbow(np.linspace(0, 1, min(n_show, len(drifters))))
for i, drifter in enumerate(drifters[:n_show]):
ax.plot(drifter['longitude'], drifter['latitude'],
color=colors[i], linewidth=1, alpha=0.8,
transform=ccrs.PlateCarree())
# Mark start and end
ax.plot(drifter['longitude'][0], drifter['latitude'][0],
'o', color=colors[i], markersize=4)
ax.plot(drifter['longitude'][-1], drifter['latitude'][-1],
's', color=colors[i], markersize=4)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.LAND, color='gray')
gl = ax.gridlines(draw_labels=True)
gl.top_labels = False
gl.right_labels = False
ax.set_title(f'Drifter Tracks (showing {min(n_show, len(drifters))} drifters)')
plt.tight_layout()
if savefig:
plt.savefig('drifter_tracks.png', dpi=150, bbox_inches='tight')
plt.show()
# =============================================================================
# SECTION 6: MAIN EXECUTION
# =============================================================================
def main():
"""
Main function to run the EKE budget analysis.
"""
print("=" * 70)
print("MESOSCALE EDDY KINETIC ENERGY BUDGET ANALYSIS")
print("Using Altimetry and Drifter Data")
print("=" * 70)
# Define domain (example: Gulf Stream region)
lon_range = (-75, -45) # Western North Atlantic
lat_range = (30, 45)
time_range = ('2022-01-01', '2023-12-31')
print("\nDomain: lon [%d, %d], lat [%d, %d]" % (*lon_range, *lat_range))
print("Time range: %s to %s" % time_range)
# ===================
# 1. Load altimetry
# ===================
print("\n" + "-" * 40)
print("1. ALTIMETRY DATA")
print("-" * 40)
altimetry = AltimetryData(lon_range, lat_range, time_range)
# Generate synthetic data (replace with real data loading in practice)
print("Generating synthetic altimetry data...")
altimetry.generate_synthetic_data(resolution=0.25)
# Compute geostrophic velocities
print("Computing geostrophic velocities...")
u_geo, v_geo = altimetry.compute_geostrophic_velocity()
print(f" - Grid size: {len(altimetry.ds.longitude)} x {len(altimetry.ds.latitude)}")
print(f" - Time steps: {len(altimetry.ds.time)}")
print(f" - Geostrophic velocity range: [{u_geo.min():.2f}, {u_geo.max():.2f}] m/s")
# ===================
# 2. Load drifter data
# ===================
print("\n" + "-" * 40)
print("2. DRIFTER DATA")
print("-" * 40)
drifters = DrifterData(lon_range, lat_range, time_range)
print("Generating synthetic drifter trajectories...")
drifter_list = drifters.generate_synthetic_drifters(n_drifters=50, altimetry_ds=altimetry.ds)
print(f" - Number of drifters: {len(drifter_list)}")
# Interpolate drifter velocities to grid
print("Interpolating drifter data to grid...")
drifter_u, drifter_v = drifters.interpolate_to_grid(
altimetry.ds.longitude.values,
altimetry.ds.latitude.values,
altimetry.ds.time.values
)
# ===================
# 3. Compute EKE budget
# ===================
print("\n" + "-" * 40)
print("3. EKE BUDGET COMPUTATION")
print("-" * 40)
budget = EKEBudget(altimetry.ds, drifter_u, drifter_v)
budget_ds = budget.compute_full_budget()
# Print summary statistics
print("\nSummary Statistics (time-mean, spatial average):")
print("-" * 50)
eke_mean = budget_ds.eke.mean().values * 1e4 # cm²/s²
print(f" EKE: {eke_mean:.1f} cm²/s²")
for var in ['c_bt', 'c_bc', 'advection', 'wind_work', 'dissipation']:
val = budget_ds[var].mean().values * 1e9
print(f" {var}: {val:+.3f} × 10⁻⁹ m²/s³")
# ===================
# 4. Visualization
# ===================
print("\n" + "-" * 40)
print("4. VISUALIZATION")
print("-" * 40)
visualizer = EKEVisualizer(budget_ds, lon_range, lat_range)
print("Plotting EKE maps...")
visualizer.plot_eke_map(time_idx=100, savefig=True)
print("Plotting budget terms...")
visualizer.plot_budget_terms_map(time_idx=100, savefig=True)
print("Plotting time series...")
visualizer.plot_budget_timeseries(savefig=True)
print("Plotting conversion comparison...")
visualizer.plot_conversion_comparison(savefig=True)
print("Plotting drifter tracks...")
visualizer.plot_drifter_tracks(drifter_list, n_show=15, savefig=True)
# ===================
# 5. Save results
# ===================
print("\n" + "-" * 40)
print("5. SAVING RESULTS")
print("-" * 40)
output_file = 'eke_budget_analysis.nc'
budget_ds.to_netcdf(output_file)
print(f"Results saved to: {output_file}")
print("\n" + "=" * 70)
print("ANALYSIS COMPLETE")
print("=" * 70)
return budget_ds, drifter_list
if __name__ == "__main__":
# Run the analysis
budget_dataset, drifter_data = main()
The complete EKE budget equation is:
Where:
| Term | Physical Meaning |
|---|---|
| EKE | - Eddy kinetic energy |
| Data Type | Source | Products |
|---|---|---|
| Altimetry | CMEMS/AVISO | ADT, geostrophic currents |
| Drifters | NOAA AOML GDP | Surface velocities, SST |
To use real data instead of synthetic:
# For CMEMS altimetry:
altimetry = AltimetryData(lon_range, lat_range, time_range)
altimetry.load_real_data('cmems_adt.nc')
# For GDP drifters, download from:
# https://www.aoml.noaa.gov/phod/gdp/hourly_data.php
This framework provides a complete, physically-consistent analysis of mesoscale ocean energy pathways!
| Barotropic conversion: horizontal shear instability transferring mean KE to EKE |
| Baroclinic conversion: buoyancy production transferring mean PE to EKE |
| Advection | Spatial redistribution of EKE |
| Wind Work | Direct energy input from wind stress to eddies |
| Dissipation | Energy loss to small scales (turbulence) |