| Title: | Download and Process ERA5, IMD, HadEX3 and CRU TS Climate Data |
|---|---|
| Description: | Download and process climate data for custom geographical regions defined by bounding boxes, 'GeoJSON' polygons, or point coordinates. Supports the fifth generation European Centre for Medium-Range Weather Forecasts atmospheric reanalysis ('ERA5'; Hersbach et al. (2020) <doi:10.1002/qj.3803>) from the 'Copernicus' Climate Data Store (CDS) <https://cds.climate.copernicus.eu/>, India Meteorological Department (IMD) gridded rainfall and temperature (Pai et al. (2014) <doi:10.54302/mausam.v65i1.851>), Hadley Centre global land climate extremes indices version 3 ('HadEX3'; Dunn et al. (2020) <doi:10.1029/2019JD032263>), and Climatic Research Unit gridded Time Series ('CRU TS'; Harris et al. (2020) <doi:10.1038/s41597-020-0453-3>). Also computes heat stress indices including heat index, wet-bulb temperature, outdoor wet-bulb globe temperature (Liljegren et al. (2008) <doi:10.1080/15459620802310770>) and the Universal Thermal Climate Index (Bröde et al. (2012) <doi:10.1007/s00484-011-0454-1>), and heat exposure indicators for health studies: heatwave and warm-night frequency and duration under India Meteorological Department and percentile definitions, the Excess Heat Factor (Nairn and Fawcett (2015) <doi:10.3390/ijerph120100227>) and diurnal temperature range. |
| Authors: | Saket Choudhary [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-5202-7633>), Darakhshan Nehal [aut] |
| Maintainer: | Saket Choudhary <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.0 |
| Built: | 2026-10-12 23:13:06 UTC |
| Source: | https://github.com/saketlab/varunayanR |
Aggregate data by temporal frequency
aggregate_by_frequency(data, frequency, verbose = FALSE)aggregate_by_frequency(data, frequency, verbose = FALSE)
data |
data.frame with datetime column |
frequency |
Character string: "daily", "monthly", "yearly" |
verbose |
Logical indicating whether to print progress messages |
data.frame with temporally aggregated data
Aggregate IMD data by temporal frequency
aggregate_imd_by_frequency(data, frequency = "daily")aggregate_imd_by_frequency(data, frequency = "daily")
data |
data.frame with IMD data |
frequency |
Character string: "daily", "monthly", "yearly" |
A data.frame with columns date (first day of each month or year), latitude, longitude and the value column, summed for rainfall and averaged for temperature. Returned unchanged when frequency = "daily".
imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) aggregate_imd_by_frequency(imd, "monthly")imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) aggregate_imd_by_frequency(imd, "monthly")
Aggregate gridded data to polygon regions
aggregate_to_polygons( data, polygons, value_col, method = c("nearest_centroid", "point_in_polygon"), polygon_id_cols = NULL, agg_fun = mean )aggregate_to_polygons( data, polygons, value_col, method = c("nearest_centroid", "point_in_polygon"), polygon_id_cols = NULL, agg_fun = mean )
data |
Data frame with longitude, latitude, and value columns |
polygons |
sf object with polygon geometries |
value_col |
Name of the column containing values to aggregate |
method |
Aggregation method: "point_in_polygon" or "nearest_centroid" |
polygon_id_cols |
Character vector of column names to use as polygon identifiers |
agg_fun |
Aggregation function (default: mean) |
A tibble with one row per polygon: the polygon_id_cols columns and value, the mean of value_col over the grid points assigned to that polygon.
grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) aggregate_to_polygons(grid, polys, value_col = "temperature")grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) aggregate_to_polygons(grid, polys, value_col = "temperature")
Get cache statistics
cache_stats()cache_stats()
A list with elements exists (logical), n_files and total_size_mb.
cache_stats()cache_stats()
Calculate all heat stress indices from temperature and dewpoint.
calc_heat_indices(temp_c, dewpoint_c)calc_heat_indices(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
Data frame with columns: temp_c, dewpoint_c, rh, wet_bulb, heat_index, wbgt, humidex
calc_heat_indices(35, 25) calc_heat_indices(c(30, 35, 40), c(20, 25, 28))calc_heat_indices(35, 25) calc_heat_indices(c(30, 35, 40), c(20, 25, 28))
Categorize variables by aggregation method
categorize_variables(var_names)categorize_variables(var_names)
var_names |
Character vector of variable names |
Named list with variables categorized by aggregation method
categorize_variables(c("2m_temperature", "total_precipitation"))categorize_variables(c("2m_temperature", "total_precipitation"))
Check grid coverage statistics for polygons
check_grid_coverage(grid_data, polygons, polygon_id_cols = NULL)check_grid_coverage(grid_data, polygons, polygon_id_cols = NULL)
grid_data |
Data frame with longitude and latitude columns |
polygons |
sf object with polygon geometries |
polygon_id_cols |
Column names to identify polygons |
A list with elements total_polygons, total_grid_points, polygons_with_points, polygons_without_points, coverage_percent, points_per_polygon (a data.frame of polygon identifiers and n_points) and summary (a one-line character description).
grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) check_grid_coverage(grid, polys)grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) check_grid_coverage(grid, polys)
Check system readiness for varunayan operations
CheckSystemReadiness(...) check_system_readiness(verbose = TRUE)CheckSystemReadiness(...) check_system_readiness(verbose = TRUE)
... |
Arguments passed to the main function (used by aliases). |
verbose |
Whether to print detailed information |
Invisibly, TRUE if all required packages, network access and CDS credentials are available, FALSE otherwise.
check_system_readiness()check_system_readiness()
Clean up temporary files matching pattern
cleanup_temp_files(pattern = "varunayan_.*", directory = tempdir())cleanup_temp_files(pattern = "varunayan_.*", directory = tempdir())
pattern |
Regular expression pattern to match files |
directory |
Directory to search (default: tempdir()) |
Number of files removed
Clear all timing data
clear_timings()clear_timings()
NULL, invisibly. Called for its side effect.
clear_timings()clear_timings()
Clear cache
ClearCache(...) clear_cache(source = NULL, older_than = NULL, confirm = TRUE)ClearCache(...) clear_cache(source = NULL, older_than = NULL, confirm = TRUE)
... |
Arguments passed to the main function (used by aliases). |
source |
Clear only "era5", "imd", "cru_ts", "hadex3", or NULL for all |
older_than |
Remove files older than this many days (NULL = all) |
confirm |
Ask for confirmation (default: TRUE) |
Invisibly, the number of files deleted.
# Remove cached ERA5 files older than 30 days clear_cache(source = "era5", older_than = 30)# Remove cached ERA5 files older than 30 days clear_cache(source = "era5", older_than = 30)
Combine multiple NetCDF files into single data.frame
combine_netcdf_files(netcdf_files, verbose = FALSE)combine_netcdf_files(netcdf_files, verbose = FALSE)
netcdf_files |
Character vector of NetCDF file paths |
verbose |
Logical indicating whether to print progress messages |
data.frame with combined data from all files
Compare multiple grids
compare_grids( ..., polygons = NULL, colors = NULL, shapes = NULL, point_size = 1, polygon_color = "#2C3E50", title = "Grid Comparison" )compare_grids( ..., polygons = NULL, colors = NULL, shapes = NULL, point_size = 1, polygon_color = "#2C3E50", title = "Grid Comparison" )
... |
Named data frames with longitude and latitude columns |
polygons |
Optional sf object to show polygon boundaries |
colors |
Named vector of colors for each grid |
shapes |
Named vector of point shapes for each grid |
point_size |
Size of grid points |
polygon_color |
Color for polygon boundaries |
title |
Plot title |
ggplot object
grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) coarse <- grid[grid$longitude < 75, ] compare_grids(fine = grid, coarse = coarse, polygons = polys)grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) coarse <- grid[grid$longitude < 75, ] compare_grids(fine = grid, coarse = coarse, polygons = polys)
Convert data to GeoJSON format
convert_to_geojson(data)convert_to_geojson(data)
data |
Data to convert (must be data.frame with lon/lat columns) |
GeoJSON formatted data
Create GeoJSON from bounding box coordinates
create_geojson_from_bbox(north, south, east, west)create_geojson_from_bbox(north, south, east, west)
north |
Northern latitude |
south |
Southern latitude |
east |
Eastern longitude |
west |
Western longitude |
GeoJSON object representing the bounding box
Create temporary GeoJSON file
create_temp_geojson_file(geojson_data, request_id)create_temp_geojson_file(geojson_data, request_id)
geojson_data |
GeoJSON data to write |
request_id |
Request identifier for unique filename |
Path to temporary GeoJSON file
Chunk size defaults to compute_optimal_chunk_size(frequency), which
scales with the CDS field limit (hourly: 24 fields/day, daily: 1/day,
monthly: 12/year) so each chunk fills one CDS job.
create_temporal_chunks( start_date, end_date, frequency, n_variables = 1L, max_days_per_chunk = NA )create_temporal_chunks( start_date, end_date, frequency, n_variables = 1L, max_days_per_chunk = NA )
start_date |
Start date |
end_date |
End date |
frequency |
Temporal frequency ("hourly", "daily", "monthly") |
n_variables |
Number of variables in the request (fields = vars x steps) |
max_days_per_chunk |
Maximum days per chunk. NA (default) -> derive from
frequency via |
List of date pairs for chunked processing
Functions to download and process the University of East Anglia Climatic Research Unit Time-Series (CRU TS) gridded monthly climate dataset. Covers global land areas (excl. Antarctica) at 0.5 degree resolution, 1901-2022.
.CRU_TS_VERSION.CRU_TS_VERSION
Harris et al. (2020) Version 4 of the CRU TS monthly high-resolution gridded multivariate climate dataset. Sci. Data 7:109. doi:10.1038/s41597-020-0453-3
Downloads and filters CRU TS v4.07 monthly gridded climate data to a geographic bounding box. Data covers global land areas at 0.5 degree resolution, 1901-2022.
CRUTSBbox(...) cru_ts_bbox( variable, start_year, end_year, north, south, east, west, output_dir = tempdir(), use_cache = TRUE, ... )CRUTSBbox(...) cru_ts_bbox( variable, start_year, end_year, north, south, east, west, output_dir = tempdir(), use_cache = TRUE, ... )
... |
Arguments passed to the main function (used by aliases). |
variable |
CRU TS variable code. See |
start_year |
Start year (1901-2022). |
end_year |
End year (1901-2022). |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
output_dir |
Directory for temporary files (default: |
use_cache |
Whether to use cached data (default: TRUE). |
data.frame with columns: year, month, latitude, longitude, value, variable.
# Monthly mean temperature for India 2010-2020 data <- cru_ts_bbox( variable = "tmp", start_year = 2010, end_year = 2020, north = 35, south = 8, east = 97, west = 68 ) # Precipitation for Europe 1981-2010 data <- cru_ts_bbox( variable = "pre", start_year = 1981, end_year = 2010, north = 71, south = 36, east = 40, west = -10 )# Monthly mean temperature for India 2010-2020 data <- cru_ts_bbox( variable = "tmp", start_year = 2010, end_year = 2020, north = 35, south = 8, east = 97, west = 68 ) # Precipitation for Europe 1981-2010 data <- cru_ts_bbox( variable = "pre", start_year = 1981, end_year = 2010, north = 71, south = 36, east = 40, west = -10 )
Downloads and filters CRU TS v4.07 monthly gridded climate data to a geographic region defined by a GeoJSON polygon.
CRUTSGeojson(...) cru_ts_geojson( variable, start_year, end_year, geojson_file, output_dir = tempdir(), use_cache = TRUE, ... )CRUTSGeojson(...) cru_ts_geojson( variable, start_year, end_year, geojson_file, output_dir = tempdir(), use_cache = TRUE, ... )
... |
Arguments passed to the main function (used by aliases). |
variable |
CRU TS variable code. See |
start_year |
Start year (1901-2022). |
end_year |
End year (1901-2022). |
geojson_file |
Path to a GeoJSON file defining the region. |
output_dir |
Directory for temporary files (default: |
use_cache |
Whether to use cached data (default: TRUE). |
data.frame with columns: year, month, latitude, longitude, value, variable.
region <- system.file("extdata", "region.geojson", package = "varunayan") data <- cru_ts_geojson( variable = "tmp", start_year = 1981, end_year = 2010, geojson_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") data <- cru_ts_geojson( variable = "tmp", start_year = 1981, end_year = 2010, geojson_file = region )
Describe ERA5 variables in detail
DescribeVariables(...) describe_variables(variables, dataset_type = "all")DescribeVariables(...) describe_variables(variables, dataset_type = "all")
... |
Arguments passed to the main function (used by aliases). |
variables |
Character vector of variable names to describe |
dataset_type |
Character string indicating dataset type ("single", "pressure", or "all") |
A data.frame with columns variable_name, description, units, dataset_type and category, one row per matched variable.
# Describe specific variables descriptions <- describe_variables(c("2m_temperature", "total_precipitation")) # Get descriptions for pressure level variables pressure_desc <- describe_variables("temperature", dataset_type = "pressure")# Describe specific variables descriptions <- describe_variables(c("2m_temperature", "total_precipitation")) # Get descriptions for pressure level variables pressure_desc <- describe_variables("temperature", dataset_type = "pressure")
Download ERA5 pressure-level data using ecmwfr
download_era5_pressure( variables, pressure_levels, start_date, end_date, area = NULL, resolution = 0.25, frequency = "hourly", output_file, use_cache = TRUE, verbose = FALSE )download_era5_pressure( variables, pressure_levels, start_date, end_date, area = NULL, resolution = 0.25, frequency = "hourly", output_file, use_cache = TRUE, verbose = FALSE )
variables |
Character vector of variable names |
pressure_levels |
Character vector of pressure levels (e.g., c("1000", "850", "500")) |
start_date |
Date object or character string (YYYY-MM-DD) |
end_date |
Date object or character string (YYYY-MM-DD) |
area |
Numeric vector of 4 elements: c(north, west, south, east) in decimal degrees |
resolution |
Numeric value for grid resolution (default: 0.25 degrees) |
frequency |
Character string: "hourly", "daily", "monthly" |
output_file |
Character string path for output NetCDF file |
use_cache |
Use cached data if available (default: TRUE) |
verbose |
Logical indicating whether to print progress messages |
Character string path to downloaded file
Download ERA5 single-level data using ecmwfr
download_era5_single( variables, start_date, end_date, area = NULL, resolution = 0.25, frequency = "hourly", output_file, timeout = 3600, retry_attempts = 5, use_cache = TRUE, verbose = FALSE )download_era5_single( variables, start_date, end_date, area = NULL, resolution = 0.25, frequency = "hourly", output_file, timeout = 3600, retry_attempts = 5, use_cache = TRUE, verbose = FALSE )
variables |
Character vector of variable names |
start_date |
Date object or character string (YYYY-MM-DD) |
end_date |
Date object or character string (YYYY-MM-DD) |
area |
Numeric vector of 4 elements: c(north, west, south, east) in decimal degrees |
resolution |
Numeric value for grid resolution (default: 0.25 degrees) |
frequency |
Character string: "hourly", "daily", "monthly" |
output_file |
Character string path for output NetCDF file |
timeout |
Numeric value for request timeout in seconds (default: 3600) |
retry_attempts |
Integer number of retry attempts (default: 5) |
use_cache |
Use cached data if available (default: TRUE) |
verbose |
Logical indicating whether to print progress messages |
Character string path to downloaded file
Downloads daily gridded rainfall data from IMD at specified resolution.
download_imd_rainfall( start_year, end_year, resolution = 0.25, output_dir = tempdir(), use_cache = TRUE )download_imd_rainfall( start_year, end_year, resolution = 0.25, output_dir = tempdir(), use_cache = TRUE )
start_year |
Start year. |
end_year |
End year. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees. |
output_dir |
Directory to save downloaded files. |
use_cache |
Whether to use cached data if available (default: TRUE). |
Character vector of downloaded file paths
# Download 0.25 degree rainfall for 2023-2025 files <- download_imd_rainfall( start_year = 2023, end_year = 2025, resolution = 0.25 )# Download 0.25 degree rainfall for 2023-2025 files <- download_imd_rainfall( start_year = 2023, end_year = 2025, resolution = 0.25 )
Downloads daily gridded temperature data (max or min) from IMD. Temperature data is at 1.0 degree resolution only.
download_imd_temperature( start_year, end_year, var_type = "tmax", output_dir = tempdir(), use_cache = TRUE )download_imd_temperature( start_year, end_year, var_type = "tmax", output_dir = tempdir(), use_cache = TRUE )
start_year |
Start year. |
end_year |
End year. |
var_type |
Type of temperature: "tmax" or "tmin". |
output_dir |
Directory to save downloaded files. |
use_cache |
Whether to use cached data if available (default: TRUE). |
Character vector of downloaded file paths
# Download max temperature for 2023-2025 files <- download_imd_temperature( start_year = 2023, end_year = 2025, var_type = "tmax" )# Download max temperature for 2023-2025 files <- download_imd_temperature( start_year = 2023, end_year = 2025, var_type = "tmax" )
Create output directory if it doesn't exist
ensure_output_dir(output_dir)ensure_output_dir(output_dir)
output_dir |
Path to output directory |
Character string path to created/existing directory
Download and process ERA5 data for a bounding box
ERA5ifyBbox(...) era5ify_bbox( request_id, variables, start_date, end_date, north, south, east, west, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", resolution = 0.25, save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE )ERA5ifyBbox(...) era5ify_bbox( request_id, variables, start_date, end_date, north, south, east, west, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", resolution = 0.25, save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the data request. |
variables |
List of ERA5 variables to download. |
start_date |
Start date in "YYYY-MM-DD" format. |
end_date |
End date in "YYYY-MM-DD" format. |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
dataset_type |
Type of dataset ("single" or "pressure"). |
pressure_levels |
Pressure levels for pressure dataset. |
frequency |
Temporal frequency ("hourly", "daily", "monthly"). |
resolution |
Spatial resolution in degrees (default: 0.25). |
save_raw |
Whether to save raw downloaded files. |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
convert_units |
Whether to convert units to user-friendly formats (default: TRUE). When TRUE, temperature variables are returned in Celsius (converted from Kelvin) and precipitation variables are returned in mm (converted from meters). |
verbose |
Whether to print detailed progress messages. |
data.frame with processed climate data. When convert_units = TRUE:
Temperature variables (e.g., 2m_temperature): Celsius
Precipitation variables (e.g., total_precipitation): mm
Other variables: original ERA5 units
setup_cds_credentials(key = "your-cds-api-key") data <- era5ify_bbox( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", north = 40, south = 35, east = -70, west = -75 ) # Temperature is in Celsius, precipitation is in mmsetup_cds_credentials(key = "your-cds-api-key") data <- era5ify_bbox( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", north = 40, south = 35, east = -70, west = -75 ) # Temperature is in Celsius, precipitation is in mm
Download and process ERA5 data for a point location
ERA5ifyPoint(...) era5ify_point( request_id, variables, start_date, end_date, lat, lon, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE, use_timeseries_api = NA )ERA5ifyPoint(...) era5ify_point( request_id, variables, start_date, end_date, lat, lon, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE, use_timeseries_api = NA )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the data request. |
variables |
List of ERA5 variables to download. |
start_date |
Start date in "YYYY-MM-DD" format. |
end_date |
End date in "YYYY-MM-DD" format. |
lat |
Latitude of the point location. |
lon |
Longitude of the point location. |
dataset_type |
Type of dataset ("single" or "pressure"). |
pressure_levels |
Pressure levels for pressure dataset. |
frequency |
Temporal frequency ("hourly", "daily", "monthly"). |
save_raw |
Whether to save raw downloaded files. |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
convert_units |
Whether to convert units to user-friendly formats (default: TRUE). When TRUE, temperature variables are returned in Celsius (converted from Kelvin) and precipitation variables are returned in mm (converted from meters). |
verbose |
Whether to print detailed progress messages. |
use_timeseries_api |
Whether to use the CDS time-series endpoint, which serves a point directly and is much faster than subsetting a gridded download (default: NA, meaning use it for hourly single-level requests, the only ones it supports). Set FALSE to force the gridded download. The gridded download is used automatically if the endpoint is unavailable. |
data.frame with processed climate data. When convert_units = TRUE:
Temperature variables (e.g., 2m_temperature): Celsius
Precipitation variables (e.g., total_precipitation): mm
Other variables: original ERA5 units
setup_cds_credentials(key = "your-cds-api-key") data <- era5ify_point( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", lat = 40.7128, lon = -74.0060 ) # Temperature is in Celsius, precipitation is in mmsetup_cds_credentials(key = "your-cds-api-key") data <- era5ify_point( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", lat = 40.7128, lon = -74.0060 ) # Temperature is in Celsius, precipitation is in mm
Excess Heat Factor (EHF) of Nairn & Fawcett (2015). Daily mean temperature
(DMT) pairs each day's maximum with the following night's minimum,
T_i = (tmax_i + tmin_(i+1)) / 2. For the three-day period starting on day
i, EHI_sig = mean(T_i, T_i+1, T_i+2) - T95 and EHI_accl = mean(T_i, T_i+1, T_i+2) - mean(T_i-1, ..., T_i-30), with T95 the 95th percentile of
DMT over the baseline years; EHF = EHI_sig * max(1, EHI_accl). Positive EHF
marks heatwave conditions; EHF85, the 85th percentile of positive baseline
EHF values, is the severe threshold and 3 * EHF85 the extreme threshold.
excess_heat_factor(date, tmax, tmin, baseline)excess_heat_factor(date, tmax, tmin, baseline)
date |
Dates of a strictly increasing daily series for one location.
Missing days leave the windows that span them |
tmax, tmin
|
Daily maximum and minimum temperature (degrees Celsius). |
baseline |
Climatology years, |
A data.frame with date, dmt, ehi_sig, ehi_accl and ehf
(degrees Celsius squared), indexed by the first day of each three-day
period, with attributes t95 and ehf85. NA where the windows are
incomplete.
Nairn, J.R. & Fawcett, R.J.B. (2015). The Excess Heat Factor: A Metric for Heatwave Intensity and Its Use in Classifying Heatwave Severity. International Journal of Environmental Research and Public Health, 12(1), 227-253. doi:10.3390/ijerph120100227
d <- seq(as.Date("2001-01-01"), as.Date("2003-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2003-05-10") & d <= as.Date("2003-05-16")] <- 47 ehf <- excess_heat_factor(d, tmax, tmax - 12, baseline = c(2001, 2002)) subset(ehf, ehf > 0 & date > as.Date("2003-05-01") & date < as.Date("2003-05-31"))d <- seq(as.Date("2001-01-01"), as.Date("2003-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2003-05-10") & d <= as.Date("2003-05-16")] <- 47 ehf <- excess_heat_factor(d, tmax, tmax - 12, baseline = c(2001, 2002)) subset(ehf, ehf > 0 & date > as.Date("2003-05-01") & date < as.Date("2003-05-31"))
These are coordinate and metadata columns that should not be aggregated.
exclude_colsexclude_cols
A character vector of variable names.
head(exclude_cols)head(exclude_cols)
Summarizes daily temperature (and optionally humidity) into heat exposure indicators per location and year or month, as used in heat-health vulnerability indices: heatwave and warm-night frequency and duration, diurnal temperature range, WBGT, heat index and wet-bulb temperature, plus the ETCCDI indices TX90p, TN90p, WSDI and tropical nights.
exposure_indicators( data, by = c("latitude", "longitude"), period = c("year", "month"), months = NULL, baseline = c(1991, 2020), heatwave_method = c("imd", "percentile", "ehf"), warm_night_method = c("imd", "percentile", "absolute"), terrain = c("auto", "plains", "coastal", "hilly"), hill_elevation = 1200, cell_size = NULL )exposure_indicators( data, by = c("latitude", "longitude"), period = c("year", "month"), months = NULL, baseline = c(1991, 2020), heatwave_method = c("imd", "percentile", "ehf"), warm_night_method = c("imd", "percentile", "absolute"), terrain = c("auto", "plains", "coastal", "hilly"), hill_elevation = 1200, cell_size = NULL )
data |
A data.frame of daily values; see Details. |
by |
Columns identifying a location, or |
period |
Summarize by |
months |
Months (1-12) to include, e.g. |
baseline |
Climatology years, |
heatwave_method |
Passed to |
warm_night_method |
Passed to |
terrain |
Passed to |
hill_elevation, cell_size
|
Passed to |
data needs columns date, tmax and tmin (degrees Celsius), one row
per day per location, covering the baseline years. With a dewpoint
column (degrees Celsius), afternoon humidity metrics are computed from
tmax and dewpoint: WBGT by wbgt_simple(), heat index and wet-bulb
temperature. A wbgt column, such as daily maxima of wbgt_liljegren(),
replaces the wbgt_simple() estimate.
Spells are found on the full series, so a heatwave spanning two periods
counts as an event in the period where it starts and its days count where
they fall. months filters the summary.
A data.frame with one row per location and period and columns:
days with data
mean daily maximum and minimum temperature
mean diurnal temperature range (ETCCDI DTR)
days with Tmax of at least 40 C
nights with Tmin above 20 C (ETCCDI TR)
percent of days above the calendar-day 90th percentile of Tmax and Tmin
days in runs of at least 6 days with Tmax above its 90th percentile (ETCCDI WSDI)
heatwave
duration (total days), frequency (events starting in the period), longest event and
severe days, from heatwave_days()
the same
for warm_nights()
With humidity: wbgt_mean, wbgt_max, wbgt_days_high (WBGT of at
least 29.4 C, 85 F) and wbgt_days_extreme (at least 31.1 C, 88 F),
heat_index_max, heat_index_days_danger (at least 39.4 C, 103 F),
wet_bulb_max and wet_bulb_days_31 (wet bulb of at least 31 C, near the
30.55 C mean critical limit of Vecellio et al. 2022).
Vecellio, D.J., Wolf, S.T., Cottle, R.M. & Kenney, W.L. (2022). Evaluating the 35 C wet-bulb temperature adaptability threshold for young, healthy subjects (PSU HEAT Project). Journal of Applied Physiology, 132(2), 340-345. doi:10.1152/japplphysiol.00738.2021
imd_exposure_bbox() to download IMD data and compute these in one
call; ndvi() and ndbi() for the land-surface indicators.
d <- seq(as.Date("2001-01-01"), as.Date("2004-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2004-05-10") & d <= as.Date("2004-05-14")] <- 46.5 daily <- data.frame(date = d, tmax = tmax, tmin = tmax - 13, dewpoint = 18) exposure_indicators(daily, by = NULL, baseline = c(2001, 2003), terrain = "plains") # Jaipur: terrain looked up from the coordinates daily$latitude <- 26.9 daily$longitude <- 75.8 exposure_indicators(daily, baseline = c(2001, 2003))d <- seq(as.Date("2001-01-01"), as.Date("2004-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2004-05-10") & d <= as.Date("2004-05-14")] <- 46.5 daily <- data.frame(date = d, tmax = tmax, tmin = tmax - 13, dewpoint = 18) exposure_indicators(daily, by = NULL, baseline = c(2001, 2003), terrain = "plains") # Jaipur: terrain looked up from the coordinates daily$latitude <- 26.9 daily$longitude <- 75.8 exposure_indicators(daily, baseline = c(2001, 2003))
Extract data for specific point location (nearest neighbor)
extract_point_data(netcdf_file, target_lat, target_lon)extract_point_data(netcdf_file, target_lat, target_lon)
netcdf_file |
Character string path to NetCDF file |
target_lat |
Target latitude |
target_lon |
Target longitude |
data.frame with data for nearest point
Tests only unique (lat, lon) coordinates against the polygon, then joins back to full dataset via data.table keyed semi-join.
filter_dataframe_by_geojson(df, geojson_file)filter_dataframe_by_geojson(df, geojson_file)
df |
data.frame with latitude and longitude columns |
geojson_file |
Character string path to GeoJSON file |
data.frame with spatially filtered data
Filter IMD data by spatial boundaries
filter_imd_by_bbox(data, north, south, east, west)filter_imd_by_bbox(data, north, south, east, west)
data |
data.frame with IMD data |
north |
Northern latitude boundary |
south |
Southern latitude boundary |
east |
Eastern longitude boundary |
west |
Western longitude boundary |
The input data.frame restricted to rows whose latitude/longitude fall inside the region; columns are unchanged.
imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) filter_imd_by_bbox(imd, north = 22, south = 18, east = 76, west = 72)imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) filter_imd_by_bbox(imd, north = 22, south = 18, east = 76, west = 72)
Filter IMD data by GeoJSON polygon
filter_imd_by_geojson(data, geojson_file)filter_imd_by_geojson(data, geojson_file)
data |
data.frame with IMD data |
geojson_file |
Path to GeoJSON file |
The input data.frame restricted to rows whose latitude/longitude fall inside the region; columns are unchanged.
imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) region <- system.file("extdata", "region.geojson", package = "varunayan") filter_imd_by_geojson(imd, region)imd <- data.frame( date = rep(as.Date("2023-01-01") + 0:59, each = 2), latitude = 20.5, longitude = c(73.5, 79.5), rainfall = 1 ) region <- system.file("extdata", "region.geojson", package = "varunayan") filter_imd_by_geojson(imd, region)
Filter NetCDF data by spatial boundaries (bounding box)
filter_netcdf_by_bbox(netcdf_file, north, south, east, west)filter_netcdf_by_bbox(netcdf_file, north, south, east, west)
netcdf_file |
Character string path to NetCDF file |
north |
Northern latitude boundary |
south |
Southern latitude boundary |
east |
Eastern longitude boundary |
west |
Western longitude boundary |
data.frame with spatially filtered data
Filter NetCDF data by GeoJSON polygon
filter_netcdf_by_geojson(netcdf_file, geojson_file)filter_netcdf_by_geojson(netcdf_file, geojson_file)
netcdf_file |
Character string path to NetCDF file |
geojson_file |
Character string path to GeoJSON file |
data.frame with spatially filtered data
Format date range for CDS API requests
format_date_range(start_date, end_date)format_date_range(start_date, end_date)
start_date |
Start date (Date object) |
end_date |
End date (Date object) |
Character vector of date strings in YYYY-MM-DD format
Convert pressure levels to character format required by CDS API
format_pressure_levels(pressure_levels)format_pressure_levels(pressure_levels)
pressure_levels |
Numeric or character vector of pressure levels |
Character vector of pressure levels
Get available dataset types
get_available_datasets()get_available_datasets()
Character vector of available dataset types
get_available_datasets()get_available_datasets()
Get bounding box from sf object
get_bbox_from_sf(sf_obj)get_bbox_from_sf(sf_obj)
sf_obj |
sf object |
Named numeric vector with xmin, ymin, xmax, ymax
Checks the CDS_API_KEY environment variable, then the 'ecmwfr' keyring,
then ~/.cdsapirc. A key found in the environment variable or in
~/.cdsapirc is registered with 'ecmwfr' via ecmwfr::wf_set_key().
get_cds_credentials(silent = FALSE)get_cds_credentials(silent = FALSE)
silent |
Suppress informational messages |
TRUE if credentials are available, FALSE otherwise.
get_cds_credentials()get_cds_credentials()
Returns grid specifications for different IMD datasets.
get_imd_grid_specs(dataset)get_imd_grid_specs(dataset)
dataset |
Dataset identifier: "rainfall_0.25", "rainfall_1.0", "tmax_1.0", "tmin_1.0". |
A list with elements nlat, nlon, lat_start, lat_end, lon_start, lon_end, resolution (degrees), unit, missing_value, format and description.
specs <- get_imd_grid_specs("rainfall_0.25")specs <- get_imd_grid_specs("rainfall_0.25")
Get all valid pressure-level variable names
get_pressure_level_variable_names()get_pressure_level_variable_names()
Character vector of valid pressure-level variable names
Get pressure-level variables dataset
get_pressure_level_variables()get_pressure_level_variables()
List containing pressure-level variable categories
Get all valid single-level variable names
get_single_level_variable_names()get_single_level_variable_names()
Character vector of valid single-level variable names
Get single-level variables dataset
get_single_level_variables()get_single_level_variables()
List containing single-level variable categories
Get time values based on frequency
get_time_values(frequency)get_time_values(frequency)
frequency |
Character string indicating temporal frequency |
Character vector of time strings
Get all recorded timings
get_timings()get_timings()
A data.frame with columns label, elapsed_seconds, timestamp and duration (formatted), one row per timed operation; zero rows if nothing has been timed.
get_timings()get_timings()
Get standard pressure levels available in ERA5
GetAvailablePressureLevels(...) get_available_pressure_levels()GetAvailablePressureLevels(...) get_available_pressure_levels()
... |
Arguments passed to the main function (used by aliases). |
Character vector of pressure levels in hPa
get_available_pressure_levels()get_available_pressure_levels()
Defaults to tools::R_user_dir("varunayan", "cache"). Set the option
varunayan.cache_dir to use a different directory.
GetCacheDir(...) get_cache_dir(create = TRUE)GetCacheDir(...) get_cache_dir(create = TRUE)
... |
Arguments passed to the main function (used by aliases). |
create |
Create directory if it doesn't exist (default: TRUE) |
Character string with cache directory path
get_cache_dir(create = FALSE)get_cache_dir(create = FALSE)
Download and aggregate ERA5 temperature data for a country.
Resolves the country boundary, downloads monthly data via
era5ify_geojson(), and returns area-weighted (cosine-latitude) country-level
averages by year and month.
GetERA5CountryTemperature(...) get_era5_country_temperature( country, start_date, end_date, variables = "mean", request_id = NULL, resolution = 0.25, verbose = FALSE, ... )GetERA5CountryTemperature(...) get_era5_country_temperature( country, start_date, end_date, variables = "mean", request_id = NULL, resolution = 0.25, verbose = FALSE, ... )
... |
Additional arguments passed to |
country |
One of: a country name string (resolved via
|
start_date |
Start date in |
end_date |
End date in |
variables |
Character vector of temperature shorthand names or ERA5
variable names. Shorthands: |
request_id |
Optional request identifier. Auto-generated from the country name if not provided. |
resolution |
Spatial resolution in degrees (default: 0.25). |
verbose |
Whether to print detailed progress messages. |
A data.frame with columns year, month, and one column per
requested variable (e.g., temperature_mean, temperature_max,
temperature_min). Temperature values are in Celsius.
# Monthly mean temperature for India get_era5_country_temperature("India", "2023-06-01", "2023-06-30") # Mean and max temperature for USA get_era5_country_temperature("USA", "2023-01-01", "2023-12-31", variables = c("mean", "max") ) # Using an sf object directly library(sf) poly <- st_read("my_country.geojson") get_era5_country_temperature(poly, "2023-01-01", "2023-06-30")# Monthly mean temperature for India get_era5_country_temperature("India", "2023-06-01", "2023-06-30") # Mean and max temperature for USA get_era5_country_temperature("USA", "2023-01-01", "2023-12-31", variables = c("mean", "max") ) # Using an sf object directly library(sf) poly <- st_read("my_country.geojson") get_era5_country_temperature(poly, "2023-01-01", "2023-06-30")
Download ERA5 climate variables (temperature, humidity, wet bulb, wind, solar radiation) for a region.
GetERA5DailyClimate( request_id, start_date, end_date, variables = c("temperature", "humidity"), json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_climate( request_id, start_date, end_date, variables = c("temperature", "humidity"), json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyClimate( request_id, start_date, end_date, variables = c("temperature", "humidity"), json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_climate( request_id, start_date, end_date, variables = c("temperature", "humidity"), json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
variables |
Character vector of variables to download. Options: "temperature", "humidity", "wet_bulb", "wind", "solar" |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with date, latitude, longitude, and requested variables
region <- system.file("extdata", "region.geojson", package = "varunayan") # Get temperature and humidity climate <- GetERA5DailyClimate( request_id = "india_climate", start_date = "2023-05-01", end_date = "2023-05-31", variables = c("temperature", "humidity"), json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") # Get temperature and humidity climate <- GetERA5DailyClimate( request_id = "india_climate", start_date = "2023-05-01", end_date = "2023-05-31", variables = c("temperature", "humidity"), json_file = region )
Download ERA5 temperature, dewpoint, and wind data for a region and calculate heat stress indices.
GetERA5DailyHeatIndexData( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_heat_index_data( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) GetERA5DailyHeatData( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_heat_data( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyHeatIndexData( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_heat_index_data( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) GetERA5DailyHeatData( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_heat_data( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region (for geojson method) |
north |
Northern latitude boundary (for bbox method) |
south |
Southern latitude boundary (for bbox method) |
east |
Eastern longitude boundary (for bbox method) |
west |
Western longitude boundary (for bbox method) |
solar_load |
Whether to include solar radiation in calculations (default: FALSE). When TRUE, downloads solar radiation data and uses it for WBGT and UTCI. |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data if available (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with columns: date, latitude, longitude, temp_c, dewpoint_c, wind_speed, rh, wet_bulb, heat_index, wbgt, utci, humidex, wbgt_risk, heat_index_risk, utci_stress. When solar_load=TRUE, also includes solar_radiation.
region <- system.file("extdata", "region.geojson", package = "varunayan") heat_data <- GetERA5DailyHeatIndexData( request_id = "india_heat_2023", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region ) # With solar radiation for outdoor WBGT heat_data <- GetERA5DailyHeatIndexData( request_id = "india_heat_2023_solar", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region, solar_load = TRUE )region <- system.file("extdata", "region.geojson", package = "varunayan") heat_data <- GetERA5DailyHeatIndexData( request_id = "india_heat_2023", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region ) # With solar radiation for outdoor WBGT heat_data <- GetERA5DailyHeatIndexData( request_id = "india_heat_2023_solar", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region, solar_load = TRUE )
Downloads temperature, dewpoint, and calculates relative humidity.
GetERA5DailyHumidity( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_humidity( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyHumidity( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_humidity( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with date, latitude, longitude, temp_c, dewpoint_c, rh
region <- system.file("extdata", "region.geojson", package = "varunayan") humidity <- GetERA5DailyHumidity( request_id = "india_humidity", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") humidity <- GetERA5DailyHumidity( request_id = "india_humidity", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )
Download daily ERA5 temperature data
GetERA5DailyTemperature( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_temperature( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyTemperature( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_temperature( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with date, latitude, longitude, temp_c
region <- system.file("extdata", "region.geojson", package = "varunayan") temp <- GetERA5DailyTemperature( request_id = "india_temp", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") temp <- GetERA5DailyTemperature( request_id = "india_temp", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )
Downloads temperature, dewpoint, and calculates RH and wet bulb temperature.
GetERA5DailyWetBulb( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_wet_bulb( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyWetBulb( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_wet_bulb( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with date, latitude, longitude, temp_c, dewpoint_c, rh, wet_bulb
region <- system.file("extdata", "region.geojson", package = "varunayan") wetbulb <- GetERA5DailyWetBulb( request_id = "india_wetbulb", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") wetbulb <- GetERA5DailyWetBulb( request_id = "india_wetbulb", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )
Downloads 10m wind components and calculates wind speed.
GetERA5DailyWind( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_wind( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5DailyWind( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_daily_wind( request_id, start_date, end_date, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
data.frame with date, latitude, longitude, wind_speed
region <- system.file("extdata", "region.geojson", package = "varunayan") wind <- GetERA5DailyWind( request_id = "india_wind", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") wind <- GetERA5DailyWind( request_id = "india_wind", start_date = "2023-05-01", end_date = "2023-05-31", json_file = region )
Download ERA5 heat stress indices aggregated to a given month.
GetERA5MonthlyHeatIndexData( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_monthly_heat_index_data( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) GetERA5MonthlyHeatData( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_monthly_heat_data( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE )GetERA5MonthlyHeatIndexData( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_monthly_heat_index_data( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) GetERA5MonthlyHeatData( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE ) get_era5_monthly_heat_data( request_id, year, month, json_file = NULL, north = NULL, south = NULL, east = NULL, west = NULL, solar_load = FALSE, resolution = 0.25, use_cache = TRUE, verbose = FALSE )
request_id |
Unique identifier for the data request |
year |
Year (e.g., 2023) |
month |
Month (1-12) |
json_file |
Path to GeoJSON file defining the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
solar_load |
Whether to include solar radiation (default: FALSE) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
Whether to use cached data (default: TRUE) |
verbose |
Whether to print progress messages (default: FALSE) |
A data.frame with one row per grid point for the requested month: year, month, latitude, longitude, monthly means of the daily heat stress variables, and the categorical columns wbgt_risk, heat_index_risk and utci_stress.
region <- system.file("extdata", "region.geojson", package = "varunayan") heat_may <- GetERA5MonthlyHeatIndexData( request_id = "india_may2023", year = 2023, month = 5, json_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") heat_may <- GetERA5MonthlyHeatIndexData( request_id = "india_may2023", year = 2023, month = 5, json_file = region )
Get package version information
GetPackageInfo(...) get_package_info()GetPackageInfo(...) get_package_info()
... |
Arguments passed to the main function (used by aliases). |
The utils::sessionInfo() object, invisibly. Called for its side effect of reporting the R version, platform and versions of key dependencies as messages.
get_package_info()get_package_info()
Functions to download and process the Met Office HadEX3 global climate extremes dataset based on ETCCDI indices.
.HADEX3_ANNUAL_INDICES.HADEX3_ANNUAL_INDICES
Dunn et al. (2020) Development of an updated global land in-situ-based dataset of temperature and precipitation extremes: HadEX3. J. Geophys. Res. Atmos. doi:10.1029/2019JD032263
Downloads and filters HadEX3 ETCCDI climate extremes data to a geographic bounding box. Data covers 1901-2018 at 1.25 x 1.875 degree resolution.
HadEX3Bbox(...) hadex3_bbox( index, start_year, end_year, north, south, east, west, frequency = "annual", baseline = "61-90", output_dir = tempdir(), use_cache = TRUE )HadEX3Bbox(...) hadex3_bbox( index, start_year, end_year, north, south, east, west, frequency = "annual", baseline = "61-90", output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
index |
ETCCDI index name (e.g. "TXx", "Rx1day"). See |
start_year |
Start year (1901-2018). |
end_year |
End year (1901-2018). |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
frequency |
Temporal frequency: "annual" or "monthly" (default: "annual"). |
baseline |
Reference period for percentile-based indices: "61-90" (default) or "81-10". Only applies to annual frequency. |
output_dir |
Directory for temporary files (default: |
use_cache |
Whether to use cached data (default: TRUE). |
data.frame with columns: year (+ month for monthly), latitude, longitude, value, index.
# Annual maximum daily maximum temperature for Europe 1981-2010 data <- hadex3_bbox( index = "TXx", start_year = 1981, end_year = 2010, north = 71, south = 36, east = 40, west = -10 ) # Monthly Rx1day for India data <- hadex3_bbox( index = "Rx1day", start_year = 2000, end_year = 2018, north = 35, south = 8, east = 97, west = 68, frequency = "monthly" )# Annual maximum daily maximum temperature for Europe 1981-2010 data <- hadex3_bbox( index = "TXx", start_year = 1981, end_year = 2010, north = 71, south = 36, east = 40, west = -10 ) # Monthly Rx1day for India data <- hadex3_bbox( index = "Rx1day", start_year = 2000, end_year = 2018, north = 35, south = 8, east = 97, west = 68, frequency = "monthly" )
Downloads and filters HadEX3 ETCCDI climate extremes data to a geographic region defined by a GeoJSON polygon.
HadEX3Geojson(...) hadex3_geojson( index, start_year, end_year, geojson_file, frequency = "annual", baseline = "61-90", output_dir = tempdir(), use_cache = TRUE )HadEX3Geojson(...) hadex3_geojson( index, start_year, end_year, geojson_file, frequency = "annual", baseline = "61-90", output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
index |
ETCCDI index name (e.g. "TXx", "Rx1day"). See |
start_year |
Start year (1901-2018). |
end_year |
End year (1901-2018). |
geojson_file |
Path to a GeoJSON file defining the region. |
frequency |
Temporal frequency: "annual" or "monthly" (default: "annual"). |
baseline |
Reference period for percentile-based indices: "61-90" (default) or "81-10". Only applies to annual frequency. |
output_dir |
Directory for temporary files (default: |
use_cache |
Whether to use cached data (default: TRUE). |
data.frame with columns: year (+ month for monthly), latitude, longitude, value, index.
region <- system.file("extdata", "region.geojson", package = "varunayan") data <- hadex3_geojson( index = "TXx", start_year = 1981, end_year = 2010, geojson_file = region )region <- system.file("extdata", "region.geojson", package = "varunayan") data <- hadex3_geojson( index = "TXx", start_year = 1981, end_year = 2010, geojson_file = region )
US National Weather Service heat index: Steadman's simple formula, replaced by the Rothfusz (1990) regression with its low- and high-humidity adjustments once the simple value averaged with temperature reaches 80F.
heat_index(temp_c, rh)heat_index(temp_c, rh)
temp_c |
Air temperature in Celsius |
rh |
Relative humidity as percentage (0-100) |
Heat index in Celsius
Rothfusz, L.P. (1990). The Heat Index Equation. NWS Southern Region Technical Attachment, SR/SSD 90-23. https://www.weather.gov/media/ffc/ta_htindx.PDF
heat_index(35, 70)heat_index(35, 70)
Calculate heat index from dewpoint
heat_index_from_dewpoint(temp_c, dewpoint_c)heat_index_from_dewpoint(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
Heat index in Celsius
heat_index_from_dewpoint(35, 25)heat_index_from_dewpoint(35, 25)
Classify heat stress risk based on heat index using NWS categories.
heat_index_risk_category(hi)heat_index_risk_category(hi)
hi |
Heat index value in Celsius |
A factor of risk categories, the same length as the input.
heat_index_risk_category(c(27, 33, 40, 46, 55))heat_index_risk_category(c(27, 33, 40, 46, 55))
Flags the days of a daily maximum temperature series that fall in a heatwave, under one of three definitions:
"imd": India Meteorological Department. A day qualifies when Tmax is at
least 40 C (plains), 37 C (coastal) or 30 C (hilly) and departs at least
4.5 C from the calendar-day normal, or when Tmax is at least 45 C. Severe:
departure above 6.4 C with Tmax at least 40 C (plains, coastal) or 30 C
(hilly), or Tmax of at least 47 C. A heatwave needs min_duration (2)
consecutive qualifying days. IMD also requires 2 stations in a
meteorological sub-division; each series here is judged on its own.
"percentile": Tmax above the calendar-day percentile of the baseline
years (5-day window) for at least min_duration (3) days, as in Rohini et
al. (2016) for India.
"ehf": days covered by a three-day period with positive
excess_heat_factor(); severe when EHF reaches EHF85.
heatwave_days( date, tmax, tmin = NULL, method = c("imd", "percentile", "ehf"), baseline = c(1991, 2020), terrain = c("plains", "coastal", "hilly"), percentile = 0.9, min_duration = NULL, window = 2L )heatwave_days( date, tmax, tmin = NULL, method = c("imd", "percentile", "ehf"), baseline = c(1991, 2020), terrain = c("plains", "coastal", "hilly"), percentile = 0.9, min_duration = NULL, window = 2L )
date |
Dates of a strictly increasing daily series for one location. |
tmax |
Daily maximum temperature (degrees Celsius). |
tmin |
Daily minimum temperature; required for |
method |
|
baseline |
Climatology years, |
terrain |
For |
percentile |
Threshold quantile for |
min_duration |
Minimum run of qualifying days; defaults to 2 for
|
window |
Half-width in days of the calendar-day window. |
The calendar-day normal is the baseline mean over a 2 * window + 1 day
window. Percentiles use stats::quantile() type 8 without the in-base
bootstrap of the ETCCDI indices.
A data.frame with date, day (in a heatwave), severe,
spell_start and spell_length (on the first day of each heatwave).
India Meteorological Department. Heat wave and warm night definitions. https://mausam.imd.gov.in/pdfs/heatcolduser/Definition.pdf
Rohini, P., Rajeevan, M. & Srivastava, A.K. (2016). On the Variability and Increasing Trends of Heat Waves over India. Scientific Reports, 6, 26153. doi:10.1038/srep26153
d <- seq(as.Date("2001-01-01"), as.Date("2003-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2003-05-10") & d <= as.Date("2003-05-13")] <- 46 hw <- heatwave_days(d, tmax, baseline = c(2001, 2002)) subset(hw, day)d <- seq(as.Date("2001-01-01"), as.Date("2003-12-31"), by = "day") doy <- as.POSIXlt(d)$yday tmax <- 33 + 8 * sin(2 * pi * (doy - 80) / 365) tmax[d >= as.Date("2003-05-10") & d <= as.Date("2003-05-13")] <- 46 hw <- heatwave_days(d, tmax, baseline = c(2001, 2002)) subset(hw, day)
Calculate humidex (Canadian heat index)
humidex(temp_c, dewpoint_c)humidex(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
Humidex in Celsius
Masterson, J. & Richardson, F.A. (1979). Humidex, A Method of Quantifying Human Discomfort Due to Excessive Heat and Humidity. Environment Canada, Atmospheric Environment Service.
Environment and Climate Change Canada. Glossary: Humidex. https://climate.weather.gc.ca/glossary_e.html
humidex(30, 22)humidex(30, 22)
Unlike imd_temperature_geojson(), which returns grid points clipped to
the GeoJSON boundary, this returns one row per feature (e.g. per state)
per time period, with the region-mean temperature.
imd_temperature_by_region( request_id, start_year, end_year, geojson_file, feature_col = NULL, var_type = "tmean", frequency = "monthly", use_cache = TRUE )imd_temperature_by_region( request_id, start_year, end_year, geojson_file, feature_col = NULL, var_type = "tmean", frequency = "monthly", use_cache = TRUE )
request_id |
Unique identifier for the request. |
start_year |
Start year (>= 1951). |
end_year |
End year (<= 2024). |
geojson_file |
Path to a GeoJSON whose features are the regions. |
feature_col |
Name of the GeoJSON property to group by (e.g.
|
var_type |
|
frequency |
|
use_cache |
Use cached IMD downloads if available (default TRUE). |
A data.frame: region, year, month (if monthly), temperature.
## Not run: temp <- imd_temperature_by_region( request_id = "india_states", start_year = 2009, end_year = 2024, geojson_file = "india_states.geojson", feature_col = "state_name", var_type = "tmean", frequency = "monthly" ) ## End(Not run)## Not run: temp <- imd_temperature_by_region( request_id = "india_states", start_year = 2009, end_year = 2024, geojson_file = "india_states.geojson", feature_col = "state_name", var_type = "tmean", frequency = "monthly" ) ## End(Not run)
Classifies locations as "hilly", "coastal" or "plains" for the IMD
heatwave definition in heatwave_days(). IMD sets the Tmax floor by
terrain but does not define it. A location is hilly when it lies in Jammu
and Kashmir, Ladakh, Himachal Pradesh or Uttarakhand, whose sub-divisions
IMD treats as hilly down to the Jammu plains, or when its
india_elevation() reaches hill_elevation, the 1200 m boundary of the
mid-hill regions by default. Otherwise it is coastal when land and open sea
both lie within about 9 km.
imd_terrain(latitude, longitude, hill_elevation = 1200, cell_size = NULL)imd_terrain(latitude, longitude, hill_elevation = 1200, cell_size = NULL)
latitude, longitude
|
Coordinates in decimal degrees. |
hill_elevation |
Elevation (m) at or above which a location is hilly. |
cell_size |
Grid spacing in degrees when the coordinates are cell
centres, such as 1 for the IMD temperature grid; |
For gridded data set cell_size to classify whole cells from their Indian
land: a cell is hilly when most of it lies in those states or its median
elevation reaches hill_elevation, and coastal when any of it is.
A character vector of "hilly", "coastal" or "plains", NA
outside the grid or over sea.
NOAA National Centers for Environmental Information (2022). ETOPO 2022 15 Arc-Second Global Relief Model. doi:10.25921/fd45-gt74
Ministry of Panchayati Raj. Local Government Directory district boundaries, via https://bharatviz.org.
heatwave_days(), exposure_indicators()
# Shimla, Jammu, Delhi, Chennai imd_terrain(c(31.10, 32.73, 28.61, 13.08), c(77.17, 74.86, 77.21, 80.27)) # IMD 1 degree cells holding Jammu and Rajkot imd_terrain(c(32.5, 22.5), c(74.5, 70.5), cell_size = 1)# Shimla, Jammu, Delhi, Chennai imd_terrain(c(31.10, 32.73, 28.61, 13.08), c(77.17, 74.86, 77.21, 80.27)) # IMD 1 degree cells holding Jammu and Rajkot imd_terrain(c(32.5, 22.5), c(74.5, 70.5), cell_size = 1)
Downloads IMD gridded daily maximum and minimum temperature (1 degree) for
the requested years and the baseline, then computes
exposure_indicators() for each grid cell.
IMDExposureBbox(...) imd_exposure_bbox( start_year, end_year, north, south, east, west, baseline = c(1991, 2020), ..., output_dir = tempdir(), use_cache = TRUE )IMDExposureBbox(...) imd_exposure_bbox( start_year, end_year, north, south, east, west, baseline = c(1991, 2020), ..., output_dir = tempdir(), use_cache = TRUE )
... |
Further arguments to |
start_year, end_year
|
Years to report (1951-2025). |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
baseline |
Climatology years, |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
The data.frame of exposure_indicators() for start_year to
end_year, one row per grid cell (latitude, longitude) and period.
jaipur <- imd_exposure_bbox(2022, 2024, north = 28, south = 26, east = 77, west = 75, months = 3:6 )jaipur <- imd_exposure_bbox(2022, 2024, north = 28, south = 26, east = 77, west = 75, months = 3:6 )
Downloads IMD gridded rainfall data and filters it to a specified bounding box.
IMDRainfallBbox(...) imd_rainfall_bbox( request_id, start_year, end_year, north, south, east, west, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )IMDRainfallBbox(...) imd_rainfall_bbox( request_id, start_year, end_year, north, south, east, west, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the request. |
start_year |
Start year. |
end_year |
End year. |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency: "daily", "monthly", "yearly" (default: "daily"). |
save_raw |
Whether to save raw downloaded files (default: FALSE). |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
A data.frame with columns date, latitude, longitude and rainfall (mm), restricted to the requested region and aggregated to frequency.
data <- imd_rainfall_bbox( request_id = "maharashtra_rain", start_year = 2023, end_year = 2024, north = 22, south = 16, east = 80, west = 73, resolution = 0.25, frequency = "monthly" )data <- imd_rainfall_bbox( request_id = "maharashtra_rain", start_year = 2023, end_year = 2024, north = 22, south = 16, east = 80, west = 73, resolution = 0.25, frequency = "monthly" )
Download and process IMD rainfall data for a GeoJSON region
IMDRainfallGeojson(...) imd_rainfall_geojson( request_id, start_year, end_year, geojson_file, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )IMDRainfallGeojson(...) imd_rainfall_geojson( request_id, start_year, end_year, geojson_file, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the request. |
start_year |
Start year (1901-2025). |
end_year |
End year (1901-2025). |
geojson_file |
Path to GeoJSON file. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
Whether to save raw files (default: FALSE). |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
A data.frame with columns date, latitude, longitude and rainfall (mm), restricted to the requested region and aggregated to frequency.
region <- system.file("extdata", "region.geojson", package = "varunayan") data <- imd_rainfall_geojson( request_id = "mh_rain", start_year = 2023, end_year = 2023, geojson_file = region, frequency = "monthly" )region <- system.file("extdata", "region.geojson", package = "varunayan") data <- imd_rainfall_geojson( request_id = "mh_rain", start_year = 2023, end_year = 2023, geojson_file = region, frequency = "monthly" )
Extracts the daily rainfall series for the IMD grid cell nearest to a (lat, lon). Reads only that one cell off disk per year, so it is the cheapest way to get a long series for a location.
IMDRainfallPoint(...) imd_rainfall_point( request_id, start_year, end_year, latitude, longitude, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )IMDRainfallPoint(...) imd_rainfall_point( request_id, start_year, end_year, latitude, longitude, resolution = 0.25, frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the request. |
start_year |
Start year (1901-2024). |
end_year |
End year (1901-2024). |
latitude |
Point latitude. |
longitude |
Point longitude. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency: "daily", "monthly", "yearly" (default: "daily"). |
save_raw |
Whether to save raw downloaded files (default: FALSE). |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
data.frame with the nearest cell's rainfall series.
## Not run: powai <- imd_rainfall_point("powai", 1901, 2024, 19.1277, 72.9047) ## End(Not run)## Not run: powai <- imd_rainfall_point("powai", 1901, 2024, 19.1277, 72.9047) ## End(Not run)
Retrieves the India Meteorological Department (IMD) city-weather station list
and, optionally, each station's latitude/longitude. IMD's legacy endpoints
expose only station names; its responsive site serves a per-station JSON record
(api/fetchCity_static.php) that includes lat/lon, which this function
pairs with the station list. The returned coordinates can be fed directly to
era5ify_point() or used to build maps.
IMDStations(...) imd_stations(with_coordinates = TRUE, cores = 4)IMDStations(...) imd_stations(with_coordinates = TRUE, cores = 4)
... |
Ignored (present for alias compatibility). |
with_coordinates |
Logical; if |
cores |
Integer; number of parallel workers used to fetch coordinates
(passed to |
A data.frame with columns station_id, name, and — when
with_coordinates = TRUE — latitude, longitude (NA where IMD has no
coordinate for a station).
## Not run: stations <- imd_stations() shimla <- stations[grepl("Shimla", stations$name), ] ## End(Not run)## Not run: stations <- imd_stations() shimla <- stations[grepl("Shimla", stations$name), ] ## End(Not run)
Download and process IMD temperature data for a bounding box
IMDTemperatureBbox(...) imd_temperature_bbox( request_id, start_year, end_year, north, south, east, west, var_type = "tmax", frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )IMDTemperatureBbox(...) imd_temperature_bbox( request_id, start_year, end_year, north, south, east, west, var_type = "tmax", frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the request. |
start_year |
Start year (1951-2025). |
end_year |
End year (1951-2025). |
north |
Northern latitude boundary. |
south |
Southern latitude boundary. |
east |
Eastern longitude boundary. |
west |
Western longitude boundary. |
var_type |
Temperature type: "tmax" or "tmin". |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
Whether to save raw files (default: FALSE). |
output_dir |
Directory to save files (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
A data.frame with columns date, latitude, longitude and temperature (degrees Celsius), restricted to the requested region and aggregated to frequency.
data <- imd_temperature_bbox( request_id = "delhi_tmax", start_year = 2023, end_year = 2024, north = 29, south = 28, east = 78, west = 76, var_type = "tmax" )data <- imd_temperature_bbox( request_id = "delhi_tmax", start_year = 2023, end_year = 2024, north = 29, south = 28, east = 78, west = 76, var_type = "tmax" )
Download and process IMD temperature data for a GeoJSON region
IMDTemperatureGeojson(...) imd_temperature_geojson( request_id, start_year, end_year, geojson_file, var_type = "tmax", frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )IMDTemperatureGeojson(...) imd_temperature_geojson( request_id, start_year, end_year, geojson_file, var_type = "tmax", frequency = "daily", save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier. |
start_year |
Start year (1951-2025). |
end_year |
End year (1951-2025). |
geojson_file |
Path to GeoJSON file. |
var_type |
Temperature type: "tmax" or "tmin". |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
Whether to save raw files (default: FALSE). |
output_dir |
Directory for output (default: tempdir()). |
use_cache |
Whether to use cached data if available (default: TRUE). |
A data.frame with columns date, latitude, longitude and temperature (degrees Celsius), restricted to the requested region and aggregated to frequency.
region <- system.file("extdata", "region.geojson", package = "varunayan") data <- imd_temperature_geojson( request_id = "mh_tmax", start_year = 2023, end_year = 2023, geojson_file = region, var_type = "tmax", frequency = "monthly" )region <- system.file("extdata", "region.geojson", package = "varunayan") data <- imd_temperature_geojson( request_id = "mh_tmax", start_year = 2023, end_year = 2023, geojson_file = region, var_type = "tmax", frequency = "monthly" )
Looks up surface elevation from a 5 arc-minute (about 9 km) grid bundled
with the package, covering 6-38 N and 66-98 E. Each value is the median
land elevation of the 5 arc-minute cell holding the location, built by
data-raw/imd_terrain.R from ETOPO 2022 at 60 arc-seconds.
india_elevation(latitude, longitude)india_elevation(latitude, longitude)
latitude, longitude
|
Coordinates in decimal degrees. |
Elevation in metres, NA over open sea or outside the grid.
NOAA National Centers for Environmental Information (2022). ETOPO 2022 15 Arc-Second Global Relief Model. doi:10.25921/fd45-gt74
# Shimla, Delhi, Leh india_elevation(c(31.10, 28.61, 34.16), c(77.17, 77.21, 77.58))# Shimla, Delhi, Leh india_elevation(c(31.10, 28.61, 34.16), c(77.17, 77.21, 77.58))
Check if a variable should use maximum
is_max_var(var_name)is_max_var(var_name)
var_name |
Character string variable name |
Logical indicating if variable should use max
is_max_var("2m_temperature")is_max_var("2m_temperature")
Check if a variable should use minimum
is_min_var(var_name)is_min_var(var_name)
var_name |
Character string variable name |
Logical indicating if variable should use min
is_min_var("2m_temperature")is_min_var("2m_temperature")
Check if a variable is a rate variable
is_rate_var(var_name)is_rate_var(var_name)
var_name |
Character string variable name |
Logical indicating if variable is a rate
is_rate_var("2m_temperature")is_rate_var("2m_temperature")
Check if a variable should be summed
is_sum_var(var_name)is_sum_var(var_name)
var_name |
Character string variable name |
Logical indicating if variable should be summed
is_sum_var("total_precipitation")is_sum_var("total_precipitation")
Check if data is valid GeoJSON
is_valid_geojson(data)is_valid_geojson(data)
data |
List or data structure to check |
Logical indicating if data is valid GeoJSON
List cached files
list_cache(source = NULL)list_cache(source = NULL)
source |
Filter by source: "era5", "imd", "cru_ts", "hadex3", or NULL for all |
A data.frame with columns file, source, size_mb and modified, one row per cached file; zero rows if the cache is empty.
list_cache()list_cache()
List available IMD datasets
list_imd_datasets()list_imd_datasets()
data.frame with available IMD datasets and their characteristics
list_imd_datasets()list_imd_datasets()
List all available variables for a dataset type
ListAvailableVariables(...) list_available_variables(dataset_type = "all")ListAvailableVariables(...) list_available_variables(dataset_type = "all")
... |
Arguments passed to the main function (used by aliases). |
dataset_type |
Character string indicating dataset type |
Character vector of variable names
head(list_available_variables("single"))head(list_available_variables("single"))
Maps CRU TS variable codes to common names, units, and ERA5 equivalents.
ListCRUTSVariables(...) list_cru_ts_variables(...)ListCRUTSVariables(...) list_cru_ts_variables(...)
... |
Arguments passed to the main function (used by aliases). |
data.frame with columns: variable, name, description, unit, era5_equivalent, hadex3_equivalent.
list_cru_ts_variables()list_cru_ts_variables()
Returns a data.frame describing all ETCCDI climate extremes indices available in the HadEX3 dataset, including their temporal availability and physical interpretation.
ListHadEX3Indices(...) list_hadex3_indices(frequency = "all")ListHadEX3Indices(...) list_hadex3_indices(frequency = "all")
... |
Arguments passed to the main function (used by aliases). |
frequency |
Filter by frequency: "annual", "monthly", or "all" (default). |
data.frame with columns: index, category, description, unit, annual, monthly.
list_hadex3_indices() list_hadex3_indices(frequency = "monthly")list_hadex3_indices() list_hadex3_indices(frequency = "monthly")
Variables that should use maximum aggregation
max_varsmax_vars
A character vector of variable names.
head(max_vars)head(max_vars)
Estimates mean radiant temperature (Tmrt) from meteorological variables. Uses simplified approach when full radiation data unavailable.
mean_radiant_temperature(temp_c, solar_radiation = NULL, wind_speed = NULL)mean_radiant_temperature(temp_c, solar_radiation = NULL, wind_speed = NULL)
temp_c |
Air temperature in Celsius |
solar_radiation |
Solar radiation in W/m2 (optional) |
wind_speed |
Wind speed in m/s (optional) |
Mean radiant temperature in Celsius
mean_radiant_temperature(30, solar_radiation = 800, wind_speed = 2)mean_radiant_temperature(30, solar_radiation = 800, wind_speed = 2)
Variables that should use minimum aggregation
min_varsmin_vars
A character vector of variable names.
head(min_vars)head(min_vars)
NDBI = (SWIR - NIR) / (SWIR + NIR) from surface reflectance, using the
1.55-1.75 um shortwave infrared band, e.g. Landsat 8-9 bands 6 and 5,
Sentinel-2 bands 11 and 8, or Landsat 5 TM bands 5 and 4 as in Zha et al.
(2003). Positive values indicate built-up or bare surfaces. Works on numeric
vectors and on terra::SpatRaster layers.
ndbi(swir, nir)ndbi(swir, nir)
swir |
Shortwave infrared reflectance. |
nir |
Near-infrared reflectance. |
NDBI in the range -1 to 1, the same shape as the inputs.
Zha, Y., Gao, J. & Ni, S. (2003). Use of normalized difference built-up index in automatically mapping urban areas from TM imagery. International Journal of Remote Sensing, 24(3), 583-594. doi:10.1080/01431160304987
ndbi(swir = 0.30, nir = 0.22)ndbi(swir = 0.30, nir = 0.22)
NDVI = (NIR - Red) / (NIR + Red) from surface reflectance, e.g. Landsat 8-9
bands 5 and 4, Sentinel-2 bands 8 and 4, or MODIS bands 2 and 1. Works on
numeric vectors and on terra::SpatRaster layers.
ndvi(nir, red)ndvi(nir, red)
nir |
Near-infrared reflectance. |
red |
Red reflectance. |
NDVI in the range -1 to 1, the same shape as the inputs.
Tucker, C.J. (1979). Red and photographic infrared linear combinations for monitoring vegetation. Remote Sensing of Environment, 8(2), 127-150. doi:10.1016/0034-4257(79)90013-0
ndvi(nir = 0.45, red = 0.08)ndvi(nir = 0.45, red = 0.08)
Parse date string flexibly
parse_date_flexible(date_string)parse_date_flexible(date_string)
date_string |
Character string in various date formats |
Date object
Copies sample IMD data files to cache for offline testing.
PopulateSampleCache(...) populate_sample_cache(force = FALSE)PopulateSampleCache(...) populate_sample_cache(force = FALSE)
... |
Arguments passed to the main function (used by aliases). |
force |
Overwrite existing cached files (default: FALSE) |
Invisibly, a named list of paths to the cached sample files, or NULL if no sample directory exists.
populate_sample_cache()populate_sample_cache()
Print timing summary
print_timing_summary()print_timing_summary()
The timing data frame from get_timings(), invisibly (NULL if empty).
print_timing_summary()print_timing_summary()
Reads and combines multiple IMD data files.
process_imd_files( file_paths, var_type, resolution = NULL, years = NULL, bbox = NULL )process_imd_files( file_paths, var_type, resolution = NULL, years = NULL, bbox = NULL )
file_paths |
Character vector of file paths. |
var_type |
Variable type: "rain", "tmax", or "tmin". |
resolution |
Resolution (for rainfall): 0.25 or 1.0. |
years |
Integer vector. Years corresponding to each file. |
bbox |
Optional named list/vector (north, south, east, west) passed to the rainfall reader to crop at read time; NULL reads the full grid (default). |
A data.frame with columns date, latitude, longitude and the value column (rainfall or temperature), combining all files.
files <- download_imd_temperature(2023, 2024, var_type = "tmax") data <- process_imd_files(files, "tmax", years = c(2023, 2024))files <- download_imd_temperature(2023, 2024, var_type = "tmax") data <- process_imd_files(files, "tmax", years = c(2023, 2024))
Uses ncdf4 directly for fast reading, with stars as fallback.
process_netcdf_to_dataframe(netcdf_file)process_netcdf_to_dataframe(netcdf_file)
netcdf_file |
Character string path to NetCDF file |
data.frame with processed climate data
Rate variables that should be averaged
rate_varsrate_vars
A character vector of variable names.
head(rate_vars)head(rate_vars)
Read CDS API credentials from ~/.cdsapirc file
read_cdsapirc(file_path = "~/.cdsapirc")read_cdsapirc(file_path = "~/.cdsapirc")
file_path |
Path to .cdsapirc file (default: "~/.cdsapirc") |
A named list of the fields in the file (typically url and key), or NULL if the file does not exist or cannot be parsed.
f <- tempfile() writeLines(c("url: https://cds.climate.copernicus.eu/api", "key: abc-123"), f) read_cdsapirc(f)f <- tempfile() writeLines(c("url: https://cds.climate.copernicus.eu/api", "key: abc-123"), f) read_cdsapirc(f)
Reads IMD NetCDF rainfall data and converts to data.frame.
read_imd_rainfall(file_path, resolution, year, bbox = NULL)read_imd_rainfall(file_path, resolution, year, bbox = NULL)
file_path |
Path to IMD NetCDF file (.nc). |
resolution |
Spatial resolution: 0.25 or 1.0. |
year |
Year of the data. |
bbox |
Optional named list/vector (north, south, east, west). When set, only that spatial slab is read off disk (fast path); NULL reads the full grid. |
data.frame with columns: date, latitude, longitude, rainfall
f <- download_imd_rainfall(2023, 2023, resolution = 0.25) rain_data <- read_imd_rainfall(f, 0.25, 2023)f <- download_imd_rainfall(2023, 2023, resolution = 0.25) rain_data <- read_imd_rainfall(f, 0.25, 2023)
Reads IMD binary temperature data (max or min) and converts to data.frame.
read_imd_temperature(file_path, var_type, year)read_imd_temperature(file_path, var_type, year)
file_path |
Path to IMD binary file (.grd). |
var_type |
Variable type: "tmax" or "tmin". |
year |
Year of the data. |
data.frame with columns: date, latitude, longitude, temperature
f <- download_imd_temperature(2023, 2023, var_type = "tmax") tmax_data <- read_imd_temperature(f, "tmax", 2023)f <- download_imd_temperature(2023, 2023, var_type = "tmax") tmax_data <- read_imd_temperature(f, "tmax", 2023)
Uses the Magnus-Tetens approximation to calculate relative humidity from air temperature and dewpoint temperature.
relative_humidity_from_dewpoint(temp_c, dewpoint_c)relative_humidity_from_dewpoint(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
Relative humidity as percentage (0-100)
relative_humidity_from_dewpoint(25, 18)relative_humidity_from_dewpoint(25, 18)
Search for ERA5 variables by keyword
SearchVariable(...) search_variable(keyword, dataset_type = "all", exact_match = FALSE)SearchVariable(...) search_variable(keyword, dataset_type = "all", exact_match = FALSE)
... |
Arguments passed to the main function (used by aliases). |
keyword |
Character string to search for in variable names and descriptions |
dataset_type |
Character string indicating dataset type ("single", "pressure", or "all") |
exact_match |
Logical indicating whether to use exact matching |
A data.frame with columns variable_name, description, units, dataset_type and category, one row per matching variable.
# Search for temperature variables temp_vars <- search_variable("temperature") # Search in pressure level data only pressure_temp <- search_variable("temperature", dataset_type = "pressure")# Search for temperature variables temp_vars <- search_variable("temperature") # Search in pressure level data only pressure_temp <- search_variable("temperature", dataset_type = "pressure")
Sets up Copernicus Climate Data Store (CDS) credentials for ERA5 downloads. Credentials are checked in the following order:
Directly provided key argument
CDS_API_KEY environment variable
~/.cdsapirc file
SetupCdsCredentials(...) setup_cds_credentials(key = NULL)SetupCdsCredentials(...) setup_cds_credentials(key = NULL)
... |
Arguments passed to the main function (used by aliases). |
key |
Your CDS API key (UUID format). If NULL, attempts to read from
environment variable |
Invisibly, TRUE once the key has been registered with 'ecmwfr'. Errors if no key can be found.
## Not run: setup_cds_credentials(key = "your-cds-api-key-here") Sys.setenv(CDS_API_KEY = "your-cds-api-key-here") setup_cds_credentials() ## End(Not run)## Not run: setup_cds_credentials(key = "your-cds-api-key-here") Sys.setenv(CDS_API_KEY = "your-cds-api-key-here") setup_cds_credentials() ## End(Not run)
Show cache contents and statistics
ShowCacheInfo(...) show_cache_info()ShowCacheInfo(...) show_cache_info()
... |
Arguments passed to the main function (used by aliases). |
Invisibly, a data.frame with columns name, size_mb and mtime describing cached files, or NULL if the cache is empty. Called mainly for its side effect of printing a summary as messages.
show_cache_info()show_cache_info()
Accumulation variables (precipitation, radiation) that use sum for temporal aggregation.
sum_varssum_vars
A character vector of variable names.
head(sum_vars)head(sum_vars)
Time an operation and log the duration
time_operation(expr, label, verbose = TRUE)time_operation(expr, label, verbose = TRUE)
expr |
Expression to time |
label |
Label for the operation |
verbose |
Whether to print timing info (default: TRUE) |
The value of expr. The elapsed time is recorded and can be retrieved with get_timings().
x <- time_operation(sum(1:10), "sum") get_timings()x <- time_operation(sum(1:10), "sum") get_timings()
Calculates UTCI using the polynomial approximation from Bröde et al. (2012), based on a multi-node model of human thermoregulation.
utci(temp_c, wind_speed, dewpoint_c, tmrt = NULL)utci(temp_c, wind_speed, dewpoint_c, tmrt = NULL)
temp_c |
Air temperature in Celsius (-50 to 50) |
wind_speed |
Wind speed at 10m height in m/s (0.5 to 17) |
dewpoint_c |
Dewpoint temperature in Celsius (to calculate vapor pressure) |
tmrt |
Mean radiant temperature in Celsius (optional, defaults to temp_c) |
UTCI in Celsius
Bröde, P., et al. (2012). Deriving the operational procedure for the Universal Thermal Climate Index (UTCI). International Journal of Biometeorology, 56(3), 481-494. doi:10.1007/s00484-011-0454-1
utci(30, wind_speed = 2, dewpoint_c = 20) utci(35, wind_speed = 1, dewpoint_c = 25, tmrt = 45)utci(30, wind_speed = 2, dewpoint_c = 20) utci(35, wind_speed = 1, dewpoint_c = 25, tmrt = 45)
Classify thermal stress based on UTCI values.
utci_category(utci_val)utci_category(utci_val)
utci_val |
UTCI value in Celsius |
A factor of thermal stress categories, the same length as the input.
utci_category(c(-20, 0, 20, 30, 40))utci_category(c(-20, 0, 20, 30, 40))
Calculates UTCI using the sparse regression approximation with Legendre polynomials from Roman et al. (2025). This is a more accurate approximation than the original Bröde et al. (2012) polynomial, with fewer terms and better numerical stability.
utci_sparse(temp_c, tmrt, wind_speed, rh)utci_sparse(temp_c, tmrt, wind_speed, rh)
temp_c |
Air temperature in Celsius (-50 to 50) |
tmrt |
Mean radiant temperature in Celsius |
wind_speed |
Wind speed at 10m height in m/s (0.5 to 30.3) |
rh |
Relative humidity as percentage (5 to 100) |
UTCI in Celsius
Roman, S., Todorovski, L., Dzeroski, S., & Skok, G. (2025). Approximating the universal thermal climate index using sparse regression with orthogonal polynomials. doi:10.48550/arXiv.2508.11307
Roman, S. (2025). Code for Approximating the universal thermal climate index (UTCI) using sparse regression with orthogonal polynomials. Zenodo. doi:10.5281/zenodo.17465548
utci_sparse(30, tmrt = 40, wind_speed = 2, rh = 60) utci_sparse(35, tmrt = 35, wind_speed = 1, rh = 80)utci_sparse(30, tmrt = 40, wind_speed = 2, rh = 60) utci_sparse(35, tmrt = 35, wind_speed = 1, rh = 80)
Validate bounding box coordinates
validate_bbox(north, south, east, west)validate_bbox(north, south, east, west)
north |
Northern boundary |
south |
Southern boundary |
east |
Eastern boundary |
west |
Western boundary |
Logical indicating if bounding box is valid
Validate geographic coordinates
validate_coordinates(lat, lon)validate_coordinates(lat, lon)
lat |
Latitude value |
lon |
Longitude value |
Logical indicating if coordinates are valid
Validate ERA5 variable names
validate_era5_variables(variables, dataset_type)validate_era5_variables(variables, dataset_type)
variables |
Character vector of variable names to validate |
dataset_type |
Character string: "single" or "pressure" |
Logical vector indicating which variables are valid
Calculate vapor pressure from dewpoint temperature
vapor_pressure_from_dewpoint(dewpoint_c)vapor_pressure_from_dewpoint(dewpoint_c)
dewpoint_c |
Dewpoint temperature in Celsius |
Vapor pressure in hPa (hectopascals)
vapor_pressure_from_dewpoint(20)vapor_pressure_from_dewpoint(20)
PascalCase aliases for all exported functions for backward compatibility.
ERA5ifyGeojson(...) era5ify_geojson( request_id, variables, start_date, end_date, json_file, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", resolution = 0.25, save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE )ERA5ifyGeojson(...) era5ify_geojson( request_id, variables, start_date, end_date, json_file, dataset_type = "single", pressure_levels = NULL, frequency = "hourly", resolution = 0.25, save_raw = FALSE, output_dir = tempdir(), use_cache = TRUE, convert_units = TRUE, verbose = FALSE )
... |
Arguments passed to the main function (used by aliases). |
request_id |
Unique identifier for the data request |
variables |
List of ERA5 variables to download |
start_date |
Start date in "YYYY-MM-DD" format |
end_date |
End date in "YYYY-MM-DD" format |
json_file |
Path to GeoJSON file defining the region |
dataset_type |
Type of dataset ("single" or "pressure") |
pressure_levels |
Pressure levels for pressure dataset |
frequency |
Temporal frequency ("hourly", "daily", "monthly") |
resolution |
Spatial resolution in degrees (default: 0.25) |
save_raw |
Whether to save raw downloaded files |
output_dir |
Directory to save files (default: tempdir()) |
use_cache |
Whether to use cached data if available (default: TRUE) |
convert_units |
Whether to convert units to user-friendly formats (default: TRUE). When TRUE, temperature variables are returned in Celsius (converted from Kelvin) and precipitation variables are returned in mm (converted from meters). |
verbose |
Whether to print detailed progress messages |
data.frame with processed climate data. When convert_units = TRUE:
Temperature variables (e.g., 2m_temperature): Celsius
Precipitation variables (e.g., total_precipitation): mm
Other variables: original ERA5 units
region <- system.file("extdata", "region.geojson", package = "varunayan") setup_cds_credentials(key = "your-cds-api-key") data <- era5ify_geojson( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", json_file = region ) # Temperature is in Celsius, precipitation is in mmregion <- system.file("extdata", "region.geojson", package = "varunayan") setup_cds_credentials(key = "your-cds-api-key") data <- era5ify_geojson( request_id = "my_request", variables = c("2m_temperature", "total_precipitation"), start_date = "2023-01-01", end_date = "2023-01-31", json_file = region ) # Temperature is in Celsius, precipitation is in mm
Visualize grid-polygon overlap
visualize_grid_overlap( grid_data, polygons, show_centroids = TRUE, grid_color = "#E74C3C", polygon_fill = NA, polygon_color = "#2C3E50", centroid_color = "#3498DB", title = "Grid-Polygon Overlap" )visualize_grid_overlap( grid_data, polygons, show_centroids = TRUE, grid_color = "#E74C3C", polygon_fill = NA, polygon_color = "#2C3E50", centroid_color = "#3498DB", title = "Grid-Polygon Overlap" )
grid_data |
Data frame with longitude and latitude columns, or path to NetCDF/CSV |
polygons |
sf object or path to GeoJSON file |
show_centroids |
Logical, whether to show polygon centroids |
grid_color |
Color for grid points |
polygon_fill |
Fill color for polygons |
polygon_color |
Border color for polygons |
centroid_color |
Color for centroids |
title |
Plot title |
ggplot object
grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) visualize_grid_overlap(grid, polys)grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1)) grid$temperature <- seq_len(nrow(grid)) cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox( c(xmin = 72, ymin = 18, xmax = 78, ymax = 22), crs = 4326 )), n = c(2, 1)) polys <- sf::st_sf(region = c("west", "east"), geometry = cells) visualize_grid_overlap(grid, polys)
Flags warm nights in a daily minimum temperature series:
"imd": India Meteorological Department. Tmax of at least 40 C and Tmin
departing at least 4.5 C from the calendar-day normal; very warm (flagged
severe) above 6.4 C.
"percentile": Tmin above the calendar-day percentile of the baseline
years (ETCCDI TN90p with the default 0.9).
"absolute": Tmin above threshold (ETCCDI tropical nights, TR, with the
default 20 C).
warm_nights( date, tmin, tmax = NULL, method = c("imd", "percentile", "absolute"), baseline = c(1991, 2020), percentile = 0.9, threshold = 20, min_duration = 1L, window = 2L )warm_nights( date, tmin, tmax = NULL, method = c("imd", "percentile", "absolute"), baseline = c(1991, 2020), percentile = 0.9, threshold = 20, min_duration = 1L, window = 2L )
date |
Dates of a strictly increasing daily series for one location. |
tmin |
Daily minimum temperature (degrees Celsius). |
tmax |
Daily maximum temperature; required for |
method |
|
baseline |
Climatology years, |
percentile |
Threshold quantile for |
threshold |
Tmin threshold for |
min_duration |
Minimum run of warm nights counted as a spell. |
window |
Half-width in days of the calendar-day window. |
A data.frame with date, day (a warm night within a spell),
severe, spell_start and spell_length.
India Meteorological Department. Heat wave and warm night definitions. https://mausam.imd.gov.in/pdfs/heatcolduser/Definition.pdf
Zhang, X., Alexander, L., Hegerl, G.C., Jones, P., Klein Tank, A., Peterson, T.C., Trewin, B. & Zwiers, F.W. (2011). Indices for monitoring changes in extremes based on daily temperature and precipitation data. WIREs Climate Change, 2(6), 851-870. doi:10.1002/wcc.147
d <- seq(as.Date("2001-01-01"), as.Date("2001-12-31"), by = "day") tmin <- 22 + 6 * sin(2 * pi * (as.POSIXlt(d)$yday - 80) / 365) wn <- warm_nights(d, tmin, method = "absolute", threshold = 27) sum(wn$day)d <- seq(as.Date("2001-01-01"), as.Date("2001-12-31"), by = "day") tmin <- 22 + 6 * sin(2 * pi * (as.POSIXlt(d)$yday - 80) / 365) wn <- warm_nights(d, tmin, method = "absolute", threshold = 27) sum(wn$day)
Computes WBGT by one of two methods:
"simple": the Australian Bureau of Meteorology closed form
0.567 * T + 0.393 * e + 3.94 from temperature and dewpoint only
(wbgt_simple()). Assumes moderate sun and light wind; suited to daily
data.
"liljegren": the physical outdoor model of wbgt_liljegren(), which
needs wind, solar radiation, time and location; suited to hourly data.
wbgt(temp_c, dewpoint_c, method = c("simple", "liljegren"), ...)wbgt(temp_c, dewpoint_c, method = c("simple", "liljegren"), ...)
temp_c |
Air temperature (degrees Celsius). |
dewpoint_c |
Dewpoint temperature (degrees Celsius). |
method |
|
... |
For |
A numeric vector of WBGT (degrees Celsius).
wbgt(38, 24) wbgt(38, 24, method = "liljegren", wind_speed = 3, solar = 800, datetime = as.POSIXct("2024-05-20 08:30:00", tz = "UTC"), lat = 26.9, lon = 75.8 )wbgt(38, 24) wbgt(38, 24, method = "liljegren", wind_speed = 3, solar = 800, datetime = as.POSIXct("2024-05-20 08:30:00", tz = "UTC"), lat = 26.9, lon = 75.8 )
Alias for wbgt_simple() (BoM closed-form WBGT from temperature and
dewpoint).
wbgt_from_dewpoint(temp_c, dewpoint_c)wbgt_from_dewpoint(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
WBGT in Celsius
wbgt_from_dewpoint(35, 25)wbgt_from_dewpoint(35, 25)
Physically based outdoor WBGT from standard meteorological variables,
following Liljegren et al. (2008). Globe and natural wet bulb temperatures
are solved iteratively from energy balances that include direct and diffuse
solar radiation, so this is the sun-exposed WBGT of ISO 7243. Inputs should
be instantaneous or hourly values; for ERA5, solar is the hourly
accumulated surface solar radiation downwards divided by 3600 and
datetime the middle of the accumulation hour.
wbgt_liljegren( temp_c, rh, wind_speed, solar, datetime, lat, lon, pressure = 1013.25, wind_height = 10, urban = FALSE, delta_t = 0, components = FALSE )wbgt_liljegren( temp_c, rh, wind_speed, solar, datetime, lat, lon, pressure = 1013.25, wind_height = 10, urban = FALSE, delta_t = 0, components = FALSE )
temp_c |
Air temperature (degrees Celsius). |
rh |
Relative humidity (percent). |
wind_speed |
Wind speed (m/s) measured at |
solar |
Global horizontal solar irradiance (W/m2). |
datetime |
|
lat, lon
|
Latitude and longitude (decimal degrees). |
pressure |
Surface pressure (hPa). |
wind_height |
Height of the wind measurement (m). Values other than 2 are scaled to 2 m with a stability-dependent power law. |
urban |
Use the urban ( |
delta_t |
Vertical temperature difference, upper minus lower level (degrees Celsius); sets the night-time stability class only. |
components |
If |
This product includes software produced by UChicago Argonne, LLC under Contract No. DE-AC02-06CH11357 with the Department of Energy.
A numeric vector of WBGT (degrees Celsius), or with
components = TRUE a data.frame with columns wbgt, globe,
natural_wet_bulb, wet_bulb and wind_2m. NA where the iteration
does not converge.
Liljegren, J.C., Carhart, R.A., Lawday, P., Tschopp, S. & Sharp, R. (2008). Modeling the Wet Bulb Globe Temperature Using Standard Meteorological Measurements. Journal of Occupational and Environmental Hygiene, 5(10), 645-655. doi:10.1080/15459620802310770
wbgt() to choose between this and the closed-form estimate.
t <- as.POSIXct("2024-05-20 08:30:00", tz = "UTC") # 14:00 IST wbgt_liljegren(42, rh = 25, wind_speed = 3, solar = 850, datetime = t, lat = 26.9, lon = 75.8 ) wbgt_liljegren(42, 25, 3, 850, t, 26.9, 75.8, components = TRUE)t <- as.POSIXct("2024-05-20 08:30:00", tz = "UTC") # 14:00 IST wbgt_liljegren(42, rh = 25, wind_speed = 3, solar = 850, datetime = t, lat = 26.9, lon = 75.8 ) wbgt_liljegren(42, 25, 3, 850, t, 26.9, 75.8, components = TRUE)
Classify heat stress risk using the US National Weather Service WBGT flag thresholds of 78, 82, 85 and 88 F (25.6, 27.8, 29.4 and 31.1 C).
wbgt_risk_category(wbgt)wbgt_risk_category(wbgt)
wbgt |
WBGT value in Celsius |
A factor of risk categories, the same length as the input.
wbgt_risk_category(c(25, 28, 31, 34))wbgt_risk_category(c(25, 28, 31, 34))
Uses the indoor formula 0.7Tw + 0.3Ta. For a closed-form estimate from
temperature and humidity alone, use wbgt_simple().
wbgt_shade(temp_c, wet_bulb_c)wbgt_shade(temp_c, wet_bulb_c)
temp_c |
Air temperature in Celsius |
wet_bulb_c |
Wet bulb temperature in Celsius |
WBGT in Celsius
wbgt_shade(35, 27)wbgt_shade(35, 27)
Australian Bureau of Meteorology approximation
WBGT = 0.567 * T + 0.393 * e + 3.94, with e the vapour pressure in hPa.
It assumes moderately high solar radiation and light wind, so it
overestimates WBGT in cloudy or windy conditions and at night. Use daily
maximum temperature for afternoon conditions. For the physical outdoor
model see wbgt_liljegren().
wbgt_simple(temp_c, dewpoint_c)wbgt_simple(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
WBGT in Celsius
Australian Bureau of Meteorology. Thermal Comfort observations: About the approximation to the WBGT. https://www.bom.gov.au/info/thermal_stress/ (formula from American College of Sports Medicine (1984), Prevention of thermal injuries during distance running: position stand, Medical Journal of Australia, 141, 876).
Carter, A.W., Zaitchik, B.F., Gohlke, J.M., Wang, S., & Richardson, M.B. (2020). Methods for Estimating Wet Bulb Globe Temperature From Remote and Low-Cost Data: A Comparative Study in Central Alabama. GeoHealth, 4(5), e2019GH000231. doi:10.1029/2019GH000231
wbgt_simple(35, 25)wbgt_simple(35, 25)
Calculate wet bulb temperature from dewpoint
wet_bulb_from_dewpoint(temp_c, dewpoint_c)wet_bulb_from_dewpoint(temp_c, dewpoint_c)
temp_c |
Air temperature in Celsius |
dewpoint_c |
Dewpoint temperature in Celsius |
Wet bulb temperature in Celsius
wet_bulb_from_dewpoint(30, 22)wet_bulb_from_dewpoint(30, 22)
Calculates wet bulb temperature using the Stull (2011) empirical formula. Valid for temperatures between -20C and 50C and RH between 5% and 99%.
wet_bulb_temperature(temp_c, rh)wet_bulb_temperature(temp_c, rh)
temp_c |
Air temperature in Celsius |
rh |
Relative humidity as percentage (0-100) |
Wet bulb temperature in Celsius
Stull, R. (2011). Wet-Bulb Temperature from Relative Humidity and Air Temperature. Journal of Applied Meteorology and Climatology, 50(11), 2267-2269. doi:10.1175/JAMC-D-11-0143.1
wet_bulb_temperature(30, 60)wet_bulb_temperature(30, 60)