# Load packages
library(tabula)
library(magrittr)


# Introduction

The matrix seriation problem in archaeology is based on three conditions and two assumptions, which Dunnell (1970) summarizes as follows.

The homogeneity conditions state that all the groups included in a seriation must:

• Be of comparable duration,
• Belong to the same cultural tradition,
• Come from the same local area.

The mathematical assumptions state that the distribution of any historical or temporal class:

• Is continuous through time,
• Exhibits the form of a unimodal curve.

Theses assumptions create a distributional model and ordering is accomplished by arranging the matrix so that the class distributions approximate the required pattern. The resulting order is inferred to be chronological.

# Reciprocal ranking

Reciprocal ranking iteratively rearrange rows and/or columns according to their weighted rank in the data matrix until convergence (Ihm 2005).

For a given incidence matrix $$C$$:

• The rows of $$C$$ are rearranged in increasing order of:

$x_{i} = \sum_{j = 1}^{p} j \frac{c_{ij}}{c_{i \cdot}}$

• The columns of $$C$$ are rearranged in a similar way:

$y_{j} = \sum_{i = 1}^{m} i \frac{c_{ij}}{c_{\cdot j}}$

These two steps are repeated until convergence. Note that this procedure could enter into an infinite loop.

## Build an incidence matrix with random data
set.seed(12345)
incidence1 <- IncidenceMatrix(data = sample(0:1, 400, TRUE, c(0.6, 0.4)),
nrow = 20)

## Get seriation order on rows and columns
## If no convergence is reached before the maximum number of iterations (100),
## it stops with a warning.
(indices <- seriate_rank(incidence1, margin = c(1, 2), stop = 100))
#> <PermutationOrder>
#> Permutation order for matrix seriation:
#> - Row order: 1 4 20 3 9 16 19 10 13 2 11 7 17 5 6 18 14 15 8 12...
#> - Column order: 1 16 9 4 8 14 3 20 13 2 6 18 7 17 5 11 19 12 15 10...
#> - Method: reciprocal ranking

## Permute matrix rows and columns
incidence2 <- permute(incidence1, indices)

## Plot matrix
plot_heatmap(incidence1) +
ggplot2::labs(title = "Original matrix") +
ggplot2::scale_fill_manual(values = c("TRUE" = "black", "FALSE" = "white"))
plot_heatmap(incidence2) +
ggplot2::labs(title = "Rearranged matrix") +
ggplot2::scale_fill_manual(values = c("TRUE" = "black", "FALSE" = "white"))


The positive difference from the column mean percentage (in french “écart positif au pourcentage moyen”, EPPM) represents a deviation from the situation of statistical independence (Desachy 2004). As independence can be interpreted as the absence of relationships between types and the chronological order of the assemblages, EPPM is a useful graphical tool to explore significance of relationship between rows and columns related to seriation (Desachy 2004).

## Replicates Desachy 2004 results
## Coerce dataset to an abundance matrix
compiegne_counts <- as_count(compiegne)

## Plot original data matrix
plot_ford(compiegne_counts, EPPM = TRUE) +
ggplot2::labs(title = "Original dataset") +
khroma::scale_fill_bright()

## Get seriation order for columns on EPPM using the reciprocal averaging method
## Expected column order: N, A, C, K, P, L, B, E, I, M, D, G, O, J, F, H
compiegne_indices <- seriate_rank(compiegne_counts, EPPM = TRUE, margin = 2)

## Permute columns
compiegne_seriation <- permute(compiegne_counts, compiegne_indices)

## Plot new matrix
plot_ford(compiegne_seriation, EPPM = TRUE) +
ggplot2::labs(title = "Reordered dataset") +
khroma::scale_fill_bright()


# correspondence analysis

## Seriation

correspondence Analysis (CA) is an effective method for the seriation of archaeological assemblages. The order of the rows and columns is given by the coordinates along one dimension of the CA space, assumed to account for temporal variation. The direction of temporal change within the correspondence analysis space is arbitrary: additional information is needed to determine the actual order in time.

## Coerce dataset to an count matrix
zuni_counts <- as_count(zuni)
## correspondence analysis of the whole dataset
corresp <- run_ca(zuni_counts)
## Plot CA results
plot_ca(corresp, axes = c(1, 2), map = c("rows", "columns"))  +
ggplot2::theme_bw()


## Get row permutations from CA coordinates
zuni_indices <- zuni_counts %>%
seriate_correspondence(margin = 1)

## Permute data matrix
zuni_seriation <- permute(zuni_counts, zuni_indices)

## Plot Ford diagram
## Warning: this may take a few seconds!
plot_ford(zuni_seriation) +
ggplot2::theme(axis.text = ggplot2::element_blank(),
axis.ticks = ggplot2::element_blank())


## Refining

Peeples and Schachner (2012) propose a procedure to identify samples that are subject to sampling error or samples that have underlying structural relationships and might be influencing the ordering along the CA space. This relies on a partial bootstrap approach to CA-based seriation where each sample is replicated n times. The maximum dimension length of the convex hull around the sample point cloud allows to remove samples for a given cutoff value.

According to Peeples and Schachner (2012), “[this] point removal procedure [results in] a reduced dataset where the position of individuals within the CA are highly stable and which produces an ordering consistend with the assumptions of frequency seriation.”

## Replicates Peeples and Schachner 2012 results
## Samples with convex hull maximum dimension length greater than the cutoff
## value will be marked for removal.
## Define cutoff as one standard deviation above the mean
fun <- function(x) { mean(x) + sd(x) }

## Get indices of samples to be kept
## Warning: this may take a few seconds!
zuni_keep <- refine_ca(corresp, cutoff = fun, n = 1000)
#>
|
|                                                                      |   0%
|
|                                                                      |   1%
|
|=                                                                     |   1%
|
|=                                                                     |   2%
|
|==                                                                    |   2%
|
|==                                                                    |   3%
|
|==                                                                    |   4%
|
|===                                                                   |   4%
|
|===                                                                   |   5%
|
|====                                                                  |   5%
|
|====                                                                  |   6%
|
|=====                                                                 |   7%
|
|=====                                                                 |   8%
|
|======                                                                |   8%
|
|======                                                                |   9%
|
|=======                                                               |  10%
|
|========                                                              |  11%
|
|========                                                              |  12%
|
|=========                                                             |  12%
|
|=========                                                             |  13%
|
|==========                                                            |  14%
|
|==========                                                            |  15%
|
|===========                                                           |  15%
|
|===========                                                           |  16%
|
|============                                                          |  16%
|
|============                                                          |  17%
|
|============                                                          |  18%
|
|=============                                                         |  18%
|
|=============                                                         |  19%
|
|==============                                                        |  19%
|
|==============                                                        |  20%
|
|==============                                                        |  21%
|
|===============                                                       |  21%
|
|===============                                                       |  22%
|
|================                                                      |  22%
|
|================                                                      |  23%
|
|================                                                      |  24%
|
|=================                                                     |  24%
|
|=================                                                     |  25%
|
|==================                                                    |  25%
|
|==================                                                    |  26%
|
|===================                                                   |  27%
|
|===================                                                   |  28%
|
|====================                                                  |  28%
|
|====================                                                  |  29%
|
|=====================                                                 |  30%
|
|======================                                                |  31%
|
|======================                                                |  32%
|
|=======================                                               |  32%
|
|=======================                                               |  33%
|
|========================                                              |  34%
|
|========================                                              |  35%
|
|=========================                                             |  35%
|
|=========================                                             |  36%
|
|==========================                                            |  36%
|
|==========================                                            |  37%
|
|==========================                                            |  38%
|
|===========================                                           |  38%
|
|===========================                                           |  39%
|
|============================                                          |  39%
|
|============================                                          |  40%
|
|============================                                          |  41%
|
|=============================                                         |  41%
|
|=============================                                         |  42%
|
|==============================                                        |  42%
|
|==============================                                        |  43%
|
|==============================                                        |  44%
|
|===============================                                       |  44%
|
|===============================                                       |  45%
|
|================================                                      |  45%
|
|================================                                      |  46%
|
|=================================                                     |  47%
|
|=================================                                     |  48%
|
|==================================                                    |  48%
|
|==================================                                    |  49%
|
|===================================                                   |  50%
|
|====================================                                  |  51%
|
|====================================                                  |  52%
|
|=====================================                                 |  52%
|
|=====================================                                 |  53%
|
|======================================                                |  54%
|
|======================================                                |  55%
|
|=======================================                               |  55%
|
|=======================================                               |  56%
|
|========================================                              |  56%
|
|========================================                              |  57%
|
|========================================                              |  58%
|
|=========================================                             |  58%
|
|=========================================                             |  59%
|
|==========================================                            |  59%
|
|==========================================                            |  60%
|
|==========================================                            |  61%
|
|===========================================                           |  61%
|
|===========================================                           |  62%
|
|============================================                          |  62%
|
|============================================                          |  63%
|
|============================================                          |  64%
|
|=============================================                         |  64%
|
|=============================================                         |  65%
|
|==============================================                        |  65%
|
|==============================================                        |  66%
|
|===============================================                       |  67%
|
|===============================================                       |  68%
|
|================================================                      |  68%
|
|================================================                      |  69%
|
|=================================================                     |  70%
|
|==================================================                    |  71%
|
|==================================================                    |  72%
|
|===================================================                   |  72%
|
|===================================================                   |  73%
|
|====================================================                  |  74%
|
|====================================================                  |  75%
|
|=====================================================                 |  75%
|
|=====================================================                 |  76%
|
|======================================================                |  76%
|
|======================================================                |  77%
|
|======================================================                |  78%
|
|=======================================================               |  78%
|
|=======================================================               |  79%
|
|========================================================              |  79%
|
|========================================================              |  80%
|
|========================================================              |  81%
|
|=========================================================             |  81%
|
|=========================================================             |  82%
|
|==========================================================            |  82%
|
|==========================================================            |  83%
|
|==========================================================            |  84%
|
|===========================================================           |  84%
|
|===========================================================           |  85%
|
|============================================================          |  85%
|
|============================================================          |  86%
|
|=============================================================         |  87%
|
|=============================================================         |  88%
|
|==============================================================        |  88%
|
|==============================================================        |  89%
|
|===============================================================       |  90%
|
|================================================================      |  91%
|
|================================================================      |  92%
|
|=================================================================     |  92%
|
|=================================================================     |  93%
|
|==================================================================    |  94%
|
|==================================================================    |  95%
|
|===================================================================   |  95%
|
|===================================================================   |  96%
|
|====================================================================  |  96%
|
|====================================================================  |  97%
|
|====================================================================  |  98%
|
|===================================================================== |  98%
|
|===================================================================== |  99%
|
|======================================================================|  99%
|
|======================================================================| 100%
#>
|
|                                                                      |   0%
|
|====                                                                  |   6%
|
|========                                                              |  11%
|
|============                                                          |  17%
|
|================                                                      |  22%
|
|===================                                                   |  28%
|
|=======================                                               |  33%
|
|===========================                                           |  39%
|
|===============================                                       |  44%
|
|===================================                                   |  50%
|
|=======================================                               |  56%
|
|===========================================                           |  61%
|
|===============================================                       |  67%
|
|===================================================                   |  72%
|
|======================================================                |  78%
|
|==========================================================            |  83%
|
|==============================================================        |  89%
|
|==================================================================    |  94%
|
|======================================================================| 100%

## Plot convex hull
## blue: convex hull for samples; red: convex hull for types
### All bootstrap samples
plot_ca(zuni_keep) +
ggplot2::scale_fill_manual(values = c(columns = "red", rows = "blue")) +
ggplot2::theme_bw()
### Only retained samples
plot_ca(zuni_keep, keep = "rows") +
ggplot2::scale_fill_manual(values = c(columns = "red", rows = "blue")) +
ggplot2::theme_bw()

## Histogram of convex hull maximum dimension length
hull_length <- cbind.data.frame(length = zuni_keep[["lengths"]][[1]])
ggplot2::ggplot(data = hull_length, mapping = ggplot2::aes(x = length)) +
ggplot2::geom_histogram(breaks = seq(0, 4.5, by = 0.5), fill = "grey70") +
ggplot2::geom_vline(xintercept = fun(hull_length\$length), colour = "red") +
ggplot2::labs(title = "Convex hull max. dim.",
x = "Maximum length", y = "Count") +
ggplot2::theme_bw()

If the results of refine_seriation is used as an input argument in seriate, a correspondence analysis is performed on the subset of object which matches the samples to be kept. Then excluded samples are projected onto the dimensions of the CA coordinate space using the row transition formulae. Finally, row coordinates onto the first dimension give the seriation order.

## Get CA-based seriation order
(zuni_refined <- seriate_correspondence(zuni_counts, zuni_keep, margin = 1))
#> <PermutationOrder>
#> Permutation order for matrix seriation:
#> - Row order: 372 350 387 367 110 417 364 357 407 406 344 348 16...
#> - Column order: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18...
#> - Method: refined correspondence


# References

Desachy, Bruno. 2004. “Le Sériographe EPPM: Un Outil Informatisé de Sériation Graphique Pour Tableaux de Comptages.” Revue Archéologique de Picardie 3 (1): 39–56. https://doi.org/10.3406/pica.2004.2396.

Dunnell, Robert C. 1970. “Seriation Method and Its Evaluation.” American Antiquity 35 (3): 305–19. https://doi.org/10.2307/278341.

Ihm, Peter. 2005. “A Contribution to the History of Seriation in Archaeology.” In Classification – the Ubiquitous Challenge, edited by Claus Weihs and Wolfgang Gaul, 307–16. Berlin Heidelberg: Springer. https://doi.org/10.1007/3-540-28084-7_34.

Peeples, Matthew A., and Gregson Schachner. 2012. “Refining Correspondence Analysis-Based Ceramic Seriation of Regional Data Sets.” Journal of Archaeological Science 39 (8): 2818–27. https://doi.org/10.1016/j.jas.2012.04.040.