Create a deep-sea mining plume dispersion modeling and sampling.
- User
Create a deep-sea mining plume dispersion modeling and sampling.
Assistant
Create a deep-sea mining plume dispersion modeling and sampling.
The user wants a simulation of deep-sea mining plume dispersion modeling and sampling. This is a complex environmental simulation that involves:
Plume Dispersion Physics:
Key Components:
Physical Laws to Follow:
Visualization Elements:
Interactive Features:
Let me create a comprehensive simulation with:
I'll use matplotlib for plotting embedded in tkinter, with numpy for calculations.
Key equations:
Let me build this simulation with a professional oceanographic theme. This is an interesting environmental modeling challenge! I'll create a comprehensive deep-sea mining plume dispersion simulation that includes:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.patches import Circle, Rectangle, FancyArrowPatch
from matplotlib.collections import PatchCollection
import matplotlib.colors as mcolors
from matplotlib.animation import FuncAnimation
import tkinter as tk
from tkinter import ttk
from dataclasses import dataclass
from typing import List, Tuple
import colorsys
# Physical constants and parameters
@dataclass
class EnvironmentalConditions:
"""Deep-sea environmental conditions"""
water_density: float = 1027.0 # kg/m³
water_viscosity: float = 1.08e-3 # Pa·s at ~4°C
current_velocity: float = 0.1 # m/s
current_direction: float = 45.0 # degrees
depth: float = 4000.0 # m
temperature: float = 2.0 # °C
@dataclass
class SedimentProperties:
"""Properties of mined sediment/particles"""
particle_density: float = 2650.0 # kg/m³
mean_diameter: float = 30e-6 # m (30 micrometers)
release_rate: float = 100.0 # kg/s
@property
def settling_velocity(self) -> float:
"""Calculate Stokes settling velocity"""
g = 9.81
return (self.particle_density - 1027.0) * g * self.mean_diameter**2 / (18 * 1.08e-3)
class PlumeModel:
"""3D Gaussian plume model for sediment dispersion"""
def __init__(self, env: EnvironmentalConditions, sed: SedimentProperties):
self.env = env
self.sed = sed
self.time = 0.0
self.dt = 10.0 # time step in seconds
# Domain setup (in meters)
self.x_range = 5000 # downcurrent distance
self.y_range = 3000 # crosscurrent distance
self.z_range = 500 # height above seafloor
# Grid resolution
self.nx, self.ny, self.nz = 100, 60, 30
self.x = np.linspace(0, self.x_range, self.nx)
self.y = np.linspace(-self.y_range/2, self.y_range/2, self.ny)
self.z = np.linspace(0, self.z_range, self.nz)
self.X, self.Y, self.Z = np.meshgrid(self.x, self.y, self.z, indexing='ij')
# Concentration field
self.concentration = np.zeros((self.nx, self.ny, self.nz))
# Dispersion coefficients (empirical for deep-sea conditions)
self.alpha_y = 0.08 # lateral dispersion
self.alpha_z = 0.04 # vertical dispersion
# Particle tracking for visualization
self.particles = []
self.max_particles = 2000
def dispersion_coefficients(self, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Calculate dispersion coefficients as function of distance"""
# Modified for deep-sea low-turbulence environment
sigma_y = self.alpha_y * np.sqrt(x + 1)
sigma_z = self.alpha_z * np.sqrt(x + 1)
# Limit maximum spreading
sigma_y = np.minimum(sigma_y, 500)
sigma_z = np.minimum(sigma_z, 200)
return sigma_y, sigma_z
def gaussian_plume_3d(self, x: np.ndarray, y: np.ndarray, z: np.ndarray,
source_strength: float, source_height: float = 20.0) -> np.ndarray:
"""Calculate 3D Gaussian plume concentration"""
u = max(self.env.current_velocity, 0.01) # Prevent division by zero
sigma_y, sigma_z = self.dispersion_coefficients(x)
# Effective source height considering plume rise
H = source_height
# Gaussian plume formula with settling
decay = np.exp(-self.sed.settling_velocity * x / (u * H + 1))
C = (source_strength / (2 * np.pi * u * sigma_y * sigma_z + 1e-10)) * \
np.exp(-0.5 * (y / (sigma_y + 1e-10))**2) * \
(np.exp(-0.5 * ((z - H) / (sigma_z + 1e-10))**2) + \
np.exp(-0.5 * ((z + H) / (sigma_z + 1e-10))**2)) * \
decay
return C
def update(self):
"""Update concentration field"""
self.time += self.dt
# Rotate coordinates based on current direction
angle = np.radians(self.env.current_direction)
# Calculate concentration field
Q = self.sed.release_rate # Source strength (kg/s)
self.concentration = self.gaussian_plume_3d(
self.X, self.Y, self.Z, Q
)
# Update particle positions for visualization
self._update_particles()
def _update_particles(self):
"""Update Lagrangian particle positions"""
# Add new particles at source
n_new = int(self.sed.release_rate * self.dt / 10)
n_new = min(n_new, 50) # Limit new particles per step
for _ in range(n_new):
if len(self.particles) < self.max_particles:
# Random initial position near source
particle = {
'x': np.random.normal(0, 20),
'y': np.random.normal(0, 20),
'z': np.random.normal(20, 5),
'age': 0,
'size': np.random.lognormal(np.log(self.sed.mean_diameter), 0.5)
}
self.particles.append(particle)
# Update existing particles
angle = np.radians(self.env.current_direction)
u = self.env.current_velocity
new_particles = []
for p in self.particles:
# Advection
p['x'] += u * np.cos(angle) * self.dt
p['y'] += u * np.sin(angle) * self.dt
# Settling
p['z'] -= self.sed.settling_velocity * self.dt
# Turbulent diffusion
sigma_t = 0.5 * np.sqrt(self.dt)
p['x'] += np.random.normal(0, sigma_t)
p['y'] += np.random.normal(0, sigma_t)
p['z'] += np.random.normal(0, sigma_t * 0.3)
p['age'] += self.dt
# Keep particle if within domain and above seafloor
if (0 < p['x'] < self.x_range and
abs(p['y']) < self.y_range/2 and
p['z'] > 0 and p['age'] < 3600):
new_particles.append(p)
self.particles = new_particles
def get_concentration_at(self, x: float, y: float, z: float = 10.0) -> float:
"""Get interpolated concentration at a point"""
# Find nearest grid indices
ix = int(x / self.x_range * (self.nx - 1))
iy = int((y + self.y_range/2) / self.y_range * (self.ny - 1))
iz = int(z / self.z_range * (self.nz - 1))
ix = np.clip(ix, 0, self.nx - 1)
iy = np.clip(iy, 0, self.ny - 1)
iz = np.clip(iz, 0, self.nz - 1)
return self.concentration[ix, iy, iz]
class SamplingStation:
"""Sampling station for measuring plume concentration"""
def __init__(self, x: float, y: float, name: str):
self.x = x
self.y = y
self.name = name
self.measurements = []
self.times = []
self.current_value = 0.0
self.threshold = 0.01 # Alert threshold (mg/L)
self.alert = False
def sample(self, model: PlumeModel, time: float):
"""Take a sample from current plume state"""
conc = model.get_concentration_at(self.x, self.y, z=10.0)
# Convert to mg/L (assuming concentration is in kg/m³)
conc_mgl = conc * 1000
self.measurements.append(conc_mgl)
self.times.append(time)
self.current_value = conc_mgl
self.alert = conc_mgl > self.threshold
# Keep only last 100 measurements
if len(self.measurements) > 100:
self.measurements = self.measurements[-100:]
self.times = self.times[-100:]
class DeepSeaMiningSimulation:
"""Main simulation application"""
def __init__(self, root):
self.root = root
self.root.title("Deep-Sea Mining Plume Dispersion Model")
self.root.geometry("1600x900")
self.root.configure(bg='#1a1a2e')
# Initialize models
self.env = EnvironmentalConditions()
self.sed = SedimentProperties()
self.model = PlumeModel(self.env, self.sed)
# Sampling stations
self.stations: List[SamplingStation] = []
self._create_default_stations()
# Simulation state
self.running = False
self.time_elapsed = 0.0
# Setup UI
self._setup_ui()
# Animation
self.ani = None
def _create_default_stations(self):
"""Create default sampling station network"""
station_positions = [
(500, 0, "S1-Near"),
(500, 200, "S2-East"),
(500, -200, "S3-West"),
(1500, 0, "S4-Mid"),
(1500, 300, "S5-MidE"),
(1500, -300, "S6-MidW"),
(3000, 0, "S7-Far"),
(3000, 400, "S8-FarE"),
]
for x, y, name in station_positions:
self.stations.append(SamplingStation(x, y, name))
def _setup_ui(self):
"""Setup the user interface"""
# Main container
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Style configuration
style = ttk.Style()
style.theme_use('clam')
style.configure('TFrame', background='#1a1a2e')
style.configure('TLabel', background='#1a1a2e', foreground='#eee')
style.configure('TLabelframe', background='#1a1a2e', foreground='#eee')
style.configure('TLabelframe.Label', background='#1a1a2e', foreground='#00d4ff')
style.configure('TButton', background='#16213e', foreground='#eee')
style.configure('TScale', background='#1a1a2e')
# Left panel - Controls
control_frame = ttk.LabelFrame(main_frame, text="Control Panel", padding=10)
control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)
self._create_controls(control_frame)
# Center - Main visualization
viz_frame = ttk.Frame(main_frame)
viz_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
self._create_visualization(viz_frame)
# Right panel - Station data
data_frame = ttk.LabelFrame(main_frame, text="Sampling Data", padding=10)
data_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=5, pady=5)
self._create_data_panel(data_frame)
def _create_controls(self, parent):
"""Create control widgets"""
# Current controls
current_frame = ttk.LabelFrame(parent, text="Current Settings", padding=5)
current_frame.pack(fill=tk.X, pady=5)
ttk.Label(current_frame, text="Velocity (m/s):").pack(anchor=tk.W)
self.velocity_var = tk.DoubleVar(value=self.env.current_velocity)
velocity_scale = ttk.Scale(current_frame, from_=0.01, to=0.5,
variable=self.velocity_var, orient=tk.HORIZONTAL)
velocity_scale.pack(fill=tk.X)
self.velocity_label = ttk.Label(current_frame, text=f"{self.env.current_velocity:.2f}")
self.velocity_label.pack()
velocity_scale.configure(command=lambda v: self._update_velocity())
ttk.Label(current_frame, text="Direction (°):").pack(anchor=tk.W)
self.direction_var = tk.DoubleVar(value=self.env.current_direction)
direction_scale = ttk.Scale(current_frame, from_=0, to=360,
variable=self.direction_var, orient=tk.HORIZONTAL)
direction_scale.pack(fill=tk.X)
self.direction_label = ttk.Label(current_frame, text=f"{self.env.current_direction:.0f}°")
self.direction_label.pack()
direction_scale.configure(command=lambda v: self._update_direction())
# Mining controls
mining_frame = ttk.LabelFrame(parent, text="Mining Parameters", padding=5)
mining_frame.pack(fill=tk.X, pady=5)
ttk.Label(mining_frame, text="Release Rate (kg/s):").pack(anchor=tk.W)
self.release_var = tk.DoubleVar(value=self.sed.release_rate)
release_scale = ttk.Scale(mining_frame, from_=10, to=500,
variable=self.release_var, orient=tk.HORIZONTAL)
release_scale.pack(fill=tk.X)
self.release_label = ttk.Label(mining_frame, text=f"{self.sed.release_rate:.0f}")
self.release_label.pack()
release_scale.configure(command=lambda v: self._update_release())
ttk.Label(mining_frame, text="Particle Size (µm):").pack(anchor=tk.W)
self.diameter_var = tk.DoubleVar(value=self.sed.mean_diameter * 1e6)
diameter_scale = ttk.Scale(mining_frame, from_=5, to=200,
variable=self.diameter_var, orient=tk.HORIZONTAL)
diameter_scale.pack(fill=tk.X)
self.diameter_label = ttk.Label(mining_frame, text=f"{self.sed.mean_diameter*1e6:.0f}")
self.diameter_label.pack()
diameter_scale.configure(command=lambda v: self._update_diameter())
# Simulation controls
sim_frame = ttk.LabelFrame(parent, text="Simulation", padding=5)
sim_frame.pack(fill=tk.X, pady=5)
self.time_label = ttk.Label(sim_frame, text="Time: 0:00:00", font=('Consolas', 12))
self.time_label.pack(pady=5)
button_frame = ttk.Frame(sim_frame)
button_frame.pack(fill=tk.X, pady=5)
self.start_btn = ttk.Button(button_frame, text="▶ Start", command=self._toggle_simulation)
self.start_btn.pack(side=tk.LEFT, padx=2)
ttk.Button(button_frame, text="↺ Reset", command=self._reset_simulation).pack(side=tk.LEFT, padx=2)
# Status indicators
status_frame = ttk.LabelFrame(parent, text="Status", padding=5)
status_frame.pack(fill=tk.X, pady=5)
self.v_settling_label = ttk.Label(status_frame, text=f"Settling vel: {self.sed.settling_velocity*1000:.3f} mm/s")
self.v_settling_label.pack(anchor=tk.W)
self.particles_label = ttk.Label(status_frame, text="Particles: 0")
self.particles_label.pack(anchor=tk.W)
self.alerts_label = ttk.Label(status_frame, text="Alerts: 0", foreground='#00ff00')
self.alerts_label.pack(anchor=tk.W)
def _create_visualization(self, parent):
"""Create matplotlib visualization"""
self.fig = plt.figure(figsize=(12, 8), facecolor='#1a1a2e')
# Create subplots with custom layout
gs = self.fig.add_gridspec(2, 3, height_ratios=[2, 1], width_ratios=[2, 1, 1],
hspace=0.3, wspace=0.3)
# Main plume view (top-down)
self.ax_main = self.fig.add_subplot(gs[0, :2])
self.ax_main.set_facecolor('#0a1628')
# Vertical profile
self.ax_profile = self.fig.add_subplot(gs[0, 2])
self.ax_profile.set_facecolor('#0a1628')
# Time series
self.ax_time = self.fig.add_subplot(gs[1, :])
self.ax_time.set_facecolor('#0a1628')
# Initial plot setup
self._setup_plots()
# Embed in tkinter
self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
self.canvas.draw()
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def _setup_plots(self):
"""Setup initial plot elements"""
# Main view
self.ax_main.set_xlim(0, self.model.x_range)
self.ax_main.set_ylim(-self.model.y_range/2, self.model.y_range/2)
self.ax_main.set_xlabel('Distance (m)', color='#aaa')
self.ax_main.set_ylabel('Cross-track (m)', color='#aaa')
self.ax_main.set_title('Plume Dispersion - Top View', color='#00d4ff', fontsize=12)
self.ax_main.tick_params(colors='#888')
self.ax_main.grid(True, alpha=0.2, color='#444')
# Mining source
self.source_marker = Circle((0, 0), 100, color='#ff6b35', zorder=10)
self.ax_main.add_patch(self.source_marker)
# Concentration colormap
self.conc_img = self.ax_main.imshow(
np.zeros((self.model.ny, self.model.nx)),
extent=[0, self.model.x_range, -self.model.y_range/2, self.model.y_range/2],
origin='lower', cmap='YlOrRd', alpha=0.7,
vmin=0, vmax=0.1, aspect='auto'
)
# Particle scatter
self.particle_scatter = self.ax_main.scatter([], [], c=[], s=1, cmap='YlOrRd', alpha=0.5)
# Station markers
self.station_markers = []
for station in self.stations:
marker, = self.ax_main.plot(station.x, station.y, 's', markersize=8,
color='#00ff00', markeredgecolor='white', zorder=5)
self.station_markers.append(marker)
self.ax_main.annotate(station.name, (station.x, station.y),
xytext=(5, 5), textcoords='offset points',
fontsize=7, color='#aaa')
# Current direction arrow
self.current_arrow = self.ax_main.annotate('', xy=(500, 0), xytext=(0, 0),
arrowprops=dict(arrowstyle='->', color='#00d4ff', lw=2))
# Colorbar
cbar = self.fig.colorbar(self.conc_img, ax=self.ax_main, shrink=0.6, pad=0.02)
cbar.set_label('Concentration (kg/m³)', color='#aaa')
cbar.ax.tick_params(colors='#888')
# Profile view
self.ax_profile.set_xlim(0, self.model.x_range)
self.ax_profile.set_ylim(0, self.model.z_range)
self.ax_profile.set_xlabel('Distance (m)', color='#aaa')
self.ax_profile.set_ylabel('Height (m)', color='#aaa')
self.ax_profile.set_title('Vertical Profile', color='#00d4ff', fontsize=10)
self.ax_profile.tick_params(colors='#888')
self.profile_img = self.ax_profile.imshow(
np.zeros((self.model.nz, self.model.nx)),
extent=[0, self.model.x_range, 0, self.model.z_range],
origin='lower', cmap='YlOrRd', alpha=0.8,
vmin=0, vmax=0.1, aspect='auto'
)
# Time series
self.ax_time.set_xlim(0, 3600)
self.ax_time.set_ylim(0, 100)
self.ax_time.set_xlabel('Time (s)', color='#aaa')
self.ax_time.set_ylabel('Concentration (mg/L)', color='#aaa')
self.ax_time.set_title('Station Measurements Over Time', color='#00d4ff', fontsize=10)
self.ax_time.tick_params(colors='#888')
self.ax_time.grid(True, alpha=0.2, color='#444')
# Threshold line
self.ax_time.axhline(y=10, color='#ff6b35', linestyle='--', label='Alert threshold')
self.ax_time.legend(loc='upper right', fontsize=8)
# Station lines
self.station_lines = {}
colors = plt.cm.tab10(np.linspace(0, 1, len(self.stations)))
for i, station in enumerate(self.stations):
line, = self.ax_time.plot([], [], '-', color=colors[i],
label=station.name, linewidth=1.5)
self.station_lines[station.name] = line
self.ax_time.legend(loc='upper right', fontsize=6, ncol=4)
def _create_data_panel(self, parent):
"""Create data display panel"""
# Station readings
readings_frame = ttk.LabelFrame(parent, text="Live Readings", padding=5)
readings_frame.pack(fill=tk.BOTH, expand=True, pady=5)
# Create scrollable frame
canvas = tk.Canvas(readings_frame, bg='#1a1a2e', highlightthickness=0)
scrollbar = ttk.Scrollbar(readings_frame, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
self.station_labels = {}
for station in self.stations:
frame = ttk.Frame(scrollable_frame)
frame.pack(fill=tk.X, pady=2, padx=2)
ttk.Label(frame, text=f"{station.name}:", font=('Consolas', 9)).pack(anchor=tk.W)
value_label = ttk.Label(frame, text="0.00 mg/L", font=('Consolas', 10, 'bold'))
value_label.pack(anchor=tk.W)
pos_label = ttk.Label(frame, text=f"({station.x}m, {station.y}m)",
font=('Consolas', 8), foreground='#888')
pos_label.pack(anchor=tk.W)
self.station_labels[station.name] = value_label
# Statistics
stats_frame = ttk.LabelFrame(parent, text="Statistics", padding=5)
stats_frame.pack(fill=tk.X, pady=5)
self.stats_labels = {}
stats = ['Max conc:', 'Mean conc:', 'Plume area:', 'Affected stations:']
for stat in stats:
frame = ttk.Frame(stats_frame)
frame.pack(fill=tk.X, pady=1)
ttk.Label(frame, text=stat, font=('Consolas', 9)).pack(side=tk.LEFT)
label = ttk.Label(frame, text="--", font=('Consolas', 9, 'bold'), foreground='#00d4ff')
label.pack(side=tk.RIGHT)
self.stats_labels[stat] = label
# Legend
legend_frame = ttk.LabelFrame(parent, text="Legend", padding=5)
legend_frame.pack(fill=tk.X, pady=5)
legends = [
("●", "#ff6b35", "Mining source"),
("■", "#00ff00", "Normal station"),
("■", "#ff0000", "Alert station"),
("→", "#00d4ff", "Current direction")
]
for symbol, color, text in legends:
frame = ttk.Frame(legend_frame)
frame.pack(fill=tk.X, pady=1)
ttk.Label(frame, text=symbol, foreground=color, font=('Consolas', 12)).pack(side=tk.LEFT)
ttk.Label(frame, text=text, font=('Consolas', 9)).pack(side=tk.LEFT, padx=5)
def _update_velocity(self):
"""Update current velocity"""
self.env.current_velocity = self.velocity_var.get()
self.velocity_label.config(text=f"{self.env.current_velocity:.2f}")
self.model.env.current_velocity = self.env.current_velocity
def _update_direction(self):
"""Update current direction"""
self.env.current_direction = self.direction_var.get()
self.direction_label.config(text=f"{self.env.current_direction:.0f}°")
self.model.env.current_direction = self.env.current_direction
def _update_release(self):
"""Update release rate"""
self.sed.release_rate = self.release_var.get()
self.release_label.config(text=f"{self.sed.release_rate:.0f}")
self.model.sed.release_rate = self.sed.release_rate
def _update_diameter(self):
"""Update particle diameter"""
self.sed.mean_diameter = self.diameter_var.get() * 1e-6
self.diameter_label.config(text=f"{self.sed.mean_diameter*1e6:.0f}")
self.model.sed.mean_diameter = self.sed.mean_diameter
self.v_settling_label.config(text=f"Settling vel: {self.sed.settling_velocity*1000:.3f} mm/s")
def _toggle_simulation(self):
"""Start/stop simulation"""
if self.running:
self.running = False
self.start_btn.config(text="▶ Start")
if self.ani:
self.ani.event_source.stop()
else:
self.running = True
self.start_btn.config(text="⏸ Pause")
self._start_animation()
def _start_animation(self):
"""Start the animation loop"""
def update(frame):
if not self.running:
return
self._update_simulation()
self._update_visualization()
self.ani = FuncAnimation(self.fig, update, interval=100, blit=False, cache_frame_data=False)
self.canvas.draw()
def _update_simulation(self):
"""Update simulation state"""
self.model.update()
self.time_elapsed += self.model.dt
# Update stations
for station in self.stations:
station.sample(self.model, self.time_elapsed)
# Update time display
hours = int(self.time_elapsed // 3600)
minutes = int((self.time_elapsed % 3600) // 60)
seconds = int(self.time_elapsed % 60)
self.time_label.config(text=f"Time: {hours}:{minutes:02d}:{seconds:02d}")
# Update particle count
self.particles_label.config(text=f"Particles: {len(self.model.particles)}")
# Count alerts
alert_count = sum(1 for s in self.stations if s.alert)
self.alerts_label.config(text=f"Alerts: {alert_count}",
foreground='#ff0000' if alert_count > 0 else '#00ff00')
def _update_visualization(self):
"""Update all visualization elements"""
# Update main concentration view
conc_2d = self.model.concentration[:, :, 5].T # Near-bottom slice
self.conc_img.set_array(conc_2d)
self.conc_img.set_clim(0, np.max(conc_2d) * 1.2 + 0.001)
# Update profile view
conc_profile = self.model.concentration[:, self.model.ny//2, :].T
self.profile_img.set_array(conc_profile)
self.profile_img.set_clim(0, np.max(conc_profile) * 1.2 + 0.001)
# Update particles
if self.model.particles:
px = [p['x'] for p in self.model.particles]
py = [p['y'] for p in self.model.particles]
pz = [p['z'] for p in self.model.particles]
ages = [p['age'] for p in self.model.particles]
# Color by age
colors = np.array(ages) / max(max(ages), 1)
self.particle_scatter.set_offsets(np.c_[px, py])
self.particle_scatter.set_array(1 - colors)
# Update current arrow
angle = np.radians(self.env.current_direction)
length = 500
dx = length * np.cos(angle)
dy = length * np.sin(angle)
self.current_arrow.xy = (dx, dy)
# Update station markers
for i, station in enumerate(self.stations):
color = '#ff0000' if station.alert else '#00ff00'
self.station_markers[i].set_color(color)
# Update time series
for station in self.stations:
if station.times:
self.station_lines[station.name].set_data(station.times, station.measurements)
# Adjust time axis
if self.time_elapsed > 3600:
self.ax_time.set_xlim(self.time_elapsed - 3600, self.time_elapsed)
else:
self.ax_time.set_xlim(0, max(3600, self.time_elapsed + 100))
# Adjust y axis for time series
max_conc = max([max(s.measurements) if s.measurements else 1 for s in self.stations])
self.ax_time.set_ylim(0, max(max_conc * 1.2, 10))
# Update station labels
for station in self.stations:
color = '#ff0000' if station.alert else '#00d4ff'
self.station_labels[station.name].config(
text=f"{station.current_value:.2f} mg/L",
foreground=color
)
# Update statistics
max_conc = np.max(self.model.concentration) * 1000 # Convert to mg/L
mean_conc = np.mean(self.model.concentration[self.model.concentration > 0]) * 1000 if np.any(self.model.concentration > 0) else 0
plume_area = np.sum(self.model.concentration[:, :, 5] > 0.001) * \
(self.model.x_range / self.model.nx) * (self.model.y_range / self.model.ny) / 1000 # km²
self.stats_labels['Max conc:'].config(text=f"{max_conc:.2f} mg/L")
self.stats_labels['Mean conc:'].config(text=f"{mean_conc:.2f} mg/L")
self.stats_labels['Plume area:'].config(text=f"{plume_area:.1f} km²")
self.stats_labels['Affected stations:'].config(
text=str(sum(1 for s in self.stations if s.alert))
)
self.canvas.draw_idle()
def _reset_simulation(self):
"""Reset simulation to initial state"""
self.running = False
self.start_btn.config(text="▶ Start")
self.time_elapsed = 0.0
self.model = PlumeModel(self.env, self.sed)
# Reset stations
for station in self.stations:
station.measurements = []
station.times = []
station.current_value = 0.0
station.alert = False
# Update parameters from current UI values
self._update_velocity()
self._update_direction()
self._update_release()
self._update_diameter()
# Reset time display
self.time_label.config(text="Time: 0:00:00")
# Clear visualization
self.conc_img.set_array(np.zeros((self.model.ny, self.model.nx)))
self.profile_img.set_array(np.zeros((self.model.nz, self.model.nx)))
self.particle_scatter.set_offsets(np.empty((0, 2)))
for station in self.stations:
self.station_lines[station.name].set_data([], [])
self.ax_time.set_xlim(0, 3600)
self.canvas.draw()
def main():
root = tk.Tk()
app = DeepSeaMiningSimulation(root)
root.mainloop()
if __name__ == "__main__":
main()
Run the simulation and adjust parameters to see how different conditions affect plume dispersion in the deep ocean!