|
|
|
|
|
""" |
|
Example usage of the Weather Geo ERA5 Dataset |
|
|
|
This script demonstrates how to use the weather_geo_utils module to load |
|
and analyze weather data from the HuggingFace dataset. |
|
|
|
Requirements: |
|
pip install pandas huggingface-hub matplotlib seaborn |
|
""" |
|
|
|
import pandas as pd |
|
import matplotlib.pyplot as plt |
|
import seaborn as sns |
|
from weather_geo_utils import ( |
|
load_point_data, |
|
load_cities_data, |
|
convert_temperature_units, |
|
get_dataset_info |
|
) |
|
|
|
def example_single_city(): |
|
"""Example: Load data for a single city (Paris).""" |
|
print("=" * 60) |
|
print("EXAMPLE 1: Single City Analysis (Paris)") |
|
print("=" * 60) |
|
|
|
|
|
print("Loading Paris weather data for 2023...") |
|
df = load_point_data( |
|
lat=48.8566, |
|
lon=2.3522, |
|
start_date="2023-01-01", |
|
end_date="2023-12-31" |
|
) |
|
|
|
|
|
df = convert_temperature_units(df, from_unit='K', to_unit='C') |
|
|
|
print(f"Loaded {len(df)} records") |
|
print(f"Date range: {df['time'].min()} to {df['time'].max()}") |
|
print(f"Temperature range: {df['t2m'].min():.1f}°C to {df['t2m'].max():.1f}°C") |
|
print(f"Average temperature: {df['t2m'].mean():.1f}°C") |
|
|
|
|
|
plt.figure(figsize=(12, 6)) |
|
plt.plot(df['time'], df['t2m'], linewidth=0.5, alpha=0.7) |
|
plt.title('Paris Temperature 2023') |
|
plt.xlabel('Date') |
|
plt.ylabel('Temperature (°C)') |
|
plt.grid(True, alpha=0.3) |
|
plt.tight_layout() |
|
plt.savefig('paris_temperature_2023.png', dpi=300, bbox_inches='tight') |
|
plt.show() |
|
|
|
return df |
|
|
|
def example_multiple_cities(): |
|
"""Example: Compare multiple European cities.""" |
|
print("\n" + "=" * 60) |
|
print("EXAMPLE 2: Multiple Cities Comparison") |
|
print("=" * 60) |
|
|
|
|
|
cities = [ |
|
(48.8566, 2.3522, "Paris"), |
|
(51.5074, -0.1278, "London"), |
|
(52.5200, 13.4050, "Berlin"), |
|
(41.9028, 12.4964, "Rome"), |
|
(59.3293, 18.0686, "Stockholm"), |
|
] |
|
|
|
print(f"Loading data for {len(cities)} cities...") |
|
|
|
|
|
df = load_cities_data(cities, start_date="2023-01-01", end_date="2023-12-31") |
|
|
|
|
|
df = convert_temperature_units(df, from_unit='K', to_unit='C') |
|
|
|
print(f"Total records loaded: {len(df)}") |
|
|
|
|
|
df['month'] = df['time'].dt.month |
|
monthly_temps = df.groupby(['city', 'month'])['t2m'].mean().reset_index() |
|
monthly_temps['month_name'] = pd.to_datetime(monthly_temps['month'], format='%m').dt.strftime('%b') |
|
|
|
|
|
plt.figure(figsize=(12, 8)) |
|
|
|
|
|
plt.subplot(2, 1, 1) |
|
for city in df['city'].unique(): |
|
city_data = monthly_temps[monthly_temps['city'] == city] |
|
plt.plot(city_data['month'], city_data['t2m'], marker='o', label=city, linewidth=2) |
|
|
|
plt.title('Monthly Average Temperature Comparison 2023') |
|
plt.xlabel('Month') |
|
plt.ylabel('Temperature (°C)') |
|
plt.legend() |
|
plt.grid(True, alpha=0.3) |
|
plt.xticks(range(1, 13), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', |
|
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) |
|
|
|
|
|
plt.subplot(2, 1, 2) |
|
annual_stats = df.groupby('city')['t2m'].agg(['mean', 'min', 'max']).reset_index() |
|
|
|
x = range(len(annual_stats)) |
|
plt.bar(x, annual_stats['mean'], alpha=0.7, label='Average') |
|
plt.errorbar(x, annual_stats['mean'], |
|
yerr=[annual_stats['mean'] - annual_stats['min'], |
|
annual_stats['max'] - annual_stats['mean']], |
|
fmt='none', color='black', capsize=5, alpha=0.8) |
|
|
|
plt.title('Annual Temperature Statistics 2023') |
|
plt.xlabel('City') |
|
plt.ylabel('Temperature (°C)') |
|
plt.xticks(x, annual_stats['city'], rotation=45) |
|
plt.grid(True, alpha=0.3) |
|
|
|
plt.tight_layout() |
|
plt.savefig('cities_temperature_comparison.png', dpi=300, bbox_inches='tight') |
|
plt.show() |
|
|
|
|
|
print("\nAnnual Temperature Summary (°C):") |
|
print(annual_stats.round(1)) |
|
|
|
return df |
|
|
|
def example_climate_analysis(): |
|
"""Example: Long-term climate analysis.""" |
|
print("\n" + "=" * 60) |
|
print("EXAMPLE 3: Long-term Climate Analysis (Paris)") |
|
print("=" * 60) |
|
|
|
print("Loading historical data for Paris (1980-2023)...") |
|
df = load_point_data( |
|
lat=48.8566, |
|
lon=2.3522, |
|
start_date="1980-01-01", |
|
end_date="2023-12-31" |
|
) |
|
|
|
|
|
df = convert_temperature_units(df, from_unit='K', to_unit='C') |
|
|
|
print(f"Loaded {len(df)} records over {df['time'].dt.year.nunique()} years") |
|
|
|
|
|
df['year'] = df['time'].dt.year |
|
annual_temps = df.groupby('year')['t2m'].mean().reset_index() |
|
|
|
|
|
plt.figure(figsize=(14, 10)) |
|
|
|
|
|
plt.subplot(2, 2, 1) |
|
plt.plot(annual_temps['year'], annual_temps['t2m'], linewidth=1, alpha=0.7) |
|
|
|
|
|
from numpy.polynomial import Polynomial |
|
p = Polynomial.fit(annual_temps['year'], annual_temps['t2m'], 1) |
|
plt.plot(annual_temps['year'], p(annual_temps['year']), 'r--', linewidth=2, label='Trend') |
|
|
|
plt.title('Annual Average Temperature (Paris)') |
|
plt.xlabel('Year') |
|
plt.ylabel('Temperature (°C)') |
|
plt.legend() |
|
plt.grid(True, alpha=0.3) |
|
|
|
|
|
plt.subplot(2, 2, 2) |
|
df['month'] = df['time'].dt.month |
|
monthly_climate = df.groupby('month')['t2m'].agg(['mean', 'std']).reset_index() |
|
|
|
plt.plot(monthly_climate['month'], monthly_climate['mean'], 'b-', linewidth=2, label='Average') |
|
plt.fill_between(monthly_climate['month'], |
|
monthly_climate['mean'] - monthly_climate['std'], |
|
monthly_climate['mean'] + monthly_climate['std'], |
|
alpha=0.3, label='±1 std dev') |
|
|
|
plt.title('Monthly Temperature Climatology') |
|
plt.xlabel('Month') |
|
plt.ylabel('Temperature (°C)') |
|
plt.legend() |
|
plt.grid(True, alpha=0.3) |
|
plt.xticks(range(1, 13), ['J', 'F', 'M', 'A', 'M', 'J', |
|
'J', 'A', 'S', 'O', 'N', 'D']) |
|
|
|
|
|
plt.subplot(2, 2, 3) |
|
plt.hist(df['t2m'], bins=50, alpha=0.7, density=True) |
|
plt.axvline(df['t2m'].mean(), color='red', linestyle='--', linewidth=2, label=f'Mean: {df["t2m"].mean():.1f}°C') |
|
plt.title('Temperature Distribution') |
|
plt.xlabel('Temperature (°C)') |
|
plt.ylabel('Density') |
|
plt.legend() |
|
plt.grid(True, alpha=0.3) |
|
|
|
|
|
plt.subplot(2, 2, 4) |
|
df['decade'] = (df['year'] // 10) * 10 |
|
decade_temps = df.groupby('decade')['t2m'].mean().reset_index() |
|
|
|
plt.bar(decade_temps['decade'], decade_temps['t2m'], width=8, alpha=0.7) |
|
plt.title('Average Temperature by Decade') |
|
plt.xlabel('Decade') |
|
plt.ylabel('Temperature (°C)') |
|
plt.grid(True, alpha=0.3) |
|
|
|
plt.tight_layout() |
|
plt.savefig('paris_climate_analysis.png', dpi=300, bbox_inches='tight') |
|
plt.show() |
|
|
|
|
|
warming_rate = p.coef[1] |
|
total_warming = warming_rate * (annual_temps['year'].max() - annual_temps['year'].min()) |
|
|
|
print(f"\nClimate Analysis Results:") |
|
print(f"Period: {annual_temps['year'].min()}-{annual_temps['year'].max()}") |
|
print(f"Average temperature: {df['t2m'].mean():.1f}°C") |
|
print(f"Warming rate: {warming_rate:.3f}°C/year") |
|
print(f"Total warming: {total_warming:.1f}°C over {annual_temps['year'].max() - annual_temps['year'].min()} years") |
|
|
|
return df |
|
|
|
def main(): |
|
"""Run all examples.""" |
|
print("Weather Geo ERA5 Dataset - Example Usage") |
|
print("=" * 60) |
|
|
|
|
|
info = get_dataset_info() |
|
print("Dataset Information:") |
|
for key, value in info.items(): |
|
print(f" {key}: {value}") |
|
|
|
try: |
|
|
|
df1 = example_single_city() |
|
|
|
|
|
df2 = example_multiple_cities() |
|
|
|
|
|
df3 = example_climate_analysis() |
|
|
|
print("\n" + "=" * 60) |
|
print("All examples completed successfully!") |
|
print("Generated plots:") |
|
print(" - paris_temperature_2023.png") |
|
print(" - cities_temperature_comparison.png") |
|
print(" - paris_climate_analysis.png") |
|
print("=" * 60) |
|
|
|
except Exception as e: |
|
print(f"\nError running examples: {e}") |
|
print("Make sure you have installed the required packages:") |
|
print(" pip install pandas huggingface-hub matplotlib seaborn") |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|