Package 'rpisco'

Title: Access and Process PISCO High-Resolution Climate Grids for Peru
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'.
Authors: Paul Efren Santos Andrade [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6635-0375>), Leonardo Gutierrez [dtc] (ORCID: <https://orcid.org/0000-0002-8658-139X>), Waldo Sven Lavado-Casimiro [dtc]
Maintainer: Paul Efren Santos Andrade <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-11-29 19:45:01 UTC
Source: https://github.com/cran/rpisco

Help Index


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

climatodiagrama

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 ("6") si la temperatura y la precipitación tienen el mismo periodo de registro, o dos valores separados por un guion ("5-6"): el primero para la temperatura y el segundo para la precipitación.

estilo

Estilo de las áreas: "color" (por defecto) o "trama" (rayas y puntos en blanco y negro). Ver Details.

col_mes, col_temp, col_prec

Nombres de las columnas de datos con el mes, la temperatura media y la precipitación total. Por defecto "MES", "TMED" y "PTOT".

color_seco, color_humedo, color_perhumedo

Colores de los periodos seco, húmedo y perhúmedo. En estilo = "trama" son los colores de las rayas (seco), los puntos (húmedo) y el relleno sólido (perhúmedo).

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 "white".

alpha_area

Transparencia (0 a 1) del relleno de las áreas. Solo se aplica a estilo = "color". Por defecto 0.85.

grosor_linea

Grosor de las curvas de temperatura y precipitación. Por defecto 1.

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 estilo = "trama". Por defecto 0.07.

leyenda

Si es TRUE (por defecto) se muestra la leyenda (o el texto explicativo en estilo = "trama").

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 100.

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 con geom_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:

  • "year": Aggregates across each calendar year (e.g., annual rainfall).

  • "month": Multi-year monthly aggregation (produces 12 layers for Jan–Dec).

  • "season_senamhi": SENAMHI official hydrological seasons: Wet season (wet_Nov_Apr: Nov, Dec, Jan, Feb, Mar, Apr) and Dry season (dry_May_Oct: May, Jun, Jul, Aug, Sep, Oct). November and December are grouped with the following calendar year's hydrological period.

  • "hydrological_year": Annual aggregation based on the Peruvian hydrological year starting in November (Nov 1 to Oct 31).

  • "climatology": Multi-year monthly mean normals (12 layers).

fun

Character or function. Aggregation function ("sum", "mean", "max", etc.). Default is "sum" (for precipitation accumulations).

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. pisco_read("climatology")). If NULL, the baseline is computed internally as the multi-year monthly mean of x.

type

Character. Type of anomaly: "difference" (absolute anomaly: x - baseline in mm) or "percentage" (relative anomaly: ((x - baseline) / baseline) * 100 in \%). Default is "percentage".

eps

Numeric. Small epsilon to prevent division by zero in arid regions when type = "percentage". Default is 0.1 (mm).

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 NULL, returns current cache.

dataset

Character. Dataset name ("monthly", "daily", "climatology"), or "all" to remove every cached file known to rpisco. Files unrelated to rpisco are never removed.

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: "all", "precipitation", "temperature", "evapotranspiration", "erosivity", or "streamflow". Default is "all".

dataset

Character. Optional dataset filter (e.g., "monthly", "daily", "tmax_daily", "tmax_clim", "streamflow_monthly"). Supports all dataset aliases and file names. Default is NULL.

refresh

Logical. If TRUE, explicitly refreshes the in-session metadata from the Figshare and HydroShare APIs. This never downloads data.

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: "all", "precipitation" ("piscop"), "temperature" ("piscot"), "evapotranspiration" ("piscoeo"), "erosivity" ("pisco_reed"), or "streamflow" ("pisco_hym"). Default is "all".

format

Character. Citation format: "text" (formatted string for papers/reports) or "bibtex" (BibTeX entry). Default is "text".

variable

Character. Optional alias for dataset for consistency with pisco_catalog(). Default is NULL.

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 sf object, terra::SpatVector, sf::st_bbox, terra::SpatExtent, or numeric bounding box (c(xmin, ymin, xmax, ymax)).

crop_only

Logical. If TRUE, only crops to bounding box without masking values outside polygon. Default is FALSE.

touches

Logical. If TRUE, all cells touched by polygon boundaries are included in the mask. Default is TRUE (matching default terra::mask() behavior).

...

Additional arguments passed directly to terra::crop().

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:

  • Precipitation: "monthly" ("PISCOp_m"), "daily" ("PISCOp_d"), "climatology" ("PISCOp_clim2").

  • Temperature: "tmax_daily", "tmin_daily", "tmax_clim", "tmin_clim".

  • Evapotranspiration: "eto_clim" ("PISCOeo_pm").

  • Erosivity: "erosivity_r", "erosivity_density".

  • Streamflow: "streamflow_monthly", "streamflow_daily", "catchments_gr2m", "rivers_gr2m", "catchments_arnovic", or "rivers_arnovic". Default is "monthly".

destdir

Character. Destination directory. Default is pisco_cache_dir().

overwrite

Logical. If TRUE, re-downloads the file even if present in cache.

verify_md5

Logical. If TRUE and an MD5 hash is registered, validates the checksum. Default is TRUE.

timeout

Numeric. Maximum seconds to allow for download. Default is 3600 (1 hour).

quiet

Logical. If TRUE, suppresses progress messages. Default is FALSE.

refresh

Logical. If TRUE, refreshes public repository metadata before downloading an uncached file. This is safe because calling this function is an explicit user request to download data. Default is TRUE.

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: "vector" (named numeric vector c(xmin, ymin, xmax, ymax)), "bbox" (sf::st_bbox object), or "ext" (terra::ext object). Default is "vector".

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 sf point object, a matrix/data.frame with lon and lat columns, or a numeric coordinate vector c(lon, lat).

polygons

Optional. An sf polygon object or terra::SpatVector for zonal statistics.

fun

Character or function. Summary statistic when extracting across polygons (e.g., "mean", "sum", "median"). Default is "mean".

id_col

Character. Name of the column in polygons or points to identify features.

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 (drd_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 TRUE, pairs with missing values (NA) are removed. Default is TRUE.

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:

  • Precipitation: "monthly" ("PISCOp_m"), "daily" ("PISCOp_d"), "climatology" ("PISCOp_clim2").

  • Temperature: "tmax_daily", "tmin_daily", "tmax_clim", "tmin_clim".

  • Evapotranspiration: "eto_clim" ("PISCOeo_pm").

  • Erosivity: "erosivity_r", "erosivity_density".

  • Streamflow: "streamflow_monthly", "streamflow_daily", "catchments_gr2m", "rivers_gr2m", "catchments_arnovic", or "rivers_arnovic". Default is "monthly".

file

Character. Optional custom path to a PISCO NetCDF or GeoPackage file. If NULL, looks in the local cache.

dates

Vector of dates, years, year-months, or indices to filter layers.

  • For daily/monthly rasters: Date objects, character dates ("1998-01-01"), character year-months (c("1997-01", "1998-12")), or numeric years (1998 or c(1997, 1998)).

  • For climatologies (12 months): integer month numbers (1:12) or month names.

aoi

Optional spatial object (sf, SpatVector, or bounding box vector) to crop/mask the raster upon reading. Alias for mask.

mask

Optional spatial mask. Same as aoi.

download

Logical. If TRUE and file is not cached, downloads it after this explicit request. Default is FALSE to avoid implicit network access.

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 TRUE, suppresses informational messages.

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 terra::SpatRaster or terra::SpatVector object.

y

Optional second argument for bivariate plotting in terra.

...

Additional graphical parameters forwarded to terra::plot().

Value

Invisibly returns the plotted object or NULL, creating a plot on the active device.