---
title: "Introduction to aion"
author: "N. Frerebeau"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    number_sections: yes
    fig_caption: yes
    toc: true
bibliography: bibliography.bib
vignette: >
  %\VignetteIndexEntry{Introduction to aion}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

```{r setup}
library(aion)
```

Base R ships with a lot of functionality useful for time series, in particular in the **stats** package. However, these features are not adapted to most archaeological time series. These are indeed defined for a given calendar era, they can involve dates very far in the past and the sampling of the observation time is (in most cases) not constant. **aion** provides a system of classes and methods to represent and work with such time-series.

# Calendars

**aion** currently supports both Julian and Gregorian calendars (with the most common eras for the latter, e.g. Before Present, Common Era...). A calendar can be defined using the `calendar()` function:

```{r}
## Create a calendar object
## (Gregorian Common Era)
calendar("CE")
```

Or by using the shortcuts:

```{r}
## Common Era (Gregorian)
CE()

## Before Present (Gregorian)
BP()
```

When creating date vectors or time series, you *must* specify the calendar corresponding to your data (see below). This allows to select the correct method for converting dates to *rata die*. 

**Outputs generated by aion are expressed in _rata die_ by default (this can be modified on a per-function basis).** The only two exceptions are the `plot()` and `format()` functions, which default to the calendar specified in the package options (see below). You can change the default calendar to be used throughout the package by modifying the `aion.calendar` option, or on a per-function basis.

```{r}
## Get default calendar
getOption("aion.calendar")

## Change default calendar to BP
options(aion.calendar = BP())
getOption("aion.calendar")

## Set it back to Gregorian Common Era
options(aion.calendar = CE())
getOption("aion.calendar")
```

# Vectors of dates

In base R, dates are represented by default as the number of days since 1970-01-01 (Gregorian), with negative values for earlier dates (see `help(Date)`). **aion** uses a different approach: it allows to create date vectors represented as *rata die* [@reingold2018], i.e. as number of days since 01-01-01 (Gregorian)^[It is intended that the *rata die* should be an integer value, but this is not enforced in the internal representation.].

This makes it possible to get rid of a specific calendar and to make calculations easier. It is then possible to convert a vector of *rata die* into dates or (decimal) years of any calendar.

The `fixed()` function allows to create a vector of *rata die* from dates belonging to a specific calendar:

```{r}
## Convert 2000-02-29 (Gregorian) to rata die
fixed(2000, 02, 29, calendar = calendar("CE"))

## If days and months are missing, decimal years are expected
fixed(2000.161, calendar = calendar("CE"))
```

A *rata die* vector can be converted into dates (or years) of a particular calendar:

```{r}
## Create a vector of 10 years BP (Gregorian)
## (every 20 years starting from 2000 BP)
(years <- seq(from = 20000, by = -20, length.out = 10))

## Convert years to rata die
(rd <- fixed(years, calendar = calendar("BP")))

## Convert back to Gregorian years
as_year(rd, calendar = calendar("CE"))  # Common Era
as_year(rd, calendar = calendar("BP"))  # Before Present
as_year(rd, calendar = calendar("b2k")) # Before 2000
```

*Rata die* can be represented as (nicely formated) character vectors:

```{r}
format(rd) # Default calendar (Gregorian Common Era)
format(rd, prefix = "ka", calendar = calendar("BP"))
```

The *rata die* vector provides the internal time representation of the **aion** time-series (if you want to work with numeric vectors that represent year-based time scales, you may be interested in the [**era**](https://github.com/joeroe/era) package).

# Time series

A time series is a sequence of observation time and value pairs with strictly increasing observation times. 

A time series object is an $n \times m \times p$ array, with $n$ being the number of observations, $m$ being the number of series and with the $p$ columns of the third dimension containing extra variables for each series. It can be created from a numeric `vector`, `matrix` or `array`.

```{r}
## Set seed for reproductibility
set.seed(12345)

## 6 x 50 observations...
obs <- matrix(rnorm(300), nrow = 50, ncol = 6)

## ...sampled every two years starting from 2000 BP
spl <- seq(from = 2000, by = -2, length.out = 50)

## Create time series
(X <- series(object = obs, time = spl, calendar = BP()))
```

Time series terminal and sampling times can be retrieved and expressed according to different calendars (**remember that outputs are expressed in _rata die_ by default**):

```{r}
## Time series duration
span(X) # Default: rata die
span(X, calendar = CE())

## Time of first observation
start(X) # Default: rata die
start(X, calendar = CE())

## Time of last observation
end(X) # Default: rata die
end(X, calendar = CE())

## Sampling times
time(X, calendar = BP())
```

Plot one or more time series:

```{r plot-multiple, fig.width=7, fig.height=5}
## Multiple plot
plot(X) # Default calendar
```

```{r plot-single, fig.width=7, fig.height=3.5}
## Extract the first series
Y <- X[, 1, ]

## Plot a single series
plot(
  Y,
  calendar = b2k(), # b2k time scale
  panel.first = graphics::grid() # Add a grid
)
year_axis(side = 3, calendar = CE()) # Add a secondary time axis
mtext(format(CE()), side = 3, line = 3) # Add secondary axis title
```

Note that **aion** uses the astronomical notation for Gregorian years (there *is* a year 0).

# References
