File size: 8,973 Bytes
91899e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
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)
    
    # Load 2023 data for Paris
    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"
    )
    
    # Convert temperatures to Celsius
    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")
    
    # Plot temperature timeline
    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)
    
    # Define cities
    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...")
    
    # Load 2023 data for all cities
    df = load_cities_data(cities, start_date="2023-01-01", end_date="2023-12-31")
    
    # Convert temperatures to Celsius
    df = convert_temperature_units(df, from_unit='K', to_unit='C')
    
    print(f"Total records loaded: {len(df)}")
    
    # Calculate monthly averages
    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')
    
    # Plot comparison
    plt.figure(figsize=(12, 8))
    
    # Temperature comparison
    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'])
    
    # Annual statistics
    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 summary statistics
    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"
    )
    
    # Convert temperatures to Celsius
    df = convert_temperature_units(df, from_unit='K', to_unit='C')
    
    print(f"Loaded {len(df)} records over {df['time'].dt.year.nunique()} years")
    
    # Calculate annual averages
    df['year'] = df['time'].dt.year
    annual_temps = df.groupby('year')['t2m'].mean().reset_index()
    
    # Plot long-term trend
    plt.figure(figsize=(14, 10))
    
    # Annual temperature trend
    plt.subplot(2, 2, 1)
    plt.plot(annual_temps['year'], annual_temps['t2m'], linewidth=1, alpha=0.7)
    
    # Add trend line
    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)
    
    # Monthly climatology
    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'])
    
    # Temperature distribution
    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)
    
    # Decade comparison
    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()
    
    # Calculate warming trend
    warming_rate = p.coef[1]  # Slope of trend line
    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)
    
    # Display dataset info
    info = get_dataset_info()
    print("Dataset Information:")
    for key, value in info.items():
        print(f"  {key}: {value}")
    
    try:
        # Example 1: Single city
        df1 = example_single_city()
        
        # Example 2: Multiple cities
        df2 = example_multiple_cities()
        
        # Example 3: Climate analysis
        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()