Spaces:
Runtime error
Runtime error
Upload forecast.py
Browse filesForecast data upload
- forecast.py +125 -0
forecast.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import xarray as xr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Mapping of variable names to metadata (title, unit, and NetCDF variable key)
|
| 7 |
+
VARIABLE_MAPPING = {
|
| 8 |
+
'surface_downwelling_shortwave_radiation': ('Surface Downwelling Shortwave Radiation', 'W/m²', 'rsds'),
|
| 9 |
+
'moisture_in_upper_portion_of_soil_column': ('Moisture in Upper Portion of Soil Column', 'kg m-2', 'mrsos'),
|
| 10 |
+
'precipitation': ('Precipitation', 'kg m-2 s-1', 'pr'),
|
| 11 |
+
'near_surface_relative_humidity': ('Relative Humidity', '%', 'hurs'),
|
| 12 |
+
'evaporation_including_sublimation_and_transpiration': ('Evaporation (including sublimation and transpiration)', 'kg m-2 s-1', 'evspsbl'),
|
| 13 |
+
'total_runoff': ('Total Runoff', 'kg m-2 s-1', 'mrro'),
|
| 14 |
+
'daily_minimum_near_surface_air_temperature': ('Daily Minimum Near Surface Air Temperature', '°C', 'tasmin'),
|
| 15 |
+
'daily_maximum_near_surface_air_temperature': ('Daily Maximum Near Surface Air Temperature', '°C', 'tasmax'),
|
| 16 |
+
'near_surface_wind_speed': ('Near Surface Wind Speed', 'm/s', 'sfcWind'),
|
| 17 |
+
'near_surface_air_temperature': ('Near Surface Air Temperature', '°C', 'tas'),
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_data(variable: str, ds: xr.Dataset, lat: float, lon: float) -> xr.DataArray:
|
| 22 |
+
"""
|
| 23 |
+
Load data for a given variable from the dataset at the nearest latitude and longitude.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
variable (str): The variable to extract from the dataset.
|
| 27 |
+
ds (xr.Dataset): The xarray dataset containing climate data.
|
| 28 |
+
lat (float): Latitude for nearest data point.
|
| 29 |
+
lon (float): Longitude for nearest data point.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
xr.DataArray: The data array containing the variable values for the specified location.
|
| 33 |
+
"""
|
| 34 |
+
try:
|
| 35 |
+
data = ds[variable].sel(lat=lat, lon=lon, method="nearest")
|
| 36 |
+
|
| 37 |
+
# Convert temperature from Kelvin to Celsius for specific variables
|
| 38 |
+
if variable in ["tas", "tasmin", "tasmax"]:
|
| 39 |
+
data = data - 273.15
|
| 40 |
+
|
| 41 |
+
return data
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Error loading {variable}: {e}")
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_forecast_datasets(climate_sub_files: list) -> dict:
|
| 48 |
+
"""
|
| 49 |
+
Get the forecast datasets by loading NetCDF files for each variable.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
climate_sub_files (list): List of file paths to the NetCDF files.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
dict: Dictionary with variable names as keys and xarray datasets as values.
|
| 56 |
+
"""
|
| 57 |
+
datasets = {}
|
| 58 |
+
|
| 59 |
+
# Iterate over each file and check if the variable exists in the filename
|
| 60 |
+
for file_path in climate_sub_files:
|
| 61 |
+
filename = os.path.basename(file_path)
|
| 62 |
+
|
| 63 |
+
for long_name, (title, unit, var_key) in VARIABLE_MAPPING.items():
|
| 64 |
+
if var_key in filename: # Check for presence of variable in filename
|
| 65 |
+
if var_key in ["tas", "tasmax", "tasmin"]:
|
| 66 |
+
if f"_{var_key}_" in f"_{filename}_" or filename.endswith(f"_{var_key}.nc"):
|
| 67 |
+
datasets[long_name] = xr.open_dataset(file_path, engine="netcdf4")
|
| 68 |
+
else:
|
| 69 |
+
datasets[long_name] = xr.open_dataset(file_path, engine="netcdf4")
|
| 70 |
+
|
| 71 |
+
return datasets
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_forecast_data(datasets: dict, lat: float, lon: float) -> pd.DataFrame:
|
| 75 |
+
"""
|
| 76 |
+
Extract climate data from the forecast datasets for a given location and convert to a DataFrame.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
datasets (dict): Dictionary of datasets, one for each variable.
|
| 80 |
+
lat (float): Latitude of the location to extract data for.
|
| 81 |
+
lon (float): Longitude of the location to extract data for.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
pd.DataFrame: A DataFrame containing time series data for each variable.
|
| 85 |
+
"""
|
| 86 |
+
time_series_data = {'time': []}
|
| 87 |
+
|
| 88 |
+
# Iterate over the variable mapping to load and process data for each variable
|
| 89 |
+
for long_name, (title, unit, variable) in VARIABLE_MAPPING.items():
|
| 90 |
+
print(f"Processing {long_name} ({title}, {unit}, {variable})...")
|
| 91 |
+
|
| 92 |
+
# Load the data for the current variable
|
| 93 |
+
data = load_data(variable, datasets[long_name], lat, lon)
|
| 94 |
+
|
| 95 |
+
if data is not None:
|
| 96 |
+
print(f"Time values: {data.time.values[:5]}") # Preview first few time values
|
| 97 |
+
print(f"Data values: {data.values[:5]}") # Preview first few data values
|
| 98 |
+
|
| 99 |
+
# Add the time values to the 'time' list
|
| 100 |
+
time_series_data['time'] = data.time.values
|
| 101 |
+
|
| 102 |
+
# Format the column name with unit (e.g., "Precipitation (kg m-2 s-1)")
|
| 103 |
+
column_name = f"{title} ({unit})"
|
| 104 |
+
time_series_data[column_name] = data.values
|
| 105 |
+
|
| 106 |
+
# Convert the time series data into a pandas DataFrame
|
| 107 |
+
return pd.DataFrame(time_series_data)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Define the directory to parse
|
| 111 |
+
folder_to_parse = "climate_data_pessimist/"
|
| 112 |
+
|
| 113 |
+
# Retrieve the subfolders and files to parse
|
| 114 |
+
climate_sub_folder = [os.path.join(folder_to_parse, e) for e in os.listdir(folder_to_parse) if os.path.isdir(os.path.join(folder_to_parse, e))]
|
| 115 |
+
climate_sub_files = [os.path.join(e, i) for e in climate_sub_folder for i in os.listdir(e) if i.endswith('.nc')]
|
| 116 |
+
|
| 117 |
+
# Load the forecast datasets
|
| 118 |
+
datasets = get_forecast_datasets(climate_sub_files)
|
| 119 |
+
|
| 120 |
+
# Get the forecast data for a specific latitude and longitude
|
| 121 |
+
lat, lon = 47.0, 5.0 # Example coordinates
|
| 122 |
+
final_df = get_forecast_data(datasets, lat, lon)
|
| 123 |
+
|
| 124 |
+
# Display the resulting DataFrame
|
| 125 |
+
print(final_df.head())
|