---
title: "Introduction to climatrends"
package: climatrends
author:
- name: Kauê de Sousa
  affiliation: Department of Agricultural Sciences, University of Inland Norway, Hamar, Norway </br> Digital Inclusion, Bioversity International, Montpellier, France
output: html_document
vignette: >
  %\VignetteIndexEntry{Overview}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown_notangle}
bibliography: ["climatrends.bib"]
csl: citation_style.csl
---

# Summary

Understanding how climate variability influences ecological and agricultural systems is essential for climate adaptation, biodiversity conservation, and environmental modeling. **climatrends** provides a unified framework to compute temperature, precipitation, and crop-related climate indices. These indices serve as inputs for crop models, ecological analyses, phenology studies, and assessments of climate trends.

The methods implemented in **climatrends** have been applied in several research domains, including crop growing cycle analysis[@Kehel2016], regional climate trend detection[@Aguilar2005; @Challinor2016; @Trnka2014; @Zohner2020], citizen science in agriculture[@vanEtten2019], and studies comparing climate trends with farmers’ perceptions[@DeSousa2018].

# Statement of need

Reproducibility (being able to repeat an analysis) and replicability (being able to repeat an experiment) are essential principles in science, yet they remain challenging in many agricultural and ecological studies. Analyses often rely on custom scripts, inconsistent definitions of climate indices, or non-standard workflows, making results difficult to reuse across locations and seasons.

**climatrends** was developed to address this gap. The package evolved from a collection of scripts used in previous studies and now provides standardized, transparent, and reproducible methods to compute well-established climate indices. The functions are designed to handle heterogeneous testing environments—a common characteristic of decentralized agricultural trials—where locations differ in climate, timing, and growing seasons. The package also supports fixed-period time-series analysis and integrates smoothly with API-based climate data sources (e.g., *nasapower*).

The temperature, precipitation, and crop-sensitive indices implemented in **climatrends** draw from validated methods in climatology and crop science. The package is listed in the [CRAN Task View for Agricultural Science](https://cran.r-project.org/view=Agriculture).

# Usage

Most functions in **climatrends** accept a numeric vector of climate data and, optionally, a vector of dates to enable time-series calculations. The package provides S3 methods for objects of classes:

- `numeric`  
- `array` / `matrix`  
- `data.frame`  
- `sf`

Methods for `sf` and `data.frame` allow seamless integration with climate data services accessed through API clients such as *nasapower*[@Sparks2018].

This vignette introduces the main functions and illustrates how to compute indices commonly used in ecological and agricultural research.

---

# Temperature

Temperature-based indices are foundational in ecological and crop modeling. They summarize daily temperature dynamics and help identify heat accumulation, thermal stress, and seasonality.

Below we compute temperature indices for the first half of 2019 in Innlandet county, Norway:

```{r temperature, message=TRUE, eval=TRUE, echo=TRUE}
library("climatrends")

data("innlandet", package = "climatrends")

temp1 = temperature(innlandet$tmax, innlandet$tmin)

temp1
```

To compute indices for a time series, set `timeseries = TRUE`. The argument intervals defines the window size (in days) for each period:

```{r temperature2, message=TRUE, eval=TRUE, echo=TRUE}
temp2 = temperature(innlandet$tmax, innlandet$tmin,
                    dates = innlandet$dates,
                    timeseries = TRUE, 
                    intervals = 30)

temp2
```

# Growing Degree-Days

Growing degree-days (GDD) represent accumulated heat over time and are widely used in phenology to estimate plant and insect developmental rates[@Prentice1992]. `climatrends` computes GDD using the `GDD()` function.
Here we calculate GDD using an adjusted equation suited for cold regions:

```{r gdd, message=TRUE, eval=TRUE, echo=TRUE}
gdd = GDD(innlandet$tmax, innlandet$tmin, tbase = 2, equation = "b")

gdd
```

The function can also:

- return daily degree-day values (`return.as = "daily"`), or
- compute the number of days needed to reach a specified heat sum (`return.as = "ndays"`).

For example, the Korean pine (*Pinus koraiensis*) requires 105 $^\circ C$ accumulated GDD to initiate photosynthesis[@JWu2013]. Below, we ask the function to compute the number of days required to reach 150 °C for a given location:

```{r gdd2, message=FALSE, eval=FALSE, echo=TRUE}
lonlat = data.frame(lon = 129.19,
                    lat = 36.39)

GDD(lonlat, 
    day.one = "2019-04-01",
    last.day = "2019-10-01",
    degree.days = 150, 
    return.as = "ndays")
```

This means that 45 days were needed to accumulate 150 $^\circ C$ degree-days during the 2019 season.

## Late spring frost

Late spring frost occurs when a freezing event follows a period of accumulated warmth—potentially damaging sensitive early growth stages. The `late_frost()` function identifies frost events and describes:

- frost duration,
- accumulated GDD during frost,
-latency periods (no frost, no GDD),
- warming periods (positive GDD accumulation).

```{r latefrost, message=TRUE, eval=TRUE, echo=TRUE}
lf = late_frost(innlandet$tmax, 
                 innlandet$tmin, 
                 dates = innlandet$date, 
                 base = 2)

lf
```

## Rainfall 

Precipitation indices are available through the `rainfall()` function. They follow the same principles as the temperature indices but use daily precipitation.

Below we illustrate how climatrends works with remote-sensing data retrieved from NASA POWER through `nasapower` package: 

```{r rain, message=FALSE, eval=FALSE, echo=TRUE}
library("nasapower")

lonlat = data.frame(lon = c(-73.3, -74.5),
                     lat = c(-6.1, - 6.2))

rain = rainfall(lonlat, 
                 day.one = "2018-11-01",
                 last.day = "2018-12-31")

rain
```

## Crop sensitive indices

Crop-sensitive indices capture climatic variability during key developmental stages in crop growth. These indices have been used in agroclimatic assessments and impact studies[@Challinor2016; @Trnka2014]. Below, we compute them using the `sf` method for five spatial locations in Sinop, Brazil:

```{r csenstive, message=FALSE, eval=FALSE, echo=TRUE}
library("sf")
data("lonlatsf", package = "climatrends")

crop_sensitive(lonlatsf, 
               day.one = "2018-12-01",
               last.day = "2019-01-31", 
               as.sf = FALSE)
```

Thresholds for individual indices can be modified using arguments of the form `*.threshold` (e.g., `tmax.threshold`).

## Reference evapotranspiration

Evapotranspiration (ETo) is the combined loss of water through evaporation and plant transpiration, representing a fundamental component of ecological and agricultural models. `climatrends` computes reference evapotranspiration using the Blaney–Criddle method[@Brouwer1986], which is suitable when only temperature data are available.

The `ETo()` function supports array inputs, where each row represents a location and each column a day. The argument:

- span defines the number of days per time series,
- lat sets the latitude used in the calculation,
- Kc is the crop coefficient.

```{r eto, message=TRUE, eval=TRUE, echo=TRUE}
data("temp_dat", package = "climatrends")

eto = ETo(temp_dat, 
           day.one = "2013-10-28",
           span = c(9, 10, 11, 12, 8, 10, 11, 11, 12, 10),
           lat = rep(25, 10),
           Kc = 0.92)

eto
```

## References

