---
title: "STMotif R Package"
author: "Heraldo Borges, Amin Bazaz, Eduardo Ogasawara"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Spatial-Time Motif Discovery with STMotif}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

The goal of the `STMotif` R package is to allow the discovery and ranking
of motifs in spatial-time series quickly and efficiently.

```{r load-package}
library(STMotif)
```

### Introduction

A pattern that significantly occurs in a time series is called a motif.
In spatial time series data, these patterns may not be substantially present
in a single time series but dispersed over several time series, limited in
both space and time. The `STMotif` package was developed to simplify
spatio-temporal data mining in the search for these motifs. We present the
functions available in the package through the sample dataset, also available
in this package.

Install the package from CRAN:

```{r, eval = FALSE}
install.packages("STMotif")
```

The package provides two categories of functions: functions for discovering
and ranking motifs (`CSAMiningProcess`) and functions for viewing the
identified motifs.


### 1. CSAMiningProcess

1. The function `NormSAX` normalizes the dataset and applies SAX encoding.

```{r normsax}
# Load the example dataset
dim(D <- STMotif::example_dataset)

# Normalization and SAX encoding
DS <- NormSAX(D = STMotif::example_dataset, a = 5)

# Preview the SAX-encoded dataset
head(NormSAX(D = STMotif::example_dataset, a = 5)[, 1:10])
```

2. The function `SearchSTMotifs` checks and filters the motifs, grouping
   motifs from neighboring blocks.

```{r search}
# Discover motifs
stmotifs <- SearchSTMotifs(D, DS, 4, 5, 4, 10, 2, 2)
stmotifs[[1]]
```

3. The function `RankSTMotifs` ranks the motifs, balancing distance among
   occurrences with the encoded information of the motif and its quantity.

```{r rank}
# Rank the discovered motifs
rstmotifs <- RankSTMotifs(stmotifs)
rstmotifs[[1]]
```

4. The complete workflow is wrapped in `CSAMiningProcess`:

```{r csa}
# Full CSA workflow in one call
rstmotifs <- CSAMiningProcess(D, DS, 4, 5, 4, 10, 2, 2)
rstmotifs[[1]]
```


### 2. Visualization

Plot a heatmap of the dataset with the selected motifs highlighted:

```{r fig-heatmap, fig.height = 4, fig.width = 5, fig.align = "center"}
display_motifsDataset(
  dataset = STMotif::example_dataset,
  rstmotifs[c(1:4)],
  5
)
```

Plot the selected spatial-time series with the motifs highlighted:

```{r fig-series, fig.height = 4, fig.width = 5, fig.align = "center"}
display_motifsSTSeries(
  dataset = STMotif::example_dataset,
  rstmotifs[c(1:4)],
  space = c(1:4, 10:12)
)
```
