| Title: | Download and Process 'ERA5', IMD, 'HadEX3' and 'CRU TS' 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], James C. Liljegren [ctb] (Author of the original WBGT C code translated in R/wbgt_liljegren.R), UChicago Argonne, LLC [cph] (Copyright holder of the original WBGT C code) |
| Maintainer: | Saket Choudhary <saketc@iitb.ac.in> |
| License: | MIT + file LICENSE |
| Version: | 0.2.0 |
| Built: | 2026-10-18 06:11:04 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. If TRUE, the function prints 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")
Assigns each grid cell to a polygon, then aggregates the values of the cells in each polygon. The spatial match uses only the distinct cells. Thus, a daily series with many dates does not make the match slower.
aggregate_to_polygons( data, polygons, value_col, method = c("nearest_centroid", "point_in_polygon"), polygon_id_cols = NULL, agg_fun = function(x) mean(x, na.rm = TRUE), by = NULL, fill_empty = FALSE )aggregate_to_polygons( data, polygons, value_col, method = c("nearest_centroid", "point_in_polygon"), polygon_id_cols = NULL, agg_fun = function(x) mean(x, na.rm = TRUE), by = NULL, fill_empty = FALSE )
data |
Data frame with longitude, latitude, and value columns |
polygons |
sf object with polygon geometries (CRS 4326) |
value_col |
Name of the column to aggregate, or a character vector
of names. Give names to set the result columns, for example
|
method |
Aggregation method: |
polygon_id_cols |
Character vector of column names to use as polygon
identifiers. The default is all the columns of |
agg_fun |
Aggregation function. It gets the values of one group,
which can include |
by |
Optional character vector of more group columns in |
fill_empty |
For |
Data frame with the polygon identifiers, the by columns and the
aggregated values. It has one row for each polygon and each value of
by. A polygon with no cell has NA.
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()
This function calculates 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))
Sort variables by aggregation method
categorize_variables(var_names)categorize_variables(var_names)
var_names |
Character vector of variable names |
Named list of the variables, sorted by aggregation method
categorize_variables(c("2m_temperature", "total_precipitation"))categorize_variables(c("2m_temperature", "total_precipitation"))
Calculate the 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 that identify the 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)
Make sure that the system is ready for varunayan operations
CheckSystemReadiness(...) check_system_readiness(verbose = TRUE)CheckSystemReadiness(...) check_system_readiness(verbose = TRUE)
... |
Arguments for the main function (for use by aliases). |
verbose |
If TRUE, print detailed information |
Invisibly, TRUE if all required packages, network access and CDS credentials are available, FALSE otherwise.
check_system_readiness()check_system_readiness()
Delete temporary files that match a pattern
cleanup_temp_files(pattern = "varunayan_.*", directory = tempdir())cleanup_temp_files(pattern = "varunayan_.*", directory = tempdir())
pattern |
Regular expression pattern to match files |
directory |
Directory for the search (default: tempdir()) |
Number of files removed
Clear all time 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 for the main function (for use by aliases). |
source |
Clear only "era5", "imd", "cru_ts", "hadex3", or NULL for all |
older_than |
Remove files that are older than this number of 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 NetCDF files into one 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. If TRUE, the function prints progress messages |
data.frame with combined data from all files
Compare two or more 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) |
Data in GeoJSON format
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 that shows 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 a unique filename |
Path to temporary GeoJSON file
The default chunk size is compute_optimal_chunk_size(frequency). This size
changes with the CDS field limit (hourly: 24 fields/day, daily: 1/day,
monthly: 12/year). Thus, 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. If NA (default), the function
calculates the value from frequency with |
List of date pairs, with one pair for each chunk
Downloads CRU TS v4.07 monthly gridded climate data and filters the data to a geographic bounding box. The data is for the global land areas at a resolution of 0.5 degrees, for 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 that the aliases send to the primary function. |
variable |
CRU TS variable code. See |
start_year |
Start year (1901-2022). |
end_year |
End year (1901-2022). |
north |
North boundary (latitude). |
south |
South boundary (latitude). |
east |
East boundary (longitude). |
west |
West boundary (longitude). |
output_dir |
Directory for temporary files (default: |
use_cache |
If TRUE, use the data in the cache (default: TRUE). |
A data.frame with the 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 CRU TS v4.07 monthly gridded climate data and filters the data to a geographic region. A GeoJSON polygon defines the region.
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 that the aliases send to the primary function. |
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 that defines the region. |
output_dir |
Directory for temporary files (default: |
use_cache |
If TRUE, use the data in the cache (default: TRUE). |
A data.frame with the 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 that the aliases send to the primary function. |
variables |
Character vector of variable names to describe |
dataset_type |
Character string that gives the 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 with 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 |
If TRUE, use cached data when it is available (default: TRUE) |
verbose |
Logical. If TRUE, print progress messages |
Character string path to downloaded file
Download ERA5 single-level data with 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 |
If TRUE, use cached data when it is available (default: TRUE) |
verbose |
Logical. If TRUE, print progress messages |
Character string path to downloaded file
Downloads daily gridded rainfall data from IMD at the 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 for the downloaded files. |
use_cache |
If TRUE, use the cached data when it is available (default: TRUE). |
Character vector of the paths to the downloaded files.
# 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 (maximum or minimum) from IMD. Temperature data is available only at 1.0 degree resolution.
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 for the downloaded files. |
use_cache |
If TRUE, use the cached data when it is available (default: TRUE). |
Character vector of the paths to the downloaded files.
# Download maximum temperature for 2023-2025 files <- download_imd_temperature( start_year = 2023, end_year = 2025, var_type = "tmax" )# Download maximum temperature for 2023-2025 files <- download_imd_temperature( start_year = 2023, end_year = 2025, var_type = "tmax" )
Create the output directory if it does not exist
ensure_output_dir(output_dir)ensure_output_dir(output_dir)
output_dir |
Path to output directory |
Character string. The path to the directory that the function made or found
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 |
If TRUE, save the raw downloaded files. |
output_dir |
Directory for the saved files (default: tempdir()). |
use_cache |
If TRUE, use cached data when it is available (default: TRUE). |
convert_units |
If TRUE, convert units to user-friendly formats (default: TRUE). When TRUE, the function returns temperature variables in Celsius (converted from Kelvin). It returns precipitation variables in mm (converted from meters). |
verbose |
If TRUE, 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 mm.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 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 |
If TRUE, save the raw downloaded files. |
output_dir |
Directory for the saved files (default: tempdir()). |
use_cache |
If TRUE, use cached data when it is available (default: TRUE). |
convert_units |
If TRUE, convert units to user-friendly formats (default: TRUE). When TRUE, the function returns temperature variables in Celsius (converted from Kelvin). It returns precipitation variables in mm (converted from meters). |
verbose |
If TRUE, print detailed progress messages. |
use_timeseries_api |
If TRUE, use the CDS time-series endpoint. This endpoint gives the data for a point directly. It is much faster than a subset of a gridded download. The default is NA: use the endpoint only for hourly single-level requests, because the endpoint supports only these requests. Set FALSE to always use the gridded download. If the endpoint is not available, the function automatically uses the gridded download. |
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 mm.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 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"))
Aggregation does not apply to these coordinate and metadata columns.
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 a specified point location (nearest neighbor)
extract_point_data(netcdf_file, target_lat, target_lon)extract_point_data(netcdf_file, target_lat, target_lon)
netcdf_file |
Path to the NetCDF file, as a character string |
target_lat |
Target latitude |
target_lon |
Target longitude |
data.frame with data for the nearest point
This function does a test of only the unique (lat, lon) coordinates against the polygon. Then it joins the result to the full dataset with a 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 |
Latitude of the north boundary |
south |
Latitude of the south boundary |
east |
Longitude of the east boundary |
west |
Longitude of the west 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 the 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 |
Path to the NetCDF file, as a character string |
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 |
Path to the NetCDF file, as a character string |
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 the character format necessary for the 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 |
If TRUE, do not show information messages |
TRUE if credentials are available, FALSE otherwise.
get_cds_credentials()get_cds_credentials()
Returns the grid specifications for an IMD dataset.
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 the dataset of pressure-level variables
get_pressure_level_variables()get_pressure_level_variables()
List that contains the 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 the dataset of single-level variables
get_single_level_variables()get_single_level_variables()
List that contains the single-level variable categories
Get time values for a frequency
get_time_values(frequency)get_time_values(frequency)
frequency |
Character string that gives the temporal frequency |
Character vector of time strings
Get all recorded time measurements
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 the standard pressure levels that are available in ERA5
GetAvailablePressureLevels(...) get_available_pressure_levels()GetAvailablePressureLevels(...) get_available_pressure_levels()
... |
Arguments that the aliases send to the primary function. |
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 for the main function (for use by aliases). |
create |
Create the directory when it does not exist (default: TRUE) |
Character string with cache directory path
get_cache_dir(create = FALSE)get_cache_dir(create = FALSE)
Downloads ERA5 temperature data for a country and aggregates the data.
The function finds the country boundary and downloads monthly data with
era5ify_geojson(). It returns country-level averages for each year and
month, with area weights (cosine of latitude).
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, ... )
... |
More arguments that the function sends to |
country |
One of: a country name string (the function uses
|
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. If you do not supply it, the function makes it from the country name. |
resolution |
Spatial resolution in degrees (default: 0.25). |
verbose |
If TRUE, show detailed progress messages. |
A data.frame with the columns year, month, and one column for
each requested variable (for example, temperature_mean, temperature_max,
temperature_min). The 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 the USA get_era5_country_temperature("USA", "2023-01-01", "2023-12-31", variables = c("mean", "max") ) # Use 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 the USA get_era5_country_temperature("USA", "2023-01-01", "2023-12-31", variables = c("mean", "max") ) # Use an sf object directly library(sf) poly <- st_read("my_country.geojson") get_era5_country_temperature(poly, "2023-01-01", "2023-06-30")
This function downloads 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 the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 )
This function downloads ERA5 temperature, dewpoint, and wind data for a region. Then it calculates the 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 the GeoJSON file that defines the region (for the geojson method) |
north |
Northern latitude boundary (for the bbox method) |
south |
Southern latitude boundary (for the bbox method) |
east |
Eastern longitude boundary (for the bbox method) |
west |
Western longitude boundary (for the bbox method) |
solar_load |
If TRUE, include solar radiation in the calculations (default: FALSE). If TRUE, the function downloads solar radiation data and uses these data for WBGT and UTCI. |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data when the data is available (default: TRUE) |
verbose |
If TRUE, the function prints 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. If solar_load=TRUE, the data.frame also contains 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 )
This function downloads temperature and dewpoint data. Then it calculates the 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 the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 )
This function downloads temperature and dewpoint data. Then it calculates RH and the 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 the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 )
This function downloads the 10m wind components. Then it calculates the 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 the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 )
This function downloads ERA5 heat stress indices and aggregates them to the specified 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 (for example, 2023) |
month |
Month (1-12) |
json_file |
Path to the GeoJSON file that defines the region |
north, south, east, west
|
Bounding box coordinates (alternative to json_file) |
solar_load |
If TRUE, include solar radiation (default: FALSE) |
resolution |
Spatial resolution in degrees (default: 0.25) |
use_cache |
If TRUE, the function uses cached data (default: TRUE) |
verbose |
If TRUE, the function prints 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 for the main function (for use 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()
Downloads HadEX3 data on ETCCDI climate extremes and filters the data to a geographic bounding box. The data is for 1901-2018 at a resolution of 1.25 x 1.875 degrees.
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 that the aliases send to the primary function. |
index |
ETCCDI index name (e.g. "TXx", "Rx1day"). See |
start_year |
Start year (1901-2018). |
end_year |
End year (1901-2018). |
north |
North boundary (latitude). |
south |
South boundary (latitude). |
east |
East boundary (longitude). |
west |
West boundary (longitude). |
frequency |
Temporal frequency: "annual" or "monthly" (default: "annual"). |
baseline |
Reference period for the indices that use percentiles: "61-90" (default) or "81-10". This argument applies only to the annual frequency. |
output_dir |
Directory for temporary files (default: |
use_cache |
If TRUE, use the data in the cache (default: TRUE). |
A data.frame with the columns: year (and month for monthly data), latitude, longitude, value, index.
# Annual maximum of the 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 of the 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 HadEX3 data on ETCCDI climate extremes and filters the data to a geographic region. A GeoJSON polygon defines the region.
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 that the aliases send to the primary function. |
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 that defines the region. |
frequency |
Temporal frequency: "annual" or "monthly" (default: "annual"). |
baseline |
Reference period for the indices that use percentiles: "61-90" (default) or "81-10". This argument applies only to the annual frequency. |
output_dir |
Directory for temporary files (default: |
use_cache |
If TRUE, use the data in the cache (default: TRUE). |
A data.frame with the columns: year (and month for monthly data), 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 a 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)
This function puts heat index values into heat stress risk categories. It uses the NWS categories.
heat_index_risk_category(hi)heat_index_risk_category(hi)
hi |
Heat index value in Celsius |
Factor with the risk category
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)
imd_temperature_geojson() returns the grid points in the GeoJSON boundary.
This function is different. It returns one row for each feature (for example,
each state) and each time period. Each row contains the mean temperature of
the region.
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 file. Each feature in the file is one region. |
feature_col |
Name of the GeoJSON property that sets the groups (for
example, |
var_type |
|
frequency |
|
use_cache |
If TRUE, use the cached IMD downloads when they are available (default TRUE). |
A data.frame with the columns region, year, month (only for monthly data), and temperature.
temp <- tryCatch( imd_temperature_by_region( request_id = "demo_region", start_year = 2023, end_year = 2023, geojson_file = system.file("extdata", "region.geojson", package = "varunayan"), var_type = "tmax", frequency = "monthly", use_cache = FALSE ), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )temp <- tryCatch( imd_temperature_by_region( request_id = "demo_region", start_year = 2023, end_year = 2023, geojson_file = system.file("extdata", "region.geojson", package = "varunayan"), var_type = "tmax", frequency = "monthly", use_cache = FALSE ), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )
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 |
Latitude of the north boundary. |
south |
Latitude of the south boundary. |
east |
Longitude of the east boundary. |
west |
Longitude of the west boundary. |
baseline |
Climatology years, |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is 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 keeps only the data in the 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 that the aliases send to the primary function. |
request_id |
Unique identifier for the request. |
start_year |
Start year. |
end_year |
End year. |
north |
Latitude of the north boundary. |
south |
Latitude of the south boundary. |
east |
Longitude of the east boundary. |
west |
Longitude of the west boundary. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency: "daily", "monthly", "yearly" (default: "daily"). |
save_raw |
If TRUE, keep the raw downloaded files (default: FALSE). |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is 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 that the aliases send to the primary function. |
request_id |
Unique identifier for the request. |
start_year |
Start year (1901-2025). |
end_year |
End year (1901-2025). |
geojson_file |
Path to the GeoJSON file. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
If TRUE, keep the raw files (default: FALSE). |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is 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 that is nearest to a (lat, lon) point. For each year, the function reads only that one cell from the disk. Thus, this function is the method with the lowest cost to get a long series for one 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 that the aliases send to the primary function. |
request_id |
Unique identifier for the request. |
start_year |
Start year (1901-2024). |
end_year |
End year (1901-2024). |
latitude |
Latitude of the point. |
longitude |
Longitude of the point. |
resolution |
Spatial resolution: 0.25 or 1.0 degrees (default: 0.25). |
frequency |
Temporal frequency: "daily", "monthly", "yearly" (default: "daily"). |
save_raw |
If TRUE, keep the raw downloaded files (default: FALSE). |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is available (default: TRUE). |
data.frame with the rainfall series of the nearest cell.
powai <- tryCatch( imd_rainfall_point("powai", 2023, 2023, 19.1277, 72.9047, resolution = 1, use_cache = FALSE ), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )powai <- tryCatch( imd_rainfall_point("powai", 2023, 2023, 19.1277, 72.9047, resolution = 1, use_cache = FALSE ), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )
Gets the India Meteorological Department (IMD) city-weather station list.
As an option, it also gets the latitude and longitude of each station. The
legacy IMD endpoints give only the station names. The responsive IMD site
gives a JSON record for each station (api/fetchCity_static.php). This record
contains lat and lon. The function adds these values to the station list.
You can use the returned coordinates directly as input to era5ify_point().
You can also use them to make maps.
IMDStations(...) imd_stations( with_coordinates = TRUE, cores = if (.Platform$OS.type == "windows") 1L else 2L )IMDStations(...) imd_stations( with_coordinates = TRUE, cores = if (.Platform$OS.type == "windows") 1L else 2L )
... |
Not used. This argument is necessary for compatibility with the aliases. |
with_coordinates |
Logical. If |
cores |
Integer. The number of parallel workers that get the
coordinates (the function sends this value to |
A data.frame with the columns station_id and name. If
with_coordinates = TRUE, the data frame also has the columns latitude
and longitude. The value is NA if IMD has no coordinate for a station.
stations <- tryCatch( imd_stations(with_coordinates = FALSE), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )stations <- tryCatch( imd_stations(with_coordinates = FALSE), error = function(e) message("IMD server unavailable: ", conditionMessage(e)) )
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 that the aliases send to the primary function. |
request_id |
Unique identifier for the request. |
start_year |
Start year (1951-2025). |
end_year |
End year (1951-2025). |
north |
Latitude of the north boundary. |
south |
Latitude of the south boundary. |
east |
Longitude of the east boundary. |
west |
Longitude of the west boundary. |
var_type |
Temperature type: "tmax" or "tmin". |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
If TRUE, keep the raw files (default: FALSE). |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is 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 that the aliases send to the primary function. |
request_id |
Unique identifier for the request. |
start_year |
Start year (1951-2025). |
end_year |
End year (1951-2025). |
geojson_file |
Path to the GeoJSON file. |
var_type |
Temperature type: "tmax" or "tmin". |
frequency |
Temporal frequency (default: "daily"). |
save_raw |
If TRUE, keep the raw files (default: FALSE). |
output_dir |
Directory for the output files (default: tempdir()). |
use_cache |
If TRUE, use the cached data when it is 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))
Find if a variable uses maximum aggregation
is_max_var(var_name)is_max_var(var_name)
var_name |
Variable name as a character string |
Logical. TRUE if the variable uses maximum aggregation
is_max_var("2m_temperature")is_max_var("2m_temperature")
Find if a variable uses minimum aggregation
is_min_var(var_name)is_min_var(var_name)
var_name |
Variable name as a character string |
Logical. TRUE if the variable uses minimum aggregation
is_min_var("2m_temperature")is_min_var("2m_temperature")
Find if a variable is a rate variable
is_rate_var(var_name)is_rate_var(var_name)
var_name |
Variable name as a character string |
Logical. TRUE if the variable is a rate
is_rate_var("2m_temperature")is_rate_var("2m_temperature")
Find if a variable uses sum aggregation
is_sum_var(var_name)is_sum_var(var_name)
var_name |
Variable name as a character string |
Logical. TRUE if the variable uses sum aggregation
is_sum_var("total_precipitation")is_sum_var("total_precipitation")
Find if data is valid GeoJSON
is_valid_geojson(data)is_valid_geojson(data)
data |
List or data structure to examine |
Logical. TRUE if the 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 the available IMD datasets and their properties.
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 that the aliases send to the primary function. |
dataset_type |
Character string that gives the dataset type |
Character vector of variable names
head(list_available_variables("single"))head(list_available_variables("single"))
Gives the common names, units, and ERA5 equivalents of the CRU TS variable codes.
ListCRUTSVariables(...) list_cru_ts_variables(...)ListCRUTSVariables(...) list_cru_ts_variables(...)
... |
Arguments that the aliases send to the primary function. |
A data.frame with the columns: variable, name, description, unit, era5_equivalent, hadex3_equivalent.
list_cru_ts_variables()list_cru_ts_variables()
Returns a data.frame that describes all the ETCCDI indices of climate extremes in the HadEX3 dataset. The data.frame shows the temporal availability and the physical quantity of each index.
ListHadEX3Indices(...) list_hadex3_indices(frequency = "all")ListHadEX3Indices(...) list_hadex3_indices(frequency = "all")
... |
Arguments that the aliases send to the primary function. |
frequency |
Filter by frequency: "annual", "monthly", or "all" (default). |
A data.frame with the columns: index, category, description, unit, annual, monthly.
list_hadex3_indices() list_hadex3_indices(frequency = "monthly")list_hadex3_indices() list_hadex3_indices(frequency = "monthly")
Variables for maximum aggregation
max_varsmax_vars
A character vector of variable names.
head(max_vars)head(max_vars)
This function estimates the mean radiant temperature (Tmrt) from meteorological variables. If full radiation data is not available, the function uses a simplified method.
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 for 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 a date string in different formats
parse_date_flexible(date_string)parse_date_flexible(date_string)
date_string |
Character string in one of different date formats |
Date object
Copies sample IMD data files to the cache for offline tests.
PopulateSampleCache(...) populate_sample_cache(force = FALSE)PopulateSampleCache(...) populate_sample_cache(force = FALSE)
... |
Arguments for the main function (for use by aliases). |
force |
If TRUE, overwrite the cached files that exist (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 a summary of the time data
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. The year of each file. |
bbox |
Optional named list or vector (north, south, east, west). The function sends it to the rainfall reader, which crops the grid at read time. If NULL, the function 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))
This function uses ncdf4 to read the file quickly. If ncdf4 fails, it uses stars.
process_netcdf_to_dataframe(netcdf_file)process_netcdf_to_dataframe(netcdf_file)
netcdf_file |
Path to the NetCDF file, as a character string |
data.frame with processed climate data
Rate variables to average
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 the data to a data.frame.
read_imd_rainfall(file_path, resolution, year, bbox = NULL)read_imd_rainfall(file_path, resolution, year, bbox = NULL)
file_path |
Path to the IMD NetCDF file (.nc). |
resolution |
Spatial resolution: 0.25 or 1.0. |
year |
Year of the data. |
bbox |
Optional named list or vector (north, south, east, west). If you set it, the function reads only that spatial slab from the disk (fast path). If NULL, the function 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 (maximum or minimum) and converts the data to a data.frame.
read_imd_temperature(file_path, var_type, year)read_imd_temperature(file_path, var_type, year)
file_path |
Path to the 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)
This function uses the Magnus-Tetens approximation to calculate the relative humidity from the air temperature and the 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 a 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 that the aliases send to the primary function. |
keyword |
Character string to find in variable names and descriptions |
dataset_type |
Character string that gives the dataset type ("single", "pressure", or "all") |
exact_match |
Logical. If TRUE, use an exact match |
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 only in pressure level data pressure_temp <- search_variable("temperature", dataset_type = "pressure")# Search for temperature variables temp_vars <- search_variable("temperature") # Search only in pressure level data pressure_temp <- search_variable("temperature", dataset_type = "pressure")
This function configures the Copernicus Climate Data Store (CDS) credentials for ERA5 downloads. The function examines the credentials in this order:
The key argument that you give directly
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, the function tries to read
the key from the |
Invisibly, TRUE once the key has been registered with 'ecmwfr'. Errors if no key can be found.
setup_cds_credentials()setup_cds_credentials()
Show cache contents and statistics
ShowCacheInfo(...) show_cache_info()ShowCacheInfo(...) show_cache_info()
... |
Arguments for the main function (for use 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). Temporal aggregation uses the sum for these variables.
sum_varssum_vars
A character vector of variable names.
head(sum_vars)head(sum_vars)
Measure the time of an operation and record the duration
time_operation(expr, label, verbose = TRUE)time_operation(expr, label, verbose = TRUE)
expr |
Expression to measure |
label |
Label for the operation |
verbose |
If TRUE, print the time information (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()
This function uses the polynomial approximation of Bröde et al. (2012) to calculate UTCI. The approximation uses 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, the default is 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)
This function puts UTCI values into thermal stress categories.
utci_category(utci_val)utci_category(utci_val)
utci_val |
UTCI value in Celsius |
Factor with the thermal stress category
utci_category(c(-20, 0, 20, 30, 40))utci_category(c(-20, 0, 20, 30, 40))
This function uses the sparse regression approximation of Roman et al. (2025) to calculate UTCI. This approximation uses Legendre polynomials. It is more accurate than the original polynomial of Bröde et al. (2012). It has 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 a 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)
Make sure that bounding box coordinates are valid
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. TRUE if the bounding box is valid
Make sure that geographic coordinates are valid
validate_coordinates(lat, lon)validate_coordinates(lat, lon)
lat |
Latitude value |
lon |
Longitude value |
Logical. TRUE if the 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 that shows 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. The aliases keep 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, level = c("union", "feature") )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, level = c("union", "feature") )
... |
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 the GeoJSON file that defines 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 |
If TRUE, save the raw downloaded files |
output_dir |
Directory for the saved files (default: tempdir()) |
use_cache |
If TRUE, use cached data when it is available (default: TRUE) |
convert_units |
If TRUE, convert units to user-friendly formats (default: TRUE). When TRUE, the function returns temperature variables in Celsius (converted from Kelvin). It returns precipitation variables in mm (converted from meters). |
verbose |
If TRUE, print detailed progress messages |
level |
|
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 mm.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 mm.
Show the overlap of grid points and polygons
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 the path to a NetCDF or CSV file |
polygons |
sf object, or the path to a GeoJSON file |
show_centroids |
Logical. If TRUE, show the 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 )
This function is an alias for wbgt_simple(). It calculates the 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 |
Factor with the risk category
wbgt_risk_category(c(25, 28, 31, 34))wbgt_risk_category(c(25, 28, 31, 34))
This function uses the indoor formula 0.7Tw + 0.3Ta. To get a closed-form
estimate from only temperature and humidity, 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)
This function uses the Stull (2011) empirical formula to calculate the wet bulb temperature. The formula is applicable to temperatures between -20C and 50C and to 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 a 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)