---
title: "phenocamr functionality"
author: "Koen Hufkens"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{phenocamr functionality}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

# check if server is reachable
# returns bolean TRUE if so
phenocam_running <- function(url = "https://phenocam.nau.edu"){
  ct <- try(httr::GET(url))
  if(inherits(ct,"try-error")){return(FALSE)}
  if(ct$status_code > 400){
    FALSE  
  } else {
    TRUE
  }
}

# load the library
library(phenocamr)

check <- phenocam_running()
```

A programmatic interface to the [PhenoCam web services](https://phenocam.nau.edu/webcam/). Allows for easy downloads of PhenoCam near-surface remote sensing greenness (Gcc) time series directly to your R workspace or your computer. Post-processing allows for the smoothing of the time-series and the calculation of phenological transition dates as a final product.

The package gives access to the latest generated PhenoCam time series (at most 1-day old for running sites) and allows for the extraction of up-to-date phenological transition dates. However, the data acquired through the package will not be curated and vetted for data quality.

For a quality controlled and fully described dataset I suggest downloading the dataset as described by Richardson et al. (2018). This dataset uses the phenocamr packages in its final processing steps however quality control is gauranteed through careful review of the data. The data can be interactively explored on [explore.phenocam.us](http://explore.phenocam.us) and downloaded in full from the [ORNL DAAC](https://daac.ornl.gov/cgi-bin/dsviewer.pl?ds_id=1511). If in need of more recent data you can use the package and its functionality but be mindful of quality control especially the region-of-interest (ROI) used and potential unaccounted field-of-view (FOV) shifts in the dataset.

## A worked example

Below I describe the most common use of the package, downloading recent PhenoCam time series and generating phenological transition dates for a given site and data type. I intentionally disable most automated processing and step through some of the routines to illustrate the workflow which normally happens internally to the main function download_phenocam(). Generated transition date files can be used in later analysis or modelling exercises using for example the [phenor R package](https://github.com/bluegreen-labs/phenor).

### Select a site

A full list of meta-data for all sites can be queried using the list_sites() function.

```{r eval = check}
sites <- list_sites()
head(sites)
```

To select a site first download an overview meta-data table of all available sites together with their ROI id's and vegetation type and a limited set of meta-data parameters.

```{r eval = check}
rois <- list_rois()
head(rois)
```

### Download a PhenoCam time series.

The below code shows you how to download a PhenoCam time series for the "**harvard**" site, ROI (roi_id) 1 and a time step frequency of 3-days. In this case the default outlier detection and smoothing routines has been disabled and will be run separately in subsequent steps. In normal use these will be enabled by default. The default output directory is tempdir() but any directory can be specified for data management purposes. If default settings are maintained, outlier detection and smoothing will be performed automatically. If so desired phenology dates can be estimated in one pass. In the latter case new data will be written in the same directory as specified for downloading the time series data.

```{r eval = check}
  download_phenocam(site = "harvard$",
                    veg_type = "DB",
                    roi_id = "1000",
                    frequency = 3,
                    outlier_detection = FALSE,
                    smooth = FALSE,
                    out_dir = tempdir())
```

After downloading we read in the data from disk. The data has a header and is comma separated.

```{r eval = check}
df <- read_phenocam(file.path(tempdir(),"harvard_DB_1000_3day.csv"))
print(str(df))
```


### Expanding 3-day data for maximum phenology resolution

The downloaded time series is of a 3-day resolution. However, to correctly evaluate the phenology on a daily time step the time series needs to be expanded to this one day time step. This can be achieved using the expand_phenocam() function.

```{r eval = check}
df <- expand_phenocam(df)
```

### Detect data outlier

After reading in the data as a data frame you can apply the outlier detection routine. This routine uses an iterative method to detect outlier values in the Gcc time series. This routine filters out most spurious values due contaminiation by snow, mist, rain or otherwise very bright events. Warnings are suppressed as the routine is iterative and might throw warnings if it does not converge on a solution. This has no implications for the routine and data returned.

```{r eval = check}
  df <- detect_outliers(df)
```

### Smoothing a time series

After detecting outliers you can smooth the data. This function uses an AIC based methodology to find the opitmal loess smoothing window. Warnings are suppressed as the routine uses an optimization in which certain parameter settings return warnings. This has no implications for the routine and data returned.

```{r eval = check}
  df <- smooth_ts(df)
```

### Calculating phenophases

Finally, if smoothed data is available you can calculate phenological transition dates. This routine uses a PELT changepoint detection based approach to find meaningful seasonal cycles in the data. By default start of growing season dates are returned. If the reverse parameter is set to TRUE the end of growing season dates are returned. Dates are formatted as unix time and will be provided for three default threshold values (10 / 25 / 50%) of the Gcc amplitude.

```{r eval = check}
start_of_season <- transition_dates(df)
print(head(start_of_season))
```

Alternatively you can use the phenophases() function which is a wrapper of the transition_dates() function. However, as it potentially writes data to disk it needs additional information such as the roi_id, site name etc. The phenophases() function is the function which generated the final data products in the Richardson et al. (2018) paper. If used internally the output will be formatted in unix time, when written to file the dates will be human readable in YYYY-MM-DD format. Both start and end of season estimates will be provided.

```{r eval = check}
phenology_dates <- phenophases(df, internal = TRUE)
```

With the phenoogy dates calculated we can plot their respective locations on the smoothed time series. In this case the plot will show the 50% amplitude threshold values for both rising and falling parts of the 90th percentile Gcc curve, marked with green and brown vertical lines respectivelly.

```{r fig.width = 7, fig.height = 3, eval = check}
plot(as.Date(df$data$date),
     df$data$smooth_gcc_90,
     type = "l",
     xlab = "date",
     ylab = "Gcc")

# rising "spring" greenup dates
abline(v = phenology_dates$rising$transition_50,
       col = "green")

# falling "autumn" senescence dates
abline(v = phenology_dates$falling$transition_50,
       col = "brown")

```


## References

Hufkens K., Basler J. D., Milliman T. Melaas E., Richardson A.D. 2018 [An integrated phenology modelling framework in R: Phenology modelling with phenor. Methods in Ecology & Evolution](https://onlinelibrary.wiley.com/doi/10.1111/2041-210X.12970/full), 9: 1-10.

## Acknowledgements

This project was is supported by the National Science Foundation’s Macro-system Biology Program (awards EF-1065029 and EF-1702697).
