HOT / weather /weather_figure.py
BuildingBench's picture
All TMY and AMY files uploaded
dc44c29 verified
"""
Weather Locations World Map Generator
====================================
This script creates a world map visualization showing weather stations with:
- Different climate zones (color-coded)
- Different data types: Real weather data vs TMY (Typical Meteorological Year)
- Geographic distribution of weather monitoring stations
Data Sources:
- Real weather data: tables/weather_real.csv
- Base TMY data: tables/weather_base.csv
- Expanded TMY data: tables/weather.csv
Author: Generated for weather data visualization
Version: 2.0 (CSV file input version)
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
import warnings
warnings.filterwarnings('ignore')
# Try to use cartopy for better world map, fall back to basic plotting if not available
try:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
CARTOPY_AVAILABLE = True
except ImportError:
CARTOPY_AVAILABLE = False
print("Cartopy not available. Using basic matplotlib plotting.")
def create_location_database():
"""Create a database of approximate coordinates for weather locations"""
locations = {
# UAE
'Dubai.Intl.AP': (25.2532, 55.3657),
'Abu.Dhabi.Intl.AP': (24.4539, 54.6511),
'Dubai.Minhad.Ab': (25.0269, 55.3625),
# USA
'Atlanta-Hartsfield-Jackson Intl AP': (33.6407, -84.4277),
'Aurora-Buckley AFB': (39.7016, -104.7513),
'Fairbanks Intl AP': (64.8378, -147.8562),
'Tampa-MacDill AFB': (27.8492, -82.5203),
'Albuquerque Intl Sunport': (35.0402, -106.6093),
'El Paso Intl AP': (31.8072, -106.3781),
'Seattle-Tacoma Intl AP': (47.4502, -122.3088),
'Miami Intl AP': (25.7959, -80.2870),
'Rochester Intl AP': (43.9056, -92.4924),
'New York-Kennedy Intl AP': (40.6413, -73.7781),
'Great Falls Intl AP': (47.4820, -111.3706),
'International Falls-Falls Intl AP': (48.5663, -93.4030),
'Port Angeles-Fairchild Intl AP': (48.1202, -123.5004),
'Buffalo Niagara Intl AP': (42.9405, -78.7322),
'Tucscon-Davis-Monthan AFB': (32.1665, -110.8837),
'Chula Vista-Brown Muni Field AP': (32.5725, -117.0261),
'Chula Vista-Brown Field Muni AP': (32.639954, -117.1067),
'Salt Lake City Intl AP': (40.7899, -111.9791),
'Boise AP-Gowen Field ANGB': (43.5644, -116.2228),
'Twin Falls-Magic Valley Rgnl AP-Joslin Field': (42.4818, -114.4877),
'Mitchell Muni AP': (43.7058, -98.0428),
'Rapid City Rgnl AP': (44.0453, -103.0645),
'Sioux Falls Rgnl AP-Foss Field': (43.5820, -96.7419),
# Vietnam
'Ho.Chi.Minh-Tan.Son.Nhat.Intl.AP': (10.8188, 106.6519),
# India
'Jaipur': (26.8247, 75.8130),
'New.Delhi-Gandhi.Intl.AP': (28.5562, 77.1000),
'New.Delhi-Safdarjung.Intl.AP': (28.5844, 77.2066),
'Sikar': (27.6094, 75.1399),
# Other countries
'Cotonou-Cadjehoun.AP': (6.3573, 2.3844), # Benin
'Foz.do.Iguacu-Cataratas.Intl.AP': (-25.6008, -54.4858), # Brazil
'Formosa.Intl.AP': (-26.2128, -58.2281), # Argentina
'Albany': (-35.0275, 117.8840), # Australia
'Bridgetown': (-33.9567, 116.1428), # Australia
'Busselton': (-33.6775, 115.4006), # Australia
'Alberni.Valley.Rgnl.AP': (49.3189, -124.9356), # Canada
'Campbell.River.AP': (50.0881, -125.2714), # Canada
'Nanaimo.AP': (49.0522, -123.8700), # Canada
'Ottawa-Macdonald-Cartier.Intl.AP': (45.3192, -75.6692), # Canada
'Montreal-Trudeau.Intl.AP': (45.4706, -73.7408), # Canada
'Trois.Rivieres': (46.3528, -72.5478), # Canada
'Nanjing': (32.0603, 118.7969), # China
'Shanghai-Hongqiao.Intl.AP': (31.1979, 121.3365), # China
'Hangzhou': (30.2741, 120.1551), # China
'Praha-Ruzyne.AP': (50.1008, 14.2632), # Czech Republic
'Dresden.AP': (51.1328, 13.7671), # Germany
'Tanta': (30.7865, 31.0004), # Egypt
'Alexandria-Nozha.Intl.AP': (31.1834, 29.9489), # Egypt
'Cairo.Intl.AP': (30.1219, 31.4056), # Egypt
'Leon.AP': (42.5886, -5.6556), # Spain
'Salamanca.AP': (40.9321, -5.5017), # Spain
'Rovaniemi.AP': (66.5648, 25.8307), # Finland
'Oulu.AP': (65.0324, 25.3540), # Finland
'Suva.Kings.Wharf': (-18.1416, 178.4419), # Fiji
'Labasa.ap': (-16.4667, 179.3397), # Fiji
'Lautoka.Queens.Wharf': (-17.6125, 177.4203), # Fiji
'Aktau': (43.6506, 51.2089), # Kazakhstan
'Kuryk-Eralievo': (43.2056, 51.3711), # Kazakhstan
'Wonju.WS': (37.3422, 127.9502), # South Korea
'Seoul.WS': (37.5665, 126.9780), # South Korea
'Daejeon.WS': (36.3504, 127.3845), # South Korea
'Ulaanbaatar-Chinggis.Khaan.Intl.AP': (47.8430, 106.7665), # Mongolia
'Lagos-Muhammed.Intl.AP': (6.5774, 3.3212), # Nigeria
'Muscat-Sultan.Qaboos.Port': (23.5859, 58.4059), # Oman
'Legnica': (51.2070, 16.1610), # Poland
'Braganca.AP': (41.8581, -6.7075), # Portugal
'Asuncion-Pettirossi.Intl.AP': (-25.2397, -57.5197), # Paraguay
'Ulan-Ude.AP': (51.8081, 107.4375), # Russia
'Chita-Kadala.AP': (52.0263, 113.3056), # Russia
'Lulea.AP': (65.5439, 22.1218), # Sweden
'Lome-Tokoin-Eyadema.Intl.AP': (6.1656, 1.2547), # Togo
'Turkmenbashi': (40.0775, 53.0072), # Turkmenistan
'Douglas': (-29.0414, 23.7519), # South Africa
'Kimberley.AP': (-28.8025, 24.7650), # South Africa
'Postmasburg': (-28.3289, 23.3678), # South Africa
}
return locations
def standardize_dataframe_columns(df):
"""Standardize column names across different datasets"""
# Create a mapping of possible column name variations
column_mapping = {
# Climate zone code variations
'climate zone code': 'climate_zone_code',
'climate_zone_code': 'climate_zone_code',
'Climate Zone Code': 'climate_zone_code',
'climatezonecode': 'climate_zone_code',
# Climate zone description variations
'climate zone description': 'climate_zone_description',
'climate_zone_description': 'climate_zone_description',
'Climate Zone Description': 'climate_zone_description',
'climatzonedescription': 'climate_zone_description',
# Place variations
'place': 'place',
'Place': 'place',
'location': 'place',
'Location': 'place',
# Country variations
'country': 'country',
'Country': 'country',
# ID variations
'id': 'id',
'ID': 'id',
'Id': 'id'
}
# Rename columns based on mapping
df_renamed = df.rename(columns=column_mapping)
return df_renamed
def parse_weather_data():
"""Read weather data from CSV files"""
try:
# Read Real weather data
print("Reading real weather data from tables/weather_real.csv...")
real_df = pd.read_csv('tables/weather_real.csv')
real_df = standardize_dataframe_columns(real_df)
# Read Base TMY data
print("Reading base weather data from tables/weather_base.csv...")
base_df = pd.read_csv('tables/weather_base.csv')
base_df = standardize_dataframe_columns(base_df)
# Read Expanded TMY data
print("Reading expanded weather data from tables/weather.csv...")
expanded_df = pd.read_csv('tables/weather.csv')
expanded_df = standardize_dataframe_columns(expanded_df)
return real_df, base_df, expanded_df
except FileNotFoundError as e:
print(f"Error: Could not find CSV file - {e}")
print("Please ensure the following files exist:")
print("- tables/weather_real.csv")
print("- tables/weather_base.csv")
print("- tables/weather.csv")
raise
except Exception as e:
print(f"Error reading CSV files: {e}")
raise
def get_climate_zone_color(zone_code):
"""Return color for each climate zone"""
colors = {
'0A': '#8B0000', # Extremely Hot Humid - Dark Red
'0B': '#FF4500', # Extremely Hot Dry - Orange Red
'1A': '#DC143C', # Very Hot Humid - Crimson
'1B': '#FF6347', # Very Hot Dry - Tomato
'2A': '#FF69B4', # Hot Humid - Hot Pink
'2B': '#FFB6C1', # Hot Dry - Light Pink
'3A': '#32CD32', # Warm Humid - Lime Green
'3B': '#90EE90', # Warm Dry - Light Green
'3C': '#00CED1', # Warm Marine - Dark Turquoise
'4A': '#4169E1', # Mixed Humid - Royal Blue
'4B': '#87CEEB', # Mixed Dry - Sky Blue
'4C': '#1E90FF', # Mixed Marine - Dodger Blue
'5A': '#9370DB', # Cool Humid - Medium Purple
'5B': '#DDA0DD', # Cool Dry - Plum
'5C': '#6495ED', # Cool Marine - Cornflower Blue
'6A': '#4B0082', # Cold Humid - Indigo
'6B': '#9932CC', # Cold Dry - Dark Orchid
'7': '#000080', # Very Cold - Navy
'8': '#483D8B', # Subarctic/Arctic - Dark Slate Blue
}
return colors.get(zone_code, '#808080') # Default to gray
def create_world_map_with_cartopy(real_df, base_df, expanded_df, location_coords):
"""Create world map using Cartopy"""
fig = plt.figure(figsize=(20, 12))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# Add map features
ax.add_feature(cfeature.COASTLINE, linewidth=0.5)
ax.add_feature(cfeature.BORDERS, linewidth=0.3)
ax.add_feature(cfeature.LAND, color='lightgray', alpha=0.3)
ax.add_feature(cfeature.OCEAN, color='lightblue', alpha=0.3)
ax.set_global()
# Plot locations
plotted_zones = set()
plotted_types = set()
# Helper function to safely plot data
def plot_dataset(df, marker, label, dataset_name):
plotted_count = 0
if df is None or len(df) == 0:
print(f"Warning: {dataset_name} dataset is empty or None")
return plotted_count
if 'place' not in df.columns or 'climate_zone_code' not in df.columns:
print(f"Warning: {dataset_name} dataset missing required columns")
print(f"Available columns: {list(df.columns)}")
return plotted_count
for _, row in df.iterrows():
place = row['place']
if pd.isna(place) or place not in location_coords:
continue
lat, lon = location_coords[place]
climate_zone = row['climate_zone_code']
if pd.isna(climate_zone):
continue
color = get_climate_zone_color(climate_zone)
ax.plot(lon, lat, marker, color=color, markersize=10 if marker == 'o' else 8,
markeredgecolor='black', markeredgewidth=1,
transform=ccrs.PlateCarree(),
label=label if label not in plotted_types else '')
plotted_types.add(label)
plotted_zones.add(climate_zone)
plotted_count += 1
return plotted_count
# Plot each dataset
real_plotted = plot_dataset(real_df, 'o', 'Real Data', 'Real')
base_plotted = plot_dataset(base_df, 's', 'Base TMY', 'Base')
expanded_plotted = plot_dataset(expanded_df, '^', 'Expanded TMY', 'Expanded')
print(f"\nPlotted locations:")
print(f"- Real data: {real_plotted} locations")
print(f"- Base TMY: {base_plotted} locations")
print(f"- Expanded TMY: {expanded_plotted} locations")
print(f"- Total plotted: {real_plotted + base_plotted + expanded_plotted}")
return fig, ax, plotted_zones, real_plotted, base_plotted, expanded_plotted
def create_world_map_basic(real_df, base_df, expanded_df, location_coords):
"""Create world map using basic matplotlib"""
fig, ax = plt.subplots(figsize=(20, 12))
# Simple world map outline (very basic)
ax.set_xlim(-180, 180)
ax.set_ylim(-90, 90)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.grid(True, alpha=0.3)
# Plot locations
plotted_zones = set()
plotted_types = set()
# Helper function to safely plot data
def plot_dataset(df, marker, label, dataset_name):
plotted_count = 0
if df is None or len(df) == 0:
print(f"Warning: {dataset_name} dataset is empty or None")
return plotted_count
if 'place' not in df.columns or 'climate_zone_code' not in df.columns:
print(f"Warning: {dataset_name} dataset missing required columns")
print(f"Available columns: {list(df.columns)}")
return plotted_count
for _, row in df.iterrows():
place = row['place']
if pd.isna(place) or place not in location_coords:
continue
lat, lon = location_coords[place]
climate_zone = row['climate_zone_code']
if pd.isna(climate_zone):
continue
color = get_climate_zone_color(climate_zone)
ax.plot(lon, lat, marker, color=color, markersize=10 if marker == 'o' else 8,
markeredgecolor='black', markeredgewidth=1,
label=label if label not in plotted_types else '')
plotted_types.add(label)
plotted_zones.add(climate_zone)
plotted_count += 1
return plotted_count
# Plot each dataset
real_plotted = plot_dataset(real_df, 'o', 'Real Data', 'Real')
base_plotted = plot_dataset(base_df, 's', 'Base TMY', 'Base')
expanded_plotted = plot_dataset(expanded_df, '^', 'Expanded TMY', 'Expanded')
print(f"\nPlotted locations:")
print(f"- Real data: {real_plotted} locations")
print(f"- Base TMY: {base_plotted} locations")
print(f"- Expanded TMY: {expanded_plotted} locations")
print(f"- Total plotted: {real_plotted + base_plotted + expanded_plotted}")
return fig, ax, plotted_zones, real_plotted, base_plotted, expanded_plotted
def add_legends(fig, ax, plotted_zones):
"""Add legends for climate zones and data types"""
# Create legend for data types (markers)
marker_legend_elements = [
plt.Line2D([0], [0], marker='o', color='gray', linestyle='None',
markersize=10, markeredgecolor='black', label='Real Data'),
plt.Line2D([0], [0], marker='s', color='gray', linestyle='None',
markersize=8, markeredgecolor='black', label='Base TMY'),
plt.Line2D([0], [0], marker='^', color='gray', linestyle='None',
markersize=8, markeredgecolor='black', label='Expanded TMY')
]
# Create legend for climate zones (colors)
zone_descriptions = {
'0A': 'Extremely Hot Humid',
'0B': 'Extremely Hot Dry',
'1A': 'Very Hot Humid',
'1B': 'Very Hot Dry',
'2A': 'Hot Humid',
'2B': 'Hot Dry',
'3A': 'Warm Humid',
'3B': 'Warm Dry',
'3C': 'Warm Marine',
'4A': 'Mixed Humid',
'4B': 'Mixed Dry',
'4C': 'Mixed Marine',
'5A': 'Cool Humid',
'5B': 'Cool Dry',
'5C': 'Cool Marine',
'6A': 'Cold Humid',
'6B': 'Cold Dry',
'7': 'Very Cold',
'8': 'Subarctic/Arctic',
}
color_legend_elements = []
for zone in sorted(plotted_zones):
color = get_climate_zone_color(zone)
description = zone_descriptions.get(zone, zone)
color_legend_elements.append(
plt.Line2D([0], [0], marker='o', color=color, linestyle='None',
markersize=8, label=f'{zone}: {description}')
)
# Position legends
legend1 = ax.legend(handles=marker_legend_elements,
loc='upper left',
bbox_to_anchor=(0.02, 0.98),
title='Data Types',
fontsize=10)
legend2 = ax.legend(handles=color_legend_elements,
loc='upper right',
bbox_to_anchor=(0.98, 0.98),
title='Climate Zones',
fontsize=9,
ncol=2)
ax.add_artist(legend1) # Add the first legend back
plt.setp(legend1.get_title(), fontsize=12, fontweight='bold')
plt.setp(legend2.get_title(), fontsize=12, fontweight='bold')
def main():
"""Main function to create the weather locations world map"""
print("Creating Weather Locations World Map...")
print("=" * 50)
# Get location coordinates
location_coords = create_location_database()
# Parse weather data from CSV files
try:
real_df, base_df, expanded_df = parse_weather_data()
print(f"\nSuccessfully loaded weather data:")
print(f"- Real weather locations: {len(real_df)}")
print(f"- Base TMY locations: {len(base_df)}")
print(f"- Expanded TMY locations: {len(expanded_df)}")
# Display column information for debugging
print(f"\nDataset overview:")
print(f"- Real data: {len(real_df)} locations")
if len(real_df) > 0:
print(f" Columns: {list(real_df.columns)}")
print(f" Sample: {real_df['place'].iloc[0] if 'place' in real_df.columns else 'No place column'}")
print(f"- Base data: {len(base_df)} locations")
if len(base_df) > 0:
print(f" Columns: {list(base_df.columns)}")
print(f" Sample: {base_df['place'].iloc[0] if 'place' in base_df.columns else 'No place column'}")
print(f"- Expanded data: {len(expanded_df)} locations")
if len(expanded_df) > 0:
print(f" Columns: {list(expanded_df.columns)}")
print(f" Sample: {expanded_df['place'].iloc[0] if 'place' in expanded_df.columns else 'No place column'}")
# Check for locations that can be mapped
all_places = set()
if 'place' in real_df.columns:
all_places.update(real_df['place'].unique())
if 'place' in base_df.columns:
all_places.update(base_df['place'].unique())
if 'place' in expanded_df.columns:
all_places.update(expanded_df['place'].unique())
mappable_places = [place for place in all_places if place in location_coords]
unmappable_places = [place for place in all_places if place not in location_coords]
print(f"\nLocation mapping status:")
print(f"- Total unique places in data: {len(all_places)}")
print(f"- Places that can be mapped: {len(mappable_places)}")
print(f"- Places missing coordinates: {len(unmappable_places)}")
if unmappable_places:
print(f"- Unmappable places: {unmappable_places[:10]}{'...' if len(unmappable_places) > 10 else ''}")
except Exception as e:
print(f"Error loading data: {e}")
return
# Create the map
real_plotted = 0
base_plotted = 0
expanded_plotted = 0
if CARTOPY_AVAILABLE:
print("Using Cartopy for world map...")
fig, ax, plotted_zones, real_plotted, base_plotted, expanded_plotted = create_world_map_with_cartopy(real_df, base_df, expanded_df, location_coords)
else:
print("Using basic matplotlib for world map...")
fig, ax, plotted_zones, real_plotted, base_plotted, expanded_plotted = create_world_map_basic(real_df, base_df, expanded_df, location_coords)
# Add legends
add_legends(fig, ax, plotted_zones)
# Add grid and improve layout
ax.grid(True, alpha=0.3, linestyle='--')
# Add text box with information
info_text = """Weather Data Types:
• Circles (○): Real weather data (actual recorded years)
• Squares (□): Base TMY (Typical Meteorological Year)
• Triangles (△): Expanded TMY locations
Climate zones based on international standards.
Colors represent different thermal characteristics."""
ax.text(0.02, 0.02, info_text, transform=ax.transAxes, fontsize=10,
verticalalignment='bottom', horizontalalignment='left',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8),
fontfamily='monospace')
plt.tight_layout()
# Show statistics
total_plotted = real_plotted + base_plotted + expanded_plotted
print(f"\n" + "="*50)
print(f"MAP GENERATION COMPLETE")
print(f"="*50)
print(f"Final Statistics:")
print(f"- Total locations plotted: {total_plotted}")
print(f"- Unique climate zones: {len(plotted_zones)}")
print(f"- Climate zones represented: {', '.join(sorted(plotted_zones))}")
print(f"- Dataset breakdown:")
print(f" • Real weather data: {real_plotted} locations")
print(f" • Base TMY data: {base_plotted} locations")
print(f" • Expanded TMY data: {expanded_plotted} locations")
if total_plotted == 0:
print("\nWARNING: No locations were plotted. This might be due to:")
print("- Missing or incorrect column names in CSV files")
print("- Location names not matching coordinate database")
print("- Empty or corrupted CSV files")
return
# Save the plot
try:
plt.savefig('weather_locations_world_map.png', dpi=300, bbox_inches='tight')
print(f"\n✅ Map saved as 'weather_locations_world_map.png'")
except Exception as e:
print(f"\n❌ Error saving map: {e}")
try:
plt.show()
print("✅ Map displayed successfully")
except Exception as e:
print(f"❌ Error displaying map: {e}")
print("Map file has been saved even if display failed.")
if __name__ == "__main__":
main()