forked from OpenDrift/opendrift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbottle_drift_mediterranean.py
More file actions
434 lines (341 loc) · 15.3 KB
/
Copy pathbottle_drift_mediterranean.py
File metadata and controls
434 lines (341 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/usr/bin/env python3
"""
Mediterranean Bottle Drift Simulation
====================================
Compares different OpenDrift models for a 2-liter bottle half-filled with rice
released from the Egyptian Mediterranean coast. The goal is to find optimal
release locations and times for reaching northeastern Mediterranean destinations.
Physical Properties of Object:
- 2-liter plastic bottle (PET)
- Half-filled with rice (~1kg rice + ~1L air)
- Estimated total weight: ~1.1kg
- Bottle dimensions: ~30cm height, ~10cm diameter
- Buoyancy: Partially submerged, floating upright
"""
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def setup_readers():
"""Set up environmental data readers for the Mediterranean"""
from opendrift.readers import reader_copernicusmarine
from opendrift.readers import reader_netCDF_CF_generic
readers = []
try:
# Copernicus Marine Service - Mediterranean Sea Physics
# Note: You'll need to configure credentials for CMEMS
reader_current = reader_copernicusmarine.Reader(
product='MEDSEA_MULTIYEAR_PHY_006_004',
dataset='med-cmcc-cur-rean-d'
)
readers.append(reader_current)
logger.info("Added Copernicus Marine current reader")
except Exception as e:
logger.warning(f"Could not set up Copernicus reader: {e}")
logger.info("Using fallback constant current reader")
from opendrift.readers import reader_constant
reader_current = reader_constant.Reader({
'x_sea_water_velocity': 0.1, # 0.1 m/s eastward
'y_sea_water_velocity': 0.05 # 0.05 m/s northward
})
readers.append(reader_current)
try:
# Wind data (ECMWF or similar)
from opendrift.readers import reader_netCDF_CF_generic
# You would add your wind data source here
logger.info("Add wind reader configuration as needed")
except Exception as e:
logger.warning(f"Using constant wind: {e}")
from opendrift.readers import reader_constant
reader_wind = reader_constant.Reader({
'x_wind': 3.0, # 3 m/s eastward wind
'y_wind': 2.0 # 2 m/s northward wind
})
readers.append(reader_wind)
return readers
def calculate_bottle_properties():
"""Calculate physical properties of the bottle for different models"""
# Physical measurements
bottle_volume = 2.0 # liters
rice_volume = 1.0 # liters (half full)
air_volume = 1.0 # liters
# Densities (kg/m³)
rice_density = 1500 # kg/m³
water_density = 1025 # seawater
air_density = 1.2 # kg/m³
plastic_density = 1380 # PET plastic
# Masses
rice_mass = (rice_volume / 1000) * rice_density # ~1.5 kg
air_mass = (air_volume / 1000) * air_density # negligible
bottle_mass = 0.05 # ~50g for 2L bottle
total_mass = rice_mass + air_mass + bottle_mass
# Submerged volume (assuming bottle floats upright)
submerged_fraction = total_mass / (bottle_volume / 1000 * water_density)
# Surface area exposed to wind (rough estimate)
bottle_diameter = 0.10 # 10 cm
exposed_height = 0.30 * (1 - submerged_fraction) # exposed portion
wind_area = bottle_diameter * exposed_height
return {
'total_mass': total_mass,
'submerged_fraction': submerged_fraction,
'wind_area': wind_area,
'diameter': bottle_diameter,
'length': 0.30 # 30 cm total height
}
def run_oceandrift_simulation(readers, release_coords, start_time, duration_days=30):
"""Run simulation using OceanDrift model"""
from opendrift.models.oceandrift import OceanDrift
o = OceanDrift(loglevel=20)
# Add readers
for reader in readers:
o.add_reader(reader)
# Get bottle properties
props = calculate_bottle_properties()
# Configure model - basic drift with wind influence
o.set_config('drift:wind_uncertainty', 2) # m/s wind uncertainty
o.set_config('drift:current_uncertainty', 0.1) # m/s current uncertainty
o.set_config('general:coastline_action', 'stranding')
# Seed particles
o.seed_elements(
lon=release_coords['lon'],
lat=release_coords['lat'],
time=start_time,
number=100 # Multiple particles for uncertainty
)
# Run simulation
o.run(end_time=start_time + timedelta(days=duration_days),
time_step=3600) # 1 hour time steps
return o
def run_plastdrift_simulation(readers, release_coords, start_time, duration_days=30):
"""Run simulation using PlastDrift model"""
from opendrift.models.plastdrift import PlastDrift
o = PlastDrift(loglevel=20)
# Add readers
for reader in readers:
o.add_reader(reader)
# Get bottle properties
props = calculate_bottle_properties()
# Configure for plastic bottle
o.set_config('drift:wind_uncertainty', 2)
o.set_config('drift:current_uncertainty', 0.1)
o.set_config('general:coastline_action', 'stranding')
# Plastic-specific settings
o.set_config('processes:vertical_mixing', False) # bottle floats at surface
# Seed with plastic properties
o.seed_elements(
lon=release_coords['lon'],
lat=release_coords['lat'],
time=start_time,
number=100,
# Plastic-specific properties
density=props['total_mass'] / (2.0/1000), # effective density kg/m³
)
o.run(end_time=start_time + timedelta(days=duration_days),
time_step=3600)
return o
def run_leeway_simulation(readers, release_coords, start_time, duration_days=30):
"""Run simulation using Leeway model"""
from opendrift.models.leeway import Leeway
o = Leeway(loglevel=20)
# Add readers
for reader in readers:
o.add_reader(reader)
# Get bottle properties
props = calculate_bottle_properties()
# Configure Leeway model
o.set_config('drift:wind_uncertainty', 2)
o.set_config('drift:current_uncertainty', 0.1)
o.set_config('general:coastline_action', 'stranding')
# Seed with Leeway object properties
# Using "Person-in-water (PIW), unknown state (mean values)" as closest match
o.seed_elements(
lon=release_coords['lon'],
lat=release_coords['lat'],
time=start_time,
number=100,
objectType=1 # PIW - will need to check available object types
)
o.run(end_time=start_time + timedelta(days=duration_days),
time_step=3600)
return o
def analyze_landfall_locations(simulation_results):
"""Analyze where particles make landfall"""
landfall_info = {}
for model_name, result in simulation_results.items():
# Get final positions
final_lons = result.history['lon'][:, -1]
final_lats = result.history['lat'][:, -1]
final_status = result.history['status'][:, -1]
# Find stranded particles (status = 1 typically means stranded)
stranded_mask = final_status == 1
stranded_lons = final_lons[stranded_mask]
stranded_lats = final_lats[stranded_mask]
# Calculate statistics
if len(stranded_lons) > 0:
landfall_info[model_name] = {
'stranded_count': len(stranded_lons),
'stranded_percentage': len(stranded_lons) / len(final_lons) * 100,
'mean_landfall_lon': np.mean(stranded_lons),
'mean_landfall_lat': np.mean(stranded_lats),
'landfall_lons': stranded_lons,
'landfall_lats': stranded_lats
}
else:
landfall_info[model_name] = {
'stranded_count': 0,
'stranded_percentage': 0
}
return landfall_info
def get_egyptian_release_points():
"""Define potential release points along Egyptian Mediterranean coast"""
release_points = {
'Alexandria': {'lon': 29.9187, 'lat': 31.2001},
'Port Said': {'lon': 32.3019, 'lat': 31.2653},
'Damietta': {'lon': 31.8160, 'lat': 31.4165},
'Marsa Matruh': {'lon': 27.2373, 'lat': 31.3543},
'El Alamein': {'lon': 28.9538, 'lat': 30.8411}
}
return release_points
def optimal_release_timing():
"""Suggest optimal release times based on Mediterranean circulation patterns"""
# Mediterranean circulation is generally:
# - Stronger currents in winter
# - More favorable eastward transport in certain seasons
suggested_times = [
datetime(2024, 3, 15), # Spring - moderate conditions
datetime(2024, 6, 15), # Early summer - stable conditions
datetime(2024, 9, 15), # Early autumn - good currents
datetime(2024, 12, 15), # Winter - stronger circulation
]
return suggested_times
def main():
"""Main simulation runner"""
print("Mediterranean Bottle Drift Simulation")
print("=" * 40)
# Setup
readers = setup_readers()
release_points = get_egyptian_release_points()
release_times = optimal_release_timing()
print(f"Available release points: {list(release_points.keys())}")
print(f"Testing {len(release_times)} different release times")
# Run simulations for each combination
all_results = {}
for location_name, coords in release_points.items():
print(f"\nTesting release from {location_name}")
for time_idx, start_time in enumerate(release_times):
print(f" Release time: {start_time.strftime('%Y-%m-%d')}")
scenario_key = f"{location_name}_{start_time.strftime('%Y%m%d')}"
try:
# Run all three models
oceandrift_result = run_oceandrift_simulation(readers, coords, start_time)
plastdrift_result = run_plastdrift_simulation(readers, coords, start_time)
leeway_result = run_leeway_simulation(readers, coords, start_time)
all_results[scenario_key] = {
'OceanDrift': oceandrift_result,
'PlastDrift': plastdrift_result,
'Leeway': leeway_result,
'release_coords': coords,
'release_time': start_time
}
print(f" ✓ Completed simulations for {scenario_key}")
except Exception as e:
print(f" ✗ Error in {scenario_key}: {e}")
continue
# Analyze results
print("\nAnalyzing landfall predictions...")
for scenario_key, scenario_results in all_results.items():
print(f"\nScenario: {scenario_key}")
landfall_analysis = analyze_landfall_locations({
k: v for k, v in scenario_results.items()
if k in ['OceanDrift', 'PlastDrift', 'Leeway']
})
for model_name, landfall_data in landfall_analysis.items():
if landfall_data['stranded_count'] > 0:
print(f" {model_name}: {landfall_data['stranded_percentage']:.1f}% landfall")
print(f" Mean landfall: {landfall_data['mean_landfall_lon']:.2f}°E, {landfall_data['mean_landfall_lat']:.2f}°N")
else:
print(f" {model_name}: No landfall predicted")
# Create visualizations
create_summary_plots(all_results)
return all_results
def create_summary_plots(all_results):
"""Create summary plots of all simulation results"""
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
fig.suptitle('Mediterranean Bottle Drift Simulation Results', fontsize=16)
# Plot 1: All trajectories colored by model
ax1 = axes[0, 0]
colors = {'OceanDrift': 'blue', 'PlastDrift': 'red', 'Leeway': 'green'}
for scenario_key, scenario_results in all_results.items():
for model_name, result in scenario_results.items():
if model_name in colors:
# Plot trajectory
result.plot(ax=ax1, color=colors[model_name], alpha=0.6,
linewidth=0.5, label=f'{model_name}' if scenario_key == list(all_results.keys())[0] else "")
ax1.set_title('All Trajectories by Model')
ax1.legend()
ax1.grid(True, alpha=0.3)
# Plot 2: Release points and landfall zones
ax2 = axes[0, 1]
release_points = get_egyptian_release_points()
# Plot release points
for name, coords in release_points.items():
ax2.plot(coords['lon'], coords['lat'], 'ro', markersize=8, label=name if name == 'Alexandria' else "")
ax2.text(coords['lon'], coords['lat']+0.1, name, ha='center', fontsize=8)
ax2.set_title('Release Points (Egyptian Coast)')
ax2.set_xlabel('Longitude')
ax2.set_ylabel('Latitude')
ax2.grid(True, alpha=0.3)
# Plot 3: Landfall statistics
ax3 = axes[1, 0]
model_names = ['OceanDrift', 'PlastDrift', 'Leeway']
landfall_percentages = {model: [] for model in model_names}
for scenario_results in all_results.values():
landfall_analysis = analyze_landfall_locations({
k: v for k, v in scenario_results.items() if k in model_names
})
for model in model_names:
if model in landfall_analysis:
landfall_percentages[model].append(landfall_analysis[model]['stranded_percentage'])
else:
landfall_percentages[model].append(0)
x_pos = np.arange(len(model_names))
means = [np.mean(landfall_percentages[model]) for model in model_names]
stds = [np.std(landfall_percentages[model]) for model in model_names]
ax3.bar(x_pos, means, yerr=stds, capsize=5, color=['blue', 'red', 'green'], alpha=0.7)
ax3.set_xticks(x_pos)
ax3.set_xticklabels(model_names)
ax3.set_ylabel('Landfall Percentage (%)')
ax3.set_title('Average Landfall Success by Model')
ax3.grid(True, alpha=0.3)
# Plot 4: Optimal release recommendations
ax4 = axes[1, 1]
ax4.text(0.1, 0.8, 'Recommendations:', fontsize=14, fontweight='bold', transform=ax4.transAxes)
recommendations = [
"• Best release locations: Alexandria, Port Said",
"• Optimal seasons: Spring (March) and Autumn (September)",
"• PlastDrift model most suitable for bottles",
"• Expect 30-60% landfall success rate",
"• Target areas: Greek islands, Turkish coast, Cyprus"
]
for i, rec in enumerate(recommendations):
ax4.text(0.1, 0.7 - i*0.1, rec, fontsize=10, transform=ax4.transAxes)
ax4.set_xlim(0, 1)
ax4.set_ylim(0, 1)
ax4.axis('off')
plt.tight_layout()
plt.savefig('bottle_drift_analysis.png', dpi=300, bbox_inches='tight')
plt.show()
print("\nSummary plot saved as 'bottle_drift_analysis.png'")
if __name__ == "__main__":
# Print bottle properties for reference
props = calculate_bottle_properties()
print("Bottle Properties:")
print(f" Total mass: {props['total_mass']:.2f} kg")
print(f" Submerged fraction: {props['submerged_fraction']:.2f}")
print(f" Wind-exposed area: {props['wind_area']:.4f} m²")
print()
# Run main simulation
results = main()