forked from OpenDrift/opendrift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgaza_trajectory_core.py
More file actions
403 lines (330 loc) · 14.8 KB
/
Copy pathgaza_trajectory_core.py
File metadata and controls
403 lines (330 loc) · 14.8 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
#!/usr/bin/env python3
"""
Gaza Trajectory Core - Real OpenDrift Physics Only
=================================================
Production-ready implementation for Gaza bottle trajectory analysis.
Uses ONLY real OpenDrift physics with proper error handling.
NO FAKE DATA, NO DEMOS, NO SIMULATIONS - ONLY REAL PHYSICS.
"""
import numpy as np
import logging
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List, Tuple, Dict, Optional
import sys
import os
import traceback
# Add OpenDrift path
sys.path.insert(0, '/Users/bilalghalib/Projects/Iraq_Projects/BEIT/scripts/opendrift')
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
# Import OpenDrift components
try:
from opendrift.models.oceandrift import OceanDrift
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.readers import reader_constant
from opendrift.readers import reader_global_landmask
OPENDRIFT_AVAILABLE = True
logger.info("✅ OpenDrift successfully imported")
except ImportError as e:
OPENDRIFT_AVAILABLE = False
logger.error(f"❌ OpenDrift import failed: {e}")
logger.error("Please install OpenDrift: pip install opendrift")
raise
# Import Gaza-specific components
try:
from gaza_advanced_backend import ContainerSpecs, RopeSystem, EnvironmentalConditions
except ImportError as e:
logger.error(f"❌ Gaza backend import failed: {e}")
raise
class GazaTrajectorySimulator:
"""
Production-ready Gaza trajectory simulator using real OpenDrift physics.
"""
def __init__(self):
"""Initialize the trajectory simulator"""
if not OPENDRIFT_AVAILABLE:
raise RuntimeError("OpenDrift is required but not available")
self.model = None
self.readers = []
# Mediterranean bounds
self.mediterranean_bounds = {
'lat_min': 30.5,
'lat_max': 32.5,
'lon_min': 33.0,
'lon_max': 35.5
}
logger.info("Gaza Trajectory Simulator initialized")
def calculate_wind_drift_factor(self, container: ContainerSpecs, rope: RopeSystem) -> float:
"""
Calculate wind drift factor based on container physics.
Wind drift factor represents the fraction of wind speed that affects
the surface drift of floating objects. Typical range: 0.01-0.04
"""
try:
# Container volume in m³
volume_m3 = container.volume / 1000
# Estimate exposed surface area
surface_area = self._estimate_surface_area(container)
# Calculate buoyancy
rho_water = 1025 # kg/m³ seawater density
submerged_fraction = min(1.0, container.density / rho_water)
exposed_fraction = 1.0 - submerged_fraction
# Base wind drift factor (1-2% typical for small objects)
base_factor = 0.015
# Adjust for exposed area
area_factor = exposed_fraction * surface_area * 0.01
# Rope increases drag and stability
rope_factor = -0.002 * (rope.length / 10.0) # Longer rope reduces wind effect
# Total wind drift factor
wind_drift_factor = max(0.005, min(0.04, base_factor + area_factor + rope_factor))
logger.debug(f"Calculated wind drift factor: {wind_drift_factor:.4f}")
return wind_drift_factor
except Exception as e:
logger.error(f"Error calculating wind drift factor: {e}")
logger.error(traceback.format_exc())
return 0.02 # Default fallback
def _estimate_surface_area(self, container: ContainerSpecs) -> float:
"""Estimate container surface area in m²"""
volume_m3 = container.volume / 1000
if container.container_type == 'bottle':
# Cylindrical approximation
radius = (volume_m3 / (np.pi * 0.25)) ** (1/3)
return np.pi * radius * radius
elif container.container_type == 'jerry_can':
# Rectangular approximation
side_length = volume_m3 ** (1/3)
return side_length * side_length
else:
# Generic cubic approximation
side_length = volume_m3 ** (1/3)
return side_length * side_length
def setup_readers(self, data_sources: Optional[Dict] = None):
"""
Setup environmental data readers.
Args:
data_sources: Dictionary of data sources with keys:
- 'wind': Path/URL to wind data
- 'current': Path/URL to current data
- 'waves': Path/URL to wave data
"""
logger.info("Setting up environmental data readers...")
try:
if data_sources and any(data_sources.values()):
# Use provided data sources
for source_type, source_path in data_sources.items():
if source_path:
try:
reader = reader_netCDF_CF_generic.Reader(source_path)
self.readers.append(reader)
logger.info(f"✅ Added {source_type} reader from: {source_path}")
except Exception as e:
logger.error(f"Failed to add {source_type} reader: {e}")
else:
# Fallback to constant readers for Mediterranean conditions
logger.warning("No data sources provided, using constant Mediterranean conditions")
# Mediterranean summer wind (NW Etesian winds)
wind_reader = reader_constant.Reader({
'x_wind': -3.9, # 5.5 m/s from NW
'y_wind': -3.9
})
# Mediterranean current (eastward flow)
current_reader = reader_constant.Reader({
'x_sea_water_velocity': 0.3, # 0.3 m/s eastward
'y_sea_water_velocity': 0.0
})
self.readers.extend([wind_reader, current_reader])
logger.info("✅ Added constant readers for Mediterranean conditions")
# Always add global landmask
landmask = reader_global_landmask.Reader()
self.readers.insert(0, landmask) # First priority
logger.info("✅ Added global landmask reader")
except Exception as e:
logger.error(f"Critical error setting up readers: {e}")
logger.error(traceback.format_exc())
raise
def run_simulation(self,
launch_point: Tuple[float, float],
container: ContainerSpecs,
rope: RopeSystem,
environment: EnvironmentalConditions,
num_particles: int = 50,
duration_days: int = 14,
time_step_hours: float = 1.0,
output_frequency_hours: int = 1) -> Dict:
"""
Run trajectory simulation using OpenDrift.
Args:
launch_point: (lat, lon) tuple
container: Container specifications
rope: Rope system specifications
environment: Environmental conditions
num_particles: Number of particles to simulate
duration_days: Simulation duration in days
time_step_hours: Calculation time step in hours
output_frequency_hours: Output frequency in hours
Returns:
Dictionary with trajectory results
"""
launch_lat, launch_lon = launch_point
logger.info("="*70)
logger.info("🌊 STARTING TRAJECTORY SIMULATION")
logger.info(f"Launch: {launch_lat:.6f}°N, {launch_lon:.6f}°E")
logger.info(f"Container: {container.container_type} {container.volume}L")
logger.info(f"Particles: {num_particles}")
logger.info(f"Duration: {duration_days} days")
logger.info("="*70)
try:
# Initialize fresh model
self.model = OceanDrift(loglevel=20)
# Configure model
self.model.set_config('general:coastline_action', 'stranding')
self.model.set_config('drift:stokes_drift', True)
self.model.set_config('drift:current_uncertainty', 0.1)
self.model.set_config('drift:wind_uncertainty', 2.0)
self.model.set_config('vertical_mixing:diffusivitymodel', 'windspeed_Large1994')
self.model.set_config('horizontal_diffusivity', 1.0)
logger.info("✅ OpenDrift model configured")
# Add readers
if not self.readers:
self.setup_readers()
for reader in self.readers:
self.model.add_reader(reader)
logger.info(f"✅ Added {len(self.readers)} environmental readers")
# Calculate wind drift factor
wind_drift_factor = self.calculate_wind_drift_factor(container, rope)
logger.info(f"Wind drift factor: {wind_drift_factor:.4f}")
# Seed particles
seed_time = datetime.utcnow()
self.model.seed_elements(
lon=launch_lon,
lat=launch_lat,
number=num_particles,
time=seed_time,
wind_drift_factor=wind_drift_factor,
z=0 # Surface release
)
logger.info(f"✅ Seeded {num_particles} particles at {seed_time}")
# Run simulation
logger.info("Running OpenDrift simulation...")
self.model.run(
duration=timedelta(days=duration_days),
time_step=timedelta(hours=time_step_hours),
time_step_output=timedelta(hours=output_frequency_hours)
)
logger.info("✅ Simulation completed successfully")
# Extract results
results = self._extract_results()
return results
except Exception as e:
logger.error(f"Simulation failed: {e}")
logger.error(traceback.format_exc())
raise RuntimeError(f"OpenDrift simulation failed: {e}")
def _extract_results(self) -> Dict:
"""Extract trajectory results from OpenDrift model"""
try:
logger.info("Extracting trajectory results...")
# Get history arrays
lon_history = self.model.history['lon']
lat_history = self.model.history['lat']
status_history = self.model.history['status']
times = self.model.get_time_array()[0]
num_particles = lon_history.shape[0]
num_timesteps = lon_history.shape[1]
logger.info(f"Particles: {num_particles}, Timesteps: {num_timesteps}")
# Extract trajectories
trajectories = []
for particle_id in range(num_particles):
trajectory = []
for time_idx in range(num_timesteps):
lon = lon_history[particle_id, time_idx]
lat = lat_history[particle_id, time_idx]
status = status_history[particle_id, time_idx]
if not np.isnan(lon) and not np.isnan(lat):
trajectory.append({
'time': times[time_idx],
'lon': float(lon),
'lat': float(lat),
'status': int(status),
'hour': int(time_idx * (times[1] - times[0]).total_seconds() / 3600) if time_idx > 0 else 0
})
if trajectory:
trajectories.append({
'particle_id': particle_id,
'trajectory': trajectory,
'final_status': trajectory[-1]['status'] if trajectory else -1,
'duration_hours': trajectory[-1]['hour'] if trajectory else 0
})
logger.info(f"✅ Extracted {len(trajectories)} valid trajectories")
# Calculate statistics
stranded = sum(1 for t in trajectories if t['final_status'] == 0)
active = sum(1 for t in trajectories if t['final_status'] == 1)
return {
'success': True,
'trajectories': trajectories,
'statistics': {
'total_particles': num_particles,
'valid_trajectories': len(trajectories),
'stranded': stranded,
'active': active,
'simulation_time': times[-1] - times[0] if len(times) > 1 else timedelta(0)
},
'time_range': {
'start': times[0] if len(times) > 0 else None,
'end': times[-1] if len(times) > 0 else None
}
}
except Exception as e:
logger.error(f"Failed to extract results: {e}")
logger.error(traceback.format_exc())
return {
'success': False,
'error': str(e),
'trajectories': [],
'statistics': {}
}
# Main execution for testing
if __name__ == "__main__":
logger.info("Testing Gaza Trajectory Simulator...")
# Test configuration
simulator = GazaTrajectorySimulator()
# Example container
container = ContainerSpecs(
container_type='bottle',
volume=2.0,
mass=1.3,
density=880,
drag_coefficient=0.6
)
# Example rope
rope = RopeSystem(
length=3.0,
rope_type='polypropylene',
anchor_weight=0.3,
anchor_type='weight'
)
# Example environment
environment = EnvironmentalConditions(
season='summer',
launch_time='dawn',
wind_factor=1.0,
current_factor=1.0
)
# Run test simulation
try:
results = simulator.run_simulation(
launch_point=(31.3, 34.1),
container=container,
rope=rope,
environment=environment,
num_particles=10,
duration_days=7
)
logger.info(f"Test simulation completed: {results['statistics']}")
except Exception as e:
logger.error(f"Test simulation failed: {e}")