## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4
)
set.seed(1234)

## ----install, eval=FALSE------------------------------------------------------
# install.packages("rEMM")

## ----load-package-------------------------------------------------------------
library(rEMM)

## ----data---------------------------------------------------------------------
data("EMMsim")
dim(EMMsim_train)
head(EMMsim_train)
head(EMMsim_sequence_train, 10)

## ----sequence-plot------------------------------------------------------------
plot(EMMsim_train, type = "n", xlab = "x", ylab = "y")
lines(EMMsim_train, col = "gray80")
points(EMMsim_train, pch = EMMsim_sequence_train)
legend("topleft", legend = paste("Cluster", 1:4), pch = 1:4, bty = "n")

## ----build-model--------------------------------------------------------------
emm <- EMM(threshold = 0.1, measure = "euclidean")
build(emm, EMMsim_train)
emm

## ----inspect-model------------------------------------------------------------
size(emm)
head(cluster_centers(emm))
head(sort(cluster_counts(emm), decreasing = TRUE))
head(last_clustering(emm), 10)

## ----first-model-plot---------------------------------------------------------
plot(emm, method = "MDS", main = "EMM")

## ----recluster----------------------------------------------------------------
emm4 <- recluster_hclust(emm, k = 4, method = "average")
emm4
cluster_centers(emm4)
cluster_counts(emm4)

## ----model-plot---------------------------------------------------------------
plot(emm4, method = "MDS", main = "Reclustered EMM")

## ----transitions--------------------------------------------------------------
transition_matrix(emm4, prior = FALSE)

## ----score-sequences----------------------------------------------------------
set.seed(1234)
test_shuffled <- EMMsim_test[sample(nrow(EMMsim_test)), , drop = FALSE]
c(
  ordered = score(emm4, EMMsim_test,
    method = "product", match_cluster = "nn", prior = TRUE),
  shuffled = score(emm4, test_shuffled,
    method = "product", match_cluster = "nn", prior = TRUE)
)

## ----predict-state------------------------------------------------------------
predict(emm4, current_state = "1", n = 2,
  probabilities = TRUE, prior = TRUE)

## ----incremental-build--------------------------------------------------------
emm_updated <- copy(emm)
reset(emm_updated)
build(emm_updated, EMMsim_test)

c(
  original_observations = sum(cluster_counts(emm)),
  updated_observations = sum(cluster_counts(emm_updated))
)

