Spaces:
Running
Running
File size: 10,995 Bytes
ec5b96f |
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 |
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import folium
from streamlit_folium import st_folium
import requests
# ----------------------------------------------------
# 1. Load data
# ----------------------------------------------------
@st.cache_data
def load_data():
daily_df = pd.read_csv("daily_data_2013_2024.csv", parse_dates=["date"])
monthly_df = pd.read_csv("monthly_data_2013_2024.csv")
return daily_df, monthly_df
daily_data, monthly_data = load_data()
# Pre-define your location dictionary so we can map lat/lon
LOCATIONS = {
"Karagwe": {"lat": -1.7718, "lon": 30.9876},
"Masasi": {"lat": -10.7167, "lon": 38.8000},
"Igunga": {"lat": -4.2833, "lon": 33.8833}
}
# ----------------------------------------------------
# 2. Streamlit UI Layout
# ----------------------------------------------------
st.title("Malaria & Dengue Outbreak Analysis (2013–2024)")
st.sidebar.header("Filters & Options")
# Choose disease type
disease_choice = st.sidebar.radio("Select Disease", ["Malaria", "Dengue"])
# Choose data granularity
data_choice = st.sidebar.radio("Data Granularity", ["Monthly", "Daily"])
# Let user filter location(s)
location_list = list(LOCATIONS.keys())
selected_locations = st.sidebar.multiselect("Select Location(s)", location_list, default=location_list)
# For monthly data
if data_choice == "Monthly":
year_min = int(monthly_data["year"].min())
year_max = int(monthly_data["year"].max())
year_range = st.sidebar.slider(
"Select Year Range",
min_value=year_min,
max_value=year_max,
value=(year_min, year_max)
)
# For daily data
else:
date_min = daily_data["date"].min()
date_max = daily_data["date"].max()
date_range = st.sidebar.date_input(
"Select Date Range",
[date_min, date_max],
min_value=date_min,
max_value=date_max
)
# ----------------------------------------------------
# 3. Filter data based on user input
# ----------------------------------------------------
if data_choice == "Monthly":
df = monthly_data[monthly_data["location"].isin(selected_locations)].copy()
# Filter year range
df = df[(df["year"] >= year_range[0]) & (df["year"] <= year_range[1])]
# Create a "date" column for monthly data
df["date"] = pd.to_datetime(df["year"].astype(str) + "-" + df["month"].astype(str) + "-01")
else:
df = daily_data[daily_data["location"].isin(selected_locations)].copy()
# Filter date range
df = df[
(df["date"] >= pd.to_datetime(date_range[0]))
& (df["date"] <= pd.to_datetime(date_range[1]))
]
# ----------------------------------------------------
# 4. Interactive Plotly Time-Series
# ----------------------------------------------------
st.subheader(f"{data_choice} {disease_choice} Risk & Climate Parameters")
risk_col = "malaria_risk" if disease_choice == "Malaria" else "dengue_risk"
if data_choice == "Monthly":
fig = px.line(
df, x="date", y=risk_col, color="location",
title=f"{disease_choice} Risk Over Time ({data_choice})"
)
fig.update_layout(yaxis_title="Risk (0–1)")
st.plotly_chart(fig, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
fig_temp = px.line(
df, x="date", y="temp_avg", color="location",
title="Average Temperature (°C)"
)
st.plotly_chart(fig_temp, use_container_width=True)
with col2:
fig_rain = px.line(
df, x="date", y="monthly_rainfall_mm", color="location",
title="Monthly Rainfall (mm)"
)
st.plotly_chart(fig_rain, use_container_width=True)
# Show outbreak months
if disease_choice == "Malaria":
flag_col = "malaria_outbreak"
else:
flag_col = "dengue_outbreak"
outbreak_months = df[df[flag_col] == True]
if not outbreak_months.empty:
st.write(f"**Months with likely {disease_choice} outbreak:**")
st.dataframe(outbreak_months[[
"location","year","month","temp_avg","humidity","monthly_rainfall_mm",flag_col
]])
else:
st.write(f"No months meet the {disease_choice} outbreak criteria in this selection.")
else:
# Daily data
fig = px.line(
df, x="date", y=risk_col, color="location",
title=f"{disease_choice} Daily Risk Over Time (2013–2024)"
)
fig.update_layout(yaxis_title="Risk (0–1)")
st.plotly_chart(fig, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
fig_temp = px.line(
df, x="date", y="temp_avg", color="location",
title="Daily Avg Temperature (°C)"
)
st.plotly_chart(fig_temp, use_container_width=True)
with col2:
fig_rain = px.line(
df, x="date", y="daily_rainfall_mm", color="location",
title="Daily Rainfall (mm)"
)
st.plotly_chart(fig_rain, use_container_width=True)
# ----------------------------------------------------
# 5. Correlation Heatmap
# ----------------------------------------------------
st.subheader(f"Correlation Heatmap - {data_choice} Data")
if data_choice == "Monthly":
subset_cols = ["temp_avg", "humidity", "monthly_rainfall_mm", "malaria_risk", "dengue_risk"]
else:
subset_cols = ["temp_avg", "humidity", "daily_rainfall_mm", "malaria_risk", "dengue_risk"]
corr_df = df[subset_cols].corr()
fig_corr = px.imshow(
corr_df, text_auto=True, aspect="auto",
title="Correlation Matrix of Weather & Risk"
)
st.plotly_chart(fig_corr, use_container_width=True)
# ----------------------------------------------------
# 6. Add Real-Time Weather in Folium Map + Outbreak Info
# ----------------------------------------------------
st.subheader("Interactive Map")
st.markdown(
"""
**Note**: We only have 3 locations for the CSV data.
Markers now also show **real-time weather** from OpenWeather & an **outbreak** indicator.
"""
)
# --- 6A. Helper function to get current weather from OpenWeather ---
API_KEY = "c5b5c5ee6c497c6b1869ed926582a1ea" # <-- Your OpenWeather API key
def get_current_weather(lat, lon, api_key=API_KEY):
"""
Fetch current weather data from OpenWeather for given lat/lon.
Returns a dict with {temp, humidity, description} if successful; else None.
"""
url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
try:
resp = requests.get(url)
if resp.status_code == 200:
data = resp.json()
# Extract a few relevant fields:
current_temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
weather_desc = data["weather"][0]["description"]
return {
"temp": current_temp,
"humidity": humidity,
"description": weather_desc
}
else:
return None
except Exception as e:
# In production, you'd handle logging or fallback here
return None
# --- 6B. Create Folium Map ---
m = folium.Map(location=[-6.0, 35.0], zoom_start=6)
if disease_choice == "Malaria":
outbreak_flag_col = "malaria_outbreak"
else:
outbreak_flag_col = "dengue_outbreak"
# For each location, we show both the CSV-based stats AND real-time weather
if data_choice == "Monthly":
for loc in selected_locations:
loc_info = LOCATIONS[loc]
loc_df = df[df["location"] == loc]
if loc_df.empty:
continue
# Averages from the CSV data
avg_risk = loc_df[risk_col].mean()
avg_temp = loc_df["temp_avg"].mean()
avg_rain = loc_df["monthly_rainfall_mm"].mean()
# Check if there's an outbreak in the filtered monthly data
outbreak_count = loc_df[loc_df[outbreak_flag_col] == True].shape[0]
outbreak_status = "Yes" if outbreak_count > 0 else "No"
# Fetch real-time weather
weather_now = get_current_weather(loc_info["lat"], loc_info["lon"], API_KEY)
if weather_now:
rt_temp = weather_now["temp"]
rt_hum = weather_now["humidity"]
rt_desc = weather_now["description"]
else:
rt_temp = None
rt_hum = None
rt_desc = "N/A"
# Build the popup HTML
popup_html = f"""
<b>{loc}</b><br/>
Disease: {disease_choice}<br/>
Outbreak Now (in selection)? {outbreak_status}<br/>
<br/>
<u>Historical/Forecasted Averages (CSV)</u><br/>
Avg Risk (selected range): {avg_risk:.2f}<br/>
Avg Temp (°C): {avg_temp:.2f}<br/>
Avg Rainfall (mm): {avg_rain:.2f}<br/>
<br/>
<u>Real-Time Weather (OpenWeather)</u><br/>
Current Temp (°C): {rt_temp if rt_temp else 'N/A'}<br/>
Current Humidity (%): {rt_hum if rt_hum else 'N/A'}<br/>
Conditions: {rt_desc}
"""
folium.Marker(
location=[loc_info["lat"], loc_info["lon"]],
popup=popup_html,
tooltip=f"{loc} ({disease_choice})"
).add_to(m)
else:
# Daily data
for loc in selected_locations:
loc_info = LOCATIONS[loc]
loc_df = df[df["location"] == loc]
if loc_df.empty:
continue
avg_risk = loc_df[risk_col].mean()
avg_temp = loc_df["temp_avg"].mean()
avg_rain = loc_df["daily_rainfall_mm"].mean()
# Check outbreak
outbreak_count = loc_df[loc_df[outbreak_flag_col] == True].shape[0]
outbreak_status = "Yes" if outbreak_count > 0 else "No"
# Real-time weather
weather_now = get_current_weather(loc_info["lat"], loc_info["lon"], API_KEY)
if weather_now:
rt_temp = weather_now["temp"]
rt_hum = weather_now["humidity"]
rt_desc = weather_now["description"]
else:
rt_temp = None
rt_hum = None
rt_desc = "N/A"
popup_html = f"""
<b>{loc}</b><br/>
Disease: {disease_choice}<br/>
Outbreak Now (in selection)? {outbreak_status}<br/>
<br/>
<u>Historical/Forecasted Averages (CSV)</u><br/>
Avg Risk (selected range): {avg_risk:.2f}<br/>
Avg Temp (°C): {avg_temp:.2f}<br/>
Avg Rain (mm/day): {avg_rain:.2f}<br/>
<br/>
<u>Real-Time Weather (OpenWeather)</u><br/>
Current Temp (°C): {rt_temp if rt_temp else 'N/A'}<br/>
Current Humidity (%): {rt_hum if rt_hum else 'N/A'}<br/>
Conditions: {rt_desc}
"""
folium.Marker(
location=[loc_info["lat"], loc_info["lon"]],
popup=popup_html,
tooltip=f"{loc} ({disease_choice})"
).add_to(m)
# Render Folium map in Streamlit
st_data = st_folium(m, width=700, height=500)
|