NaaVrug commited on
Commit
91899e8
·
1 Parent(s): 7889497

Add Python utilities and usage examples

Browse files
Files changed (2) hide show
  1. examples.py +265 -0
  2. weather_geo_utils.py +380 -0
examples.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Example usage of the Weather Geo ERA5 Dataset
5
+
6
+ This script demonstrates how to use the weather_geo_utils module to load
7
+ and analyze weather data from the HuggingFace dataset.
8
+
9
+ Requirements:
10
+ pip install pandas huggingface-hub matplotlib seaborn
11
+ """
12
+
13
+ import pandas as pd
14
+ import matplotlib.pyplot as plt
15
+ import seaborn as sns
16
+ from weather_geo_utils import (
17
+ load_point_data,
18
+ load_cities_data,
19
+ convert_temperature_units,
20
+ get_dataset_info
21
+ )
22
+
23
+ def example_single_city():
24
+ """Example: Load data for a single city (Paris)."""
25
+ print("=" * 60)
26
+ print("EXAMPLE 1: Single City Analysis (Paris)")
27
+ print("=" * 60)
28
+
29
+ # Load 2023 data for Paris
30
+ print("Loading Paris weather data for 2023...")
31
+ df = load_point_data(
32
+ lat=48.8566,
33
+ lon=2.3522,
34
+ start_date="2023-01-01",
35
+ end_date="2023-12-31"
36
+ )
37
+
38
+ # Convert temperatures to Celsius
39
+ df = convert_temperature_units(df, from_unit='K', to_unit='C')
40
+
41
+ print(f"Loaded {len(df)} records")
42
+ print(f"Date range: {df['time'].min()} to {df['time'].max()}")
43
+ print(f"Temperature range: {df['t2m'].min():.1f}°C to {df['t2m'].max():.1f}°C")
44
+ print(f"Average temperature: {df['t2m'].mean():.1f}°C")
45
+
46
+ # Plot temperature timeline
47
+ plt.figure(figsize=(12, 6))
48
+ plt.plot(df['time'], df['t2m'], linewidth=0.5, alpha=0.7)
49
+ plt.title('Paris Temperature 2023')
50
+ plt.xlabel('Date')
51
+ plt.ylabel('Temperature (°C)')
52
+ plt.grid(True, alpha=0.3)
53
+ plt.tight_layout()
54
+ plt.savefig('paris_temperature_2023.png', dpi=300, bbox_inches='tight')
55
+ plt.show()
56
+
57
+ return df
58
+
59
+ def example_multiple_cities():
60
+ """Example: Compare multiple European cities."""
61
+ print("\n" + "=" * 60)
62
+ print("EXAMPLE 2: Multiple Cities Comparison")
63
+ print("=" * 60)
64
+
65
+ # Define cities
66
+ cities = [
67
+ (48.8566, 2.3522, "Paris"),
68
+ (51.5074, -0.1278, "London"),
69
+ (52.5200, 13.4050, "Berlin"),
70
+ (41.9028, 12.4964, "Rome"),
71
+ (59.3293, 18.0686, "Stockholm"),
72
+ ]
73
+
74
+ print(f"Loading data for {len(cities)} cities...")
75
+
76
+ # Load 2023 data for all cities
77
+ df = load_cities_data(cities, start_date="2023-01-01", end_date="2023-12-31")
78
+
79
+ # Convert temperatures to Celsius
80
+ df = convert_temperature_units(df, from_unit='K', to_unit='C')
81
+
82
+ print(f"Total records loaded: {len(df)}")
83
+
84
+ # Calculate monthly averages
85
+ df['month'] = df['time'].dt.month
86
+ monthly_temps = df.groupby(['city', 'month'])['t2m'].mean().reset_index()
87
+ monthly_temps['month_name'] = pd.to_datetime(monthly_temps['month'], format='%m').dt.strftime('%b')
88
+
89
+ # Plot comparison
90
+ plt.figure(figsize=(12, 8))
91
+
92
+ # Temperature comparison
93
+ plt.subplot(2, 1, 1)
94
+ for city in df['city'].unique():
95
+ city_data = monthly_temps[monthly_temps['city'] == city]
96
+ plt.plot(city_data['month'], city_data['t2m'], marker='o', label=city, linewidth=2)
97
+
98
+ plt.title('Monthly Average Temperature Comparison 2023')
99
+ plt.xlabel('Month')
100
+ plt.ylabel('Temperature (°C)')
101
+ plt.legend()
102
+ plt.grid(True, alpha=0.3)
103
+ plt.xticks(range(1, 13), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
104
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
105
+
106
+ # Annual statistics
107
+ plt.subplot(2, 1, 2)
108
+ annual_stats = df.groupby('city')['t2m'].agg(['mean', 'min', 'max']).reset_index()
109
+
110
+ x = range(len(annual_stats))
111
+ plt.bar(x, annual_stats['mean'], alpha=0.7, label='Average')
112
+ plt.errorbar(x, annual_stats['mean'],
113
+ yerr=[annual_stats['mean'] - annual_stats['min'],
114
+ annual_stats['max'] - annual_stats['mean']],
115
+ fmt='none', color='black', capsize=5, alpha=0.8)
116
+
117
+ plt.title('Annual Temperature Statistics 2023')
118
+ plt.xlabel('City')
119
+ plt.ylabel('Temperature (°C)')
120
+ plt.xticks(x, annual_stats['city'], rotation=45)
121
+ plt.grid(True, alpha=0.3)
122
+
123
+ plt.tight_layout()
124
+ plt.savefig('cities_temperature_comparison.png', dpi=300, bbox_inches='tight')
125
+ plt.show()
126
+
127
+ # Print summary statistics
128
+ print("\nAnnual Temperature Summary (°C):")
129
+ print(annual_stats.round(1))
130
+
131
+ return df
132
+
133
+ def example_climate_analysis():
134
+ """Example: Long-term climate analysis."""
135
+ print("\n" + "=" * 60)
136
+ print("EXAMPLE 3: Long-term Climate Analysis (Paris)")
137
+ print("=" * 60)
138
+
139
+ print("Loading historical data for Paris (1980-2023)...")
140
+ df = load_point_data(
141
+ lat=48.8566,
142
+ lon=2.3522,
143
+ start_date="1980-01-01",
144
+ end_date="2023-12-31"
145
+ )
146
+
147
+ # Convert temperatures to Celsius
148
+ df = convert_temperature_units(df, from_unit='K', to_unit='C')
149
+
150
+ print(f"Loaded {len(df)} records over {df['time'].dt.year.nunique()} years")
151
+
152
+ # Calculate annual averages
153
+ df['year'] = df['time'].dt.year
154
+ annual_temps = df.groupby('year')['t2m'].mean().reset_index()
155
+
156
+ # Plot long-term trend
157
+ plt.figure(figsize=(14, 10))
158
+
159
+ # Annual temperature trend
160
+ plt.subplot(2, 2, 1)
161
+ plt.plot(annual_temps['year'], annual_temps['t2m'], linewidth=1, alpha=0.7)
162
+
163
+ # Add trend line
164
+ from numpy.polynomial import Polynomial
165
+ p = Polynomial.fit(annual_temps['year'], annual_temps['t2m'], 1)
166
+ plt.plot(annual_temps['year'], p(annual_temps['year']), 'r--', linewidth=2, label='Trend')
167
+
168
+ plt.title('Annual Average Temperature (Paris)')
169
+ plt.xlabel('Year')
170
+ plt.ylabel('Temperature (°C)')
171
+ plt.legend()
172
+ plt.grid(True, alpha=0.3)
173
+
174
+ # Monthly climatology
175
+ plt.subplot(2, 2, 2)
176
+ df['month'] = df['time'].dt.month
177
+ monthly_climate = df.groupby('month')['t2m'].agg(['mean', 'std']).reset_index()
178
+
179
+ plt.plot(monthly_climate['month'], monthly_climate['mean'], 'b-', linewidth=2, label='Average')
180
+ plt.fill_between(monthly_climate['month'],
181
+ monthly_climate['mean'] - monthly_climate['std'],
182
+ monthly_climate['mean'] + monthly_climate['std'],
183
+ alpha=0.3, label='±1 std dev')
184
+
185
+ plt.title('Monthly Temperature Climatology')
186
+ plt.xlabel('Month')
187
+ plt.ylabel('Temperature (°C)')
188
+ plt.legend()
189
+ plt.grid(True, alpha=0.3)
190
+ plt.xticks(range(1, 13), ['J', 'F', 'M', 'A', 'M', 'J',
191
+ 'J', 'A', 'S', 'O', 'N', 'D'])
192
+
193
+ # Temperature distribution
194
+ plt.subplot(2, 2, 3)
195
+ plt.hist(df['t2m'], bins=50, alpha=0.7, density=True)
196
+ plt.axvline(df['t2m'].mean(), color='red', linestyle='--', linewidth=2, label=f'Mean: {df["t2m"].mean():.1f}°C')
197
+ plt.title('Temperature Distribution')
198
+ plt.xlabel('Temperature (°C)')
199
+ plt.ylabel('Density')
200
+ plt.legend()
201
+ plt.grid(True, alpha=0.3)
202
+
203
+ # Decade comparison
204
+ plt.subplot(2, 2, 4)
205
+ df['decade'] = (df['year'] // 10) * 10
206
+ decade_temps = df.groupby('decade')['t2m'].mean().reset_index()
207
+
208
+ plt.bar(decade_temps['decade'], decade_temps['t2m'], width=8, alpha=0.7)
209
+ plt.title('Average Temperature by Decade')
210
+ plt.xlabel('Decade')
211
+ plt.ylabel('Temperature (°C)')
212
+ plt.grid(True, alpha=0.3)
213
+
214
+ plt.tight_layout()
215
+ plt.savefig('paris_climate_analysis.png', dpi=300, bbox_inches='tight')
216
+ plt.show()
217
+
218
+ # Calculate warming trend
219
+ warming_rate = p.coef[1] # Slope of trend line
220
+ total_warming = warming_rate * (annual_temps['year'].max() - annual_temps['year'].min())
221
+
222
+ print(f"\nClimate Analysis Results:")
223
+ print(f"Period: {annual_temps['year'].min()}-{annual_temps['year'].max()}")
224
+ print(f"Average temperature: {df['t2m'].mean():.1f}°C")
225
+ print(f"Warming rate: {warming_rate:.3f}°C/year")
226
+ print(f"Total warming: {total_warming:.1f}°C over {annual_temps['year'].max() - annual_temps['year'].min()} years")
227
+
228
+ return df
229
+
230
+ def main():
231
+ """Run all examples."""
232
+ print("Weather Geo ERA5 Dataset - Example Usage")
233
+ print("=" * 60)
234
+
235
+ # Display dataset info
236
+ info = get_dataset_info()
237
+ print("Dataset Information:")
238
+ for key, value in info.items():
239
+ print(f" {key}: {value}")
240
+
241
+ try:
242
+ # Example 1: Single city
243
+ df1 = example_single_city()
244
+
245
+ # Example 2: Multiple cities
246
+ df2 = example_multiple_cities()
247
+
248
+ # Example 3: Climate analysis
249
+ df3 = example_climate_analysis()
250
+
251
+ print("\n" + "=" * 60)
252
+ print("All examples completed successfully!")
253
+ print("Generated plots:")
254
+ print(" - paris_temperature_2023.png")
255
+ print(" - cities_temperature_comparison.png")
256
+ print(" - paris_climate_analysis.png")
257
+ print("=" * 60)
258
+
259
+ except Exception as e:
260
+ print(f"\nError running examples: {e}")
261
+ print("Make sure you have installed the required packages:")
262
+ print(" pip install pandas huggingface-hub matplotlib seaborn")
263
+
264
+ if __name__ == "__main__":
265
+ main()
weather_geo_utils.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Weather Geo ERA5 Dataset Utilities
5
+
6
+ Helper functions for working with the geographically partitioned ERA5 weather dataset.
7
+ This module provides convenient access patterns for the HuggingFace hosted dataset.
8
+
9
+ Dataset: https://huggingface.co/datasets/NaaVrug/weather-geo-era5
10
+ License: CC-BY-4.0
11
+ Attribution: Contains modified Copernicus Climate Change Service information 2024
12
+ """
13
+
14
+ import pandas as pd
15
+ from pathlib import Path
16
+ from typing import List, Tuple, Optional, Union
17
+ from datetime import datetime, date
18
+ import warnings
19
+
20
+ try:
21
+ from huggingface_hub import hf_hub_download
22
+ HF_AVAILABLE = True
23
+ except ImportError:
24
+ HF_AVAILABLE = False
25
+ warnings.warn("huggingface_hub not available. Install with: pip install huggingface-hub")
26
+
27
+ # Dataset configuration
28
+ REPO_ID = "NaaVrug/weather-geo-era5"
29
+ REPO_TYPE = "dataset"
30
+
31
+ # Geographic constants (30° lat × 45° lon tiles)
32
+ LAT_BANDS = [
33
+ ("m90_m60", -90, -60), # Antarctic
34
+ ("m60_m30", -60, -30), # Southern mid-latitudes
35
+ ("m30_p00", -30, 0), # Southern tropics
36
+ ("p00_p30", 0, 30), # Northern tropics
37
+ ("p30_p60", 30, 60), # Northern mid-latitudes
38
+ ("p60_p90", 60, 90), # Arctic
39
+ ]
40
+
41
+ LON_BANDS = [
42
+ ("000_045", 0, 45), # Europe/Africa West
43
+ ("045_090", 45, 90), # Middle East/Central Asia
44
+ ("090_135", 90, 135), # East Asia
45
+ ("135_180", 135, 180), # Western Pacific
46
+ ("180_225", 180, 225), # Central Pacific
47
+ ("225_270", 225, 270), # Eastern Pacific
48
+ ("270_315", 270, 315), # Americas West
49
+ ("315_360", 315, 360), # Americas East/Atlantic
50
+ ]
51
+
52
+ def get_tile_name(lat: float, lon: float) -> str:
53
+ """
54
+ Get the tile filename for given coordinates.
55
+
56
+ Args:
57
+ lat: Latitude in degrees (-90 to 90)
58
+ lon: Longitude in degrees (-180 to 180 or 0 to 360)
59
+
60
+ Returns:
61
+ Tile filename (e.g., "lat_p30_p60__lon_000_045.parquet")
62
+
63
+ Examples:
64
+ >>> get_tile_name(48.8566, 2.3522) # Paris
65
+ 'lat_p30_p60__lon_000_045.parquet'
66
+ >>> get_tile_name(40.7128, -74.0060) # NYC
67
+ 'lat_p30_p60__lon_270_315.parquet'
68
+ >>> get_tile_name(-33.8688, 151.2093) # Sydney
69
+ 'lat_m60_m30__lon_135_180.parquet'
70
+ """
71
+ # Validate inputs
72
+ if not -90 <= lat <= 90:
73
+ raise ValueError(f"Latitude must be between -90 and 90, got {lat}")
74
+
75
+ # Normalize longitude to 0-360 range
76
+ lon = lon % 360
77
+
78
+ # Find latitude band
79
+ lat_band = None
80
+ for band_name, lat_min, lat_max in LAT_BANDS:
81
+ if lat_min <= lat < lat_max or (lat == 90 and lat_max == 90):
82
+ lat_band = band_name
83
+ break
84
+
85
+ if lat_band is None:
86
+ raise ValueError(f"Could not determine latitude band for {lat}")
87
+
88
+ # Find longitude band
89
+ lon_band = None
90
+ for band_name, lon_min, lon_max in LON_BANDS:
91
+ if lon_min <= lon < lon_max or (lon == 360 and lon_max == 360):
92
+ lon_band = band_name
93
+ break
94
+
95
+ if lon_band is None:
96
+ raise ValueError(f"Could not determine longitude band for {lon}")
97
+
98
+ return f"lat_{lat_band}__lon_{lon_band}.parquet"
99
+
100
+ def get_tiles_for_region(lat_min: float, lat_max: float,
101
+ lon_min: float, lon_max: float) -> List[str]:
102
+ """
103
+ Get all tile names that overlap with a rectangular region.
104
+
105
+ Args:
106
+ lat_min, lat_max: Latitude bounds
107
+ lon_min, lon_max: Longitude bounds
108
+
109
+ Returns:
110
+ List of tile filenames
111
+
112
+ Example:
113
+ >>> # Europe region
114
+ >>> tiles = get_tiles_for_region(35, 70, -10, 40)
115
+ >>> print(len(tiles)) # Multiple tiles covering Europe
116
+ """
117
+ # Normalize longitude
118
+ lon_min = lon_min % 360
119
+ lon_max = lon_max % 360
120
+
121
+ tiles = set()
122
+
123
+ # Handle longitude wrap-around
124
+ if lon_min > lon_max:
125
+ # Region crosses 0° longitude
126
+ for lat_band_name, lat_band_min, lat_band_max in LAT_BANDS:
127
+ if not (lat_max < lat_band_min or lat_min >= lat_band_max):
128
+ for lon_band_name, lon_band_min, lon_band_max in LON_BANDS:
129
+ if lon_band_min >= lon_min or lon_band_max <= lon_max:
130
+ tiles.add(f"lat_{lat_band_name}__lon_{lon_band_name}.parquet")
131
+ else:
132
+ # Normal case
133
+ for lat_band_name, lat_band_min, lat_band_max in LAT_BANDS:
134
+ if not (lat_max < lat_band_min or lat_min >= lat_band_max):
135
+ for lon_band_name, lon_band_min, lon_band_max in LON_BANDS:
136
+ if not (lon_max < lon_band_min or lon_min >= lon_band_max):
137
+ tiles.add(f"lat_{lat_band_name}__lon_{lon_band_name}.parquet")
138
+
139
+ return sorted(list(tiles))
140
+
141
+ def load_point_data(lat: float, lon: float,
142
+ start_date: Optional[Union[str, date, datetime]] = None,
143
+ end_date: Optional[Union[str, date, datetime]] = None,
144
+ cache_dir: Optional[str] = None) -> pd.DataFrame:
145
+ """
146
+ Load weather data for a specific point.
147
+
148
+ Args:
149
+ lat: Latitude in degrees
150
+ lon: Longitude in degrees
151
+ start_date: Start date (YYYY-MM-DD or datetime object)
152
+ end_date: End date (YYYY-MM-DD or datetime object)
153
+ cache_dir: Local cache directory for downloaded files
154
+
155
+ Returns:
156
+ DataFrame with weather data for the point
157
+
158
+ Example:
159
+ >>> # Load 2020 data for Paris
160
+ >>> df = load_point_data(48.8566, 2.3522, "2020-01-01", "2020-12-31")
161
+ >>> print(f"Loaded {len(df)} records")
162
+ """
163
+ if not HF_AVAILABLE:
164
+ raise ImportError("huggingface_hub required. Install with: pip install huggingface-hub")
165
+
166
+ # Get tile name
167
+ tile_name = get_tile_name(lat, lon)
168
+
169
+ # Download tile
170
+ file_path = hf_hub_download(
171
+ repo_id=REPO_ID,
172
+ filename=f"tiles/{tile_name}",
173
+ repo_type=REPO_TYPE,
174
+ cache_dir=cache_dir
175
+ )
176
+
177
+ # Load data
178
+ df = pd.read_parquet(file_path)
179
+
180
+ # Filter for approximate coordinates (within 0.25° grid)
181
+ lat_tolerance = 0.125 # Half grid resolution
182
+ lon_tolerance = 0.125
183
+
184
+ df = df[
185
+ (df['latitude'].between(lat - lat_tolerance, lat + lat_tolerance)) &
186
+ (df['longitude'].between(lon - lon_tolerance, lon + lon_tolerance))
187
+ ]
188
+
189
+ # Filter by date range if specified
190
+ if start_date is not None:
191
+ df = df[df['time'] >= pd.to_datetime(start_date)]
192
+ if end_date is not None:
193
+ df = df[df['time'] <= pd.to_datetime(end_date)]
194
+
195
+ return df.sort_values('time').reset_index(drop=True)
196
+
197
+ def load_region_data(lat_min: float, lat_max: float,
198
+ lon_min: float, lon_max: float,
199
+ start_date: Optional[Union[str, date, datetime]] = None,
200
+ end_date: Optional[Union[str, date, datetime]] = None,
201
+ cache_dir: Optional[str] = None) -> pd.DataFrame:
202
+ """
203
+ Load weather data for a rectangular region.
204
+
205
+ Args:
206
+ lat_min, lat_max: Latitude bounds
207
+ lon_min, lon_max: Longitude bounds
208
+ start_date: Start date filter
209
+ end_date: End date filter
210
+ cache_dir: Local cache directory
211
+
212
+ Returns:
213
+ Combined DataFrame for the region
214
+
215
+ Example:
216
+ >>> # Load data for a region around Paris
217
+ >>> df = load_region_data(48, 49, 2, 3, "2023-01-01", "2023-12-31")
218
+ """
219
+ if not HF_AVAILABLE:
220
+ raise ImportError("huggingface_hub required. Install with: pip install huggingface-hub")
221
+
222
+ # Get all tiles covering the region
223
+ tiles = get_tiles_for_region(lat_min, lat_max, lon_min, lon_max)
224
+
225
+ if not tiles:
226
+ raise ValueError(f"No tiles found for region: lat[{lat_min}, {lat_max}], lon[{lon_min}, {lon_max}]")
227
+
228
+ print(f"Loading {len(tiles)} tiles for region...")
229
+
230
+ dfs = []
231
+ for tile_name in tiles:
232
+ print(f" Loading {tile_name}...")
233
+
234
+ # Download tile
235
+ file_path = hf_hub_download(
236
+ repo_id=REPO_ID,
237
+ filename=f"tiles/{tile_name}",
238
+ repo_type=REPO_TYPE,
239
+ cache_dir=cache_dir
240
+ )
241
+
242
+ # Load and filter data
243
+ df = pd.read_parquet(file_path)
244
+
245
+ # Filter by geographic bounds
246
+ df = df[
247
+ (df['latitude'].between(lat_min, lat_max)) &
248
+ (df['longitude'].between(lon_min, lon_max))
249
+ ]
250
+
251
+ # Filter by date range if specified
252
+ if start_date is not None:
253
+ df = df[df['time'] >= pd.to_datetime(start_date)]
254
+ if end_date is not None:
255
+ df = df[df['time'] <= pd.to_datetime(end_date)]
256
+
257
+ if len(df) > 0:
258
+ dfs.append(df)
259
+
260
+ if not dfs:
261
+ raise ValueError("No data found in the specified region and time range")
262
+
263
+ # Combine all data
264
+ result = pd.concat(dfs, ignore_index=True)
265
+ return result.sort_values(['time', 'latitude', 'longitude']).reset_index(drop=True)
266
+
267
+ def load_cities_data(cities: List[Tuple[float, float, str]],
268
+ start_date: Optional[Union[str, date, datetime]] = None,
269
+ end_date: Optional[Union[str, date, datetime]] = None,
270
+ cache_dir: Optional[str] = None) -> pd.DataFrame:
271
+ """
272
+ Load weather data for multiple cities.
273
+
274
+ Args:
275
+ cities: List of (lat, lon, name) tuples
276
+ start_date: Start date filter
277
+ end_date: End date filter
278
+ cache_dir: Local cache directory
279
+
280
+ Returns:
281
+ DataFrame with data for all cities, including 'city' column
282
+
283
+ Example:
284
+ >>> cities = [
285
+ ... (48.8566, 2.3522, "Paris"),
286
+ ... (51.5074, -0.1278, "London"),
287
+ ... (52.5200, 13.4050, "Berlin"),
288
+ ... ]
289
+ >>> df = load_cities_data(cities, "2023-01-01", "2023-12-31")
290
+ """
291
+ if not HF_AVAILABLE:
292
+ raise ImportError("huggingface_hub required. Install with: pip install huggingface-hub")
293
+
294
+ dfs = []
295
+ for lat, lon, city_name in cities:
296
+ print(f"Loading data for {city_name}...")
297
+
298
+ try:
299
+ df = load_point_data(lat, lon, start_date, end_date, cache_dir)
300
+ df['city'] = city_name
301
+ dfs.append(df)
302
+ except Exception as e:
303
+ print(f" Warning: Failed to load data for {city_name}: {e}")
304
+
305
+ if not dfs:
306
+ raise ValueError("No data loaded for any cities")
307
+
308
+ return pd.concat(dfs, ignore_index=True)
309
+
310
+ def convert_temperature_units(df: pd.DataFrame,
311
+ from_unit: str = 'K',
312
+ to_unit: str = 'C') -> pd.DataFrame:
313
+ """
314
+ Convert temperature units in the dataset.
315
+
316
+ Args:
317
+ df: DataFrame with temperature columns
318
+ from_unit: Source unit ('K', 'C', 'F')
319
+ to_unit: Target unit ('K', 'C', 'F')
320
+
321
+ Returns:
322
+ DataFrame with converted temperatures
323
+ """
324
+ df = df.copy()
325
+ temp_columns = ['t2m', 'd2m']
326
+
327
+ for col in temp_columns:
328
+ if col in df.columns:
329
+ # Convert to Kelvin first
330
+ if from_unit == 'C':
331
+ temps_k = df[col] + 273.15
332
+ elif from_unit == 'F':
333
+ temps_k = (df[col] - 32) * 5/9 + 273.15
334
+ else: # Assume Kelvin
335
+ temps_k = df[col]
336
+
337
+ # Convert from Kelvin to target
338
+ if to_unit == 'C':
339
+ df[col] = temps_k - 273.15
340
+ elif to_unit == 'F':
341
+ df[col] = (temps_k - 273.15) * 9/5 + 32
342
+ else: # Keep Kelvin
343
+ df[col] = temps_k
344
+
345
+ return df
346
+
347
+ def get_dataset_info() -> dict:
348
+ """Get information about the dataset."""
349
+ return {
350
+ "name": "Weather Geo ERA5 Dataset",
351
+ "repo_id": REPO_ID,
352
+ "url": f"https://huggingface.co/datasets/{REPO_ID}",
353
+ "license": "CC-BY-4.0",
354
+ "time_range": "1940-2024",
355
+ "resolution": "0.25° x 0.25°",
356
+ "total_tiles": len(LAT_BANDS) * len(LON_BANDS),
357
+ "variables": ["t2m", "tp", "d2m", "msl", "u10", "v10"],
358
+ "attribution": "Contains modified Copernicus Climate Change Service information 2024"
359
+ }
360
+
361
+ # Example usage
362
+ if __name__ == "__main__":
363
+ # Print dataset info
364
+ info = get_dataset_info()
365
+ print("Weather Geo ERA5 Dataset")
366
+ print("=" * 40)
367
+ for key, value in info.items():
368
+ print(f"{key}: {value}")
369
+
370
+ print("\nExample tile names:")
371
+ cities = [
372
+ (48.8566, 2.3522, "Paris"),
373
+ (40.7128, -74.0060, "New York"),
374
+ (-33.8688, 151.2093, "Sydney"),
375
+ (35.6762, 139.6503, "Tokyo"),
376
+ ]
377
+
378
+ for lat, lon, name in cities:
379
+ tile = get_tile_name(lat, lon)
380
+ print(f" {name} ({lat:.4f}, {lon:.4f}): {tile}")