================================================================================
  Experiment 12: USGS Earthquake Analysis Dashboard
================================================================================

FULL QUESTION:
Retrieve earthquake data for the past 7 weeks using the USGS Earthquake API. Extract the following fields: Magnitude, Place, Time, Longitude, Latitude, Depth, and Tsunami Status. Perform statistical and time-series analysis on the retrieved earthquake data. Visualize the results using suitable charts and develop a dashboard to display the earthquake data, statistical analysis, time-series visualizations, and findings.

SHORT QUESTION:
Fetch USGS GeoJSON earthquake feed, compute statistical distributions, and render multi-chart Streamlit dashboard.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# Experiment 12: USGS Earthquake Analysis Dashboard

## Objective
Retrieve earthquake events from the USGS GeoJSON API, extract Magnitude, Place, Time, Coordinates, Depth, and Tsunami Status, and perform statistical and time-series analysis on an interactive dashboard.

## Requirements
```bash
pip install requests pandas matplotlib streamlit
```

## How to Run
```bash
streamlit run app.py
```

================================================================================
SOURCE CODE FILES:
================================================================================

1. app.py
--------------------------------------------------------------------------------
"""
================================================================================
IOT EXPERIMENT 12: Real-Time USGS Global Earthquake Analytics Dashboard
================================================================================
Retrieve earthquake data for the past 7 weeks using the USGS Earthquake API.
Extract the following fields: Magnitude, Place, Time, Longitude, Latitude,
Depth, and Tsunami Status. Perform statistical and time-series analysis on
the retrieved earthquake data. Visualize the results using suitable charts
and develop a dashboard to display the earthquake data, statistical analysis,
time-series visualizations, and findings.
================================================================================
"""

# Short Description: Ingests 7 weeks of global seismic data from the USGS GeoJSON API, extracts key geological parameters, computes summary statistics, and displays analytical charts.

"""
README / BEFORE RUNNING:
- Prerequisites: Python 3.x, requests, pandas, matplotlib, seaborn (pip install requests pandas matplotlib seaborn).
- Network: Requires internet connection to query USGS Earthquake API.
- How to Run: python app.py
- Expected Behavior: Downloads seismic records, prints statistical analysis (mean magnitude, depth distribution, tsunami alerts), and generates visualizations.
"""

import streamlit as st
import pandas as pd
import requests
import matplotlib.pyplot as plt

st.set_page_config(page_title="USGS Earthquake Dashboard", layout="wide")
st.title("USGS Earthquake Analysis Dashboard")

USGS_URL = (
    "https://earthquake.usgs.gov/fdsnws/event/1/query?"
    "format=geojson&starttime=2026-08-07&endtime=2026-09-25&minmagnitude=2.5&orderby=time"
)

@st.cache_data
def fetch_earthquake_data():
    res = requests.get(USGS_URL, timeout=20).json()
    features = res.get("features", [])
    records = []
    for f in features:
        props = f["properties"]
        geom = f["geometry"]["coordinates"]
        records.append({
            "Magnitude": props.get("mag"),
            "Place": props.get("place"),
            "Time": pd.to_datetime(props.get("time"), unit="ms"),
            "Longitude": geom[0],
            "Latitude": geom[1],
            "Depth": geom[2],
            "Tsunami Status": props.get("tsunami")
        })
    return pd.DataFrame(records)

try:
    df = fetch_earthquake_data().dropna(subset=["Magnitude", "Time"])
except Exception as e:
    st.error(f"Failed to query USGS API: {e}")
    st.stop()

col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Events", len(df))
col2.metric("Mean Magnitude", f"{df['Magnitude'].mean():.2f}")
col3.metric("Max Magnitude", f"{df['Magnitude'].max():.2f}")
col4.metric("Tsunami Warnings", int(df["Tsunami Status"].sum()))

st.subheader("Statistical Summary")
st.dataframe(df[["Magnitude", "Depth", "Tsunami Status"]].describe())

st.subheader("Time-Series Visualizations")
df_sorted = df.sort_values("Time")

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
ax1.plot(df_sorted["Time"], df_sorted["Magnitude"], color="crimson", marker=".", linestyle="none", alpha=0.6)
ax1.set_ylabel("Magnitude")
ax1.set_title("Earthquake Magnitude over Time")
ax1.grid(True)

ax2.plot(df_sorted["Time"], df_sorted["Depth"], color="navy", marker=".", linestyle="none", alpha=0.6)
ax2.set_xlabel("Date")
ax2.set_ylabel("Depth (km)")
ax2.set_title("Earthquake Focal Depth over Time")
ax2.grid(True)

plt.tight_layout()
st.pyplot(fig)

st.subheader("Recent Earthquakes")
st.dataframe(df.head(50), use_container_width=True)
--------------------------------------------------------------------------------
