forked from OpenDrift/opendrift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgaza_advanced_backend.py
More file actions
833 lines (691 loc) · 33.1 KB
/
Copy pathgaza_advanced_backend.py
File metadata and controls
833 lines (691 loc) · 33.1 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
#!/usr/bin/env python3
"""
Gaza Advanced Delivery Backend
=============================
Advanced backend with full physics simulation supporting:
- Custom container parameters (rope, size, shape, mass, etc.)
- Real interactive reports with embedded trajectory data
- Trajectory animations
- Mission profiles as customizable starting points
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_agg import FigureCanvasAgg
import json
import datetime
from dataclasses import dataclass, asdict
from typing import Dict, List, Tuple, Optional, Any
import logging
import base64
from io import BytesIO
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.offline as pyo
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class ContainerSpecs:
"""Detailed container specifications"""
container_type: str # bottle, jerry_can, custom_container
volume: float # Liters
mass: float # kg
density: float # kg/m³
drag_coefficient: float
surface_area: float = None # m² (calculated if None)
shape_factor: float = 1.0 # Shape efficiency (1.0 = sphere)
def __post_init__(self):
if self.surface_area is None:
# Estimate surface area from volume
radius = (3 * self.volume / (4 * np.pi * 1000)) ** (1/3) # Convert L to m³
self.surface_area = 4 * np.pi * radius**2
@dataclass
class RopeSystem:
"""Rope and anchor system specifications"""
length: float # meters
rope_type: str # nylon, polyester, polypropylene, chain
anchor_weight: float # kg
anchor_type: str # none, weight, grappling, sandbag
rope_drag_coefficient: float = 1.2
rope_diameter: float = 0.01 # meters
def get_rope_properties(self):
"""Get rope-specific properties"""
properties = {
'nylon': {'density': 1140, 'elasticity': 0.3, 'drag_factor': 1.0},
'polyester': {'density': 1380, 'elasticity': 0.1, 'drag_factor': 0.9},
'polypropylene': {'density': 900, 'elasticity': 0.2, 'drag_factor': 0.8},
'chain': {'density': 7850, 'elasticity': 0.0, 'drag_factor': 2.0}
}
return properties.get(self.rope_type, properties['nylon'])
@dataclass
class EnvironmentalConditions:
"""Environmental conditions for simulation"""
season: str # summer, autumn, winter, spring
launch_time: str # dawn, day, dusk, night
wind_factor: float = 1.0 # Multiplier for wind effects
current_factor: float = 1.0 # Multiplier for current effects
wave_height: float = 1.0 # meters
water_temperature: float = 20.0 # Celsius
def get_seasonal_conditions(self):
"""Get season-specific conditions"""
conditions = {
'summer': {
'wind_speed': 5.5, # m/s (Etesian winds)
'wind_direction': 315, # degrees (NW)
'current_speed': 0.3, # m/s
'current_direction': 90, # degrees (E)
'wave_height': 1.2,
'stability_factor': 0.9
},
'autumn': {
'wind_speed': 4.2,
'wind_direction': 270, # W
'current_speed': 0.25,
'current_direction': 85,
'wave_height': 1.5,
'stability_factor': 0.7
},
'winter': {
'wind_speed': 7.8,
'wind_direction': 225, # SW
'current_speed': 0.4,
'current_direction': 95,
'wave_height': 2.1,
'stability_factor': 0.5
},
'spring': {
'wind_speed': 3.1,
'wind_direction': 45, # NE
'current_speed': 0.2,
'current_direction': 80,
'wave_height': 0.8,
'stability_factor': 0.8
}
}
return conditions.get(self.season, conditions['summer'])
@dataclass
class AnalysisSettings:
"""Analysis configuration settings"""
num_trajectories: int = 100
simulation_duration: int = 10 # days
time_step: float = 0.5 # hours
success_radius: float = 2.0 # km
variability: float = 0.3
include_rope_physics: bool = True
include_wave_effects: bool = True
include_turbulence: bool = True
@dataclass
class TrajectoryPoint:
"""Single point in trajectory"""
time: float # hours from start
lat: float
lon: float
depth: float = 0.0 # meters below surface
velocity_north: float = 0.0 # m/s
velocity_east: float = 0.0 # m/s
forces: Dict[str, float] = None # Force components
def __post_init__(self):
if self.forces is None:
self.forces = {}
@dataclass
class Trajectory:
"""Complete trajectory with metadata"""
id: int
points: List[TrajectoryPoint]
outcome: str # success, miss_north, miss_south, miss_offshore, lost
duration: float # hours
distance_traveled: float # km
distance_to_target: float # km at end
max_depth: float = 0.0 # meters
avg_velocity: float = 0.0 # m/s
container_specs: ContainerSpecs = None
rope_system: RopeSystem = None
class AdvancedPhysicsEngine:
"""Advanced physics simulation engine"""
def __init__(self):
self.g = 9.81 # gravity (m/s²)
self.rho_water = 1025 # seawater density (kg/m³)
self.rho_air = 1.225 # air density (kg/m³)
self.kinematic_viscosity = 1.05e-6 # m²/s for seawater
def calculate_buoyancy_force(self, container: ContainerSpecs) -> float:
"""Calculate buoyancy force on container"""
volume_submerged = container.volume / 1000 # Convert L to m³
# Assume container floats at surface (partially submerged)
submerged_fraction = min(1.0, container.density / self.rho_water)
effective_volume = volume_submerged * submerged_fraction
buoyancy = self.rho_water * self.g * effective_volume
return buoyancy
def calculate_drag_force(self, container: ContainerSpecs, rope: RopeSystem, velocity: float) -> float:
"""Calculate total drag force (container + rope)"""
# Container drag
container_drag = 0.5 * self.rho_water * container.drag_coefficient * container.surface_area * velocity**2
# Rope drag (if present)
rope_drag = 0.0
if rope.length > 0:
rope_surface_area = np.pi * rope.rope_diameter * rope.length
rope_properties = rope.get_rope_properties()
rope_drag = 0.5 * self.rho_water * rope.rope_drag_coefficient * rope_surface_area * velocity**2
rope_drag *= rope_properties['drag_factor']
return container_drag + rope_drag
def calculate_wind_force(self, container: ContainerSpecs, wind_speed: float, wind_direction: float) -> Tuple[float, float]:
"""Calculate wind force components (north, east)"""
# Estimate exposed surface area above water
submerged_fraction = min(1.0, container.density / self.rho_water)
exposed_area = container.surface_area * (1 - submerged_fraction) * 0.5 # Rough estimate
wind_force_magnitude = 0.5 * self.rho_air * container.drag_coefficient * exposed_area * wind_speed**2
# Convert wind direction to force components
wind_radians = np.radians(wind_direction)
force_north = wind_force_magnitude * np.cos(wind_radians)
force_east = wind_force_magnitude * np.sin(wind_radians)
return force_north, force_east
def calculate_current_force(self, container: ContainerSpecs, rope: RopeSystem,
current_speed: float, current_direction: float) -> Tuple[float, float]:
"""Calculate current force components"""
# Effective drag area in water
total_mass = container.mass + (rope.anchor_weight if rope.length > 0 else 0)
# Current force magnitude
current_force_magnitude = 0.5 * self.rho_water * container.drag_coefficient * container.surface_area * current_speed**2
# Add rope effects
if rope.length > 0:
rope_area = np.pi * rope.rope_diameter * rope.length
rope_force = 0.5 * self.rho_water * rope.rope_drag_coefficient * rope_area * current_speed**2
current_force_magnitude += rope_force
# Convert to components
current_radians = np.radians(current_direction)
force_north = current_force_magnitude * np.cos(current_radians)
force_east = current_force_magnitude * np.sin(current_radians)
return force_north, force_east
def calculate_wave_effects(self, container: ContainerSpecs, wave_height: float, time: float) -> Tuple[float, float]:
"""Calculate wave-induced motion"""
# Simplified wave effects - orbital motion
wave_period = 6.0 # seconds (typical Mediterranean)
wave_length = 60.0 # meters
# Wave orbital velocity at surface
wave_velocity = (2 * np.pi * wave_height) / wave_period
# Oscillating components
phase = 2 * np.pi * time / (wave_period / 3600) # Convert to hours
velocity_north = wave_velocity * np.sin(phase) * 0.3 # Reduced effect
velocity_east = wave_velocity * np.cos(phase) * 0.2
return velocity_north, velocity_east
class GazaAdvancedAnalyzer:
"""Advanced Gaza delivery analyzer with full physics"""
def __init__(self):
self.physics_engine = AdvancedPhysicsEngine()
# Mediterranean region bounds
self.region_bounds = {
'lat_min': 31.0, 'lat_max': 32.0,
'lon_min': 33.5, 'lon_max': 35.2
}
# Common Gaza coastal targets
self.gaza_targets = {
'Gaza City Beach': (31.5017, 34.4668),
'Al-Shati Beach': (31.5234, 34.4612),
'Deir al-Balah': (31.4167, 34.3500),
'Khan Younis': (31.3500, 34.3000),
'Rafah Beach': (31.2889, 34.2567)
}
def analyze_mission(self,
target_lat: float,
target_lon: float,
container: ContainerSpecs,
rope: RopeSystem,
environment: EnvironmentalConditions,
analysis: AnalysisSettings,
launch_point: Optional[Tuple[float, float]] = None) -> Dict[str, Any]:
"""Run complete advanced mission analysis"""
logger.info(f"Starting advanced analysis: {analysis.num_trajectories} trajectories")
start_time = datetime.datetime.now()
# Find optimal launch point if not provided
if launch_point is None:
launch_point = self._find_optimal_launch_point(
target_lat, target_lon, container, rope, environment
)
# Generate all trajectories
trajectories = []
for i in range(analysis.num_trajectories):
trajectory = self._simulate_single_trajectory(
i, launch_point, (target_lat, target_lon),
container, rope, environment, analysis
)
trajectories.append(trajectory)
# Calculate comprehensive metrics
metrics = self._calculate_comprehensive_metrics(trajectories, analysis)
# Generate visualizations
visualizations = self._create_visualizations(trajectories, target_lat, target_lon)
# Create interactive report data
interactive_data = self._create_interactive_report_data(
trajectories, metrics, container, rope, environment
)
analysis_time = datetime.datetime.now() - start_time
return {
'trajectories': [asdict(t) for t in trajectories],
'metrics': metrics,
'visualizations': visualizations,
'interactive_data': interactive_data,
'launch_point': launch_point,
'target_point': (target_lat, target_lon),
'container_specs': asdict(container),
'rope_system': asdict(rope),
'environment': asdict(environment),
'analysis_settings': asdict(analysis),
'analysis_time': analysis_time.total_seconds(),
'timestamp': datetime.datetime.now().isoformat()
}
def _find_optimal_launch_point(self, target_lat: float, target_lon: float,
container: ContainerSpecs, rope: RopeSystem,
environment: EnvironmentalConditions) -> Tuple[float, float]:
"""Find optimal launch point using physics-based optimization"""
seasonal_conditions = environment.get_seasonal_conditions()
# Estimate drift direction and distance
wind_direction = seasonal_conditions['wind_direction']
current_direction = seasonal_conditions['current_direction']
# Combined drift direction (weighted by forces)
wind_force_mag = seasonal_conditions['wind_speed']**2
current_force_mag = seasonal_conditions['current_speed']**2
total_force = wind_force_mag + current_force_mag
combined_direction = (
wind_direction * (wind_force_mag / total_force) +
current_direction * (current_force_mag / total_force)
)
# Estimate optimal distance
base_distance_km = 15 + (container.mass * 2) + (rope.length * 0.5)
# Apply seasonal adjustments
if environment.season == 'winter':
base_distance_km *= 1.3 # Stronger conditions
elif environment.season == 'spring':
base_distance_km *= 0.8 # Calmer conditions
# Calculate launch point
distance_deg_lat = base_distance_km / 111.0 # Rough conversion
distance_deg_lon = base_distance_km / (111.0 * np.cos(np.radians(target_lat)))
# Offset against drift direction
offset_radians = np.radians(combined_direction + 180) # Opposite direction
launch_lat = target_lat + distance_deg_lat * np.cos(offset_radians)
launch_lon = target_lon + distance_deg_lon * np.sin(offset_radians)
# Ensure launch point is in valid region
launch_lat = np.clip(launch_lat, self.region_bounds['lat_min'], self.region_bounds['lat_max'])
launch_lon = np.clip(launch_lon, self.region_bounds['lon_min'], self.region_bounds['lon_max'])
return (launch_lat, launch_lon)
def _simulate_single_trajectory(self, traj_id: int,
launch_point: Tuple[float, float],
target_point: Tuple[float, float],
container: ContainerSpecs,
rope: RopeSystem,
environment: EnvironmentalConditions,
analysis: AnalysisSettings) -> Trajectory:
"""Simulate single trajectory with advanced physics"""
launch_lat, launch_lon = launch_point
target_lat, target_lon = target_point
# Get environmental conditions
seasonal_conditions = environment.get_seasonal_conditions()
# Initialize trajectory
points = []
current_lat = launch_lat
current_lon = launch_lon
current_depth = 0.0
velocity_north = 0.0
velocity_east = 0.0
# Simulation parameters
dt = analysis.time_step * 3600 # Convert hours to seconds
max_steps = int(analysis.simulation_duration * 24 / analysis.time_step)
# Add variability for this specific trajectory
wind_variability = 1.0 + (np.random.random() - 0.5) * analysis.variability
current_variability = 1.0 + (np.random.random() - 0.5) * analysis.variability
total_distance = 0.0
for step in range(max_steps):
time_hours = step * analysis.time_step
# Environmental forces with variability
wind_speed = seasonal_conditions['wind_speed'] * environment.wind_factor * wind_variability
wind_dir = seasonal_conditions['wind_direction'] + np.random.normal(0, 15) # Direction variability
current_speed = seasonal_conditions['current_speed'] * environment.current_factor * current_variability
current_dir = seasonal_conditions['current_direction'] + np.random.normal(0, 10)
# Calculate forces
wind_force_n, wind_force_e = self.physics_engine.calculate_wind_force(
container, wind_speed, wind_dir
)
current_force_n, current_force_e = self.physics_engine.calculate_current_force(
container, rope, current_speed, current_dir
)
# Wave effects
wave_vel_n, wave_vel_e = self.physics_engine.calculate_wave_effects(
container, seasonal_conditions['wave_height'], time_hours
)
# Calculate total acceleration
total_mass = container.mass + (rope.anchor_weight if rope.length > 0 else 0)
# Net forces
net_force_north = wind_force_n + current_force_n
net_force_east = wind_force_e + current_force_e
# Add drag resistance
current_velocity = np.sqrt(velocity_north**2 + velocity_east**2)
if current_velocity > 0:
drag_force = self.physics_engine.calculate_drag_force(container, rope, current_velocity)
drag_fraction_n = velocity_north / current_velocity
drag_fraction_e = velocity_east / current_velocity
net_force_north -= drag_force * drag_fraction_n
net_force_east -= drag_force * drag_fraction_e
# Update velocities
accel_north = net_force_north / total_mass
accel_east = net_force_east / total_mass
velocity_north += accel_north * dt + wave_vel_n
velocity_east += accel_east * dt + wave_vel_e
# Apply velocity limits (terminal velocity effects)
max_velocity = 2.0 # m/s reasonable maximum
velocity_magnitude = np.sqrt(velocity_north**2 + velocity_east**2)
if velocity_magnitude > max_velocity:
scale_factor = max_velocity / velocity_magnitude
velocity_north *= scale_factor
velocity_east *= scale_factor
# Update position
# Convert velocity to lat/lon changes
lat_change = velocity_north * dt / 111000 # meters to degrees
lon_change = velocity_east * dt / (111000 * np.cos(np.radians(current_lat)))
prev_lat, prev_lon = current_lat, current_lon
current_lat += lat_change
current_lon += lon_change
# Calculate distance traveled this step
step_distance = self._calculate_distance(prev_lat, prev_lon, current_lat, current_lon)
total_distance += step_distance
# Create trajectory point
point = TrajectoryPoint(
time=time_hours,
lat=current_lat,
lon=current_lon,
depth=current_depth,
velocity_north=velocity_north,
velocity_east=velocity_east,
forces={
'wind_north': wind_force_n,
'wind_east': wind_force_e,
'current_north': current_force_n,
'current_east': current_force_e,
'total_north': net_force_north,
'total_east': net_force_east
}
)
points.append(point)
# Check for beaching/success
if current_lon > 34.2: # Simplified coastline check
distance_to_target = self._calculate_distance(
current_lat, current_lon, target_lat, target_lon
)
if distance_to_target <= analysis.success_radius:
outcome = 'success'
break
elif current_lat > target_lat + 0.05:
outcome = 'miss_north'
break
elif current_lat < target_lat - 0.05:
outcome = 'miss_south'
break
else:
outcome = 'miss_offshore'
break
# Check boundaries
if (current_lat < self.region_bounds['lat_min'] or
current_lat > self.region_bounds['lat_max'] or
current_lon < self.region_bounds['lon_min'] or
current_lon > self.region_bounds['lon_max']):
outcome = 'lost'
break
else:
# Simulation completed without reaching shore
outcome = 'lost'
# Calculate final metrics
final_point = points[-1]
distance_to_target = self._calculate_distance(
final_point.lat, final_point.lon, target_lat, target_lon
)
avg_velocity = total_distance / (len(points) * analysis.time_step) if points else 0
max_depth = max([p.depth for p in points]) if points else 0
return Trajectory(
id=traj_id,
points=points,
outcome=outcome,
duration=len(points) * analysis.time_step,
distance_traveled=total_distance,
distance_to_target=distance_to_target,
max_depth=max_depth,
avg_velocity=avg_velocity,
container_specs=container,
rope_system=rope
)
def _calculate_distance(self, lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate distance between two points in km"""
R = 6371 # Earth radius in km
lat1_rad = np.radians(lat1)
lat2_rad = np.radians(lat2)
delta_lat = np.radians(lat2 - lat1)
delta_lon = np.radians(lon2 - lon1)
a = (np.sin(delta_lat/2)**2 +
np.cos(lat1_rad) * np.cos(lat2_rad) * np.sin(delta_lon/2)**2)
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))
return R * c
def _calculate_comprehensive_metrics(self, trajectories: List[Trajectory],
analysis: AnalysisSettings) -> Dict[str, Any]:
"""Calculate comprehensive analysis metrics"""
total = len(trajectories)
if total == 0:
return {}
# Outcome counts
outcomes = {}
for trajectory in trajectories:
outcomes[trajectory.outcome] = outcomes.get(trajectory.outcome, 0) + 1
# Success metrics
successful = [t for t in trajectories if t.outcome == 'success']
success_rate = len(successful) / total * 100
# Duration statistics
durations = [t.duration for t in trajectories]
avg_duration = np.mean(durations)
std_duration = np.std(durations)
# Distance statistics
distances_traveled = [t.distance_traveled for t in trajectories]
avg_distance_traveled = np.mean(distances_traveled)
target_distances = [t.distance_to_target for t in trajectories]
avg_target_distance = np.mean(target_distances)
# Velocity statistics
avg_velocities = [t.avg_velocity for t in trajectories if t.avg_velocity > 0]
overall_avg_velocity = np.mean(avg_velocities) if avg_velocities else 0
# Success-specific metrics
success_metrics = {}
if successful:
success_durations = [t.duration for t in successful]
success_distances = [t.distance_to_target for t in successful]
success_metrics = {
'avg_duration': np.mean(success_durations),
'min_duration': np.min(success_durations),
'max_duration': np.max(success_durations),
'avg_accuracy': np.mean(success_distances),
'best_accuracy': np.min(success_distances)
}
return {
'total_trajectories': total,
'success_rate': success_rate,
'outcomes': outcomes,
'duration_stats': {
'average': avg_duration,
'std_dev': std_duration,
'min': np.min(durations),
'max': np.max(durations)
},
'distance_stats': {
'avg_traveled': avg_distance_traveled,
'avg_to_target': avg_target_distance,
'overall_avg_velocity': overall_avg_velocity
},
'success_metrics': success_metrics,
'failure_breakdown': {
'miss_north_pct': outcomes.get('miss_north', 0) / total * 100,
'miss_south_pct': outcomes.get('miss_south', 0) / total * 100,
'miss_offshore_pct': outcomes.get('miss_offshore', 0) / total * 100,
'lost_pct': outcomes.get('lost', 0) / total * 100
}
}
def _create_visualizations(self, trajectories: List[Trajectory],
target_lat: float, target_lon: float) -> Dict[str, str]:
"""Create visualization plots and return as base64 strings"""
visualizations = {}
# 1. Main trajectory plot
fig, ax = plt.subplots(figsize=(12, 10))
colors = {
'success': '#27ae60',
'miss_north': '#f39c12',
'miss_south': '#e74c3c',
'miss_offshore': '#9b59b6',
'lost': '#95a5a6'
}
for trajectory in trajectories:
lats = [p.lat for p in trajectory.points]
lons = [p.lon for p in trajectory.points]
color = colors.get(trajectory.outcome, '#95a5a6')
ax.plot(lons, lats, color=color, alpha=0.6, linewidth=1)
# Mark target
ax.plot(target_lon, target_lat, 'r*', markersize=15, label='Target')
# Mark launch points
if trajectories:
launch_lons = [t.points[0].lon for t in trajectories if t.points]
launch_lats = [t.points[0].lat for t in trajectories if t.points]
ax.scatter(launch_lons, launch_lats, c='blue', s=50, alpha=0.7, label='Launch Points')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title('All Trajectory Paths')
ax.legend()
ax.grid(True, alpha=0.3)
# Save as base64
buffer = BytesIO()
plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
buffer.seek(0)
trajectory_plot = base64.b64encode(buffer.getvalue()).decode()
plt.close()
visualizations['trajectory_plot'] = trajectory_plot
# 2. Outcome distribution pie chart
fig, ax = plt.subplots(figsize=(8, 8))
outcomes = {}
for trajectory in trajectories:
outcomes[trajectory.outcome] = outcomes.get(trajectory.outcome, 0) + 1
if outcomes:
labels = list(outcomes.keys())
sizes = list(outcomes.values())
colors_list = [colors.get(label, '#95a5a6') for label in labels]
ax.pie(sizes, labels=labels, colors=colors_list, autopct='%1.1f%%', startangle=90)
ax.set_title('Trajectory Outcomes Distribution')
buffer = BytesIO()
plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
buffer.seek(0)
outcome_plot = base64.b64encode(buffer.getvalue()).decode()
plt.close()
visualizations['outcome_plot'] = outcome_plot
return visualizations
def _create_interactive_report_data(self, trajectories: List[Trajectory],
metrics: Dict[str, Any],
container: ContainerSpecs,
rope: RopeSystem,
environment: EnvironmentalConditions) -> Dict[str, Any]:
"""Create data for interactive reports"""
# Prepare trajectory data for interactive plotting
trajectory_data = []
for trajectory in trajectories:
traj_data = {
'id': trajectory.id,
'outcome': trajectory.outcome,
'duration': trajectory.duration,
'distance_traveled': trajectory.distance_traveled,
'distance_to_target': trajectory.distance_to_target,
'points': [
{
'time': p.time,
'lat': p.lat,
'lon': p.lon,
'velocity_north': p.velocity_north,
'velocity_east': p.velocity_east,
'forces': p.forces
} for p in trajectory.points
]
}
trajectory_data.append(traj_data)
# Physics analysis
physics_analysis = {
'container_buoyancy': self.physics_engine.calculate_buoyancy_force(container),
'estimated_drag': self.physics_engine.calculate_drag_force(container, rope, 1.0), # At 1 m/s
'rope_effects': {
'total_length': rope.length,
'anchor_weight': rope.anchor_weight,
'rope_properties': rope.get_rope_properties()
},
'environmental_summary': environment.get_seasonal_conditions()
}
# Statistical summaries
statistical_data = {
'outcome_distribution': metrics.get('outcomes', {}),
'success_rate': metrics.get('success_rate', 0),
'duration_distribution': [t.duration for t in trajectories],
'velocity_distribution': [t.avg_velocity for t in trajectories],
'accuracy_distribution': [t.distance_to_target for t in trajectories]
}
return {
'trajectories': trajectory_data,
'physics': physics_analysis,
'statistics': statistical_data,
'container_specs': asdict(container),
'rope_system': asdict(rope),
'environment': asdict(environment)
}
# Example usage and testing
if __name__ == "__main__":
print("🌊 Gaza Advanced Delivery Backend - Testing")
print("=" * 50)
# Create test specifications
container = ContainerSpecs(
container_type='jerry_can',
volume=5.0, # 5L jerry can
mass=2.5, # 2.5 kg
density=500, # 500 kg/m³
drag_coefficient=0.8
)
rope = RopeSystem(
length=5.0, # 5m rope
rope_type='nylon',
anchor_weight=0.5, # 0.5kg anchor
anchor_type='sandbag'
)
environment = EnvironmentalConditions(
season='summer',
launch_time='dawn',
wind_factor=1.0,
current_factor=1.0
)
analysis = AnalysisSettings(
num_trajectories=50, # Smaller number for testing
simulation_duration=7,
success_radius=2.0,
variability=0.3
)
# Run analysis
analyzer = GazaAdvancedAnalyzer()
# Target: Gaza beach
target_lat, target_lon = 31.2794, 34.2542
print(f"🎯 Target: {target_lat:.4f}°N, {target_lon:.4f}°E")
print(f"📦 Container: {container.volume}L {container.container_type}")
print(f"🪢 Rope: {rope.length}m {rope.rope_type}")
print(f"🌊 Environment: {environment.season}, {environment.launch_time}")
print(f"🔬 Analysis: {analysis.num_trajectories} trajectories")
results = analyzer.analyze_mission(
target_lat, target_lon, container, rope, environment, analysis
)
print(f"\n📊 Results:")
print(f" Success Rate: {results['metrics']['success_rate']:.1f}%")
print(f" Total Trajectories: {results['metrics']['total_trajectories']}")
print(f" Average Duration: {results['metrics']['duration_stats']['average']:.1f} hours")
print(f" Analysis Time: {results['analysis_time']:.1f} seconds")
if results['metrics']['success_metrics']:
print(f" Successful Avg Duration: {results['metrics']['success_metrics']['avg_duration']:.1f} hours")
print(f" Best Accuracy: {results['metrics']['success_metrics']['best_accuracy']:.2f} km")
print(f"\n📍 Failure Breakdown:")
for outcome, count in results['metrics']['outcomes'].items():
if outcome != 'success':
pct = count / results['metrics']['total_trajectories'] * 100
print(f" {outcome}: {count} ({pct:.1f}%)")
print(f"\n📁 Generated:")
print(f" Visualizations: {len(results['visualizations'])} plots")
print(f" Interactive Data: {len(results['interactive_data']['trajectories'])} trajectory datasets")
print("\n✅ Advanced backend test successful!")