| Title: | Access and Process PISCO High-Resolution Climate Grids for Peru |
| Version: | 0.1.0 |
| Description: | Provides programmatic access, local caching, spatial subsetting, temporal aggregation, anomaly computation, and validation metrics for the Peruvian Interpolated data of SENAMHI's Climatological and hydrological Observations (PISCO) developed by SENAMHI DHI-SEH https://sites.google.com/view/dhi-seh/pisco. Supports the complete PISCO products included in its catalog: PISCOp v3.0 precipitation https://figshare.com/articles/dataset/High-resolution_grids_of_rainfall_for_Peru_-_PISCOp_v3_0_dataset/32411886, PISCOt v1.2 daily temperature and climatologies, PISCOeo_pm reference evapotranspiration climatology, PISCO_reed v1.0 rainfall erosivity, and PISCO_HyM GR2M and ARNOVIC streamflow with basin and river networks, hosted on Figshare https://figshare.com/articles/dataset/PISCO_HyM_GR2M_v1_1/14382758 and HydroShare. Includes optimized workflows for basin-scale extraction, seasonal aggregations, and spatial raster and vector processing based on 'terra' and 'sf'. |
| License: | MIT + file LICENSE |
| URL: | https://github.com/PaulESantos/rpisco |
| BugReports: | https://github.com/PaulESantos/rpisco/issues |
| Depends: | R (≥ 4.1.0) |
| Imports: | cli, ggplot2, grDevices, httr2, sf, stats, terra, tibble, tools |
| Suggests: | knitr, rmarkdown, testthat (≥ 3.0.0) |
| LazyData: | true |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-09 03:11:34 UTC; PC |
| Author: | Paul Efren Santos Andrade
|
| Maintainer: | Paul Efren Santos Andrade <paulefrens@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-29 13:30:02 UTC |
rpisco: Access and Process PISCO High-Resolution Climate Grids for Peru
Description
The rpisco package provides programmatic access, automated caching,
spatial subsetting, temporal analysis, and hydrological validation metrics
for the Peruvian Interpolated data of SENAMHI's Climatological and
hydrological Observations (PISCO).
Details
Supports the PISCO datasets included in the package catalog:
-
Precipitation (PISCOp): PISCOp v3.0 (1981-2025; daily, monthly, and climatological normal).
-
Temperature (PISCOt): PISCOt v1.2 (maximum and minimum daily data and climatological normals).
-
Evapotranspiration (PISCOeo_pm): PISCOeo_pm monthly climatological reference evapotranspiration.
-
Rainfall Erosivity (PISCO_reed): PISCO_reed v1.0 (1981-2016; R-factor climatology and annual erosivity series).
-
Streamflow (PISCO_HyM): Monthly gridded and vector streamflow (1981-2016) based on hydrological modeling (GR2M and ARNOVIC) with sub-basin polygons and river reach networks.
Datasets are hosted on Figshare and HydroShare by SENAMHI and collaborating
researchers. See pisco_catalog and pisco_citation
for links, dataset keys, and scientific citations.
Author(s)
Maintainer: Paul Efren Santos Andrade paulefrens@gmail.com (ORCID) [copyright holder]
Authors:
Paul Efren Santos Andrade paulefrens@gmail.com (ORCID) [copyright holder]
Other contributors:
Leonardo Gutierrez (ORCID) [data contributor]
Waldo Sven Lavado-Casimiro [data contributor]
See Also
Useful links:
Datos climatológicos de prueba para climatodiagramas
Description
Conjunto de datos de prueba con 12 observaciones mensuales representativas de una estación andina (julio a junio), conteniendo temperatura media mensual y precipitación total mensual para la construcción de climatodiagramas de Walter-Lieth.
Usage
clima_ejemplo
Format
Un data frame con 12 filas y 3 columnas:
- MES
Abreviatura del mes de registro (
"Jul"a"Jun").- TMED
Temperatura media mensual en grados Celsius (
^\circC).- PTOT
Precipitación total mensual en milímetros (mm).
Source
Elaboración propia con datos climatológicos típicos de la región andina.
See Also
Examples
data(clima_ejemplo)
head(clima_ejemplo)
Climatodiagrama de Walter-Lieth
Description
Dibuja un climatodiagrama de Walter-Lieth a partir de la temperatura media
mensual y la precipitación media mensual de una estación meteorológica.
Devuelve un objeto ggplot2::ggplot(), por lo que se puede seguir
modificando con + (temas, títulos, etc.) y guardar con
ggplot2::ggsave().
Usage
climatodiagrama(
datos,
estacion,
elevacion,
anios,
estilo = c("color", "trama"),
col_mes = "MES",
col_temp = "TMED",
col_prec = "PTOT",
color_seco = NULL,
color_humedo = NULL,
color_perhumedo = NULL,
color_temp = NULL,
color_prec = NULL,
color_fondo = "white",
alpha_area = 0.85,
grosor_linea = 1,
densidad_trama = 0.07,
leyenda = TRUE,
res = 100
)
Arguments
datos |
Data frame o tibble con 12 filas y las columnas del mes, la temperatura media mensual (°C) y la precipitación media mensual (mm). |
estacion |
Nombre de la estación meteorológica (texto). |
elevacion |
Elevación de la estación en m s. n. m. |
anios |
Años de registro. Un valor ( |
estilo |
Estilo de las áreas: |
col_mes, col_temp, col_prec |
Nombres de las columnas de |
color_seco, color_humedo, color_perhumedo |
Colores de los periodos seco,
húmedo y perhúmedo. En |
color_temp, color_prec |
Colores de las curvas de temperatura y de precipitación. También se usan para los títulos de los ejes. |
color_fondo |
Color de fondo del panel. Por defecto |
alpha_area |
Transparencia (0 a 1) del relleno de las áreas. Solo se
aplica a |
grosor_linea |
Grosor de las curvas de temperatura y precipitación.
Por defecto |
densidad_trama |
Separación horizontal entre rayas y puntos, en
unidades de mes: un valor menor da una trama más densa. Solo se aplica a
|
leyenda |
Si es |
res |
Número de puntos usados para interpolar cada tramo entre meses.
Valores más altos dan un cruce más preciso entre las curvas. Por defecto
|
Details
Convención de Walter-Lieth. La temperatura y la precipitación se representan con una relación de 1 °C = 2 mm. Cuando la curva de precipitación queda por debajo de la de temperatura el periodo es seco (la precipitación no compensa la evapotranspiración); cuando queda por encima, el periodo es húmedo. Por encima de 100 mm la escala de precipitación se comprime 10 veces y esa zona se considera perhúmeda.
Estilos.
-
estilo = "color": las zonas se rellenan con color y se añade una leyenda. -
estilo = "trama": estilo clásico en blanco y negro. El periodo seco se dibuja con rayas verticales, el húmedo con puntos y el perhúmedo con relleno sólido. Los segmentos se dibujan congeom_segment(), así que no se necesitan paquetes adicionales. La leyenda se muestra como texto al pie del gráfico.
Colores. Todos los argumentos color_* aceptan nombres de color de R
(p. ej. "firebrick") o códigos hexadecimales (p. ej. "#E8B04A"). Si se
dejan en NULL se usan los colores por defecto del estilo elegido. En
estilo = "trama", color_seco y color_humedo son los colores de las
rayas y de los puntos.
Datos de entrada. datos debe tener exactamente 12 filas (un mes por
fila, en el orden en que se quieran mostrar; tradicionalmente de julio a
junio en el hemisferio sur). Los nombres de las columnas pueden cambiarse
con col_mes, col_temp y col_prec.
Value
Un objeto ggplot2::ggplot().
References
Walter, H. y Lieth, H. (1960). Klimadiagramm-Weltatlas. VEB Gustav Fischer Verlag, Jena.
See Also
clima_ejemplo para un conjunto de datos de prueba.
Examples
# Estilo con colores (por defecto)
climatodiagrama(clima_ejemplo,
estacion = "Estación de ejemplo", elevacion = 2000,
anios = "6")
# Estilo clásico de rayas y puntos en blanco y negro
climatodiagrama(clima_ejemplo,
estacion = "Estación de ejemplo", elevacion = 2000,
anios = "6", estilo = "trama")
# Trama con colores propios
climatodiagrama(clima_ejemplo,
estacion = "Estación de ejemplo", elevacion = 2000,
anios = "6", estilo = "trama",
color_seco = "#B2182B", color_humedo = "#2166AC",
color_perhumedo = "grey20")
# Colores personalizados y años de registro distintos (temperatura-precipitación)
climatodiagrama(clima_ejemplo,
estacion = "Estación de ejemplo", elevacion = 2000,
anios = "5-6",
color_seco = "#D95F02", color_humedo = "#66C2A5",
color_perhumedo = "#08306B",
color_temp = "#B2182B", color_prec = "#2166AC",
color_fondo = "#FAFAF5", alpha_area = 0.9)
# Como devuelve un ggplot, se puede seguir modificando
climatodiagrama(clima_ejemplo, "Estación de ejemplo", 2000, "6") +
ggplot2::theme(text = ggplot2::element_text(family = "serif"))
# Guardar y leer datos desde un archivo temporal CSV
tf <- tempfile(fileext = ".csv")
utils::write.csv(clima_ejemplo, tf, row.names = FALSE)
datos <- utils::read.csv(tf)
g <- climatodiagrama(datos, "ROCOTAL", 2010, "6")
tf_png <- tempfile(fileext = ".png")
ggplot2::ggsave(tf_png, g, width = 7, height = 5.5, dpi = 300)
unlink(c(tf, tf_png))
Temporal Aggregation of PISCO Rasters
Description
Aggregates a PISCO terra::SpatRaster across time: annual totals, monthly cycle, multi-year climatology, or SENAMHI hydrological seasons (Wet: Nov–Apr, Dry: May–Oct).
Usage
pisco_aggregate(
x,
by = c("year", "month", "season_senamhi", "hydrological_year", "climatology"),
fun = "sum"
)
Arguments
x |
A terra::SpatRaster with valid time attributes. |
by |
Character. Aggregation unit:
|
fun |
Character or function. Aggregation function ( |
Value
An aggregated terra::SpatRaster.
Examples
# Toy SpatRaster with time attribute
r <- terra::rast(xmin = -80, xmax = -70, ymin = -15, ymax = -5,
resolution = 1, crs = "EPSG:4326", nlyrs = 24)
terra::values(r) <- rep(1:24, each = terra::ncell(r))
terra::time(r) <- seq(as.Date("2000-01-01"), by = "month", length.out = 24)
# Annual rainfall accumulation (mm/year)
r_ann <- pisco_aggregate(r, by = "year", fun = "sum")
# Multi-year mean monthly cycle
r_cycle <- pisco_aggregate(r, by = "month", fun = "mean")
# Real PISCO download
r_pisco <- pisco_read("monthly")
r_seas <- pisco_aggregate(r_pisco, by = "season_senamhi", fun = "sum")
Calculate Rainfall Anomalies
Description
Computes precipitation anomalies relative to a baseline climatology (such as PISCOp_clim2
or a multi-year monthly mean). Anomalies can be expressed in absolute difference (mm)
or percentage deviation (\%).
Usage
pisco_anomaly(
x,
baseline = NULL,
type = c("percentage", "difference"),
eps = 0.1
)
Arguments
x |
A monthly terra::SpatRaster with valid time attributes. |
baseline |
Optional terra::SpatRaster of monthly normals (12 layers) representing
the climatological baseline (e.g. |
type |
Character. Type of anomaly: |
eps |
Numeric. Small epsilon to prevent division by zero in arid regions when |
Value
A terra::SpatRaster of anomalies with preserved time attributes.
Examples
# Toy SpatRasters
r_m <- terra::rast(xmin = -80, xmax = -70, ymin = -15, ymax = -5,
resolution = 1, crs = "EPSG:4326", nlyrs = 12)
terra::values(r_m) <- rep(50, terra::ncell(r_m) * 12)
terra::time(r_m) <- seq(as.Date("2000-01-01"), by = "month", length.out = 12)
r_clim <- terra::rast(xmin = -80, xmax = -70, ymin = -15, ymax = -5,
resolution = 1, crs = "EPSG:4326", nlyrs = 12)
names(r_clim) <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
terra::values(r_clim) <- rep(40, terra::ncell(r_clim) * 12)
# Absolute difference anomaly
anom_diff <- pisco_anomaly(r_m, baseline = r_clim, type = "difference")
# Percentage anomaly
anom_pct <- pisco_anomaly(r_m, baseline = r_clim, type = "percentage")
# Real PISCO download
r_m <- pisco_read("monthly", dates = c(1997, 1998))
r_clim <- pisco_read("climatology")
anom_pct <- pisco_anomaly(r_m, baseline = r_clim, type = "percentage")
PISCO Cache Management
Description
Functions to inspect, set, and clear the local cache directory used by
rpisco to store downloaded NetCDF files.
Usage
pisco_cache_dir(path = NULL)
pisco_cache_status()
pisco_cache_clear(dataset = "all")
Arguments
path |
Character. Custom path to set as cache. If |
dataset |
Character. Dataset name ( |
Value
A character path to the cache directory, or logical status invisibly.
Examples
pisco_cache_dir()
pisco_cache_status()
Catalog of PISCO Products
Description
Lists the available PISCO datasets, variables, metadata, temporal ranges, resolution, official file names, hosting repositories, and local cache status across the full PISCO family (SENAMHI DHI-SEH).
Usage
pisco_catalog(
variable = c("all", "precipitation", "temperature", "evapotranspiration", "erosivity",
"streamflow"),
dataset = NULL,
refresh = FALSE
)
Arguments
variable |
Character. Variable filter: |
dataset |
Character. Optional dataset filter (e.g., |
refresh |
Logical. If |
Value
A tibble::tibble containing metadata for the selected PISCO datasets.
Examples
# Complete catalog
pisco_catalog()
# Filter by variable family
pisco_catalog("precipitation")
pisco_catalog("temperature")
pisco_catalog("streamflow")
# Filter by specific dataset
pisco_catalog(dataset = "tmax_daily")
pisco_catalog(dataset = "climatology")
Citation Information for PISCO Products
Description
Prints and returns official citation metadata for datasets in the PISCO family and their associated scientific publications from SENAMHI and international journals.
Usage
pisco_citation(
dataset = c("all", "precipitation", "temperature", "evapotranspiration", "erosivity",
"streamflow"),
format = c("text", "bibtex"),
variable = NULL
)
pisco_cite(
dataset = c("all", "precipitation", "temperature", "evapotranspiration", "erosivity",
"streamflow"),
format = c("text", "bibtex"),
variable = NULL
)
Arguments
dataset |
Character. Filter citations for a specific dataset or group:
|
format |
Character. Citation format: |
variable |
Character. Optional alias for |
Value
A character string containing the requested citation (invisibly if printed).
Examples
# Citation for all PISCO products
pisco_citation()
# BibTeX for temperature (PISCOt v1.2)
pisco_citation("temperature", format = "bibtex")
# Using variable = "precipitation"
pisco_citation(variable = "precipitation")
# Citation for streamflow (PISCO_HyM)
pisco_citation("streamflow")
Spatial Cropping and Masking for PISCO Rasters
Description
Crops and masks a PISCO terra::SpatRaster using a vector polygon (sf or SpatVector),
an sf::st_bbox object, or a spatial bounding box numeric vector.
Usage
pisco_clip(x, mask, crop_only = FALSE, touches = TRUE, ...)
Arguments
x |
A terra::SpatRaster object. |
mask |
An |
crop_only |
Logical. If |
touches |
Logical. If |
... |
Additional arguments passed directly to |
Value
A cropped (and optionally masked) terra::SpatRaster.
Examples
# Toy SpatRaster
r <- terra::rast(xmin = -80, xmax = -70, ymin = -15, ymax = -5,
resolution = 0.5, crs = "EPSG:4326")
terra::values(r) <- seq_len(terra::ncell(r))
# Crop by bounding box (c(xmin, ymin, xmax, ymax))
r_sub <- pisco_clip(r, mask = c(-78, -12, -76, -10))
# Crop and mask using an sf polygon
pt <- sf::st_point(c(-75, -10))
poly_sf <- sf::st_sf(data.frame(id = 1),
geometry = sf::st_sfc(sf::st_buffer(pt, 1), crs = 4326))
r_basin <- pisco_clip(r, mask = poly_sf)
# Real PISCO download
r_pisco <- pisco_read("monthly")
r_sub <- pisco_clip(r_pisco, mask = c(-77.5, -12.5, -76.0, -11.5))
Download PISCO Datasets
Description
Downloads a PISCO dataset from official repositories (Figshare or HydroShare)
to the local cache directory. If the file is already cached, download is skipped
unless overwrite = TRUE.
Usage
pisco_download(
dataset = c("monthly", "daily", "climatology", "tmax_daily", "tmin_daily", "tmax_clim",
"tmin_clim", "eto_clim", "erosivity_r", "erosivity_density", "streamflow_monthly",
"streamflow_daily", "catchments_gr2m", "rivers_gr2m"),
destdir = pisco_cache_dir(),
overwrite = FALSE,
verify_md5 = TRUE,
timeout = 3600,
quiet = FALSE,
refresh = TRUE
)
Arguments
dataset |
Character. The dataset to download:
|
destdir |
Character. Destination directory. Default is |
overwrite |
Logical. If |
verify_md5 |
Logical. If |
timeout |
Numeric. Maximum seconds to allow for download. Default is 3600 (1 hour). |
quiet |
Logical. If |
refresh |
Logical. If |
Value
Character. The absolute path to the downloaded (or cached) file.
Examples
# Download monthly precipitation (56.6 MB)
fpath_pr <- pisco_download("monthly")
# Download climatological normal maximum temperature (0.52 MB)
fpath_tx <- pisco_download("tmax_clim")
# Download rainfall erosivity R-factor (1.75 MB)
fpath_re <- pisco_download("erosivity_r")
Spatial Coverage Extent of PISCO
Description
Returns the official geographic bounding coordinates for the PISCOp v3.0 domain, covering Peru and its transboundary hydrologic basins (2 deg N to 19 deg S, 64 deg W to 82 deg W).
Usage
pisco_extent(format = c("vector", "bbox", "ext"))
pisco_bbox()
Arguments
format |
Character. Output format: |
Value
A named numeric vector, sf::st_bbox, or terra::ext representing the domain boundaries.
Examples
pisco_extent()
pisco_extent("bbox")
pisco_extent("ext")
Extract Time Series from PISCO Rasters
Description
Extracts precipitation time series from a PISCO terra::SpatRaster at given point coordinates or computes zonal summaries (e.g. areal mean) over spatial polygons.
Usage
pisco_extract(x, points = NULL, polygons = NULL, fun = "mean", id_col = NULL)
Arguments
x |
A terra::SpatRaster object. |
points |
Optional. An |
polygons |
Optional. An |
fun |
Character or function. Summary statistic when extracting across polygons
(e.g., |
id_col |
Character. Name of the column in |
Value
A tibble::tibble containing the extracted time series in tidy format.
Examples
# Toy SpatRaster with time attribute
r <- terra::rast(xmin = -80, xmax = -70, ymin = -15, ymax = -5,
resolution = 0.5, crs = "EPSG:4326", nlyrs = 6)
terra::values(r) <- rep(1:6, each = terra::ncell(r))
terra::time(r) <- seq(as.Date("2020-01-01"), by = "month", length.out = 6)
# Extract at point coordinates
df_pt <- pisco_extract(r, points = c(-75.5, -10.5))
# Extract areal means over polygons
p1 <- sf::st_buffer(sf::st_point(c(-76, -11)), 0.8)
poly_sf <- sf::st_sf(basin_name = "Rimac",
geometry = sf::st_sfc(p1, crs = 4326))
df_basin <- pisco_extract(r, polygons = poly_sf, id_col = "basin_name")
# Real PISCO download
r_pisco <- pisco_read("monthly")
df_pt <- pisco_extract(r_pisco, points = c(-71.96, -13.53))
Statistical Validation Metrics for PISCO
Description
Implements the statistical evaluation metrics used in the official PISCOp v3.0 validation report (Gutierrez & Lavado-Casimiro, 2025; Willmott et al., 2012):
Pearson correlation coefficient (COR)
Refined Index of Agreement (
d_r) (Willmott et al., 2012)Normalized Mean Bias (NMB, \
Normalized Mean Gross Error (NMGE)
Root Mean Squared Error (RMSE)
Mean Absolute Error (MAE)
Usage
pisco_metric_cor(sim, obs, na.rm = TRUE)
pisco_metric_dr(sim, obs, na.rm = TRUE)
pisco_metric_nmb(sim, obs, na.rm = TRUE)
pisco_metric_nmge(sim, obs, na.rm = TRUE)
pisco_metrics(sim, obs, na.rm = TRUE)
Arguments
sim |
Numeric vector of simulated or gridded values (e.g. PISCO). |
obs |
Numeric vector of observed values (e.g. rain gauge stations). |
na.rm |
Logical. If |
Value
pisco_metrics() returns a tibble::tibble containing all validation metrics.
Examples
obs <- c(12.5, 34.2, 0.0, 5.4, 60.1, 105.3)
sim <- c(10.1, 31.0, 0.2, 7.8, 55.0, 98.4)
pisco_metrics(sim, obs)
pisco_metric_dr(sim, obs)
pisco_metric_nmb(sim, obs)
pisco_metric_nmge(sim, obs)
Read PISCO Datasets as SpatRaster or sf Vector
Description
Reads a PISCO dataset into memory or memory-mapped objects (terra::SpatRaster
for raster grids, or sf for catchment/river vector layers). If the file is
not present locally, it can be downloaded after the caller explicitly sets
download = TRUE.
Usage
pisco_read(
dataset = c("monthly", "daily", "climatology", "tmax_daily", "tmin_daily", "tmax_clim",
"tmin_clim", "eto_clim", "erosivity_r", "erosivity_density", "streamflow_monthly",
"streamflow_daily", "catchments_gr2m", "rivers_gr2m"),
file = NULL,
dates = NULL,
aoi = NULL,
mask = NULL,
download = FALSE
)
Arguments
dataset |
Character. The dataset to load:
|
file |
Character. Optional custom path to a PISCO NetCDF or GeoPackage file.
If |
dates |
Vector of dates, years, year-months, or indices to filter layers.
|
aoi |
Optional spatial object ( |
mask |
Optional spatial mask. Same as |
download |
Logical. If |
Value
A terra::SpatRaster object (for gridded data) or an sf object (for vector hydrography).
Examples
# Read monthly precipitation
r_pr <- pisco_read("monthly")
# Read normal maximum temperature 1981-2010
r_tx <- pisco_read("tmax_clim")
# Read reference evapotranspiration climatology
r_eto <- pisco_read("eto_clim")
# Read rainfall erosivity R-factor
r_ero <- pisco_read("erosivity_r")
Refresh PISCO download metadata from public repositories
Description
Queries the public Figshare and HydroShare metadata APIs and refreshes the download URLs, file sizes, and checksums held in the current R session. This operation retrieves metadata only; it never downloads a PISCO data file. It is opt-in so package loading and ordinary reads remain offline.
Usage
pisco_refresh_catalog(timeout = 30, quiet = FALSE)
Arguments
timeout |
Numeric. Maximum seconds for each metadata request. |
quiet |
Logical. If |
Value
A tibble::tibble with refreshed metadata, invisibly.
Examples
pisco_refresh_catalog()
Plot SpatRaster and SpatVector Objects
Description
S3 plot methods for terra::SpatRaster and terra::SpatVector objects,
ensuring that plot(r) works seamlessly when rpisco is loaded, even if
library(terra) has not been explicitly attached.
Usage
## S3 method for class 'SpatRaster'
plot(x, y, ...)
## S3 method for class 'SpatVector'
plot(x, y, ...)
Arguments
x |
A |
y |
Optional second argument for bivariate plotting in terra. |
... |
Additional graphical parameters forwarded to |
Value
Invisibly returns the plotted object or NULL, creating a plot on the active device.