---
title: "Introduction to aion"
author: "N. Frerebeau"
date: "`r Sys.Date()`"
output:
  markdown::html_format:
    options:
      toc: true
      number_sections: true
vignette: >
  %\VignetteIndexEntry{Introduction to aion}
  %\VignetteEngine{knitr::knitr}
  %\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 with `set_calendar()`, or on a per-function basis.

```{r}
## Get default calendar
get_calendar()

## Change default calendar to BP
set_calendar("BP")
get_calendar()

## Set it back to Gregorian Common Era
set_calendar("CE")
get_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* (Reingold and Dershowitz 2018), i.e. as number of days since 01-01-01 (Gregorian)[^1].

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 = 2000, 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://cran.r-project.org/package=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}
## Get ceramic counts (data from Husi 2022)
data("loire", package = "folio")

## Keep only variables whose total is at least 600
keep <- c("01f", "01k", "01L", "08e", "08t", "09b", "15i", "15q")

## Get time midpoints
mid <- rowMeans(loire[, c("lower", "upper")])

## Create time-series
(X <- series(
  object = loire[, keep],
  time = mid,
  calendar = calendar("AD")
))
```

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 (default calendar)
plot(
  x = X, 
  type = "h" # histogram like vertical lines
)
```

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

## Plot a single series
plot(
  Y,
  type = "h", # histogram like vertical lines
  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 {.unnumbered}

Reingold, Edward M., and Nachum Dershowitz. 2018. *Calendrical Calculations: The Ultimate Edition*. 4th ed. Cambridge University Press. <https://doi.org/10.1017/9781107415058>.

[^1]: Although it is intended that the *rata die* should be an integer value, this is not enforced in the internal representation. R's numeric type is a double-precision floating-point that follows the [IEEE 754 standard](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). This means that a numeric can safely represent an integer value up to `2^53 - 1`. This covers more than the age of the Universe: `fixed(13.8, calendar = CE(), scale = 10^9)`.
