Skip to content

Commit

Permalink
Renamed HotDays to TX30 Across All Functions
Browse files Browse the repository at this point in the history
  • Loading branch information
DahyannAraya committed Sep 24, 2024
1 parent 153bfcb commit a902d03
Show file tree
Hide file tree
Showing 3 changed files with 467 additions and 465 deletions.
4 changes: 2 additions & 2 deletions climada_petals/hazard/copernicus_forecast/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def __init__(self, data_dir='.', URL = None, KEY = None):
"explanation": "Tropical Nights: This indicator counts the number of nights where the minimum temperature remains above a certain threshold, typically 20°C.",

Check warning on line 112 in climada_petals/hazard/copernicus_forecast/handler.py

View check run for this annotation

Jenkins - WCR / Pylint

line-too-long

LOW: Line too long (174/100)
Raw output
Used when a line is longer than a given number of characters.
"input_data": ["2m temperature (t2m)"]
},
"HotDays": {
"TX30": {
"explanation": "Hot Days: This indicator counts the number of days where the maximum temperature exceeds 30°C.",

Check warning on line 116 in climada_petals/hazard/copernicus_forecast/handler.py

View check run for this annotation

Jenkins - WCR / Pylint

line-too-long

LOW: Line too long (128/100)
Raw output
Used when a line is longer than a given number of characters.
"input_data": ["2m temperature (t2m)"]
}
Expand Down Expand Up @@ -356,7 +356,7 @@ def process_and_save_hazards(self, year_list, month_list, data_out, tf_index):
hazard_type = tf_index
intensity_variable = f"{tf_index}"

if tf_index in ["TR", "HotDays", "HW"]:
if tf_index in ["TR", "TX30", "HW"]:
intensity_unit = "days"
else:
intensity_unit = "°C"
Expand Down
60 changes: 26 additions & 34 deletions climada_petals/hazard/copernicus_forecast/indicator.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# indicator.py

Check warning on line 1 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

missing-module-docstring

LOW: Missing module docstring
Raw output
no description found

import xarray as xr
import numpy as np
import xarray as xr # Called in the .ipynb
#import numpy as np
import pandas as pd
import logging

Check warning on line 6 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

wrong-import-order

LOW: standard import "import logging" should be placed before "import xarray as xr"
Raw output
Used when PEP8 import order is not respected (standard imports first, thenthird-party libraries, then local imports)
import os

Check warning on line 7 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

wrong-import-order

LOW: standard import "import os" should be placed before "import xarray as xr"
Raw output
Used when PEP8 import order is not respected (standard imports first, thenthird-party libraries, then local imports)
from climada.util.coordinates import country_to_iso, get_country_geometries
from climada.util.coordinates import country_to_iso, get_country_geometries # Called in the .ipynb
import calendar

Check warning on line 9 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

unused-import

NORMAL: Unused import calendar
Raw output
Used when an imported module or variable is not used.

Check warning on line 9 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

wrong-import-order

LOW: standard import "import calendar" should be placed before "import xarray as xr"
Raw output
Used when PEP8 import order is not respected (standard imports first, thenthird-party libraries, then local imports)


Expand Down Expand Up @@ -76,7 +76,7 @@ def get_index_params(index):
"filename_lead": "2m_temps",
"index_long_name": "Tropical_Nights",
},
"HotDays": {
"TX30": {
"variables": [var_specs["2m_temperature"]["full_name"]],
"filename_lead": "2m_temps",
"index_long_name": "Hot Days (Tmax > 30°C)",
Expand Down Expand Up @@ -430,15 +430,15 @@ def calculate_and_save_tropical_nights_per_lag(base_path, year_list, month_list,
print(f"An error occurred: {e}")


def calculate_and_save_hot_days_per_lag(base_path, year_list, month_list, tf_index, area_selection):
def calculate_and_save_tx30_per_lag(base_path, year_list, month_list, tf_index, area_selection):

Check warning on line 433 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

too-many-locals

LOW: Too many local variables (38/15)
Raw output
Used when a function or method has too many local variables.
"""
Calculates and saves the Hot Days index (Tmax > 30°C).
Calculates and saves the TX30 index (Tmax > 30°C).
Parameters:
base_path (str): Base directory path for input and output data.
year_list (list of int): Years for which to calculate the index.
month_list (list of int): Months for which to calculate the index (1-12).
tf_index (str): The climate index being processed ('HotDays').
tf_index (str): The climate index being processed ('TX30').
area_selection (str): Area specification.
"""
index_params = get_index_params(tf_index)
Expand All @@ -454,45 +454,37 @@ def calculate_and_save_hot_days_per_lag(base_path, year_list, month_list, tf_ind
output_file_path = os.path.join(output_dir, f"{tf_index}_{year}{month_str}.nc")

Check warning on line 455 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

trailing-whitespace

LOW: Trailing whitespace
Raw output
Used when there is whitespace between the end of a line and the newline.
try:
# Load the dataset
ds = xr.open_dataset(grib_file_path, engine="cfgrib")

Check warning on line 457 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

invalid-name

LOW: Variable name "ds" doesn't conform to '(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$' pattern
Raw output
Used when the name doesn't match the regular expression associated to its type(constant, variable, class...).
t2m_celsius = ds["t2m"] - 273.15 # Convert temperature from Kelvin to Celsius

# Resample to get daily max temperatures
t2m_celsius = ds["t2m"] - 273.15
daily_max_temp = t2m_celsius.resample(step="1D").max()

# Align forecast steps with calendar months using "valid_time"
valid_times = pd.to_datetime(ds.valid_time.values)
forecast_months = valid_times.to_period("M")
forecast_months_str = forecast_months.astype(str)
step_to_month = dict(zip(ds.step.values, forecast_months_str))
forecast_month_da = xr.DataArray(list(step_to_month.values()), coords=[ds.step], dims=["step"])

Check warning on line 464 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

line-too-long

LOW: Line too long (111/100)
Raw output
Used when a line is longer than a given number of characters.

# Assign the "forecast_month" to the daily_max_temp DataArray
daily_max_temp.coords["forecast_month"] = forecast_month_da

# Calculate Hot Days: Days where Tmax > 30°C
hot_days = daily_max_temp > 30 # Boolean array where True means a Hot Day

# Count the number of Hot Days per forecast month
hot_days_count = hot_days.groupby("forecast_month").sum(dim="step")
hot_days_count = hot_days_count.rename(tf_index)
# Calculate TX30: Days where Tmax > 30°C
tx30_days = daily_max_temp > 30 # Boolean array where True means a TX30 day

Check warning on line 469 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

trailing-whitespace

LOW: Trailing whitespace
Raw output
Used when there is whitespace between the end of a line and the newline.
# Save the result to NetCDF
hot_days_count = hot_days_count.rename({"forecast_month": "step"})
hot_days_count.to_netcdf(output_file_path)
print(f"Hot Days saved to {output_file_path}")
# Count the number of TX30 days per forecast month
tx30_days_count = tx30_days.groupby("forecast_month").sum(dim="step")
tx30_days_count = tx30_days_count.rename(tf_index)

tx30_days_count = tx30_days_count.rename({"forecast_month": "step"})
tx30_days_count.to_netcdf(output_file_path)
print(f"TX30 saved to {output_file_path}")

# Calculate ensemble statistics (mean, median, etc.)
ensemble_mean = hot_days_count.mean(dim="number")
ensemble_median = hot_days_count.median(dim="number")
ensemble_max = hot_days_count.max(dim="number")
ensemble_min = hot_days_count.min(dim="number")
ensemble_std = hot_days_count.std(dim="number")
ensemble_mean = tx30_days_count.mean(dim="number")
ensemble_median = tx30_days_count.median(dim="number")
ensemble_max = tx30_days_count.max(dim="number")
ensemble_min = tx30_days_count.min(dim="number")
ensemble_std = tx30_days_count.std(dim="number")

Check warning on line 484 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

trailing-whitespace

LOW: Trailing whitespace
Raw output
Used when there is whitespace between the end of a line and the newline.
# Percentiles
percentile_levels = [0.05, 0.25, 0.5, 0.75, 0.95]
ensemble_percentiles = hot_days_count.quantile(percentile_levels, dim="number")
ensemble_percentiles = tx30_days_count.quantile(percentile_levels, dim="number")

Check warning on line 488 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

trailing-whitespace

LOW: Trailing whitespace
Raw output
Used when there is whitespace between the end of a line and the newline.
# Store statistics in a dataset
ds_stats = xr.Dataset({
Expand All @@ -512,7 +504,7 @@ def calculate_and_save_hot_days_per_lag(base_path, year_list, month_list, tf_ind
os.makedirs(stats_output_dir, exist_ok=True)
stats_file = os.path.join(stats_output_dir, f"{tf_index}_{year}{month_str}_statistics.nc")

Check warning on line 505 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

line-too-long

LOW: Line too long (106/100)
Raw output
Used when a line is longer than a given number of characters.
ds_stats.to_netcdf(stats_file)
print(f"Hot Days statistics saved to {stats_file}")
print(f"TX30 statistics saved to {stats_file}")

Check warning on line 508 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

trailing-whitespace

LOW: Trailing whitespace
Raw output
Used when there is whitespace between the end of a line and the newline.
except FileNotFoundError as e:

Check warning on line 509 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

invalid-name

LOW: Variable name "e" doesn't conform to '(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$' pattern
Raw output
Used when the name doesn't match the regular expression associated to its type(constant, variable, class...).
print(f"File not found: {e.filename}")
Expand Down Expand Up @@ -542,9 +534,9 @@ def calculate_index(data_out, year_list, month_list, area_selection, overwrite,
# Handle Tropical Nights (TR)
calculate_and_save_tropical_nights_per_lag(data_out, year_list, month_list, tf_index, area_selection)

Check warning on line 535 in climada_petals/hazard/copernicus_forecast/indicator.py

View check run for this annotation

Jenkins - WCR / Pylint

line-too-long

LOW: Line too long (109/100)
Raw output
Used when a line is longer than a given number of characters.

elif tf_index == "HotDays":
elif tf_index == "TX30":
# Handle Hot Days (Tmax > 30°C)
calculate_and_save_hot_days_per_lag(data_out, year_list, month_list, tf_index, area_selection)
calculate_and_save_tx30_per_lag(data_out, year_list, month_list, tf_index, area_selection)

elif tf_index == "HW":
# Handle Heat Wave Days (3 consecutive days Tmax > threshold)
Expand Down
Loading

0 comments on commit a902d03

Please sign in to comment.