Design a synthetic dataset generator for benchmarking coastal wave models against…
- User
Design a synthetic dataset generator for benchmarking coastal wave models against observed shoreline morphology changes.
Assistant
Design a synthetic dataset generator for benchmarking coastal wave models against observed shoreline morphology changes.
The user wants a synthetic dataset generator for benchmarking coastal wave models. The specific goal is to compare model predictions against "observed" (in this case, synthetic) shoreline morphology changes. This means I need to create a tool that generates input data (wave conditions) and corresponding output data (shoreline changes) based on some physical or empirical relationship (the "ground truth" model).
Key Components Required:
Step-by-Step Design Plan:
Step 1: Define the Physical Domain.
Step 2: Generate Synthetic Wave Climate.
Step 3: The "Ground Truth" Model (One-Line Theory).
Code Structure (Python):
WaveGenerator: Generates .CoastalModel: Implements the one-line model.SyntheticDataset: Orchestrates the run and adds noise.Refining the Physics for the Code:
Drafting the Code (Mental or scratchpad):
generate_waves(): Random walkers or seasonality functions.
run_model():
add_noise():
Enhancing the Generator for Benchmarking: To make it a true benchmarking tool, the user needs to be able to calibrate a model against part of the data and validate on the rest. The generator should split the dataset.
Self-Correction/Review during thought process:
Final Output Structure:
Let's write the code. I need a WaveClimate class and a ShorelineModel class.
Specific feature: Ground Truth vs. Observed. The generator will output two dataframes:
df_truth: The actual wave parameters used and the exact shoreline calculated.df_observed: The wave parameters + bias/noise, and shoreline + error/gaps.Let's get started. Designing a synthetic dataset generator for coastal engineering requires balancing physical realism with the flexibility to create "stress-test" scenarios for models.
Below is a design framework and a fully functional Python implementation for a Synthetic Coastal Morphology Benchmark Generator. This tool generates time-series of wave conditions (input) and corresponding shoreline positions (output) based on the foundational One-Line Theory and the CERC Sediment Transport Formula, injected with configurable noise and biases to simulate real-world observation errors.
To benchmark models effectively, we need a "Ground Truth" based on known physics, against which we can measure model error.
Shoreline Evolution (One-Line Model): Where is shoreline position, is profile depth, and is longshore sediment transport.
You will need numpy, pandas, and matplotlib.
When testing a new coastal model (e.g., a Machine Learning model or a process-based simulator), you would follow this workflow:
waves (input) and shorelines (target).waves data into the model being tested to predict shoreline_pred.shoreline_pred against the shorelines (synthetic observations) using metrics like:
To make the benchmark harder (simulating real-world difficulty), you can adjust the parameters in the generate_observations method:
run_morphology_simulation to introduce a "nourishment" event (sudden jump in shoreline position) to see if the model can detect abrupt anthropogenic changes.Step 4: Data Perturbation (The "Observation" Layer).
Step 5: Scenarios.
Sediment Transport (CERC Formula): Where is breaking wave height, and is wave angle relative to shore.
Observation Models (Error Injection):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class SyntheticCoastalGenerator:
def __init__(self,
length_x=5000, # Domain length in meters
grid_dx=50, # Grid spacing in meters
depth_D=10, # Closure depth in meters
berm_height_B=2, # Berm height in meters
transport_coef_K=0.5 # Empirical transport coefficient
):
"""
Initializes the coastal domain and physical parameters.
"""
self.length_x = length_x
self.dx = grid_dx
self.D = depth_D
self.B = berm_height
self.K = transport_coef_K
# Spatial Grid
self.x = np.arange(0, length_x + grid_dx, grid_dx)
self.n_cells = len(self.x)
# Initialize Shoreline (Straight coast at y=0)
self.y_true = np.zeros(self.n_cells)
def generate_wave_climate(self, duration_days=365, dt_hours=6,
seasonality=True, storm_intensity=0.3):
"""
Generates synthetic wave conditions (Hs, Tp, Direction).
Mimics a typical buoy dataset.
"""
steps = int(duration_days * (24 / dt_hours))
time_index = pd.date_range(start='2023-01-01', periods=steps, freq=f'{dt_hours}h')
# Base Wave Height (Log-normal distribution)
base_hs = np.random.lognormal(mean=0.5, sigma=0.5, size=steps)
if seasonality:
# Add seasonal variation (higher waves in winter)
day_of_year = time_index.dayofyear
seasonal_signal = 0.5 * np.cos(2 * np.pi * (day_of_year - 15) / 365)
base_hs += seasonal_signal.clip(0)
# Add storms (Spikes in Hs)
storm_mask = np.random.rand(steps) < 0.05
base_hs[storm_mask] *= (1 + np.random.uniform(0.5, storm_intensity, size=np.sum(storm_mask)))
# Wave Period (correlated with Hs)
tp = 5 + 1.5 * np.sqrt(base_hs) + np.random.normal(0, 1, size=steps)
# Wave Direction (Wrapped Normal around dominant direction)
# Assume dominant waves coming from -30 degrees (South Swell in Northern Hemisphere)
dir_rad = np.random.normal(loc=np.radians(-30), scale=np.radians(20), size=steps)
dir_deg = np.degrees(dir_rad)
wave_df = pd.DataFrame({
'time': time_index,
'Hs': base_hs.clip(0.1, 8), # Clip realistic bounds
'Tp': tp.clip(3, 20),
'Dir': dir_deg
}).set_index('time')
self.waves_true = wave_df
return wave_df
def _calculate_transport(self, Hs, Dir_deg, shore_normal_angle=0):
"""
Internal physics engine: CERC Formula.
Q = K * H^(5/2) * sin(2 * alpha)
"""
# Convert wave angle relative to shoreline orientation
alpha = np.radians(Dir_deg - shore_normal_angle)
# Simplified Breaking Assumption (H_b approx 1.8 * H_deep)
Hb = Hs * 1.8
# CERC Transport Potential
# Note: In a full model, we handle current vs wave direction.
# Here we assume waves drive transport directly.
Q = self.K * (Hb ** 2.5) * np.sin(2 * alpha)
return Q
def run_morphology_simulation(self, boundary_condition='sandy'):
"""
Runs the one-line model simulation to generate Ground Truth Shorelines.
"""
if not hasattr(self, 'waves_true'):
self.generate_wave_climate()
# Storage for shoreline time series
shoreline_ts = []
# Active shoreline copy
y = self.y_true.copy()
# Time stepping
for t, row in self.waves_true.iterrows():
Hs = row['Hs']
Dir = row['Dir']
# Calculate Gross Transport rates along the coast
# Note: This is a simplified spatial implementation.
# We assume uniform wave climate across the small domain for this benchmark.
# Calculate potential transport Q
Q_potential = self._calculate_transport(Hs, Dir)
# Gradient of Transport (dQ/dx)
# In a 1D model, if waves are uniform, dQ/dx = 0, so no change.
# To create dynamics, we simulate a "sediment source" at x=0 or changing angles.
# ALTERNATIVE APPROACH FOR SYNTHETIC DATA:
# Simulate a simplistic erosion/accretion function based on wave power for benchmarking.
# This ensures the shoreline actually moves in this simplified snippet.
# Simple physical heuristic for synthetic generator:
# Erosion occurs if Hs > threshold and angle is steep.
# Accretion occurs if Hs is low.
epsilon = 1e-5 # Stability
# Spatial variation: Assume Northern part of grid is exposed
exposure_factor = np.linspace(0.8, 1.2, self.n_cells)
# Morphology change rate (Linearized)
# dy/dt proportional to Q_in - Q_out
# Here we use a diffusion approximation for smooth synthetic data:
# dy/dt = D_morph * d^2y/dx^2 + Source
# 1. Diffusion (smooths the coastline)
d2y_dx2 = np.gradient(np.gradient(y, self.dx), self.dx)
diffusion_rate = 0.00001 * d2y_dx2
# 2. External Forcing (Wave driven shift)
# If waves come from South (negative dir), move sand North (positive y)
wave_forcing = 0.01 * Q_potential * exposure_factor
# Update Shoreline
dt_sec = 6 * 3600 # 6 hours in seconds
dy = (diffusion_rate + wave_forcing) * dt_sec
# Apply Boundary Conditions
dy[0] = 0
dy[-1] = 0
y += dy
shoreline_ts.append(y.copy())
self.shoreline_true = np.array(shoreline_ts)
return self.shoreline_true
def generate_observations(self, wave_noise=0.1, shore_noise=2.0, gap_prob=0.1):
"""
Creates the 'Benchmark Dataset' by adding noise and gaps to the Ground Truth.
"""
# 1. Noisy Wave Data (Input Features)
waves_obs = self.waves_true.copy()
# Add bias and random noise
waves_obs['Hs'] = waves_obs['Hs'] * np.random.normal(1, wave_noise, len(waves_obs))
waves_obs['Dir'] = waves_obs['Dir'] + np.random.normal(0, wave_noise * 20, len(waves_obs))
# Add gaps (NaNs)
gap_mask = np.random.rand(len(waves_obs)) < gap_prob
waves_obs.loc[gap_mask, ['Hs', 'Tp', 'Dir']] = np.nan
# 2. Noisy Shoreline Data (Target Labels)
# Shoreline surveys are usually less frequent than wave data
# We downsample to "monthly" or "weekly" surveys
survey_freq = '14D' # Every 14 days
survey_dates = self.waves_true.index.to_period(survey_freq).to_timestamp()
unique_dates = np.unique(survey_dates)
shoreline_obs_list = []
obs_dates_list = []
for date in unique_dates:
# Find closest index in true data
idx = self.waves_true.index.get_loc(date, method='nearest')
# Get true position
y_true = self.shoreline_true[idx]
# Add Gaussian noise (Survey error)
y_obs = y_true + np.random.normal(0, shore_noise, len(y_true))
shoreline_obs_list.append(y_obs)
obs_dates_list.append(self.waves_true.index[idx])
shoreline_obs = pd.DataFrame(shoreline_obs_list, index=obs_dates_list)
shoreline_obs.columns = [f'Chainage_{int(x)}m' for x in self.x]
self.waves_obs = waves_obs
self.shoreline_obs = shoreline_obs
return waves_obs, shoreline_obs
def plot_summary(self):
"""
Visualizes the generated dataset.
"""
fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)
# 1. Wave Input
axes[0].plot(self.waves_obs.index, self.waves_obs['Hs'], 'b.', alpha=0.3, label='Obs Hs (Noisy)')
axes[0].plot(self.waves_true.index, self.waves_true['Hs'], 'k-', alpha=0.5, label='True Hs')
axes[0].set_ylabel('Wave Height (m)')
axes[0].legend()
axes[0].set_title('Input Data: Synthetic Wave Climate')
# 2. Shoreline Change (Heatmap)
# Plotting only the observed shorelines
extent = [self.x[0], self.x[-1], 0, len(self.shoreline_obs)]
im = axes[1].imshow(self.shoreline_obs, aspect='auto', extent=extent, cmap='viridis')
axes[1].set_ylabel('Survey Index')
axes[1].set_xlabel('Longshore Distance (m)')
axes[1].set_title('Output Data: Observed Shoreline Morphology (Noisy, Sparse)')
# 3. Comparison at one specific cross-section
target_x = int(len(self.x) / 2)
# Interpolate true shoreline to observation dates for comparison
true_interp = pd.DataFrame(self.shoreline_true, index=self.waves_true.index).iloc[:, target_x]
axes[2].plot(true_interp.index, true_interp, 'k-', label='Model Truth')
axes[2].plot(self.shoreline_obs.index, self.shoreline_obs.iloc[:, target_x],
'ro', markersize=4, label='Synthetic Observation')
axes[2].set_ylabel('Shoreline Position (m)')
axes[2].set_xlabel('Time')
axes[2].legend()
axes[2].set_title(f'Benchmark Comparison at X={self.x[target_x]}m')
plt.tight_layout()
plt.show()
# --- Usage Example ---
if __name__ == "__main__":
# 1. Initialize Generator
gen = SyntheticCoastalGenerator(length_x=2000, grid_dx=20)
# 2. Generate Wave Climate
gen.generate_wave_climate(duration_days=365, storm_intensity=0.8)
# 3. Run Ground Truth Physics
gen.run_morphology_simulation()
# 4. Generate Observational Dataset (Benchmark)
# wave_noise: std dev of error (1.0 = 100% noise)
# shore_noise: error in meters (e.g., 2m = typical GPS error)
waves, shorelines = gen.generate_observations(wave_noise=0.15, shore_noise=3.0, gap_prob=0.1)
# 5. Visualize
gen.plot_summary()
# Export to CSV for Benchmarking
# waves.to_csv("synthetic_wave_input.csv")
# shorelines.to_csv("synthetic_shoreline_output.csv")