---
title: "Welcome to climateR"
author:
  - name: "Mike Johnson"
    url: https://github.com/mikejohnson51
    affiliation: NOAA-OWP
    affiliation_url: https://lynker.com
output: distill::distill_article
vignette: >
  %\VignetteIndexEntry{intro}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  out.width = "100%",
  dev = "jpeg",
  warning = FALSE,
  message = FALSE
)
```

# Usful Packages for climate data

```{r}
library(AOI)
library(terra)
library(climateR)
library(tidyterra)
library(ggplot2)
library(tidyr)
library(sf)
```

# climateR examples

The climateR package is supplemented by the [AOI](https://github.com/mikejohnson51/AOI) framework established in the `AOI` R package. 

To get a climate product, an area of interest must be defined:

```{r}
AOI = aoi_get(state = "NC")
plot(AOI$geometry)
```

Here we are loading a polygon for the state of North Carolina More examples of constructing AOI calls can be found [here](https://mikejohnson51.github.io/AOI/).

With an AOI, we can construct a call to a dataset for a parameter(s) and date(s) of choice. Here we are querying the PRISM dataset for maximum and minimum temperature on October 29, 2018:

```{r}
system.time({
 p = getGridMET(AOI, 
              varname = c('tmmx','tmmn'), 
              startDate = "2018-10-29")
})
```

```{r, echo = FALSE}
ggplot() +
  geom_spatraster(data = rast(p)) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + theme_minimal()
```

# Data from known bounding coordinates

`climateR` offers support for `sf`, `sfc`, and `bbox` objects. Here we are requesting wind velocity data for the four corners region of the USA by bounding coordinates.

```{r}
AOI = st_as_sfc(st_bbox(c(xmin = -112, xmax = -105, ymax = 39, ymin = 34), crs = 4326))

g = getGridMET(st_as_sf(AOI), 
               varname = "vs",
               startDate = "2018-09-01")
```

```{r, echo = FALSE}
ggplot() +
  geom_spatraster(data = rast(g)) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + 
  geom_sf(data = aoi_get(state  = c("CO", "NM", "AZ", "UT")), fill = NA) + 
  theme_minimal()
```

# Data through time ...

In addition to multiple variables we can request variables through time, here let's look at the gridMET rainfall for the Gulf Coast during Hurricane Harvey:

```{r, fig.width= 15}
harvey = getGridMET(aoi_get(state = c("TX", "FL")), 
                  varname = "pr", 
                  startDate = "2017-08-20", 
                  endDate = "2017-08-31")

ggplot() +
  geom_spatraster(data = harvey$precipitation_amount) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white") + 
  theme_minimal()
```

# Climate Projections 

Some sources are downscaled Global Climate Models (GCMs). These allow you to query forecasted ensemble members from different models and/or climate scenarios. One example is from the MACA dataset:

```{r}
system.time({
m = getMACA(AOI = aoi_get(state = "FL"), 
            model = "CCSM4", 
            varname = 'pr', 
            scenario = c('rcp45', 'rcp85'), 
            startDate = "2080-06-29", endDate = "2080-06-30")
})
```

```{r, echo = FALSE, fig.width = 15}
ggplot() +
  geom_spatraster(data = rast(m)) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + theme_minimal()
```

Getting multiple models results is also quite simple:

```{r}
models = c("BNU-ESM","CanESM2", "CCSM4")

temp =  getMACA(AOI = aoi_get(state = "CO"),
                varname = 'tasmin', 
                model = models, 
                startDate = "2080-11-29")

temp =  c(temp[[1]], mean(temp[[1]]))

names(temp) = c(models, "Ensemble Mean")

```

```{r, echo = FALSE, fig.width = 15}
# Plot
ggplot() +
  geom_spatraster(data = temp) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + 
  theme_minimal()
```

If you don't know your models, you can always grab a random set by specifying a number:

```{r, fig.width= 15}
random = getMACA(aoi_get(state = "MI"), 
                 model = 3, 
                 varname = "pr", 
                 startDate = "2050-10-29")
```

```{r, echo = FALSE, fig.width = 15}
# Plot
ggplot() +
  geom_spatraster(data = random$precipitation) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + 
  theme_minimal()
```

# Global Datasets

Not all datasets are USA focused either. TerraClimate offers global, monthly data up to the current year for many variables, and CHIRPS provides daily rainfall data:

```{r, fig.width = 15}
kenya = aoi_get(country = "Kenya")
tc = getTerraClim(kenya, varname = "pet", startDate = "2018-01-01")
chirps = getCHIRPS(kenya, startDate = "2018-01-01", endDate = "2018-01-04" )
```

```{r, echo = FALSE, fig.width = 15}
library(patchwork)

ggplot() +
  geom_spatraster(data = tc$pet) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + 
  geom_sf(data = kenya, fill = NA, lwd = 2, col = "black") + 
  theme_minimal() + 
  ggplot() +
  geom_spatraster(data = chirps$precip) +
  facet_wrap(~lyr) +
  scale_fill_whitebox_c(
    palette = "muted",
    na.value = "white"
  ) + 
  geom_sf(data = kenya, fill = NA, lwd = 2, col = "black") + 
  theme_minimal() 
```

# Point Based Data

Finally, data gathering is not limited to areal extents and can be retrieved as a time series at locations. 

```{r}
ts = data.frame(lng  = -105.0668, lat = 40.55085) %>% 
  st_as_sf(coords = c('lng', 'lat'), crs = 4326) %>% 
  getGridMET(varname =  c("pr", 'srad'), 
             startDate = "2021-01-01", 
             endDate = "2021-12-31")
```

```{r, echo = FALSE, fig.width = 15}
ggplot(data = ts, aes(x = date, y = srad)) + 
  geom_line() +
  stat_smooth(col = "red") + 
  theme_linedraw() + 
  labs(title = "Solar Radiation: Fort Collins 2019",
       x = "Date", y = "Solar Radiation") +
ggplot(data = ts, aes(x = date, y = cumsum(pr))) + 
  geom_line(color = "blue", lwd = 1) +
  theme_linedraw() + 
  labs(title = "Cumulative Rainfall: Fort Collins 2019",
       x = "Date", y = "Rainfall")

```

# Point Based Ensemble

```{r}
future = getMACA(geocode("Fort Collins", pt = TRUE), 
                 model = 5, 
                 varname = "tasmax", 
                 startDate = "2050-01-01", 
                 endDate = "2050-01-31")

future_long = pivot_longer(future, -date) 

ggplot(data = future_long, aes(x = date, y = value, col = name)) + 
  geom_line() + 
  theme_linedraw() + 
  scale_color_brewer(palette = "Dark2") + 
  labs(title = "Fort Collins Temperture: January, 2050",
       x = "Date",
       y = "Degree K",
       color = "Model")
```


# Multi site extraction

Extracting data for a set of points is an interesting challenge. It turns it is much more efficient to grab the underlying raster stack and then extract time series as opposed to iterating over the locations:

1. Starting with a set of locations in Colorado:

```{r}
f = system.file("co/cities_colorado.rds", package = "climateR")
cities = readRDS(f)
```

2. `climateR` will grab the SpatRaster underlying the bounding area of the points

```{r}
sites_stack = getTerraClim(AOI   = cities, 
                           varname = "tmax", 
                           startDate = "2018-01-01", 
                           endDate   = "2018-12-31")
```

```{r, echo = FALSE, fig.width = 15}
{
  plot(sites_stack$tmax[[1]])
  plot(vect(cities), add = TRUE, pch = 16, cex = .5)
}
```

3. Use `extract_sites` to extract the times series from these locations. The `id` parameter is the unique identifier from the site data with which to names the resulting columns.

```{r}
sites_wide = extract_sites(r = sites_stack, pts = cities, ID = "NAME")
sites_wide[1:5, 1:5]
```

To make the data 'tidy' simply pivot on the `date` column:

```{r}
tmax = tidyr::pivot_longer(sites_wide, -date)
head(tmax)
```

```{r, echo = FALSE}
ggplot(data = tmax, aes(x = date, y = value, color = name, group = name)) + 
  scale_color_viridis_d() +
  geom_line() + 
  theme_linedraw() + 
  theme(legend.position = "none") 
```


