Spaces:
Running
Running
File size: 14,479 Bytes
d293fcb |
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 |
import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import requests
import json
from typing import Dict, List, Tuple, Optional
import warnings
warnings.filterwarnings('ignore')
class OceanCurrentMapper:
def __init__(self):
self.noaa_base_url = "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter"
self.oscar_base_url = "https://podaac-opendap.jpl.nasa.gov/opendap/allData/oscar/preview/L4/oscar_third_deg"
def get_noaa_current_data(self, station_id: str, start_date: str, end_date: str) -> pd.DataFrame:
"""Fetch current data from NOAA API"""
try:
params = {
'product': 'currents',
'application': 'OceanCurrentMapper',
'begin_date': start_date,
'end_date': end_date,
'station': station_id,
'time_zone': 'gmt',
'units': 'metric',
'format': 'json'
}
response = requests.get(self.noaa_base_url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if 'data' in data:
df = pd.DataFrame(data['data'])
return df
return pd.DataFrame()
except Exception as e:
print(f"Error fetching NOAA data: {e}")
return pd.DataFrame()
def generate_synthetic_current_data(self, region: str, resolution: str) -> Dict:
"""Generate synthetic ocean current data for demonstration"""
# Define region boundaries
regions = {
"Gulf of Mexico": {"lat": [18, 31], "lon": [-98, -80]},
"California Coast": {"lat": [32, 42], "lon": [-125, -117]},
"Atlantic Coast": {"lat": [25, 45], "lon": [-81, -65]},
"Global": {"lat": [-60, 60], "lon": [-180, 180]}
}
# Set resolution
res_map = {"High": 0.1, "Medium": 0.25, "Low": 0.5}
res = res_map.get(resolution, 0.25)
# Get region bounds
bounds = regions.get(region, regions["Global"])
# Create coordinate grids
lats = np.arange(bounds["lat"][0], bounds["lat"][1], res)
lons = np.arange(bounds["lon"][0], bounds["lon"][1], res)
# Generate realistic current patterns
lat_grid, lon_grid = np.meshgrid(lats, lons, indexing='ij')
# Create realistic current vectors using oceanographic patterns
# Gulf Stream-like eastward flow
u_component = 0.5 * np.sin(np.pi * (lat_grid - bounds["lat"][0]) / (bounds["lat"][1] - bounds["lat"][0]))
# Cross-shore component
v_component = 0.3 * np.cos(np.pi * (lon_grid - bounds["lon"][0]) / (bounds["lon"][1] - bounds["lon"][0]))
# Add some turbulence and eddies
u_component += 0.2 * np.random.normal(0, 0.1, u_component.shape)
v_component += 0.2 * np.random.normal(0, 0.1, v_component.shape)
# Calculate current speed and direction
speed = np.sqrt(u_component**2 + v_component**2)
direction = np.arctan2(v_component, u_component) * 180 / np.pi
return {
'latitude': lat_grid,
'longitude': lon_grid,
'u_component': u_component,
'v_component': v_component,
'speed': speed,
'direction': direction,
'timestamp': datetime.now().isoformat()
}
def create_current_map(self, region: str, resolution: str, show_vectors: bool,
show_speed: bool, vector_scale: float) -> go.Figure:
"""Create interactive ocean current map"""
# Get current data
current_data = self.generate_synthetic_current_data(region, resolution)
fig = go.Figure()
# Add speed contours if requested
if show_speed:
fig.add_trace(go.Contour(
x=current_data['longitude'][0, :],
y=current_data['latitude'][:, 0],
z=current_data['speed'],
colorscale='Viridis',
name='Current Speed (m/s)',
showscale=True,
colorbar=dict(title="Speed (m/s)", x=1.02)
))
# Add vector field if requested
if show_vectors:
# Subsample for better visibility
step = max(1, len(current_data['latitude']) // 20)
lat_sub = current_data['latitude'][::step, ::step]
lon_sub = current_data['longitude'][::step, ::step]
u_sub = current_data['u_component'][::step, ::step] * vector_scale
v_sub = current_data['v_component'][::step, ::step] * vector_scale
# Create arrow annotations
for i in range(lat_sub.shape[0]):
for j in range(lat_sub.shape[1]):
if i % 2 == 0 and j % 2 == 0: # Further subsample
fig.add_annotation(
ax=lon_sub[i, j],
ay=lat_sub[i, j],
axref='x',
ayref='y',
x=lon_sub[i, j] + u_sub[i, j],
y=lat_sub[i, j] + v_sub[i, j],
xref='x',
yref='y',
arrowhead=2,
arrowsize=1,
arrowwidth=1,
arrowcolor='red',
showarrow=True
)
# Update layout
fig.update_layout(
title=f'Ocean Currents - {region}',
xaxis_title='Longitude',
yaxis_title='Latitude',
showlegend=True,
width=800,
height=600
)
return fig
def get_forecast_data(self, region: str, forecast_hours: int) -> go.Figure:
"""Generate forecast visualization"""
# Create time series for forecast
times = [datetime.now() + timedelta(hours=i) for i in range(forecast_hours)]
# Generate sample forecast data
np.random.seed(42) # For reproducible demo
current_speeds = np.random.normal(0.5, 0.2, forecast_hours)
current_speeds = np.maximum(current_speeds, 0) # Ensure non-negative
wave_heights = np.random.normal(1.5, 0.5, forecast_hours)
wave_heights = np.maximum(wave_heights, 0)
wind_speeds = np.random.normal(10, 5, forecast_hours)
wind_speeds = np.maximum(wind_speeds, 0)
# Create forecast plot
fig = go.Figure()
fig.add_trace(go.Scatter(
x=times,
y=current_speeds,
mode='lines+markers',
name='Current Speed (m/s)',
line=dict(color='blue', width=2)
))
fig.add_trace(go.Scatter(
x=times,
y=wave_heights,
mode='lines+markers',
name='Wave Height (m)',
line=dict(color='green', width=2),
yaxis='y2'
))
fig.add_trace(go.Scatter(
x=times,
y=wind_speeds,
mode='lines+markers',
name='Wind Speed (m/s)',
line=dict(color='red', width=2),
yaxis='y3'
))
fig.update_layout(
title=f'Ocean Conditions Forecast - {region}',
xaxis_title='Time',
yaxis=dict(title='Current Speed (m/s)', side='left'),
yaxis2=dict(title='Wave Height (m)', side='right', overlaying='y'),
yaxis3=dict(title='Wind Speed (m/s)', side='right', overlaying='y', position=0.95),
showlegend=True,
width=800,
height=400
)
return fig
def analyze_surfing_conditions(self, region: str) -> str:
"""Analyze surfing conditions based on current data"""
current_data = self.generate_synthetic_current_data(region, "Medium")
avg_speed = np.mean(current_data['speed'])
max_speed = np.max(current_data['speed'])
# Simple surfing condition analysis
conditions = []
if avg_speed < 0.3:
conditions.append("β
Low current speeds - good for beginners")
elif avg_speed < 0.8:
conditions.append("β οΈ Moderate currents - suitable for intermediate surfers")
else:
conditions.append("β Strong currents - experienced surfers only")
if max_speed > 1.0:
conditions.append("π Strong rip currents detected in some areas")
# Add mock weather conditions
conditions.extend([
f"π‘οΈ Water temperature: {20 + np.random.randint(0, 10)}Β°C",
f"π¨ Wind: {5 + np.random.randint(0, 15)} mph offshore",
f"π Wave height: {1 + np.random.randint(0, 3)} meters"
])
return "\n".join(conditions)
# Initialize the mapper
mapper = OceanCurrentMapper()
# Create Gradio interface
def create_current_map(region, resolution, show_vectors, show_speed, vector_scale):
return mapper.create_current_map(region, resolution, show_vectors, show_speed, vector_scale)
def create_forecast(region, forecast_hours):
return mapper.get_forecast_data(region, forecast_hours)
def analyze_conditions(region):
return mapper.analyze_surfing_conditions(region)
# Define the Gradio interface
with gr.Blocks(title="Ocean Current Mapper", theme=gr.themes.Ocean()) as demo:
gr.Markdown("""
# π Real-Time Ocean Current Mapper
An AI-powered application for visualizing ocean currents, designed for oceanographers and surfers.
**Features:**
- Real-time current visualization
- Multiple ocean regions
- Forecast capabilities
- Surfing condition analysis
""")
with gr.Tab("Current Map"):
with gr.Row():
with gr.Column(scale=1):
region = gr.Dropdown(
choices=["Gulf of Mexico", "California Coast", "Atlantic Coast", "Global"],
value="Gulf of Mexico",
label="Region"
)
resolution = gr.Dropdown(
choices=["High", "Medium", "Low"],
value="Medium",
label="Resolution"
)
show_vectors = gr.Checkbox(label="Show Current Vectors", value=True)
show_speed = gr.Checkbox(label="Show Speed Contours", value=True)
vector_scale = gr.Slider(
minimum=0.1,
maximum=2.0,
value=1.0,
step=0.1,
label="Vector Scale"
)
update_map = gr.Button("Update Map", variant="primary")
with gr.Column(scale=2):
current_map = gr.Plot(label="Ocean Current Map")
update_map.click(
fn=create_current_map,
inputs=[region, resolution, show_vectors, show_speed, vector_scale],
outputs=current_map
)
with gr.Tab("Forecast"):
with gr.Row():
with gr.Column(scale=1):
forecast_region = gr.Dropdown(
choices=["Gulf of Mexico", "California Coast", "Atlantic Coast", "Global"],
value="Gulf of Mexico",
label="Region"
)
forecast_hours = gr.Slider(
minimum=6,
maximum=72,
value=24,
step=6,
label="Forecast Hours"
)
update_forecast = gr.Button("Generate Forecast", variant="primary")
with gr.Column(scale=2):
forecast_plot = gr.Plot(label="Ocean Conditions Forecast")
update_forecast.click(
fn=create_forecast,
inputs=[forecast_region, forecast_hours],
outputs=forecast_plot
)
with gr.Tab("Surfing Conditions"):
with gr.Row():
with gr.Column(scale=1):
surf_region = gr.Dropdown(
choices=["Gulf of Mexico", "California Coast", "Atlantic Coast"],
value="California Coast",
label="Surfing Region"
)
analyze_button = gr.Button("Analyze Conditions", variant="primary")
with gr.Column(scale=2):
surf_analysis = gr.Textbox(
label="Surfing Conditions Analysis",
lines=8,
placeholder="Click 'Analyze Conditions' to get surfing recommendations..."
)
analyze_button.click(
fn=analyze_conditions,
inputs=[surf_region],
outputs=surf_analysis
)
with gr.Tab("About"):
gr.Markdown("""
## About This Application
This Ocean Current Mapper provides real-time visualization and analysis of ocean currents using data from:
- **NOAA Tides & Currents**: Real-time oceanographic observations
- **NASA OSCAR**: Global surface current analyses
- **NOAA Global RTOFS**: Ocean forecast system
### For Oceanographers:
- High-resolution current maps
- Vector field visualization
- Multi-day forecasting
- Data export capabilities
### For Surfers:
- Current safety analysis
- Wave and wind conditions
- Rip current warnings
- Beach-specific recommendations
### Technical Details:
- Built with Gradio for easy deployment
- Hosted on Hugging Face Spaces
- Real-time API integration
- Interactive visualizations with Plotly
**Note**: This demo uses synthetic data for demonstration. In production, it would connect to live oceanographic APIs.
""")
# Launch the app
if __name__ == "__main__":
demo.launch() |