Package {mixvlmc}


Type: Package
Title: Variable Length Markov Chains with Covariates
Version: 0.3.1
Description: Estimates Variable Length Markov Chains (VLMC) and VLMC with covariates from discrete sequences. Supports model selection via information criteria, likelihood computation, prediction and simulation of new sequences from an estimated model. See Bühlmann, P. and Wyner, A. J. (1999) <doi:10.1214/aos/1018031204> for VLMC and Zanin Zambom, A., Kim, S. and Lopes Garcia, N. (2022) <doi:10.1111/jtsa.12615> for VLMC with covariates.
License: GPL (≥ 3)
URL: https://github.com/fabrice-rossi/mixvlmc, https://fabrice-rossi.github.io/mixvlmc/
BugReports: https://github.com/fabrice-rossi/mixvlmc/issues
Encoding: UTF-8
Language: en-GB
LazyData: true
Imports: assertthat, butcher, cli, lifecycle (≥ 1.0.3), methods, nnet, pROC, Rcpp (≥ 1.0.8.3), rlang (≥ 1.0.0), stats, stringr, VGAM, withr, xtable
LinkingTo: Rcpp
Suggests: data.table, foreach, geodist, ggplot2, knitr, rmarkdown, testthat (≥ 3.0.0), tibble, vdiffr, waldo
Config/testthat/edition: 3
Config/testthat/parallel: true
Config/testthat/start-first: covlmc*
Depends: R (≥ 4.1.0)
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.0
NeedsCompilation: yes
Packaged: 2026-11-26 20:37:06 UTC; fabrice
Author: Fabrice Rossi ORCID iD [aut, cre, cph], Hugo Le Picard ORCID iD [ctb], Guénolé Joubioux [ctb]
Maintainer: Fabrice Rossi <Fabrice.Rossi@apiacoa.org>
Repository: CRAN
Date/Publication: 2026-11-27 15:40:17 UTC

mixvlmc: Variable Length Markov Chains with Covariates

Description

Estimates Variable Length Markov Chains (VLMC) and VLMC with covariates from discrete sequences. Supports model selection via information criteria, likelihood computation, prediction and simulation of new sequences from an estimated model. See Bühlmann, P. and Wyner, A. J. (1999) doi:10.1214/aos/1018031204 for VLMC and Zanin Zambom, A., Kim, S. and Lopes Garcia, N. (2022) doi:10.1111/jtsa.12615 for VLMC with covariates.

Package options

mixvlmc uses the following options(), which are set when the package is loaded (unless they are already set):

Author(s)

Maintainer: Fabrice Rossi Fabrice.Rossi@apiacoa.org (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Convert an object to a Variable Length Markov Chain with covariates (COVLMC)

Description

This generic function converts an object into a VLMC with covariates (a covlmc object).

Usage

as_covlmc(x, ...)

## S3 method for class 'tune_covlmc'
as_covlmc(x, ...)

Arguments

x

an object to convert into a covlmc object, for instance the result of tune_covlmc().

...

additional arguments for conversion functions.

Value

a covlmc object. For a tune_covlmc object, this is the best model selected by tune_covlmc().

See Also

tune_covlmc()

Examples

## conversion from the results of tune_covlmc()
pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
rdts_best_model_tune <- tune_covlmc(rdts, rdts_cov)
rdts_best_model <- as_covlmc(rdts_best_model_tune)
draw(rdts_best_model)

Extract the sequence encoded by a node

Description

This function returns the sequence represented by the node object.

Usage

as_sequence(node, reverse)

Arguments

node

a ctx_node object as returned by find_sequence()

reverse

specifies whether the sequence should be reported in reverse temporal order (TRUE) or in the temporal order (FALSE). Defaults to the order associated with the ctx_node which is determined by the parameters of the call to contexts() or find_sequence() (see is_reversed()).

Value

the sequence represented by the node object, a vector

Examples

rdts <- c("A", "B", "C", "A", "A", "B", "B", "C", "C", "A")
rdts_tree <- ctx_tree(rdts, max_depth = 3)
res <- find_sequence(rdts_tree, c("A", "B"))
as_sequence(res)
as_sequence(res, reverse = TRUE)

Convert an object to a Variable Length Markov Chain (VLMC)

Description

This generic function converts an object into a VLMC.

Usage

as_vlmc(x, ...)

## S3 method for class 'ctx_tree'
as_vlmc(x, alpha, cutoff, ...)

## S3 method for class 'tune_vlmc'
as_vlmc(x, ...)

Arguments

x

an object to convert into a VLMC.

...

additional arguments for conversion functions.

alpha

cut off parameter applied during the conversion, quantile scale (if specified).

cutoff

cut off parameter applied during the conversion, native scale (if specified). Takes precedence over alpha if both are specified.

Details

When x is a context tree, the function converts it into a VLMC. If alpha or cutoff is specified, it is used to reduce the complexity of the tree as in a direct call to vlmc() (see also prune()). Otherwise, the tree is converted without pruning (the cut off of the resulting VLMC is 0 in native scale, i.e. 1 in quantile scale).

When x is the result of tune_vlmc(), the function returns the best model selected by tune_vlmc().

Value

a VLMC.

See Also

ctx_tree()

tune_vlmc()

Examples

## conversion from a context tree
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
draw(rdts_ctree)
rdts_vlmc <- as_vlmc(rdts_ctree)
class(rdts_vlmc)
draw(rdts_vlmc)
## conversion with pruning
rdts_pruned_vlmc <- as_vlmc(rdts_ctree, alpha = 0.25)
draw(rdts_pruned_vlmc)
## conversion from the result of tune_vlmc()
pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
tune_result <- tune_vlmc(rdts)
tune_result
rdts_best_vlmc <- as_vlmc(tune_result)
draw(rdts_best_vlmc)

Convert an object to a Variable Length Markov Chain (VLMC)

Description

This generic function converts an object into a VLMC.

Usage

## S3 method for class 'ctx_tree_cpp'
as_vlmc(x, alpha, cutoff, ...)

Arguments

x

an object to convert into a VLMC.

alpha

cut off parameter applied during the conversion, quantile scale (if specified).

cutoff

cut off parameter applied during the conversion, native scale (if specified). Takes precedence over alpha if both are specified.

...

additional arguments for conversion functions.

Details

When x is a context tree, the function converts it into a VLMC. If alpha or cutoff is specified, it is used to reduce the complexity of the tree as in a direct call to vlmc() (see also prune()). Otherwise, the tree is converted without pruning (the cut off of the resulting VLMC is 0 in native scale, i.e. 1 in quantile scale).

When x is the result of tune_vlmc(), the function returns the best model selected by tune_vlmc().

Value

a VLMC.

See Also

ctx_tree()

tune_vlmc()

Examples

## conversion from a context tree
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3, backend = "C++")
draw(rdts_ctree)
rdts_vlmc <- as_vlmc(rdts_ctree)
class(rdts_vlmc)
draw(rdts_vlmc)


Create a complete ggplot for the results of automatic COVLMC complexity selection

Description

This function prepares a plot of the results of tune_covlmc() using ggplot2. The result can be passed to print() to display the plot.

Usage

## S3 method for class 'tune_covlmc'
autoplot(object, ...)

Arguments

object

a tune_covlmc object

...

additional parameters (not used currently)

Details

The graphical representation proposed by this function is complete, while the one produced by plot.tune_covlmc() is minimalist. We use here the faceting capabilities of ggplot2 to combine on a single graphical representation the evolution of multiple characteristics of the COVLMC during the pruning process (depth, number of contexts, log-likelihood, covariate depth and information criteria), while plot.tune_covlmc() shows only the selection criterion or the log-likelihood. Each facet of the resulting plot shows a quantity as a function of the cut off expressed in quantile scale (the only scale available for COVLMC).

Value

a ggplot object

Examples


pc <- powerconsumption[powerconsumption$week %in% 10:12, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
rdts_best_model_tune <- tune_covlmc(rdts, rdts_cov, criterion = "AIC")
covlmc_plot <- ggplot2::autoplot(rdts_best_model_tune)
print(covlmc_plot)


Create a complete ggplot for the results of automatic VLMC complexity selection

Description

This function prepares a plot of the results of tune_vlmc() using ggplot2. The result can be passed to print() to display the plot.

Usage

## S3 method for class 'tune_vlmc'
autoplot(object, cutoff = c("quantile", "native"), ...)

Arguments

object

a tune_vlmc object

cutoff

the scale used for the cut off criterion on the x axis, either "quantile" (default) or "native"

...

additional parameters (not used currently)

Details

The graphical representation proposed by this function is complete, while the one produced by plot.tune_vlmc() is minimalist. We use here the faceting capabilities of ggplot2 to combine on a single graphical representation the evolution of multiple characteristics of the VLMC during the pruning process (depth, number of contexts, log-likelihood and information criteria), while plot.tune_vlmc() shows only the selection criterion or the log-likelihood. Each facet of the resulting plot shows a quantity as a function of the cut off expressed in quantile or native scale.

Value

a ggplot object

Examples


pc <- powerconsumption[powerconsumption$week %in% 10:11, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_best_model_tune <- tune_vlmc(rdts, criterion = "BIC")
vlmc_plot <- ggplot2::autoplot(rdts_best_model_tune)
print(vlmc_plot)
## simple post customisation
print(vlmc_plot + ggplot2::geom_point())
## cut off in native scale
print(ggplot2::autoplot(rdts_best_model_tune, cutoff = "native"))


ASCII character set for context tree text representation

Description

This function returns a list of ASCII characters used to fine-tune the behaviour of the draw() function when it is used with format="text". It can be used as is or customised using its parameters, and is generally passed to draw_control() via its charset parameter.

Usage

charset_ascii(
  root = "*",
  first_node = "+",
  next_node = "+",
  final_node = "'",
  vbranch = "|",
  hbranch = "--",
  open_ct = "(",
  close_ct = ")",
  level_sep = " ~ ",
  time_sep = " | ",
  intercept = "(I)",
  intercept_sep = " & ",
  open_p_value = "<",
  close_p_value = ">",
  open_model = "[",
  close_model = "]"
)

Arguments

root

character used for the root node.

first_node

characters used for the first child of a node.

next_node

characters used for intermediate children of a node.

final_node

characters used for the last child of a node.

vbranch

characters used to represent a branch in a vertical way.

hbranch

characters used to represent a branch in a horizontal way.

open_ct

characters used to start the node specific text representation of each node.

close_ct

characters used to end the node specific text representation of each node.

level_sep

characters used to separate levels from models in draw.covlmc().

time_sep

characters used to separate temporal blocks in draw.covlmc().

intercept

characters used to represent the intercept in draw.covlmc().

intercept_sep

characters used to separate the intercept from the other parameters in draw.covlmc().

open_p_value

characters used as opening delimiters for the p-value of a node in draw.covlmc().

close_p_value

characters used as closing delimiters for the p-value of a node in draw.covlmc().

open_model

characters used as opening delimiters for the representation of a model in draw.covlmc().

close_model

characters used as closing delimiters for the representation of a model in draw.covlmc().

Value

a list of character strings, one per parameter.

See Also

draw(), draw_control(), charset_utf8().

Examples

charset_ascii(root = "x")
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
draw(rdts_ctree, control = draw_control(charset = charset_ascii(root = "x")))

UTF-8 character set for context tree text representation

Description

This function returns a list of UTF-8 characters and symbols used to fine-tune the behaviour of the draw() function when it is used with format="text". It can be used as is or customised using its parameters, and is generally passed to draw_control() via its charset parameter.

Usage

charset_utf8(
  root = "\u25AA",
  first_node = "\u251C",
  next_node = "\u251C",
  final_node = "\u2514",
  vbranch = "\u2502",
  hbranch = "\u2500",
  open_ct = "(",
  close_ct = ")",
  level_sep = " ~ ",
  time_sep = " \u205E ",
  intercept = "(I)",
  intercept_sep = " \u2022 ",
  open_p_value = "\u2039",
  close_p_value = "\u203A",
  open_model = "[",
  close_model = "]"
)

Arguments

root

character used for the root node.

first_node

characters used for the first child of a node.

next_node

characters used for intermediate children of a node.

final_node

characters used for the last child of a node.

vbranch

characters used to represent a branch in a vertical way.

hbranch

characters used to represent a branch in a horizontal way.

open_ct

characters used to start the node specific text representation of each node.

close_ct

characters used to end the node specific text representation of each node.

level_sep

characters used to separate levels from models in draw.covlmc().

time_sep

characters used to separate temporal blocks in draw.covlmc().

intercept

characters used to represent the intercept in draw.covlmc().

intercept_sep

characters used to separate the intercept from the other parameters in draw.covlmc().

open_p_value

characters used as opening delimiters for the p-value of a node in draw.covlmc().

close_p_value

characters used as closing delimiters for the p-value of a node in draw.covlmc().

open_model

characters used as opening delimiters for the representation of a model in draw.covlmc().

close_model

characters used as closing delimiters for the representation of a model in draw.covlmc().

Value

a list of character strings, one per parameter.

See Also

draw(), draw_control(), charset_ascii().

Examples

charset_utf8(root = "\u27E1")
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
draw(rdts_ctree,
  control = draw_control(charset = charset_utf8(root = "\u27E1"))
)

Find the children nodes of a node in a context tree

Description

This function returns a list (possibly empty) of ctx_node objects. Each object represents one of the children of the node represented by the node parameter.

Usage

## S3 method for class 'ctx_node_covlmc'
children(node)

children(node)

## S3 method for class 'ctx_node'
children(node)

## S3 method for class 'ctx_node_cpp'
children(node)

Arguments

node

a ctx_node object as returned by find_sequence()

Details

Each node of a context tree represents a sequence. When find_sequence() is called with success, the returned object represents the corresponding node in the context tree. If this node has no children, the present function returns an empty list. When the node has at least one child, the function returns a list with one value for each element in the state space (see states()). The value is NULL if the corresponding child is empty, while it is a ctx_node object when the child is present. Each ctx_node object is associated with the sequence obtained by adding to the past of the sequence represented by node an observation of the associated state (this corresponds to an extension to the left of the sequence in temporal order).

Value

a list of ctx_node objects, see details.

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
ctx_00 <- find_sequence(rdts_ctree, c(0, 0))
## this context can only be extended in the past by 1:
children(ctx_00)
ctx_10 <- find_sequence(rdts_ctree, c(1, 0))
## this context can be extended by both states
children(ctx_10)
## C++ backend
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3, backend = "C++")
ctx_00 <- find_sequence(rdts_ctree, c(0, 0))
## this context can only be extended in the past by 1:
children(ctx_00)
ctx_10 <- find_sequence(rdts_ctree, c(1, 0))
## this context can be extended by both states
children(ctx_10)

Number of contexts of a context tree

Description

This function returns the number of distinct contexts in a context tree.

Usage

context_number(ct)

Arguments

ct

a context tree.

Value

the number of contexts of the tree.

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
# should be 8
context_number(rdts_ctree)

Number of contexts of a VLMC with covariates

Description

This function returns the total number of contexts of a VLMC with covariates.

Usage

## S3 method for class 'covlmc'
context_number(ct)

Arguments

ct

a fitted VLMC with covariates (a covlmc object).

Value

the number of contexts present in the VLMC with covariates.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
dts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
dts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(dts, dts_cov, min_size = 10)
# should be 3
context_number(m_cov)

Contexts of a context tree

Description

This function extracts from a context tree a description of all of its contexts.

Usage

contexts(ct, sequence = FALSE, reverse = FALSE, ...)

Arguments

ct

a context tree.

sequence

if TRUE the function returns its results as a data.frame, if FALSE (default) as a list of ctx_node objects (see details).

reverse

logical (defaults to FALSE). If TRUE, contexts are given in reverse temporal order. See the dedicated section.

...

additional arguments for the contexts function.

Details

The default behaviour consists in returning a list of all the contexts contained in the tree using ctx_node objects (as returned by e.g. find_sequence()). The properties of the contexts can then be explored using adapted functions such as counts() and positions(). The result list is of class contexts. When sequence=TRUE, the method returns a data.frame whose first column, named context, contains the contexts as vectors (i.e. the value returned by as_sequence() applied to a ctx_node object). Other columns contain context specific values which depend on the actual class of the tree and on additional parameters. In all implementations of contexts(), setting the additional parameters to any non-default value leads to a data.frame result.

Value

A list of class contexts containing the contexts represented in this tree (as ctx_node) or a data.frame.

State order in a context

Notice that contexts are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. Set reverse to TRUE for the reverse convention which is somewhat easier to relate to the way the context trees are represented by draw() (i.e. recent values at the top of the tree).

See Also

find_sequence() and find_sequence.covlmc() for direct access to a specific context, and contexts.ctx_tree(), contexts.vlmc() and contexts.covlmc() for concrete implementations of contexts().

Examples

set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
rdts_tree <- ctx_tree(rdts, max_depth = 3, min_size = 5)
contexts(rdts_tree)
contexts(rdts_tree, sequence = TRUE, reverse = TRUE)

Contexts of a VLMC with covariates

Description

This function returns the different contexts present in a VLMC with covariates, possibly with some associated data.

Usage

## S3 method for class 'covlmc'
contexts(
  ct,
  sequence = FALSE,
  reverse = FALSE,
  frequency = NULL,
  positions = FALSE,
  local = FALSE,
  metrics = FALSE,
  model = NULL,
  hsize = FALSE,
  merging = FALSE,
  ...
)

Arguments

ct

a fitted VLMC with covariates (a covlmc object).

sequence

if TRUE the function returns its results as a data.frame, if FALSE (default) as a list of ctx_node objects (see details).

reverse

logical (defaults to FALSE). If TRUE, contexts are given in reverse temporal order. See the dedicated section.

frequency

specifies the counts to be included in the result data.frame. The default value of NULL does not include anything. "total" gives the number of occurrences of each context in the original sequence. "detailed" includes in addition the breakdown of these occurrences into all the possible states.

positions

logical (defaults to FALSE). Specifies whether the positions of each context in the time series used to build the context tree should be reported in a positions column of the result data frame. The availability of the positions depends on the way the context tree was built (see the keep_position parameter of ctx_tree()). See the dedicated section for the definition of a position.

local

specifies how the counts reported by frequency are computed. When local is FALSE (default value) the counts include both counts that are specific to the context (if any) and counts from the descendants of the context in the tree. When local is TRUE the counts include only the number of times the context appears without being the last part of a longer context.

metrics

if TRUE, adds predictive metrics for each context (see metrics() for the definition of predictive metrics).

model

specifies whether to include the model associated with each context. The default result with model=NULL does not include any model. Setting model to "coef" adds the coefficients of the models in a coef column, while "full" includes the models themselves (as R objects) in a model column (not supported by fully trimmed models, see trim.covlmc()).

hsize

if TRUE, adds a hsize column to the result data frame that gives for each context the size of the history of covariates used by the model (see covariate_memory()).

merging

if TRUE, adds a merged column to the result data frame. For a normal context, the value of merged is FALSE. Contexts that share the same model have a TRUE merged value (see is_merged()).

...

additional arguments for the contexts function.

Details

The default behaviour of the function is to return a list of all the contexts using ctx_node_covlmc objects (as returned by find_sequence.covlmc()). The properties of the contexts can then be explored using adapted functions such as counts(), covariate_memory(), cutoff.ctx_node(), metrics.ctx_node(), model(), merged_with() and positions().

When sequence=TRUE the method returns a data.frame whose first column, named context, contains the contexts as vectors (i.e. the value returned by as_sequence() applied to a ctx_node object). Other columns contain context specific values specified by the additional parameters. Setting any of those parameters to a value that asks for reporting information will toggle the result type of the function to data.frame.

See contexts.ctx_tree() for details about the frequency parameter. When model is non NULL, the resulting data.frame contains the models associated with each context (either the full R model or its coefficients). Other columns are added if the corresponding parameters are set to TRUE.

Value

A list of class contexts containing the contexts represented in this tree (as ctx_node_covlmc) or a data.frame.

Positions

A position of a context ctx in the time series x is an index value t such that the context ends with x[t]. Thus x[t+1], when it exists, is the value that follows the context. For instance if x=c(0, 0, 1, 1) and ctx=c(0, 1) (in standard state order), then the position of ctx in x is 3.

Positions include all the occurrences of a context, including an occurrence at the end of the time series (t=length(x)), which is not followed by any value. Such an occurrence is not included in the frequencies, which count the values that follow the context: the number of positions of a context can therefore exceed its frequency by one.

State order in a context

Notice that contexts are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. Set reverse to TRUE for the reverse convention which is somewhat easier to relate to the way the context trees are represented by draw() (i.e. recent values at the top of the tree).

See Also

find_sequence() and find_sequence.covlmc() for direct access to a specific context, and contexts.ctx_tree(), contexts.vlmc() and contexts.covlmc() for concrete implementations of contexts().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(0, median(pc$active_power), max(pc$active_power))
dts <- cut(pc$active_power, breaks = breaks)
dts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(dts, dts_cov, min_size = 5)
## direct representation with ctx_node_covlmc objects
m_cov_ctxs <- contexts(m_cov)
m_cov_ctxs
sapply(m_cov_ctxs, covariate_memory)
sapply(m_cov_ctxs, is_merged)
sapply(m_cov_ctxs, model)
## data.frame interface
contexts(m_cov, model = "coef")
contexts(m_cov, model = "full", hsize = TRUE)
contexts(m_cov, metrics = TRUE, merging = TRUE)

Contexts of a context tree

Description

This function extracts from a context tree a description of all of its contexts.

Usage

## S3 method for class 'ctx_tree'
contexts(
  ct,
  sequence = FALSE,
  reverse = FALSE,
  frequency = NULL,
  positions = FALSE,
  ...
)

## S3 method for class 'ctx_tree_cpp'
contexts(
  ct,
  sequence = FALSE,
  reverse = FALSE,
  frequency = NULL,
  positions = FALSE,
  ...
)

Arguments

ct

a context tree.

sequence

if TRUE the function returns its results as a data.frame, if FALSE (default) as a list of ctx_node objects (see details).

reverse

logical (defaults to FALSE). If TRUE, contexts are given in reverse temporal order. See the dedicated section.

frequency

specifies the counts to be included in the result data.frame. The default value of NULL does not include anything. "total" gives the number of occurrences of each context in the original sequence. "detailed" includes in addition the breakdown of these occurrences into all the possible states.

positions

logical (defaults to FALSE). Specifies whether the positions of each context in the time series used to build the context tree should be reported in a positions column of the result data frame. The availability of the positions depends on the way the context tree was built (see the keep_position parameter of ctx_tree()). See the dedicated section for the definition of a position.

...

additional arguments for the contexts function.

Details

The default behaviour of the function is to return a list of all the contexts using ctx_node objects (as returned by find_sequence()). The properties of the contexts can then be explored using adapted functions such as counts() and positions().

When sequence=TRUE the method returns a data.frame whose first column, named context, contains the contexts as vectors (i.e. the value returned by as_sequence() applied to a ctx_node object). Other columns contain context specific values specified by the additional parameters. Setting any of those parameters to a value that asks for reporting information will toggle the result type of the function to data.frame.

If frequency="total", an additional column named freq gives the number of occurrences of each context in the series used to build the tree. If frequency="detailed", one additional column is added per state in the context space. Each column records the number of times a given context is followed by the corresponding value in the original series.

Value

A list of class contexts containing the contexts represented in this tree (as ctx_node) or a data.frame.

Positions

A position of a context ctx in the time series x is an index value t such that the context ends with x[t]. Thus x[t+1], when it exists, is the value that follows the context. For instance if x=c(0, 0, 1, 1) and ctx=c(0, 1) (in standard state order), then the position of ctx in x is 3.

Positions include all the occurrences of a context, including an occurrence at the end of the time series (t=length(x)), which is not followed by any value. Such an occurrence is not included in the frequencies, which count the values that follow the context: the number of positions of a context can therefore exceed its frequency by one.

State order in a context

Notice that contexts are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. Set reverse to TRUE for the reverse convention which is somewhat easier to relate to the way the context trees are represented by draw() (i.e. recent values at the top of the tree).

See Also

find_sequence() and find_sequence.covlmc() for direct access to a specific context, and contexts.ctx_tree(), contexts.vlmc() and contexts.covlmc() for concrete implementations of contexts().

Examples

set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
rdts_tree <- ctx_tree(rdts, max_depth = 3, min_size = 5)
## direct representation with ctx_node objects
contexts(rdts_tree)
## data.frame format
contexts(rdts_tree, sequence = TRUE)
contexts(rdts_tree, frequency = "total")
contexts(rdts_tree, frequency = "detailed")
contexts(rdts_tree, frequency = "total", positions = TRUE)

Contexts of a VLMC

Description

This function extracts all the contexts from a fitted VLMC, possibly with some associated data.

Usage

## S3 method for class 'vlmc'
contexts(
  ct,
  sequence = FALSE,
  reverse = FALSE,
  frequency = NULL,
  positions = FALSE,
  local = FALSE,
  cutoff = NULL,
  metrics = FALSE,
  ...
)

## S3 method for class 'vlmc_cpp'
contexts(
  ct,
  sequence = FALSE,
  reverse = FALSE,
  frequency = NULL,
  positions = FALSE,
  local = FALSE,
  cutoff = NULL,
  metrics = FALSE,
  ...
)

Arguments

ct

a context tree.

sequence

if TRUE the function returns its results as a data.frame, if FALSE (default) as a list of ctx_node objects (see details).

reverse

logical (defaults to FALSE). If TRUE, contexts are given in reverse temporal order. See the dedicated section.

frequency

specifies the counts to be included in the result data.frame. The default value of NULL does not include anything. "total" gives the number of occurrences of each context in the original sequence. "detailed" includes in addition the breakdown of these occurrences into all the possible states.

positions

logical (defaults to FALSE). Specifies whether the positions of each context in the time series used to build the context tree should be reported in a positions column of the result data frame. The availability of the positions depends on the way the context tree was built (see the keep_position parameter of ctx_tree()). See the dedicated section for the definition of a position.

local

specifies how the counts reported by frequency are computed. When local is FALSE (default value) the counts include both counts that are specific to the context (if any) and counts from the descendants of the context in the tree. When local is TRUE the counts include only the number of times the context appears without being the last part of a longer context.

cutoff

specifies whether to include the cut off value associated with each context (see cutoff() and prune()). The default result with cutoff=NULL does not include those values. Setting cutoff to "quantile" adds the cut off values in quantile scale, while cutoff="native" adds them in the native scale. The returned values are directly based on the log likelihood ratio computed in the context tree and are not modified to ensure pruning (as when cutoff() is called with raw=TRUE).

metrics

if TRUE, adds predictive metrics for each context (see metrics() for the definition of predictive metrics). As in metrics.ctx_node(), the AUC of a context is NA.

...

additional arguments for the contexts function.

Details

The default behaviour of the function is to return a list of all the contexts using ctx_node objects (as returned by find_sequence()). The properties of the contexts can then be explored using adapted functions such as counts(), cutoff.ctx_node(), metrics.ctx_node() and positions().

When sequence=TRUE the method returns a data.frame whose first column, named context, contains the contexts as vectors (i.e. the value returned by as_sequence() applied to a ctx_node object). Other columns contain context specific values specified by the additional parameters. Setting any of those parameters to a value that asks for reporting information will toggle the result type of the function to data.frame.

The frequency parameter is described in detail in the documentation of contexts.ctx_tree(). When cutoff is non NULL, the resulting data.frame contains a cutoff column with the cut off values, either in quantile or in native scale. See cutoff.vlmc() and prune.vlmc() for the definitions of cut off values and of the two scales.

Value

A list of class contexts containing the contexts represented in this tree (as ctx_node) or a data.frame.

Cut off values

The cut off values reported by contexts.vlmc() can be different from the ones reported by cutoff.vlmc() for three reasons:

  1. cutoff.vlmc() reports only useful cut off values, i.e., cut off values that should induce a simplification of the VLMC when used in prune(). This excludes cut off values associated with simple contexts that are smaller than the ones of their descendants in the context tree. Those values are reported by contexts.vlmc().

  2. contexts.vlmc() reports only cut off values of actual contexts, while cutoff.vlmc() reports cut off values for all nodes of the context tree.

  3. values are not modified to induce pruning, unlike the default behaviour of cutoff.vlmc().

Positions

A position of a context ctx in the time series x is an index value t such that the context ends with x[t]. Thus x[t+1], when it exists, is the value that follows the context. For instance if x=c(0, 0, 1, 1) and ctx=c(0, 1) (in standard state order), then the position of ctx in x is 3.

Positions include all the occurrences of a context, including an occurrence at the end of the time series (t=length(x)), which is not followed by any value. Such an occurrence is not included in the frequencies, which count the values that follow the context: the number of positions of a context can therefore exceed its frequency by one.

State order in a context

Notice that contexts are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. Set reverse to TRUE for the reverse convention which is somewhat easier to relate to the way the context trees are represented by draw() (i.e. recent values at the top of the tree).

See Also

find_sequence() and find_sequence.covlmc() for direct access to a specific context, and contexts.ctx_tree(), contexts.vlmc() and contexts.covlmc() for concrete implementations of contexts().

Examples

set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
model <- vlmc(rdts, alpha = 0.5)
## direct representation with ctx_node objects
model_ctxs <- contexts(model)
model_ctxs
sapply(model_ctxs, cutoff, scale = "quantile")
sapply(model_ctxs, cutoff, scale = "native")
sapply(model_ctxs, function(x) metrics(x)$accuracy)
## data.frame format
contexts(model, frequency = "total")
contexts(model, cutoff = "quantile")
contexts(model, cutoff = "native", metrics = TRUE)

Report the distribution of values that follow occurrences of a sequence

Description

This function reports the number of occurrences of the sequence represented by node in the original time series used to build the associated context tree (not including a possible final occurrence not followed by any value at the end of the original time series). In addition if frequency="detailed" (default), the function reports the frequencies of each of the possible values of the time series when they appear just after the sequence.

Usage

counts(node, frequency = c("detailed", "total"), local = FALSE)

## S3 method for class 'ctx_node'
counts(node, frequency = c("detailed", "total"), local = FALSE)

## S3 method for class 'ctx_node_cpp'
counts(node, frequency = c("detailed", "total"), local = FALSE)

Arguments

node

a ctx_node object as returned by find_sequence()

frequency

specifies the counts to be included in the result. "total" gives the number of occurrences of the sequence in the original sequence. "detailed" (default) includes in addition the breakdown of these occurrences into all the possible states.

local

specifies how the counts are computed. When local is FALSE (default value) the counts include both counts that are specific to the context (if any) and counts from the descendants of the context in the tree. When local is TRUE the counts include only the number of times the context appears without being the last part of a longer context.

Value

either an integer when frequency="total" which gives the total number of occurrences of the sequence represented by node or a data.frame with a total column with the same value and a column for each of the possible values of the original time series, reporting counts in each column (see the description above).

See Also

contexts() and contexts.ctx_tree()

Examples

set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
rdts_tree <- ctx_tree(rdts, max_depth = 3, min_size = 5)
subseq <- find_sequence(rdts_tree, factor(c("A", "A"), levels = c("A", "B", "C")))
if (!is.null(subseq)) {
  print(counts(subseq))
  print(counts(subseq, frequency = "total"))
  ## counts of "A", "A" when it is not the end of a longer context
  print(counts(subseq, local = TRUE))
}

Maximal covariate memory of a VLMC with covariates

Description

This function returns the longest covariate memory used by a VLMC with covariates, i.e. the largest number of past values of the covariates used by the logistic models of its contexts (see covariate_memory()).

Usage

covariate_depth(model)

Arguments

model

a fitted VLMC with covariates (a covlmc object)

Value

the longest covariate memory of this model (an integer, 0 when no logistic model uses the covariates)

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 10)
covariate_depth(m_cov)
## memory of each context
sapply(contexts(m_cov), covariate_memory)

Covariate memory length for a COVLMC context

Description

This function returns the length of the covariate memory of a COVLMC context represented by a ctx_node_covlmc object, i.e. the number of past values of the covariates used by the logistic model of the context.

Usage

covariate_memory(node)

Arguments

node

A ctx_node_covlmc object as returned by find_sequence.covlmc() or contexts.covlmc()

Value

the memory length, an integer (NULL if node is not a context)

See Also

covariate_depth()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 10)
ctxs <- contexts(m_cov)
## get all the memory lengths
sapply(ctxs, covariate_memory)

Fit a Variable Length Markov Chain with Covariates (COVLMC)

Description

This function fits a Variable Length Markov Chain with covariates (COVLMC) to a discrete time series coupled with a time series of covariates.

Usage

covlmc(
  x,
  covariate,
  alpha = 0.05,
  min_size = 5L,
  max_depth = 100L,
  keep_data = TRUE,
  control = covlmc_control(...),
  ...
)

Arguments

x

an object that can be interpreted as a discrete time series: a numeric, character, factor or logical vector, or a dts object (see dts()). Its state space must contain at least two states.

covariate

a data frame of covariates, with one row per observation of x, at least one column and no missing values.

alpha

number in (0,1] (default: 0.05) cut off value in the pruning phase (in quantile scale).

min_size

number >= 1 (default: 5). Tune the minimum number of observations for a context in the growing phase of the context tree (see below for details).

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

keep_data

logical (defaults to TRUE). If TRUE, the original data are stored in the resulting object to enable post-pruning (see prune.covlmc()).

control

a list with control parameters, see covlmc_control().

...

arguments passed to covlmc_control().

Details

The model is built using the algorithm described in Zanin Zambom et al. As for the vlmc() approach, the algorithm builds first a context tree (see ctx_tree()). The min_size parameter is used to compute the actual number of observations per context in the growing phase of the tree. It is computed as min_size*(1+p*d)*(s-1) where d is the length of the context (a.k.a. the depth in the tree), s is the number of states and p is the number of parameters associated with one time step of the covariates (one per numerical or logical covariate, and the number of levels minus one per factor). This corresponds to ensuring min_size observations per parameter of the logistic regression during the estimation phase.

Then logistic models are fitted in the leaves of the tree: the goal of each logistic model is to estimate the conditional distribution of the next state of the time series given the context (the recent past of the time series) and delayed versions of the covariates. A pruning strategy is used to simplify the models (mainly to reduce the time window associated with the covariates) and the tree itself.

Parameters specified by control are used to fine-tune the behaviour of the algorithm.

Value

a fitted VLMC with covariates, an object of class covlmc.

Logistic models

By default, covlmc uses two different computing engines for logistic models:

It is possible to replace stats::glm() and VGAM::vglm() with nnet::multinom() by setting the global option mixvlmc.predictive to "multinom" (the default value is "glm"). The engines estimate the same models, but their results are not always identical:

The engine used to estimate a COVLMC is recorded in the model: it is also used to estimate the new logistic models needed by prune.covlmc(), even if the option has been changed in between (with a warning).

The number of parameters of a COVLMC, used by stats::AIC() and stats::BIC(), counts the coefficients of the covariates actually estimated by the engine (as a consequence of the last point of the list above) and all the intercepts: it does not depend on the engine (see the "Number of parameters" section of loglikelihood.covlmc()).

References

See Also

cutoff.covlmc() and prune.covlmc() for post-pruning, tune_covlmc() for automatic model selection.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power,
  probs = c(1 / 3, 2 / 3, 1)
)))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 15)
draw(m_cov)
withr::with_options(
  list(mixvlmc.predictive = "multinom"),
  m_cov_nnet <- covlmc(rdts, rdts_cov, min_size = 15)
)
draw(m_cov_nnet)

Fit a Variable Length Markov Chain with Covariates (COVLMC)

Description

This function fits a Variable Length Markov Chain with covariates (COVLMC) to a discrete time series coupled with a time series of covariates.

Usage

## Default S3 method:
covlmc(
  x,
  covariate,
  alpha = 0.05,
  min_size = 5L,
  max_depth = 100L,
  keep_data = TRUE,
  control = covlmc_control(...),
  ...
)

Arguments

x

a numeric, character, factor or logical vector

covariate

a data frame of covariates, with one row per observation of x, at least one column and no missing values.

alpha

number in (0,1] (default: 0.05) cut off value in the pruning phase (in quantile scale).

min_size

number >= 1 (default: 5). Tune the minimum number of observations for a context in the growing phase of the context tree (see below for details).

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

keep_data

logical (defaults to TRUE). If TRUE, the original data are stored in the resulting object to enable post-pruning (see prune.covlmc()).

control

a list with control parameters, see covlmc_control().

...

arguments passed to covlmc_control().

Details

The model is built using the algorithm described in Zanin Zambom et al. As for the vlmc() approach, the algorithm builds first a context tree (see ctx_tree()). The min_size parameter is used to compute the actual number of observations per context in the growing phase of the tree. It is computed as min_size*(1+p*d)*(s-1) where d is the length of the context (a.k.a. the depth in the tree), s is the number of states and p is the number of parameters associated with one time step of the covariates (one per numerical or logical covariate, and the number of levels minus one per factor). This corresponds to ensuring min_size observations per parameter of the logistic regression during the estimation phase.

Then logistic models are fitted in the leaves of the tree: the goal of each logistic model is to estimate the conditional distribution of the next state of the time series given the context (the recent past of the time series) and delayed versions of the covariates. A pruning strategy is used to simplify the models (mainly to reduce the time window associated with the covariates) and the tree itself.

Parameters specified by control are used to fine-tune the behaviour of the algorithm.

Value

a fitted VLMC with covariates, an object of class covlmc.

Logistic models

By default, covlmc uses two different computing engines for logistic models:

It is possible to replace stats::glm() and VGAM::vglm() with nnet::multinom() by setting the global option mixvlmc.predictive to "multinom" (the default value is "glm"). The engines estimate the same models, but their results are not always identical:

The engine used to estimate a COVLMC is recorded in the model: it is also used to estimate the new logistic models needed by prune.covlmc(), even if the option has been changed in between (with a warning).

The number of parameters of a COVLMC, used by stats::AIC() and stats::BIC(), counts the coefficients of the covariates actually estimated by the engine (as a consequence of the last point of the list above) and all the intercepts: it does not depend on the engine (see the "Number of parameters" section of loglikelihood.covlmc()).

References

See Also

cutoff.covlmc() and prune.covlmc() for post-pruning, tune_covlmc() for automatic model selection.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power,
  probs = c(1 / 3, 2 / 3, 1)
)))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 15)
draw(m_cov)
withr::with_options(
  list(mixvlmc.predictive = "multinom"),
  m_cov_nnet <- covlmc(rdts, rdts_cov, min_size = 15)
)
draw(m_cov_nnet)

Fit a Variable Length Markov Chain with Covariates (COVLMC)

Description

This function fits a Variable Length Markov Chain with covariates (COVLMC) to a discrete time series coupled with a time series of covariates.

Usage

## S3 method for class 'dts'
covlmc(
  x,
  covariate,
  alpha = 0.05,
  min_size = 5L,
  max_depth = 100L,
  keep_data = TRUE,
  control = covlmc_control(...),
  ...
)

Arguments

x

a discrete time series represented by a dts object as created by dts()

covariate

a data frame of covariates, with one row per observation of x, at least one column and no missing values.

alpha

number in (0,1] (default: 0.05) cut off value in the pruning phase (in quantile scale).

min_size

number >= 1 (default: 5). Tune the minimum number of observations for a context in the growing phase of the context tree (see below for details).

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

keep_data

logical (defaults to TRUE). If TRUE, the original data are stored in the resulting object to enable post-pruning (see prune.covlmc()).

control

a list with control parameters, see covlmc_control().

...

arguments passed to covlmc_control().

Details

The model is built using the algorithm described in Zanin Zambom et al. As for the vlmc() approach, the algorithm builds first a context tree (see ctx_tree()). The min_size parameter is used to compute the actual number of observations per context in the growing phase of the tree. It is computed as min_size*(1+p*d)*(s-1) where d is the length of the context (a.k.a. the depth in the tree), s is the number of states and p is the number of parameters associated with one time step of the covariates (one per numerical or logical covariate, and the number of levels minus one per factor). This corresponds to ensuring min_size observations per parameter of the logistic regression during the estimation phase.

Then logistic models are fitted in the leaves of the tree: the goal of each logistic model is to estimate the conditional distribution of the next state of the time series given the context (the recent past of the time series) and delayed versions of the covariates. A pruning strategy is used to simplify the models (mainly to reduce the time window associated with the covariates) and the tree itself.

Parameters specified by control are used to fine-tune the behaviour of the algorithm.

Value

a fitted VLMC with covariates, an object of class covlmc.

Logistic models

By default, covlmc uses two different computing engines for logistic models:

It is possible to replace stats::glm() and VGAM::vglm() with nnet::multinom() by setting the global option mixvlmc.predictive to "multinom" (the default value is "glm"). The engines estimate the same models, but their results are not always identical:

The engine used to estimate a COVLMC is recorded in the model: it is also used to estimate the new logistic models needed by prune.covlmc(), even if the option has been changed in between (with a warning).

The number of parameters of a COVLMC, used by stats::AIC() and stats::BIC(), counts the coefficients of the covariates actually estimated by the engine (as a consequence of the last point of the list above) and all the intercepts: it does not depend on the engine (see the "Number of parameters" section of loglikelihood.covlmc()).

References

See Also

cutoff.covlmc() and prune.covlmc() for post-pruning, tune_covlmc() for automatic model selection.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
power_dts <- dts(cut(pc$active_power, breaks = c(0, quantile(pc$active_power,
  probs = c(1 / 3, 2 / 3, 1)
))))
power_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(power_dts, power_cov, min_size = 15)
draw(m_cov)

Control for COVLMC fitting

Description

This function creates a list with parameters used to fine-tune the COVLMC fitting algorithm.

Usage

covlmc_control(pseudo_obs = 1)

Arguments

pseudo_obs

number of fake observations of each state to add to the observed ones (a positive number, default: 1).

Details

pseudo_obs is used to regularise the probability estimations when a context is always followed by the same state in the observed time series. Transition probabilities are then computed after adding pseudo_obs pseudo-observations of each of the states (including the observed one). This corresponds to a Bayesian posterior mean estimation with a Dirichlet prior.

Value

a list with a pseudo_obs component, to be used as the control parameter of covlmc() or tune_covlmc().

Examples

rdts <- rep(c(0, 1), 100)
rdts_cov <- data.frame(y = rep(0, length(rdts)))
default_model <- covlmc(rdts, rdts_cov)
contexts(default_model, model = "coef")$coef
control <- covlmc_control(pseudo_obs = 10)
model <- covlmc(rdts, rdts_cov, control = control)
contexts(model, model = "coef")$coef

Build a context tree for a discrete time series

Description

This function builds a context tree for a time series.

Usage

ctx_tree(
  x,
  min_size = 2L,
  max_depth = 100L,
  keep_position = TRUE,
  backend = getOption("mixvlmc.backend", "C++"),
  ...
)

Arguments

x

an object that can be interpreted as a discrete time series: a numeric, character, factor or logical vector, or a dts object (see dts()). Its state space must contain at least two states.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context to be included in the tree.

max_depth

integer >= 0 (default: 100). Maximum length of a context to be included in the tree.

keep_position

logical (default: TRUE). Specifies whether the context tree should keep the positions of the contexts in the time series.

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

...

additional parameters (not used).

Details

The tree represents all the sequences of symbols/states of length at most max_depth that appear at least min_size times in the time series and stores the frequencies of the states that follow each context. Optionally, the positions of the contexts in the time series can be stored in the tree.

Value

a context tree (an object of a class that inherits from ctx_tree).

Back ends

Two back ends are available to compute context trees:

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
## get all contexts of length 2
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
draw(rdts_ctree)
## with the C++ back end
rdts_ctree_cpp <- ctx_tree(rdts,
  min_size = 1, max_depth = 2, backend = "C++"
)
draw(rdts_ctree_cpp)

Build a context tree for a discrete time series

Description

This function builds a context tree for a time series.

Usage

## Default S3 method:
ctx_tree(
  x,
  min_size = 2L,
  max_depth = 100L,
  keep_position = TRUE,
  backend = getOption("mixvlmc.backend", "C++"),
  ...
)

Arguments

x

a numeric, character, factor or logical vector.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context to be included in the tree.

max_depth

integer >= 0 (default: 100). Maximum length of a context to be included in the tree.

keep_position

logical (default: TRUE). Specifies whether the context tree should keep the positions of the contexts in the time series.

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

...

additional parameters (not used).

Details

The tree represents all the sequences of symbols/states of length at most max_depth that appear at least min_size times in the time series and stores the frequencies of the states that follow each context. Optionally, the positions of the contexts in the time series can be stored in the tree.

Value

a context tree (an object of a class that inherits from ctx_tree).

Back ends

Two back ends are available to compute context trees:

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
## get all contexts of length 2
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
draw(rdts_ctree)
## with the C++ back end
rdts_ctree_cpp <- ctx_tree(rdts,
  min_size = 1, max_depth = 2, backend = "C++"
)
draw(rdts_ctree_cpp)

Build a context tree for a discrete time series

Description

This function builds a context tree for a time series.

Usage

## S3 method for class 'dts'
ctx_tree(
  x,
  min_size = 2L,
  max_depth = 100L,
  keep_position = TRUE,
  backend = getOption("mixvlmc.backend", "C++"),
  ...
)

Arguments

x

a discrete time series represented by a dts object as created by dts().

min_size

integer >= 1 (default: 2). Minimum number of observations for a context to be included in the tree.

max_depth

integer >= 0 (default: 100). Maximum length of a context to be included in the tree.

keep_position

logical (default: TRUE). Specifies whether the context tree should keep the positions of the contexts in the time series.

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

...

additional parameters (not used).

Details

The tree represents all the sequences of symbols/states of length at most max_depth that appear at least min_size times in the time series and stores the frequencies of the states that follow each context. Optionally, the positions of the contexts in the time series can be stored in the tree.

Value

a context tree (an object of a class that inherits from ctx_tree).

Back ends

Two back ends are available to compute context trees:

Examples

x_dts <- dts(c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0))
## get all contexts of length 2
ctree <- ctx_tree(x_dts, min_size = 1, max_depth = 2)
draw(ctree)

Cut off values for VLMC-like models

Description

This generic function returns one or more cut off values that are guaranteed to have an effect on the model passed to the function when a simplification procedure is applied (in general a tree pruning operation as provided by prune()).

Usage

cutoff(model, ...)

Arguments

model

a model.

...

additional arguments for the implementations of cutoff().

Details

The exact definition of a cut off value depends on the model type and is documented in the concrete implementations of the function (see e.g. cutoff.vlmc() and cutoff.covlmc()).

Value

a cut off value or a vector of cut off values.

See Also

prune()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts)
draw(model)
model_cuts <- cutoff(model)
model_2 <- prune(model, model_cuts[2])
draw(model_2)

Cut off values for pruning the context tree of a VLMC with covariates

Description

This function returns all the cut off values that should induce a pruning of the context tree of a VLMC with covariates.

Usage

## S3 method for class 'covlmc'
cutoff(model, raw = FALSE, tolerance = .Machine$double.eps^0.5, ...)

Arguments

model

a fitted COVLMC model.

raw

specifies whether the returned values should be limit values computed in the model or modified values that guarantee pruning (defaults to FALSE, see details).

tolerance

specifies the minimum separation between two consecutive values of the cut off in quantile scale (before any transformation). See details.

...

additional arguments for the cutoff function.

Details

Notice that the list of cut off values returned by the function is not as complete as the one computed for a VLMC without covariates. Indeed, pruning the COVLMC tree creates new pruning opportunities that are not evaluated during the construction of the initial model, while all pruning opportunities are computed during the construction of a VLMC context tree. Nevertheless, the largest value returned by the function is guaranteed to produce the least pruned tree consistent with the reference one.

For large COVLMC, some cut off values can be almost identical, with a difference of the order of the machine epsilon value. The tolerance parameter is used to keep only values that are different enough. This is done in the quantile scale, before transformations implemented when raw is FALSE.

Notice that the native scale (log-likelihood ratio) is not directly useful in COVLMC as the differences in model sizes are not constant through the pruning process. As a consequence, unlike cutoff.vlmc(), this function does not provide a scale parameter: values are always given in quantile scale (i.e. as p-values of the likelihood ratio tests).

By default (raw = FALSE), the values are slightly smaller than the p-values of the likelihood ratio tests computed from the COVLMC (in quantile scale): they are reduced by a relative margin of tolerance / 2 (and by at least the smallest representable amount). prune.covlmc() estimates new logistic models and recomputes the likelihood ratio tests, whose p-values can differ in the last digits from the ones stored in the model, depending on the linear algebra library used by R. The margin ensures that pruning with a cut off value does have an effect on the model. As consecutive values differ by at least tolerance, the margin keeps each value larger than the next one. Setting raw to TRUE returns the p-values themselves.

As automated model selection is provided by tune_covlmc(), the direct use of cutoff should be reserved to advanced exploration of the set of trees that can be obtained from a complex one, e.g. to implement model selection techniques that are not provided by tune_covlmc().

Value

a vector of cut off values in quantile scale (in decreasing order), NULL if none can be computed

See Also

prune.covlmc() and tune_covlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
draw(m_cov)
cutoff(m_cov)
## raw values are slightly larger than the default ones
cutoff(m_cov, raw = TRUE) - cutoff(m_cov)
## pruning with the largest cut off value
draw(prune(m_cov, alpha = cutoff(m_cov)[1]))

Cut off value for pruning a node in the context tree of a VLMC

Description

This function returns the cut off value associated with a specific node in the context tree interpreted as a VLMC. The node is represented by a ctx_node object as returned by find_sequence() or contexts(). For details, see cutoff.vlmc().

Usage

## S3 method for class 'ctx_node'
cutoff(model, scale = c("quantile", "native"), raw = FALSE, ...)

Arguments

model

a ctx_node object as returned by find_sequence()

scale

specifies whether the results should be "native" log-likelihood ratio values or expressed in a "quantile" scale of a chi-squared distribution (defaults to "quantile").

raw

specifies whether the returned values should be limit values computed in the model or modified values that guarantee pruning (defaults to FALSE, see details in cutoff.vlmc())

...

additional arguments for the cutoff function.

Value

a cut off value

See Also

cutoff()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts)
model_ctxs <- contexts(model)
cutoff(model_ctxs[[1]])
cutoff(model_ctxs[[2]], scale = "native", raw = TRUE)

Cut off values for pruning a node in the context tree of a COVLMC

Description

This function returns the cut off values associated with a specific node in the context tree of a VLMC with covariates. The node is represented by a ctx_node_covlmc object as returned by find_sequence() or contexts().

Usage

## S3 method for class 'ctx_node_covlmc'
cutoff(model, raw = FALSE, tolerance = .Machine$double.eps^0.5, ...)

Arguments

model

a ctx_node_covlmc object as returned by find_sequence().

raw

specifies whether the returned values should be limit values computed in the model or modified values that guarantee pruning (defaults to FALSE, see details).

tolerance

specifies the minimum separation between two consecutive values of the cut off in quantile scale (before any transformation). See details.

...

additional arguments for the cutoff function.

Details

The values are the p-values of the likelihood ratio tests associated with the node (see cutoff.covlmc() for details), in quantile scale:

As for cutoff.covlmc(), the native scale is not available. The values obtained for all the nodes are those reported by cutoff.covlmc() for the full model.

Value

a vector of cut off values in quantile scale (in decreasing order), NULL if none can be computed.

See Also

cutoff.covlmc(), prune.covlmc()

Examples

pc <- powerconsumption[powerconsumption$week %in% 15:16, ]
rdts <- cut(pc$active_power,
  breaks = c(0, 0.4, 2, 8),
  labels = c("low", "typical", "high")
)
rdts_cov <- data.frame(day = (pc$hour >= 7 & pc$hour <= 18))
m_cov <- covlmc(rdts, rdts_cov, alpha = 1e-7)
draw(m_cov, p_value = TRUE)
## the root node has a merging p-value
cutoff(find_sequence(m_cov, character()))
## a node with a collapsing p-value
cutoff(find_sequence(m_cov, c("typical", "typical")))
cutoff(m_cov)

Cut off values for pruning the context tree of a VLMC

Description

This function returns a collection of cut off values that are guaranteed to induce all valid pruned trees of the context tree of a VLMC. Pruning is implemented by the prune() function.

Usage

## S3 method for class 'vlmc'
cutoff(
  model,
  scale = c("quantile", "native"),
  raw = FALSE,
  tolerance = .Machine$double.eps^0.5,
  ...
)

## S3 method for class 'vlmc_cpp'
cutoff(
  model,
  scale = c("quantile", "native"),
  raw = FALSE,
  tolerance = .Machine$double.eps^0.5,
  ...
)

Arguments

model

a fitted VLMC model.

scale

specifies whether the results should be "native" log likelihood ratio values or expressed in a "quantile" scale of a chi-squared distribution (defaults to "quantile").

raw

specifies whether the returned values should be limit values computed in the model or modified values that guarantee pruning (defaults to FALSE, see details).

tolerance

specifies the minimum separation between two consecutive values of the cut off in native scale (before any transformation). See details.

...

additional arguments (not used).

Details

By default, the function returns values that can be used directly to induce pruning in the context tree. This is done by computing the log likelihood ratios used by the context algorithm on the reference VLMC and by keeping the relevant ones. From them the function selects intermediate values that are guaranteed to generate via pruning all the VLMC models that could be generated by using larger values of the cutoff parameter that was used to build the reference model (or smaller values of the alpha parameter in "quantile" scale).

Setting the raw parameter to TRUE removes this operation on the values and asks the function to return the relevant log likelihood ratios.

For large VLMCs, some log likelihood ratios can be almost identical, with a difference of the order of the machine epsilon value. The tolerance parameter is used to keep only values that are different enough. This is done in the native scale, before transformations implemented when raw is FALSE.

As automated model selection is provided by tune_vlmc(), the direct use of cutoff() should be reserved to advanced exploration of the set of trees that can be obtained from a complex one, e.g. to implement model selection techniques that are not provided by tune_vlmc().

Value

a vector of cut off values.

See Also

prune() and tune_vlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts)
draw(model)
model_cuts <- cutoff(model)
model_2 <- prune(model, model_cuts[2])
draw(model_2)

Depth of a context tree

Description

This function returns the depth of a context tree, i.e. the length of the longest context represented in the tree.

Usage

depth(ct)

Arguments

ct

a context tree.

Value

the depth of the tree.

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
## should be 3
depth(rdts_ctree)

Text based representation of a context tree

Description

This function 'draws' a context tree as a text.

Usage

draw(ct, format, control = draw_control(), ...)

Arguments

ct

a context tree.

format

a character string that specifies the output format of the function. Possible values are "text" (default) and "latex". See details.

control

a list of low level control parameters of the representation. See details and draw_control().

...

additional arguments for the methods of draw().

Details

The function uses different text based formats (plain "ascii art" and LaTeX) to represent the context tree. Fine-tuning of the representation can be done via the draw_control() function.

In addition to the structure of the context tree, draw() can represent information attached to the nodes (contexts and partial contexts). This is controlled by additional parameters depending on the type of the context tree. In general, parameters given directly to draw() specify what information is represented while details on how this representation is made can be controlled via the control parameter and the associated draw_control() function.

Value

an object of class mixvlmc_draw that contains the representation of the context tree. As for other R objects, it is printed automatically when it is not assigned to a variable at top level (for instance when draw(model) is called in the console), but not inside a function or a loop where it must be printed explicitly with print(draw(model)) (see print.mixvlmc_draw()).

Format

The format parameter specifies the format used for the textual output. With the default value "text" the output is produced in "ascii art". The characters used to represent the tree are given by the charset parameter of draw_control(). By default, they are UTF-8 characters when the output supports them and ASCII characters otherwise (see the mixvlmc.charset option in mixvlmc-package).

With the "latex" value, the output is produced in LaTeX, leveraging the forest LaTeX package (see https://ctan.org/pkg/forest). Each call to draw() produces a full forest LaTeX environment. This can be included as is in a LaTeX document, provided the forest package is loaded in the preamble of the document. The LaTeX output is sanitised to avoid potential problems induced by special characters in the names of the states of the context tree.

In a knitr document (R Markdown, Quarto, ...) that produces LaTeX (e.g. a PDF output), the LaTeX representation is included as is in the document and the forest package is added automatically to its preamble (unless the document loads it, possibly with options): calling draw(model, "latex") in a chunk is enough to render the tree (see print.mixvlmc_draw()).

Examples

set.seed(0)
rdts <- sample(c(0, 1), 100, replace = TRUE)
ctree <- ctx_tree(rdts, min_size = 10, max_depth = 2)
draw(ctree)
rdts_c <- sample(c("A", "B", "CD"), 100, replace = TRUE)
ctree_c <- ctx_tree(rdts_c, min_size = 10, max_depth = 2)
draw(ctree_c, control = draw_control(digits = 2))
## LaTeX output
draw(ctree_c, "latex")

Text based representation of a VLMC with covariates

Description

This function 'draws' a VLMC with covariates (a covlmc object) as text.

Usage

## S3 method for class 'covlmc'
draw(
  ct,
  format,
  control = draw_control(),
  model = c("coef", "full"),
  p_value = FALSE,
  with_state = FALSE,
  constant_as_prob = TRUE,
  ...
)

Arguments

ct

a fitted VLMC with covariates (a covlmc object).

format

a character string that specifies the output format of the function. Possible values are "text" (default) and "latex". See details.

control

a list of low level control parameters of the representation. See details and draw_control().

model

this parameter controls the display of logistic models associated with nodes (accepted values: "coef" (default), "full" and NULL). The interpretation of the parameter depends on the format, see below for details.

p_value

specifies whether the p-values of the likelihood ratio tests conducted during the construction of the model must be included in the representation (defaults to FALSE).

with_state

specifies whether to display the state associated with each dimension of the logistic model (defaults to FALSE, see details).

constant_as_prob

specifies how to represent constant logistic models for format="text" (defaults to TRUE, see details). Disregarded when format="latex".

...

not used, except for the deprecated digits and time_sep arguments (customisation options are given with draw_control()).

Details

The function uses different text based formats (plain "ascii art" and LaTeX) to represent the context tree. Fine-tuning of the representation can be done via the draw_control() function.

Unlike the draw() methods adapted to context trees (draw.ctx_tree()) and VLMC (draw.vlmc()), the present function does not try to produce similar results for the "text" format and the "latex" format as the "text" format is intrinsically more limited in terms of model representations. This is detailed below.

Value

an object of class mixvlmc_draw (see print.mixvlmc_draw()).

Format

The format parameter specifies the format used for the textual output. With the default value "text" the output is produced in "ascii art" using the charset specified by the global option mixvlmc.charset.

With the latex value, the output is produced in LaTeX, leveraging the forest LaTeX package (see https://ctan.org/pkg/forest). Each call to draw.covlmc() produces a full forest LaTeX environment. This can be included as is in a LaTeX document, provided the forest package is loaded in the preamble of the document. The LaTeX output is sanitised to avoid potential problems induced by special characters in the names of the states of the context tree.

"text" format

Parameters

When format="text" the parameters are interpreted as follows:

State representation

When model is not NULL, the coefficients of the logistic models are presented, organised in rows associated with states. One state is used as the reference state and the logistic model aims at predicting the ratio of probability between another state and the reference one (in log scale). When with_state is TRUE, the display includes for each row of coefficients the target state. This is useful when using e.g. VGAM::vglm() as unused levels of the target variable will be automatically dropped from the model, leading to a reduced number of rows. The reference state is either shown on the first row if model is "full" or after the state on each row if model is "coef". States are separated from the model representation by the character(s) specified in level_sep in the control list.

"latex" format

Parameters

When format="latex" the parameters are interpreted as follows:

State representation

When model is not NULL, the coefficients of the logistic models are presented, organised in rows or in columns (depending on tab_orientation) associated with states. One state is used as the reference state and the logistic model aims at predicting the ratio of probability between another state and the reference one (in log scale). When with_state is TRUE, the display includes for each row/column of coefficients the target state. The reference state is shown on the first row/column.

Variable representation

When the representation includes the names of the variables used by the logistic models, they are the ones generated by the underlying logistic model, e.g. stats::glm(). Numerical variable names are used as is, while factors have levels appended. The intercept is denoted by the intercept member of the control list when format="text" (as part of the charset). It is always represented by (I) when format="latex".

When format="text", the time delays are represented by an underscore followed by the time delay. For instance if the model uses the numerical covariate y with two delays, it will appear with two variables y_1 and y_2.

When format="latex", the representation uses a temporal subscript of the form t-1, t-2, etc. and levels are given between square brackets. For instance, the level B of a factor y with a delay of one is represented by y_1B in text and by y[B] with subscript t-1 in LaTeX, while a logical covariate day with a delay of one is represented by day_1TRUE and by day[TRUE] with subscript t-1.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1)))
)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
draw(m_cov, control = draw_control(digits = 3))
draw(m_cov, model = NULL)
draw(m_cov, p_value = TRUE)
draw(m_cov, p_value = FALSE, control = draw_control(digits = 2))
draw(m_cov, model = "full", control = draw_control(digits = 3))
draw(m_cov, model = "full", with_state = TRUE)
draw(m_cov, constant_as_prob = FALSE)
draw(m_cov, format = "latex", control = draw_control(orientation = "h"))

Text based representation of a context tree

Description

This function 'draws' a context tree as a text.

Usage

## S3 method for class 'ctx_tree_cpp'
draw(ct, format, control = draw_control(), frequency = NULL, ...)

## S3 method for class 'ctx_tree'
draw(ct, format, control = draw_control(), frequency = NULL, ...)

Arguments

ct

a context tree.

format

a character string that specifies the output format of the function. Possible values are "text" (default) and "latex". See details.

control

a list of low level control parameters of the representation. See details and draw_control().

frequency

this parameter controls the display of node level information in the tree. The default NULL value does not include anything. Setting frequency to "total" includes the frequency of the (partial) context of the node, while "detailed" includes the frequency of the states that follow the context (as in contexts.ctx_tree()).

...

not used (customisation options are given with draw_control()).

Details

The function uses different text based formats (plain "ascii art" and LaTeX) to represent the context tree. Fine-tuning of the representation can be done via the draw_control() function.

In addition to the structure of the context tree, draw() can represent information attached to the nodes (contexts and partial contexts). This is controlled by additional parameters depending on the type of the context tree. In general, parameters given directly to draw() specify what information is represented while details on how this representation is made can be controlled via the control parameter and the associated draw_control() function.

Value

an object of class mixvlmc_draw that contains the representation of the context tree. As for other R objects, it is printed automatically when it is not assigned to a variable at top level (for instance when draw(model) is called in the console), but not inside a function or a loop where it must be printed explicitly with print(draw(model)) (see print.mixvlmc_draw()).

Format

The format parameter specifies the format used for the textual output. With the default value "text" the output is produced in "ascii art". The characters used to represent the tree are given by the charset parameter of draw_control(). By default, they are UTF-8 characters when the output supports them and ASCII characters otherwise (see the mixvlmc.charset option in mixvlmc-package).

With the "latex" value, the output is produced in LaTeX, leveraging the forest LaTeX package (see https://ctan.org/pkg/forest). Each call to draw() produces a full forest LaTeX environment. This can be included as is in a LaTeX document, provided the forest package is loaded in the preamble of the document. The LaTeX output is sanitised to avoid potential problems induced by special characters in the names of the states of the context tree.

In a knitr document (R Markdown, Quarto, ...) that produces LaTeX (e.g. a PDF output), the LaTeX representation is included as is in the document and the forest package is added automatically to its preamble (unless the document loads it, possibly with options): calling draw(model, "latex") in a chunk is enough to render the tree (see print.mixvlmc_draw()).

Examples

set.seed(0)
rdts_c <- sample(c("A", "B", "CD"), 100, replace = TRUE)
ctree_c <- ctx_tree(rdts_c, min_size = 10, max_depth = 2)
draw(ctree_c, frequency = "total")
draw(ctree_c, frequency = "detailed")
## LaTeX output
draw(ctree_c, "latex", frequency = "detailed")
rdts_c <- sample(c("A$", "_{B", "{C}_{D}"), 100, replace = TRUE)
ctree_c <- ctx_tree(rdts_c, min_size = 10, max_depth = 2)
## the LaTeX output is sanitised
draw(ctree_c, "latex", frequency = "detailed")

Text based representation of a VLMC

Description

This function 'draws' a context tree as a text.

Usage

## S3 method for class 'vlmc'
draw(ct, format, control = draw_control(), prob = TRUE, ...)

## S3 method for class 'vlmc_cpp'
draw(ct, format, control = draw_control(), prob = TRUE, ...)

Arguments

ct

a fitted VLMC.

format

a character string that specifies the output format of the function. Possible values are "text" (default) and "latex". See details.

control

a list of low level control parameters of the representation. See details and draw_control().

prob

this parameter controls the display of node level information in the tree. The default prob=TRUE represents the conditional distribution of the states given the (partial) context associated with the node. Setting prob=FALSE replaces the conditional distribution by the frequency of the states that follow the context as in draw.ctx_tree(). Setting prob=NULL removes all additional information.

...

not used (customisation options are given with draw_control()).

Details

The function uses different text based formats (plain "ascii art" and LaTeX) to represent the context tree. Fine-tuning of the representation can be done via the draw_control() function.

In addition to the structure of the context tree, draw() can represent information attached to the nodes (contexts and partial contexts). This is controlled by additional parameters depending on the type of the context tree. In general, parameters given directly to draw() specify what information is represented while details on how this representation is made can be controlled via the control parameter and the associated draw_control() function.

Value

an object of class mixvlmc_draw that contains the representation of the context tree. As for other R objects, it is printed automatically when it is not assigned to a variable at top level (for instance when draw(model) is called in the console), but not inside a function or a loop where it must be printed explicitly with print(draw(model)) (see print.mixvlmc_draw()).

Format

The format parameter specifies the format used for the textual output. With the default value "text" the output is produced in "ascii art". The characters used to represent the tree are given by the charset parameter of draw_control(). By default, they are UTF-8 characters when the output supports them and ASCII characters otherwise (see the mixvlmc.charset option in mixvlmc-package).

With the "latex" value, the output is produced in LaTeX, leveraging the forest LaTeX package (see https://ctan.org/pkg/forest). Each call to draw() produces a full forest LaTeX environment. This can be included as is in a LaTeX document, provided the forest package is loaded in the preamble of the document. The LaTeX output is sanitised to avoid potential problems induced by special characters in the names of the states of the context tree.

In a knitr document (R Markdown, Quarto, ...) that produces LaTeX (e.g. a PDF output), the LaTeX representation is included as is in the document and the forest package is added automatically to its preamble (unless the document loads it, possibly with options): calling draw(model, "latex") in a chunk is enough to render the tree (see print.mixvlmc_draw()).

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts, max_depth = 3)
draw(model)
draw(model, prob = FALSE)
draw(model, prob = NULL)
## LaTeX output
draw(model, "latex")

Control parameters for draw()

Description

This function returns a list used to fine-tune the behaviour of the draw() function.

Usage

draw_control(
  digits = 4,
  charset = NULL,
  orientation = c("vertical", "horizontal"),
  tabular = TRUE,
  tab_orientation = c("vertical", "horizontal"),
  decoration = c("none", "rectangle", "circle", "ellipse"),
  fontsize = "normalsize",
  prob_fontsize = "small"
)

Arguments

digits

numerical parameters, probabilities and p-values are represented using the base::signif() function, using the number of significant digits specified with this parameter (defaults to 4).

charset

specifies the characters used for the "ascii art" representation when the format is "text", see the "Charset" section.

orientation

specifies the global orientation of the tree, either "vertical" (default) or "horizontal" ("latex").

tabular

if TRUE (default value), the "latex" format will use tables for each node, with one row for the state value and other rows for additional information (such as the conditional probability associated with the context). Notice that draw.covlmc() always uses tables regardless of the value of tabular.

tab_orientation

specifies the way the models are represented when used by draw.covlmc() ("latex"). The default value is "vertical": this is well adapted to models with long covariate dependencies (see covariate_depth()). The other possible value is "horizontal".

decoration

specifies node decoration in the "latex" format, see the "Decoration" section.

fontsize

font size for the state names in the "latex" format (using LaTeX standard font sizes such as "small" or "large", defaults to "normalsize").

prob_fontsize

font size for the context counts, probabilities or models in the "latex" format (using LaTeX standard font sizes, defaults to "small").

Details

Parameters are generally specific to the format used for draw(). If this is the case, the format is given at the end of the parameter description. Some parameters are also specific to some methods of draw().

Value

a list of control parameters.

Decoration

The LaTeX format ("latex") can "decorate" the nodes of the context tree by drawing borders. We support only basic decorations, but in theory all TikZ possibilities could be used (see the documentation of the forest LaTeX package). Supported decorations:

Charset

The "ascii art" format ("text") uses a collection of characters to display a context tree. The default collection is specified by the package option "mixvlmc.charset" and is used when charset=NULL (default value). If charset is set to a character value, this value is used to select the collection in the same way that "mixvlmc.charset" specifies it:

Finally, charset can be a user supplied list of characters such as the ones returned by charset_ascii() and charset_utf8().

See Also

draw(), charset_ascii() and charset_utf8().

Examples

draw_control(digits = 2, tabular = FALSE)
pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts, max_depth = 2)
draw(model, control = draw_control(digits = 2, charset = "ascii"))
draw(model, "latex",
  control = draw_control(
    orientation = "horizontal",
    decoration = "rectangle"
  )
)

Convert a vector to a discrete time series

Description

This function creates a representation of a discrete time series that can be further processed by model estimation functions.

Usage

dts(x, vals = NULL)

Arguments

x

a discrete time series; can be numeric, character, factor or logical.

vals

the set of values that can be taken by the time series, a.k.a. the state space, see details (defaults to NULL).

Details

The discrete time series x can be a vector of numeric, character, factor or logical type. If the state space of the series is not specified, that is when vals is NULL, it is computed in a way that depends on the type of x:

If vals is specified, the function makes sure that x contains only the specified values and reports an error otherwise. The state space vals may include values that do not appear in x.

Value

a discrete time series (an object of a class that inherits from dts).

Examples

set.seed(0)
x_dts <- dts(sample(c("A", "B"), 20, replace = TRUE))
x_dts
## specifying the state space
x_dts_3 <- dts(sample(c("A", "B"), 20, replace = TRUE),
  vals = c("A", "B", "C")
)
states(x_dts_3)

Basic operations on discrete time series

Description

These functions implement standard operations on discrete time series represented by dts objects (see dts()), preserving their state space.

Usage

## S3 method for class 'dts'
x[i, ...]

## S3 method for class 'dts'
x[[i, ...]]

## S3 method for class 'dts'
length(x)

## S3 method for class 'dts'
rev(x)

Arguments

x

a dts object.

i

indices specifying the elements to extract.

...

not used.

Value

See Also

dts(), dts_data(), states()

Examples

x <- dts(c("A", "B", "C", "A", "A"))
length(x)
x[[2]]
## the state space is preserved
x_short <- x[1:2]
x_short
states(x_short)
rev(x)

Extract the plain discrete time series from a dts object

Description

This function returns a copy of the discrete time series used to build the dts object (see dts()).

Usage

dts_data(x)

Arguments

x

a dts object.

Value

a vector representing the time series, whose values are taken from the state space of x (see states()).

Examples

set.seed(0)
raw_dts <- sample(c("A", "B", "C"), 50, replace = TRUE)
odts <- dts(raw_dts)
back_to_raw <- dts_data(odts)
## should be TRUE
identical(raw_dts, back_to_raw)

Find the node of a sequence in a context tree

Description

This function checks whether the sequence ctx is represented in the context tree ct. If this is the case, it returns a description of the matching node, an object of class ctx_node. If the sequence is not represented in the tree, the function returns NULL.

Usage

find_sequence(ct, ctx, reverse = FALSE, ...)

## S3 method for class 'ctx_tree'
find_sequence(ct, ctx, reverse = FALSE, ...)

## S3 method for class 'ctx_tree_cpp'
find_sequence(ct, ctx, reverse = FALSE, ...)

Arguments

ct

a context tree.

ctx

a sequence to search in the context tree

reverse

specifies whether the sequence ctx is given in the temporal order (FALSE, default value) or in the reverse temporal order (TRUE). See the dedicated section.

...

additional parameters for the find_sequence function

Details

The function looks for sequences in general. The is_context() function can be used on the resulting object to test if the sequence is in addition a proper context.

Value

an object of class ctx_node if the sequence ctx is represented in the context tree, NULL when this is not the case.

State order in a sequence

sequences are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. In the present function, reverse refers both to the order used for the ctx parameter and to the default order used by the resulting ctx_node object.

Examples

rdts <- c("A", "B", "C", "A", "A", "B", "B", "C", "C", "A")
rdts_tree <- ctx_tree(rdts, max_depth = 3)
find_sequence(rdts_tree, "A")
## returns NULL as "A" "C" does not appear in rdts
find_sequence(rdts_tree, c("A", "C"))
## "A", "B" in temporal order is "B", "A" in reverse order
find_sequence(rdts_tree, c("B", "A"), reverse = TRUE)

Find the node of a sequence in a COVLMC context tree

Description

This function checks whether the sequence ctx is represented in the context tree of the COVLMC model ct. If this is the case, it returns a description of the matching node, an object of class ctx_node_covlmc. If the sequence is not represented in the tree, the function returns NULL.

Usage

## S3 method for class 'covlmc'
find_sequence(ct, ctx, reverse = FALSE, ...)

Arguments

ct

a context tree.

ctx

a sequence to search in the context tree

reverse

specifies whether the sequence ctx is given in the temporal order (FALSE, default value) or in the reverse temporal order (TRUE). See the dedicated section.

...

additional parameters for the find_sequence function

Details

The function looks for sequences in general. The is_context() function can be used on the resulting object to test if the sequence is in addition a proper context.

Value

an object of class ctx_node_covlmc if the sequence ctx is represented in the context tree, NULL when this is not the case

State order in a sequence

sequences are given by default in the temporal order and not in the "reverse" order used by many VLMC research papers: older values are on the left. For instance, the context c(1, 0) is reported if the sequence 0, then 1 appeared in the time series used to build the context tree. In the present function, reverse refers both to the order used for the ctx parameter and to the default order used by the resulting ctx_node object.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 10)

## not in the tree
vals <- states(m_cov)
find_sequence(m_cov, c(vals[2], vals[2]))
## in the tree but not a context
node <- find_sequence(m_cov, c(vals[1]))
node
is_context(node)
## in the tree and a context
node <- find_sequence(m_cov, c(vals[1], vals[1]))
node
is_context(node)
model(node)

Significant Earthquake Dataset

Description

A data set containing the earthquakes of magnitude at least 5 that occurred during the period 1900-2022, with their GPS coordinates and magnitudes.

Usage

globalearthquake

Format

A data frame with 98785 rows and 12 variables:

date_time

date and time in POSIXct format

latitude

latitude of the earthquake, from -90° to 90°

longitude

longitude of the earthquake, from -180° to 180°

mag

the magnitude of the earthquake, indicating its strength

Date

date when the earthquake occurred

nbweeks

number of complete weeks elapsed since 1900/01/01

year

year

month

month of the year

month_day

day of the month

week

week of the year, from 1 to 53 (week 1 consists of the first seven days of the year, week 2 of the next seven days, etc.)

week_day

day of the week from 1 = Sunday to 7 = Saturday

year_day

day of the year from 1 to 366

Details

This is a compiled version of the full data set available on U.S. Geological Survey Earthquake Events (USGS) which is in the public domain.

The data set contains only the earthquakes between 1900 and 2022 with a magnitude of at least 5, sorted by date and time.

Source

Earthquake Catalog, U.S. Geological Survey, Department of the Interior. https://www.usgs.gov/programs/earthquake-hazards

Examples

summary(globalearthquake$mag)
## earthquakes in a rectangle around Japan since 1980
japan <- subset(
  globalearthquake,
  latitude > 30 & latitude < 46 & longitude > 129 & longitude < 146 &
    year >= 1980
)
## binary time series: was there at least one earthquake during the week?
weeks <- seq(min(japan$nbweeks), max(globalearthquake$nbweeks))
japan_weeks <- weeks %in% japan$nbweeks
table(japan_weeks)
japan_model <- tune_vlmc(japan_weeks)
draw(as_vlmc(japan_model))

Report the nature of a node in a context tree

Description

This function returns TRUE if the node is a proper context, FALSE in the other case.

Usage

is_context(node)

Arguments

node

a ctx_node object as returned by find_sequence()

Value

TRUE if the node node is a proper context, FALSE when this is not the case

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
draw(rdts_ctree)
## 0, 0 is a context but 1, 0 is not
is_context(find_sequence(rdts_ctree, c(0, 0)))
is_context(find_sequence(rdts_ctree, c(1, 0)))

Test if the object is a VLMC with covariates

Description

This function returns TRUE for VLMC with covariates (covlmc objects) and FALSE for other objects.

Usage

is_covlmc(x)

Arguments

x

an R object.

Value

TRUE for VLMC with covariates, FALSE for other objects.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
# should be true
is_ctx_tree(m_cov)
# should be true
is_covlmc(m_cov)
# should be false
is_vlmc(m_cov)

Test if the object is a context tree

Description

This function returns TRUE for context trees and FALSE for other objects.

Usage

is_ctx_tree(x)

Arguments

x

an R object.

Value

TRUE for context trees.

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
is_ctx_tree(rdts_ctree)
is_ctx_tree(rdts)

Test if the object is a discrete time series

Description

This function returns TRUE for discrete time series (objects of class dts) and FALSE for other objects.

Usage

is_dts(x)

Arguments

x

an R object.

Value

TRUE for discrete time series.

Examples

set.seed(0)
pre_dts <- sample(c("A", "B"), 20, replace = TRUE)
x_dts <- dts(pre_dts)
is_dts(x_dts)
is_dts(pre_dts)

Merging status of a COVLMC context

Description

The function returns TRUE if the context represented by this node is merged with at least one other context and FALSE if this is not the case.

Usage

is_merged(node)

Arguments

node

A ctx_node_covlmc object as returned by find_sequence.covlmc() or contexts.covlmc()

Details

When a COVLMC is built on a time series with at least three distinct states, some contexts can be merged: they use the same logistic model, leading to a more parsimonious model. Those contexts are reported individually by functions such as contexts.covlmc(). The present function can be used to detect such merging, while merged_with() can be used to recover the other contexts.

Value

TRUE or FALSE, depending on the nature of the context

See Also

merged_with()

Examples

pc <- powerconsumption[powerconsumption$week == 15, ]
rdts <- cut(pc$active_power, breaks = c(0, 1, 2, 3, 8))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5, alpha = 0.1)
ctxs <- contexts(m_cov)
## no merging
sapply(ctxs, is_merged)

Report the ordering convention of the node

Description

This function returns TRUE if the node is using a reverse temporal ordering and FALSE in the other case.

Usage

is_reversed(node)

Arguments

node

a ctx_node object as returned by find_sequence()

Value

TRUE if the node node uses a reverse temporal ordering, FALSE when this is not the case

See Also

rev.ctx_node()

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
is_reversed(find_sequence(rdts_ctree, c(0, 0)))
is_reversed(find_sequence(rdts_ctree, c(1, 0), reverse = TRUE))

Test if the object is a VLMC model

Description

This function returns TRUE for VLMC models and FALSE for other objects.

Usage

is_vlmc(x)

Arguments

x

an R object.

Value

TRUE for VLMC models.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts)
# should be true
is_ctx_tree(model)
# should be true
is_vlmc(model)
# should be false
is_covlmc(model)

Length of the sequence of a node

Description

This function returns the length of the sequence represented by a node of a context tree, that is its depth in the tree.

Usage

## S3 method for class 'ctx_node'
length(x)

Arguments

x

a ctx_node object as returned by find_sequence().

Value

the length of the sequence represented by x.

See Also

find_sequence(), as_sequence()

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
length(find_sequence(rdts_ctree, c(1, 0)))

Log-Likelihood of a VLMC with covariates

Description

This function evaluates the log-likelihood of a VLMC with covariates fitted on a discrete time series.

Usage

## S3 method for class 'covlmc'
logLik(object, initial = c("truncated", "specific", "extended"), ...)

Arguments

object

a fitted VLMC with covariates (a covlmc object).

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See loglikelihood() for details.

...

additional parameters (not used).

Value

an object of class logLik. This is a number, the log-likelihood of the (CO)VLMC with the following attributes:

See Also

loglikelihood()

Examples


## Likelihood for a fitted VLMC with covariates.
pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
ll <- logLik(m_cov)
attributes(ll)


Log-Likelihood of a VLMC

Description

This function evaluates the log-likelihood of a VLMC fitted on a discrete time series.

Usage

## S3 method for class 'vlmc'
logLik(object, initial = c("truncated", "specific", "extended"), ...)

## S3 method for class 'vlmc_cpp'
logLik(object, initial = c("truncated", "specific", "extended"), ...)

Arguments

object

a fitted VLMC.

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See loglikelihood() for details.

...

additional parameters (not used).

Value

an object of class logLik. This is a number, the log-likelihood of the (CO)VLMC with the following attributes:

See Also

loglikelihood()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
m_nocovariate <- vlmc(rdts)
ll <- logLik(m_nocovariate)
ll
attributes(ll)
## log-likelihood with the extended likelihood function
logLik(m_nocovariate, initial = "extended")
## logLik() enables the use of AIC() and BIC()
AIC(m_nocovariate)
BIC(m_nocovariate)

Log-Likelihood of a VLMC

Description

This function evaluates the log-likelihood of a VLMC fitted on a discrete time series. When the optional argument newdata is provided, the function evaluates instead the log-likelihood for this (new) discrete time series.

Usage

loglikelihood(
  vlmc,
  newdata,
  initial = c("truncated", "specific", "extended"),
  ignore,
  ...
)

## S3 method for class 'vlmc'
loglikelihood(
  vlmc,
  newdata,
  initial = c("truncated", "specific", "extended"),
  ignore,
  ...
)

## S3 method for class 'vlmc_cpp'
loglikelihood(
  vlmc,
  newdata,
  initial = c("truncated", "specific", "extended"),
  ignore,
  ...
)

Arguments

vlmc

a fitted VLMC.

newdata

an optional object that can be interpreted as a discrete time series (for instance a dts object), with values in the state space of the model.

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See below for details.

ignore

specifies the number of initial values for which the log-likelihood will not be computed. The minimal number depends on the likelihood function as detailed below.

...

additional parameters (not used).

Details

The definition of the likelihood function depends on the value of the initial parameter, see the section below as well as the dedicated vignette: vignette("likelihood", package = "mixvlmc").

For VLMC objects, the method loglikelihood.vlmc will be used. For VLMC with covariates, loglikelihood.covlmc will instead be called. For more information on loglikelihood methods, use methods(loglikelihood) and their associated documentation.

Value

an object of class logLikMixVLMC and logLik. This is a number, the log-likelihood of the (CO)VLMC with the following attributes:

Likelihood calculation

In a (CO)VLMC of depth()=k, we need k past values in order to compute the context of a given observation. As a consequence, in a time series x, the contexts of x[1] to x[k] are unknown. Depending on the value of initial different likelihood functions are used to tackle this difficulty:

In all cases, the first ignore values of the time series are not included in the computed likelihood, but are still used to compute contexts. If ignore is not specified, it is set to the minimal possible value, that is k for the truncated likelihood and 0 for the other ones. If it is specified, it must be larger than or equal to k for truncated. When newdata is not specified, ignore cannot be larger than k.

When newdata contains a transition that has a zero probability according to the model (in a context or, for the extended likelihood, in an extended context), the log-likelihood is -Inf.

See the dedicated vignette for a more mathematically oriented discussion: vignette("likelihood", package = "mixvlmc").

See Also

stats::logLik()

Examples

## Likelihood for a fitted VLMC.
pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
m_nocovariate <- vlmc(rdts)
ll <- loglikelihood(m_nocovariate)
ll
attr(ll, "nobs")
attr(ll, "df")

## Likelihood for a new time series with previously fitted VLMC.
pc_new <- powerconsumption[powerconsumption$week == 11, ]
rdts_new <- cut(pc_new$active_power, breaks = breaks, labels = labels)
ll_new <- loglikelihood(m_nocovariate, newdata = rdts_new)
ll_new
attributes(ll_new)
ll_new_specific <- loglikelihood(m_nocovariate,
  initial = "specific",
  newdata = rdts_new
)
ll_new_specific
attributes(ll_new_specific)
ll_new_extended <- loglikelihood(m_nocovariate,
  initial = "extended",
  newdata = rdts_new
)
ll_new_extended
attributes(ll_new_extended)


Log-Likelihood of a VLMC with covariates

Description

This function evaluates the log-likelihood of a VLMC with covariates fitted on a discrete time series. When the optional argument newdata is provided, the function evaluates instead the log-likelihood for this (new) discrete time series on the new covariates which must be provided through the newcov parameter.

Usage

## S3 method for class 'covlmc'
loglikelihood(
  vlmc,
  newdata,
  initial = c("truncated", "specific", "extended"),
  ignore,
  newcov,
  ...
)

Arguments

vlmc

a fitted VLMC with covariates (a covlmc object).

newdata

an optional object that can be interpreted as a discrete time series (for instance a dts object), with values in the state space of the model.

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See below for details.

ignore

specifies the number of initial values for which the log-likelihood will not be computed. The minimal number depends on the likelihood function as detailed below.

newcov

an optional data frame with the new values for the covariates (mandatory when newdata is provided, with one row per observation in newdata). Evaluating the likelihood on new data is not supported by fully trimmed models (see trim.covlmc()).

...

additional parameters (not used).

Details

The definition of the likelihood function depends on the value of the initial parameter, see the section below as well as the dedicated vignette: vignette("likelihood", package = "mixvlmc").

Value

an object of class logLikMixVLMC and logLik. This is a number, the log-likelihood of the (CO)VLMC with the following attributes:

Number of parameters

The df attribute of the result is the number of parameters of the logistic models of the contexts (see covlmc()), used by stats::AIC() and stats::BIC(). With s states, the model of a context has:

The second term is the number of coefficients actually estimated by the computing engines (see the "Logistic models" section of covlmc()), which ignore the states that do not follow the context and the unused levels of the factors: it does not depend on the engine. For instance, a context followed by a single state has a constant model with s-1 parameters. Counting all the intercepts ensures that each context has a cost in AIC and BIC, as in the theory of context tree selection: otherwise contexts followed by a single state would have no cost, favouring overly complex models.

The likelihood ratio tests used to build the model (see covlmc()) use instead the nominal number of parameters, (s-1)*(1+p) where p counts all the levels of the factor covariates, as in the original algorithm.

Likelihood calculation

In a (CO)VLMC of depth()=k, we need k past values in order to compute the context of a given observation. As a consequence, in a time series x, the contexts of x[1] to x[k] are unknown. Depending on the value of initial different likelihood functions are used to tackle this difficulty:

In all cases, the first ignore values of the time series are not included in the computed likelihood, but are still used to compute contexts. If ignore is not specified, it is set to the minimal possible value, that is k for the truncated likelihood and 0 for the other ones. If it is specified, it must be larger than or equal to k for truncated. When newdata is not specified, ignore cannot be larger than k.

When newdata contains a transition that has a zero probability according to the model (in a context or, for the extended likelihood, in an extended context), the log-likelihood is -Inf.

See the dedicated vignette for a more mathematically oriented discussion: vignette("likelihood", package = "mixvlmc").

See Also

stats::logLik()

Examples


## Likelihood for a fitted VLMC with covariates.
pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
ll <- loglikelihood(m_cov)
ll
attr(ll, "nobs")

## Likelihood for new time series and covariates with previously
## fitted VLMC with covariates
pc_new <- powerconsumption[powerconsumption$week == 11, ]
rdts_new <- cut(pc_new$active_power, breaks = breaks, labels = labels)
rdts_cov_new <- data.frame(day_night = (pc_new$hour >= 7 & pc_new$hour <= 17))
ll_new <- loglikelihood(m_cov, newdata = rdts_new, newcov = rdts_cov_new)
ll_new
attributes(ll_new)
## extended likelihood on the same data
ll_new_extended <- loglikelihood(m_cov,
  newdata = rdts_new, newcov = rdts_cov_new,
  initial = "extended"
)
attributes(ll_new_extended)


Merged contexts in a COVLMC

Description

The function returns NULL when the context represented by the node parameter is not merged with another context (see is_merged()). In the other case, it returns a list of contexts with which this one is merged.

Usage

merged_with(node)

Arguments

node

A ctx_node_covlmc object as returned by find_sequence.covlmc() or contexts.covlmc()

Details

If the context is merged, the function returns a list with one value for each element in the state space (see states()). The value is NULL if the corresponding context is not merged with the node context, while it is a ctx_node_covlmc object in the other case. A context merged with node differs from the context represented by node only in its oldest value (i.e. its first value in temporal order) which is used as its name in the list. For instance, if the context ABC is merged only with CBC (when represented in temporal ordering), then the resulting list is of the form list("A" = NULL, "B" = NULL, "C" = ctx_node_covlmc(CBC)).

Value

NULL or a list of contexts merged with node represented by ctx_node_covlmc objects

See Also

is_merged()

Examples

pc_week_15_16 <- powerconsumption[powerconsumption$week %in% c(15, 16), ]
elec <- pc_week_15_16$active_power
elec_rdts <- cut(elec, breaks = c(0, 0.4, 2, 8), labels = c("low", "typical", "high"))
elec_cov <- data.frame(day = (pc_week_15_16$hour >= 7 & pc_week_15_16$hour <= 18))
elec_tune <- tune_covlmc(elec_rdts, elec_cov, min_size = 5)
elec_model <- prune(as_covlmc(elec_tune), alpha = 3.961e-10)
ctxs <- contexts(elec_model)
for (ctx in ctxs) {
  if (is_merged(ctx)) {
    print(ctx)
    cat("\nis merged with\n\n")
    print(merged_with(ctx))
  }
}

Predictive quality metrics for context based models

Description

This function computes and returns predictive quality metrics for context based models such as VLMC and VLMC with covariates.

Usage

metrics(model, ...)

Arguments

model

the context based model on which to compute predictive metrics.

...

additional parameters for predictive metrics computation.

Details

A context based model computes transition probabilities for its contexts. Using a maximum transition probability decision rule, this can be used to predict the state that is the most likely to follow the current one, given the context (see predict.vlmc()). The quality of these predictions on the time series used to fit the model is evaluated using standard metrics including:

Value

The returned value is guaranteed to have at least three components:

References

David J. Hand and Robert J. Till (2001). "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning 45(2), p. 171–186. DOI: doi:10.1023/A:1010920819831.

See Also

metrics.vlmc(), metrics.covlmc(), metrics.ctx_node(), contexts.vlmc(), predict.vlmc().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
model <- vlmc(rdts)
metrics(model)


Predictive quality metrics for VLMC with covariates

Description

This function computes and returns predictive quality metrics for context based models such as VLMC and VLMC with covariates.

Usage

## S3 method for class 'covlmc'
metrics(model, ...)

## S3 method for class 'metrics.covlmc'
print(x, ...)

Arguments

model

a fitted VLMC with covariates (a covlmc object).

...

additional parameters for predictive metrics computation.

x

a metrics.covlmc object, result of a call to metrics.covlmc().

Details

A context based model computes transition probabilities for its contexts. Using a maximum transition probability decision rule, this can be used to predict the state that is the most likely to follow the current one, given the context (see predict.vlmc()). The quality of these predictions on the time series used to fit the model is evaluated using standard metrics including:

Value

An object of class metrics.covlmc with the following components:

The object has a print method that recalls basic information about the model together with the values of the components above.

Methods (by generic)

Trimmed models

The predictions of a trimmed model (see trim.covlmc()) on the time series used to fit it are not available any more. The accuracy and the confusion matrix are obtained from the confusion matrices of the contexts computed when the model was fitted (and from the one of the first observations computed when the model was trimmed), but the AUC cannot be computed: it is NA, with a warning.

Extended contexts

As explained in detail in the loglikelihood.covlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first initial values of a time series do not in general have a proper context for a COVLMC with a non-zero order. In order to predict something meaningful for those values, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.covlmc() with the parameter initial="extended". All COVLMC functions that need to manipulate initial values with no proper context use the same approach.

References

David J. Hand and Robert J. Till (2001). "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning 45(2), p. 171–186. DOI: doi:10.1023/A:1010920819831.

See Also

metrics.vlmc(), metrics.covlmc(), metrics.ctx_node(), contexts.vlmc(), predict.vlmc().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
metrics(m_cov)


Predictive quality metrics for a node of a context tree

Description

This function computes and returns predictive quality metrics for a node (ctx_node) extracted from a context tree.

Usage

## S3 method for class 'ctx_node'
metrics(model, ...)

Arguments

model

a ctx_node object as returned by find_sequence().

...

additional parameters for predictive metrics computation.

Details

Compared to metrics.vlmc(), this function focuses on a single context and assesses the quality of its predictions, disregarding observations that have other contexts. Apart from this limited scope, the function operates as metrics.vlmc(). The node must be a context (see is_context()).

As the transition probabilities are the same for all the occurrences of a context, the predictions of a context are constant and the AUC is not informative: it is always NA.

Value

The returned value is guaranteed to have at least three components:

References

David J. Hand and Robert J. Till (2001). "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning 45(2), p. 171–186. DOI: doi:10.1023/A:1010920819831.

See Also

metrics.vlmc(), metrics.covlmc(), metrics.ctx_node(), contexts.vlmc(), predict.vlmc().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts)
model_ctxs <- contexts(model)
metrics(model_ctxs[[4]])

Predictive quality metrics for a node of a COVLMC context tree

Description

This function computes and returns predictive quality metrics for a node (ctx_node_covlmc) extracted from a VLMC with covariates.

Usage

## S3 method for class 'ctx_node_covlmc'
metrics(model, ...)

Arguments

model

A ctx_node_covlmc object as returned by find_sequence.covlmc() or contexts.covlmc()

...

additional parameters for predictive metrics computation.

Details

Compared to metrics.covlmc(), this function focuses on a single context and assesses the quality of its predictions, disregarding observations that have other contexts. Apart from this limited scope, the function operates as metrics.covlmc(). The node must be a context (see is_context()).

Value

an object of class metrics.covlmc with the following components:

References

David J. Hand and Robert J. Till (2001). "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning 45(2), p. 171–186. DOI: doi:10.1023/A:1010920819831.

See Also

metrics.vlmc(), metrics.covlmc(), metrics.ctx_node(), contexts.vlmc(), predict.vlmc().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
m_ctxs <- contexts(m_cov)
## get the predictive metrics for each context
lapply(m_ctxs, metrics)

Predictive quality metrics for VLMC

Description

This function computes and returns predictive quality metrics for context based models such as VLMC and VLMC with covariates.

Usage

## S3 method for class 'vlmc'
metrics(model, ...)

## S3 method for class 'metrics.vlmc'
print(x, ...)

Arguments

model

a fitted VLMC model.

...

additional arguments (not used).

x

a metrics.vlmc object, result of a call to metrics.vlmc().

Details

A context based model computes transition probabilities for its contexts. Using a maximum transition probability decision rule, this can be used to predict the state that is the most likely to follow the current one, given the context (see predict.vlmc()). The quality of these predictions on the time series used to fit the model is evaluated using standard metrics including:

Value

An object of class metrics.vlmc with (at least) the following components:

The object has a print method that recalls basic information about the model together with the values of the components above.

Methods (by generic)

Extended contexts

As explained in detail in the loglikelihood.vlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first values of a time series do not in general have a proper context for a VLMC of non zero depth. In order to predict something meaningful for those values, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.vlmc() with the parameter initial="extended". All VLMC functions that need to manipulate initial values with no proper context use the same approach.

References

David J. Hand and Robert J. Till (2001). "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning 45(2), p. 171–186. DOI: doi:10.1023/A:1010920819831.

See Also

metrics.vlmc(), metrics.covlmc(), metrics.ctx_node(), contexts.vlmc(), predict.vlmc().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
breaks <- c(
  0,
  median(powerconsumption$active_power, na.rm = TRUE),
  max(powerconsumption$active_power, na.rm = TRUE)
)
labels <- c(0, 1)
rdts <- cut(pc$active_power, breaks = breaks, labels = labels)
model <- vlmc(rdts)
metrics(model)


Logistic model of a COVLMC context

Description

This function returns a representation of the logistic model associated with a COVLMC context from its node in the associated context tree.

Usage

model(node, type = c("coef", "full"))

Arguments

node

A ctx_node_covlmc object as returned by find_sequence.covlmc() or contexts.covlmc()

type

specifies the model information to return, either the coefficients only (type="coef", default case) or the full model object (type="full")

Details

Full model extraction is only possible if the COVLMC model was not fully trimmed (see trim.covlmc()). Notice that find_sequence.covlmc() can produce nodes that are not contexts: in this case this function returns NULL.

Value

if node is a context, the coefficients of the logistic model (as a vector or a matrix depending on the size of the state space) or a logistic model as an R object. If node is not a context, NULL.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 10)
vals <- states(m_cov)
node <- find_sequence(m_cov, c(vals[1], vals[1]))
node
model(node)
model(node, type = "full")


Find the parent of a node in a context tree

Description

This function returns the parent node of the node represented by the node parameter. The result is NULL if node is the root node of its context tree (representing the empty sequence).

Usage

parent(node)

## S3 method for class 'ctx_node'
parent(node)

## S3 method for class 'ctx_node_cpp'
parent(node)

Arguments

node

a ctx_node object as returned by find_sequence()

Details

Each node of a context tree represents a sequence. When find_sequence() is called with success, the returned object represents the corresponding node in the context tree. Unless the original sequence is empty, this node has a parent node which is returned as a ctx_node object by the present function. Another interpretation is that the function returns the ctx_node object associated with the sequence obtained by removing the oldest value from the original sequence.

Value

a ctx_node object if node does not correspond to the empty sequence or NULL when this is not the case

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3)
ctx_00 <- find_sequence(rdts_ctree, c(0, 0))
## the parent sequence/node corresponds to the 0 context
parent(ctx_00)
identical(parent(ctx_00), find_sequence(rdts_ctree, c(0)))
## C++ backend
rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 3, backend = "C++")
ctx_00 <- find_sequence(rdts_ctree, c(0, 0))
## the parent sequence/node corresponds to the 0 context
parent(ctx_00)
identical(
  as_sequence(parent(ctx_00)),
  as_sequence(find_sequence(rdts_ctree, c(0)))
)

Plot the results of automatic (CO)VLMC complexity selection

Description

This function plots the results of tune_vlmc() or tune_covlmc().

Usage

## S3 method for class 'tune_vlmc'
plot(
  x,
  value = c("criterion", "likelihood"),
  cutoff = c("quantile", "native"),
  ...
)

## S3 method for class 'tune_covlmc'
plot(
  x,
  value = c("criterion", "likelihood"),
  cutoff = c("quantile", "native"),
  ...
)

Arguments

x

a tune_vlmc or a tune_covlmc object.

value

the value to plot: either "criterion" (default) for the information criterion used for model selection or "likelihood" for the log likelihood.

cutoff

the scale used for the cut off criterion: either "quantile" (default) or "native" (only for tune_vlmc objects).

...

additional parameters passed to base::plot().

Details

The standard plot shows the evolution of the criterion used to select the model (AIC() or BIC()) as a function of the cut off criterion expressed in the quantile scale (the quantile scale is used by default to offer a common default behaviour between vlmc() and covlmc()). Parameters can be used to display instead the loglikelihood() of the model (by setting value="likelihood") and to use the native scale for the cut off when available (by setting cutoff="native", which is not supported for tune_covlmc() results).

Value

the x object, invisibly.

Customisation

The function sets several defaults before calling base::plot(), namely:

These parameters can be overridden by specifying other values when calling the function. All parameters specified in addition to x, value and cutoff are passed to base::plot().

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
tune_result <- tune_vlmc(rdts)
## default plot
plot(tune_result)
## native scale for the cut off
plot(tune_result, cutoff = "native")
## likelihood
plot(tune_result, value = "likelihood")
## parameters overriding
plot(tune_result,
  value = "likelihood",
  xlab = "Cut off", type = "b"
)
pc <- powerconsumption[powerconsumption$week %in% 10:12, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1)))
)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
rdts_best_model_tune <- tune_covlmc(rdts, rdts_cov, criterion = "AIC")
plot(rdts_best_model_tune)
plot(rdts_best_model_tune, value = "likelihood")


Report the positions of a sequence associated with a node

Description

This function returns the positions of the sequence represented by node in the time series used to build the context tree in which the sequence is represented. This is only possible if those positions were saved during the construction of the context tree (see the keep_position parameter of ctx_tree()). If positions were not saved, a call to this function produces an error.

Usage

positions(node)

## S3 method for class 'ctx_node'
positions(node)

## S3 method for class 'ctx_node_cpp'
positions(node)

Arguments

node

a ctx_node object as returned by find_sequence()

Details

A position of a sequence ctx in the time series x is an index value t such that the sequence ends with x[t]. Thus x[t+1], when it exists, is the value that follows the sequence. For instance if x=c(0, 0, 1, 1) and ctx=c(0, 1) (in standard state order), then the position of ctx in x is 3.

Positions include all the occurrences of the sequence, including an occurrence at the end of the time series (t=length(x)), which is not followed by any value. Such an occurrence is not taken into account by counts(), which reports the values that follow the sequence: the number of positions can therefore exceed the total count by one.

Value

positions of the sequence represented by node in the original time series, as an integer vector

Examples

set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
rdts_tree <- ctx_tree(rdts, max_depth = 3, min_size = 5)
subseq <- find_sequence(rdts_tree, factor(c("B", "A"), levels = c("A", "B", "C")))
if (!is.null(subseq)) {
  positions(subseq)
}

Individual household electric power consumption

Description

A data set containing measurements of the electric power consumption of one household with a time resolution of 10 minutes for the full year 2008.

Usage

powerconsumption

Format

A data frame with 52704 rows and 15 variables:

month

month of 2008

month_day

day of the month

hour

hour (0 to 23)

minute

starting minute of the 10 minute period of this row

active_power

global average active power over the 10 minute period (in kilowatt)

reactive_power

global average reactive power over the 10 minute period (in kilowatt)

voltage

average voltage over the 10 minute period (in volt)

intensity

global average current intensity over the 10 minute period (in ampere)

sub_metering_1

energy sub-metering No. 1 (in watt-hour of active energy averaged over the 10 minute period). It corresponds to the kitchen, containing mainly a dishwasher, an oven and a microwave (hot plates are not electric but gas powered).

sub_metering_2

energy sub-metering No. 2 (in watt-hour of active energy averaged over the 10 minute period). It corresponds to the laundry room, containing a washing-machine, a tumble-drier, a refrigerator and a light.

sub_metering_3

energy sub-metering No. 3 (in watt-hour of active energy averaged over the 10 minute period). It corresponds to an electric water-heater and an air-conditioner.

week

week of the year, from 1 to 53 (week 1 consists of the first seven days of the year, week 2 of the next seven days, etc.)

week_day

day of the week from 1 = Sunday to 7 = Saturday

year_day

day of the year from 1 to 366 (2008 is a leap year)

date_time

date and time in POSIXct format

Details

This is a simplified version of the full data available on the UCI Machine Learning Repository under a Creative Commons Attribution 4.0 International (CC BY 4.0) licence, and provided by Georges Hebrail and Alice Berard.

The original data (one measurement per minute) have been averaged over 10 minute periods (discarding missing data in each period). The measurements of a period in which all the original data are missing are coded as NA. The data set contains only the measurements from year 2008.

Notice that the variables are expressed in different units. In particular, the sub-meters measure active energy (in watt-hour) while the global active power is expressed in kilowatt.

Source

Individual household electric power consumption, 2012, G. Hebrail and A. Berard, UC Irvine Machine Learning repository. doi:10.24432/C58K54

Examples

## active power during the fifth week of 2008
pc <- powerconsumption[powerconsumption$week == 5, ]
summary(pc$active_power)
plot(pc$date_time, pc$active_power,
  type = "l", xlab = "Time", ylab = "Active power (kW)"
)
## discretisation into four levels using the quartiles
power_dts <- dts(cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
))
power_dts
model <- vlmc(power_dts)
draw(model)

Next state prediction in a discrete time series for a VLMC with covariates

Description

This function computes one-step-ahead predictions for a discrete time series based on a VLMC with covariates.

Usage

## S3 method for class 'covlmc'
predict(
  object,
  newdata,
  newcov,
  type = c("raw", "probs"),
  final_pred = TRUE,
  ...
)

Arguments

object

a fitted VLMC with covariates (a covlmc object). Fully trimmed models are not supported (see trim.covlmc()).

newdata

a discrete time series with the same state space as the one used to fit object.

newcov

a data frame with the new values for the covariates, with one row per observation in newdata.

type

character indicating the type of prediction required. The default "raw" returns actual predictions in the form of a new time series. The alternative "probs" returns a matrix of prediction probabilities (see details).

final_pred

if TRUE (default value), the predictions include a final prediction step, made by computing the context of the full time series. When FALSE this final prediction is not included.

...

additional arguments.

Details

Given a time series X, at time step t, a context is computed using observations from X[1] to X[t-1] (see the dedicated section). The prediction is then the most probable state for X[t] given the logistic model of the context and the corresponding values of the covariates. The time series of predictions is returned by the function when type="raw" (default case).

When type="probs", the function returns the probabilities of each state for X[t] as estimated by the logistic models. Those probabilities are returned as a matrix of probabilities with column names given by the state names.

Value

A vector of predictions if type="raw" or a matrix of state probabilities if type="probs". The number of predictions (or of rows of the matrix) is the length of newdata, plus one if final_pred=TRUE.

Extended contexts

As explained in detail in the loglikelihood.covlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first initial values of a time series do not in general have a proper context for a COVLMC with a non-zero order. In order to predict something meaningful for those values, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.covlmc() with the parameter initial="extended". All COVLMC functions that need to manipulate initial values with no proper context use the same approach.

Examples

pc <- powerconsumption[powerconsumption$week == 10, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.2, 0.7, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5, alpha = 0.5)
rdts_probs <- predict(m_cov, rdts[1:144], rdts_cov[1:144, , drop = FALSE], type = "probs")
head(rdts_probs)
rdts_preds <- predict(m_cov, rdts[1:144], rdts_cov[1:144, , drop = FALSE],
  type = "raw", final_pred = FALSE
)
## comparison between the predictions and the actual values
table(rdts_preds, rdts[1:144])

Next state prediction in a discrete time series for a VLMC

Description

This function computes one step ahead predictions for a discrete time series based on a VLMC.

Usage

## S3 method for class 'vlmc'
predict(object, newdata, type = c("raw", "probs"), final_pred = TRUE, ...)

## S3 method for class 'vlmc_cpp'
predict(object, newdata, type = c("raw", "probs"), final_pred = TRUE, ...)

Arguments

object

a fitted VLMC.

newdata

an object that can be interpreted as a discrete time series (for instance a dts object), with values in the state space of the model.

type

character indicating the type of prediction required. The default "raw" returns actual predictions in the form of a new time series. The alternative "probs" returns a matrix of prediction probabilities (see details).

final_pred

if TRUE (default value), the predictions include a final prediction step, made by computing the context of the full time series. When FALSE this final prediction is not included.

...

additional arguments (not used).

Details

Given a time series X, at time step t, a context is computed using observations from X[1] to X[t-1] (see the dedicated section). The prediction is then the most probable state for X[t] given this context. Ties are broken according to the natural order in the state space, favouring "small" values. The time series of predictions is returned by the function when type="raw" (default case).

When type="probs", each X[t] is associated with the conditional probabilities of its possible values given its context. Those probabilities are returned as a matrix of probabilities with column names given by the state names.

Value

A vector of predictions if type="raw" or a matrix of state probabilities if type="probs". The number of predictions (or of rows of the matrix) is the length of newdata, plus one if final_pred is TRUE.

Extended contexts

As explained in detail in the loglikelihood.vlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first values of a time series do not in general have a proper context for a VLMC of non zero depth. In order to predict something meaningful for those values, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.vlmc() with the parameter initial="extended". All VLMC functions that need to manipulate initial values with no proper context use the same approach.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts, min_size = 5)
predict(model, rdts[1:5])
predict(model, rdts[1:5], "probs")
## without the final prediction
predict(model, rdts[1:5], final_pred = FALSE)
## C++ backend
pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts, min_size = 5, backend = "C++")
predict(model, rdts[1:5])
predict(model, rdts[1:5], "probs")

Print a context list

Description

This function prints a list of contexts i.e. a contexts object listing ctx_node objects.

Usage

## S3 method for class 'contexts'
print(x, reverse = NULL, ...)

Arguments

x

the contexts object to print

reverse

specifies whether the contexts should be reported in temporal order (FALSE) or in reverse temporal order (TRUE). If the parameter is NULL (default), the contexts are displayed in the order specified by the call to contexts() used to build the context list.

...

additional arguments for the print function.

Value

the x object, invisibly

See Also

contexts()

Examples

rdts <- c("A", "B", "C", "A", "A", "B", "B", "C", "C", "A")
rdts_tree <- ctx_tree(rdts, max_depth = 3)
print(contexts(rdts_tree))
print(contexts(rdts_tree), reverse = TRUE)

Print a discrete time series

Description

This function prints a discrete time series.

Usage

## S3 method for class 'dts'
print(x, n = 5, ...)

Arguments

x

the dts object to print.

n

the number of time steps of the time series to print (defaults to 5).

...

additional arguments (not used).

Value

the x object, invisibly.

Examples

set.seed(0)
x_dts <- dts(sample(c("A", "B"), 20, replace = TRUE))
print(x_dts, n = 10)

Print and convert the representation of a context tree

Description

draw() returns an object of class mixvlmc_draw that contains the text or LaTeX representation of a context tree. These functions print it and convert it to a character vector.

Usage

## S3 method for class 'mixvlmc_draw'
print(x, ...)

## S3 method for class 'mixvlmc_draw'
format(x, ...)

## S3 method for class 'mixvlmc_draw'
as.character(x, ...)

Arguments

x

a representation of a context tree produced by draw().

...

additional arguments (not used).

Details

print() writes the representation, one line after another. It is called automatically when the result of draw() is not assigned to a variable, for instance when draw(model) is called in the console.

In a knitr document (R Markdown, Quarto, ...), the result of draw() is printed as standard R output, except for a LaTeX representation (format = "latex") in a document that produces LaTeX (e.g. a PDF output). In this case, the LaTeX code is included as is in the document and the forest LaTeX package is loaded automatically at the end of its preamble (with the AtEndPreamble command of the etoolbox package), so that the tree is rendered. A document can also load forest in its preamble, possibly with options: it is then not loaded a second time.

Value

print() returns its argument (invisibly), format() and as.character() return the representation as a character vector, one string per line.

See Also

draw()

Examples

set.seed(0)
rdts <- sample(c(0, 1), 100, replace = TRUE)
ctree <- ctx_tree(rdts, min_size = 10, max_depth = 2)
tree_repr <- draw(ctree)
print(tree_repr)
as.character(draw(ctree, "latex"))

Prune a Variable Length Markov Chain (VLMC)

Description

This function prunes a VLMC.

Usage

prune(vlmc, alpha = 0.05, cutoff = NULL, ...)

## S3 method for class 'vlmc'
prune(vlmc, alpha = 0.05, cutoff = NULL, ...)

## S3 method for class 'vlmc_cpp'
prune(vlmc, alpha = 0.05, cutoff = NULL, ...)

Arguments

vlmc

a fitted VLMC model.

alpha

number in (0,1] (default: 0.05) cut off value in quantile scale for pruning.

cutoff

non negative number: cut off value in native (log likelihood ratio) scale for pruning. Defaults to the value obtained from alpha. Takes precedence over alpha if specified.

...

additional arguments (not used).

Details

In general, pruning a VLMC is more efficient than constructing two VLMCs (the base one and the pruned one). Up to numerical instabilities, building a VLMC with alpha = a and then pruning it with alpha = b (with a > b) should produce the same VLMC as building directly the VLMC with alpha = b (in the native scale, the cut off used for pruning must be larger than the one used to build the VLMC). Interesting cut off values can be extracted from a VLMC using the cutoff() function.

As automated model selection is provided by tune_vlmc(), the direct use of prune() should be reserved to advanced exploration of the set of trees that can be obtained from a complex one, e.g. to implement model selection techniques that are not provided by tune_vlmc().

Value

a pruned VLMC.

See Also

cutoff() and tune_vlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
base_model <- vlmc(rdts, alpha = 0.1)
model_cuts <- cutoff(base_model)
pruned_model <- prune(base_model, model_cuts[3])
draw(pruned_model)
direct_simple <- vlmc(rdts, alpha = model_cuts[3])
draw(direct_simple)
# pruned_model and direct_simple should be identical
all.equal(pruned_model, direct_simple)

Prune a Variable Length Markov Chain with covariates

Description

This function prunes a VLMC with covariates. This model must have been estimated with keep_data=TRUE to enable the pruning (and must not have been trimmed, see trim.covlmc()).

Usage

## S3 method for class 'covlmc'
prune(vlmc, alpha = 0.05, cutoff = NULL, ...)

Arguments

vlmc

a fitted VLMC with covariates (a covlmc object).

alpha

number in (0,1] (default: 0.05) cut off value in quantile scale for pruning. A warning is issued if it is larger than the alpha of the model, as the result may then differ from a model built directly with this value.

cutoff

not supported for VLMC with covariates (must be NULL): pruning is specified only with alpha.

...

additional arguments for the prune function.

Details

Post-pruning a VLMC with covariates is not as straightforward as the same procedure applied to vlmc() (see cutoff.vlmc() and prune.vlmc()). For efficiency reasons, covlmc() estimates only the logistic models that are considered useful for a given set of construction parameters. With a more aggressive pruning threshold, some contexts become leaves of the context tree and new logistic models must be estimated. Thus the pruning opportunities given by cutoff.covlmc() are only a subset of interesting cut offs for a given COVLMC.

Contrarily to the case of vlmc(), post-pruning a COVLMC does not always give the same model as building the COVLMC directly with the post-pruning alpha (even if it is smaller than the alpha used to build the initial model). Indeed the pruning decisions depend on the logistic models available in the initial COVLMC. For the same reason, successive pruning operations (as in tune_covlmc()) can give a different model than a single pruning operation with the final alpha.

Value

a pruned covlmc object.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5, keep_data = TRUE)
draw(m_cov)
m_cov_cuts <- cutoff(m_cov)
p_cov <- prune(m_cov, alpha = m_cov_cuts[1])
draw(p_cov)

Reverse Sequence

Description

This function reverses the order in which the sequence represented by the ctx_node parameter will be reported in other functions, mainly as_sequence().

Usage

## S3 method for class 'ctx_node'
rev(x)

Arguments

x

a ctx_node object as returned by find_sequence()

Value

a ctx_node using the opposite ordering convention to the one of the parameter of the function

See Also

is_reversed()

Examples

rdts <- c("A", "B", "C", "A", "A", "B", "B", "C", "C", "A")
rdts_tree <- ctx_tree(rdts, max_depth = 3)
res <- find_sequence(rdts_tree, c("A", "B"))
print(res)
r_res <- rev(res)
print(r_res)
as_sequence(r_res)

Simulate a discrete time series for a VLMC with covariates

Description

This function simulates a time series from the distribution estimated by the given VLMC with covariates (a covlmc object).

Usage

## S3 method for class 'covlmc'
simulate(object, nsim = 1, seed = NULL, covariate, init = NULL, ...)

Arguments

object

a fitted VLMC with covariates (a covlmc object). Fully trimmed models are not supported (see trim.covlmc()).

nsim

length of the simulated time series (defaults to 1).

seed

an optional random seed (see the dedicated section).

covariate

a data frame with the values of the covariates, with at least nsim rows.

init

an optional initial sequence for the time series given by an object that can be interpreted as a discrete time series. Its length must not exceed nsim.

...

additional arguments.

Details

A VLMC with covariates needs covariates to compute its transition probabilities. The covariates must be submitted as a data frame using the covariate argument. In addition, the time series can be initiated by a fixed sequence specified via the init parameter.

Value

a simulated discrete time series of the same type as the one used to build the model, with a seed attribute (see the Random seed section). The result also has the dts_simulated class to hide the seed attribute when using print or similar functions.

Extended contexts

As explained in detail in the loglikelihood.covlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first initial values of a time series do not in general have a proper context for a COVLMC with a non-zero order. In order to simulate something meaningful for those values, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.covlmc() with the parameter initial="extended". All COVLMC functions that need to manipulate initial values with no proper context use the same approach.

Random seed

This function reproduces the behaviour of stats::simulate(). If seed is NULL, the simulation uses the current state of the random number generator (which is therefore modified) and the value of .Random.seed before the simulation is returned as a seed attribute of the result. This can be used to reproduce exactly the simulation results by setting .Random.seed to this value. Otherwise, seed is used to initialise the random number generator for the simulation, and the state of the generator is restored afterwards. Notice that if the random seed has not been initialised by R so far, the function issues a call to runif(1) to perform this initialisation (as is done in stats::simulate()).

If seed is an integer, it is used in a call to set.seed() before the simulation takes place. The integer is saved as a seed attribute in the return value. The integer seed is completed by an attribute kind which contains the value ⁠as.list([RNGkind()])⁠ exactly as with stats::simulate(). The random generator state is reset to its original value at the end of the call.

See Also

stats::simulate() for details and examples on the random number generator setting.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
# new week with daylight from 6:00 to 18:00 (144 observations per day, one
# every 10 minutes)
new_cov <- data.frame(
  day_night = rep(c(rep(FALSE, 36), rep(TRUE, 72), rep(FALSE, 36)), times = 7)
)
new_rdts <- simulate(m_cov, nrow(new_cov), seed = 0, covariate = new_cov)
table(new_rdts)
new_rdts_2 <- simulate(m_cov, nrow(new_cov), seed = 0, covariate = new_cov, init = rdts[1:10])
## the simulated time series starts with the initial values
identical(as.character(new_rdts_2[1:10]), as.character(rdts[1:10]))

Simulate a discrete time series for a VLMC

Description

This function simulates a time series from the distribution estimated by the given VLMC.

Usage

## S3 method for class 'vlmc'
simulate(object, nsim = 1L, seed = NULL, init = NULL, burnin = 0L, ...)

Arguments

object

a fitted VLMC.

nsim

length of the simulated time series (defaults to 1).

seed

an optional random seed (see the dedicated section).

init

an optional initial sequence for the time series given by an object that can be interpreted as a discrete time series, with values in the state space of the model.

burnin

number of initial observations to discard or "auto" (see the dedicated section). Defaults to 0.

...

additional arguments (not used).

Details

The time series can be initiated by a fixed sequence specified via the init parameter: the simulated time series then starts with this sequence (whose length counts in the nsim + burnin values, see below).

Value

a simulated discrete time series of the same type as the one used to build the VLMC with a seed attribute (see the Random seed section). The result has also the dts_simulated class to hide the seed attribute when using print() or similar functions.

Burn in (Warm up) period

When using a VLMC for simulation purposes, we are generally interested in the stationary distribution of the corresponding Markov chain. To reduce the dependence of the samples on the initial values and get closer to this stationary distribution (if it exists), it is recommended to discard the first samples which are produced in a so-called "burn in" (or "warm up") period. The burnin parameter can be used to implement this approach. The VLMC is used to produce a sample of size burnin + nsim but the first burnin values are discarded. Notice that these burn in values can be partially given by the init parameter if it is specified.

If burnin is set to "auto", the burnin period is set to 64 * context_number(object), following the heuristic proposed in Mächler and Bühlmann (2004).

Random seed

This function reproduces the behaviour of stats::simulate(). If seed is NULL, the simulation uses the current state of the random number generator (which is therefore modified) and the value of .Random.seed before the simulation is returned as a seed attribute of the result. This can be used to reproduce exactly the simulation results by setting .Random.seed to this value. Otherwise, seed is used to initialise the random number generator for the simulation, and the state of the generator is restored afterwards. Notice that if the random seed has not been initialised by R so far, the function issues a call to runif(1) to perform this initialisation (as is done in stats::simulate()).

If seed is an integer, it is used in a call to set.seed() before the simulation takes place. The integer is saved as a seed attribute in the return value. The integer seed is completed by an attribute kind which contains the value ⁠as.list([RNGkind()])⁠ exactly as with stats::simulate(). The random generator state is reset to its original value at the end of the call.

Extended contexts

As explained in detail in the loglikelihood.vlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first values of a time series do not in general have a proper context for a VLMC of non zero depth. In order to simulate something meaningful for those values when init is not provided, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.vlmc() with the parameter initial="extended". All VLMC functions that need to manipulate initial values with no proper context use the same approach.

References

Mächler, M. and Bühlmann, P. (2004) "Variable Length Markov Chains: Methodology, Computing, and Software" Journal of Computational and Graphical Statistics, 13 (2), 435-455, doi:10.1198/1061860043524

See Also

stats::simulate() for details and examples on the random number generator setting

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power,
    probs = c(0.25, 0.5, 0.75, 1)
  ))
)
model <- vlmc(rdts, min_size = 5)
new_rdts <- simulate(model, 500, seed = 0)
head(new_rdts, 10)
## the simulation starts with the init sequence
new_rdts_2 <- simulate(model, 500, seed = 0, init = rdts[1:5])
head(new_rdts_2, 10)
new_rdts_3 <- simulate(model, 500, seed = 0, burnin = 500)
## automatic burn in period
new_rdts_4 <- simulate(model, 500, seed = 0, burnin = "auto")

Simulate a discrete time series for a VLMC

Description

This function simulates a time series from the distribution estimated by the given VLMC.

Usage

## S3 method for class 'vlmc_cpp'
simulate(
  object,
  nsim = 1,
  seed = NULL,
  init = NULL,
  burnin = 0L,
  sample = c("fast", "slow", "R"),
  ...
)

Arguments

object

a fitted VLMC.

nsim

length of the simulated time series (defaults to 1).

seed

an optional random seed (see the dedicated section).

init

an optional initial sequence for the time series given by an object that can be interpreted as a discrete time series, with values in the state space of the model.

burnin

number of initial observations to discard or "auto" (see the dedicated section). Defaults to 0.

sample

specifies which implementation of base::sample() to use: "fast" (default), "slow" or "R". See the dedicated section.

...

additional arguments (not used).

Details

The time series can be initiated by a fixed sequence specified via the init parameter: the simulated time series then starts with this sequence (whose length counts in the nsim + burnin values, see below).

Value

a simulated discrete time series of the same type as the one used to build the VLMC with a seed attribute (see the Random seed section). The result has also the dts_simulated class to hide the seed attribute when using print() or similar functions.

Sampling method

The R backend for vlmc() uses base::sample() to generate samples for each context. Internally, this function sorts the probabilities of each state in decreasing probability order (among other things), which is not needed in our case. The C++ backend can be used with three different implementations:

Burn in (Warm up) period

When using a VLMC for simulation purposes, we are generally interested in the stationary distribution of the corresponding Markov chain. To reduce the dependence of the samples on the initial values and get closer to this stationary distribution (if it exists), it is recommended to discard the first samples which are produced in a so-called "burn in" (or "warm up") period. The burnin parameter can be used to implement this approach. The VLMC is used to produce a sample of size burnin + nsim but the first burnin values are discarded. Notice that these burn in values can be partially given by the init parameter if it is specified.

If burnin is set to "auto", the burnin period is set to 64 * context_number(object), following the heuristic proposed in Mächler and Bühlmann (2004).

Random seed

This function reproduces the behaviour of stats::simulate(). If seed is NULL, the simulation uses the current state of the random number generator (which is therefore modified) and the value of .Random.seed before the simulation is returned as a seed attribute of the result. This can be used to reproduce exactly the simulation results by setting .Random.seed to this value. Otherwise, seed is used to initialise the random number generator for the simulation, and the state of the generator is restored afterwards. Notice that if the random seed has not been initialised by R so far, the function issues a call to runif(1) to perform this initialisation (as is done in stats::simulate()).

If seed is an integer, it is used in a call to set.seed() before the simulation takes place. The integer is saved as a seed attribute in the return value. The integer seed is completed by an attribute kind which contains the value ⁠as.list([RNGkind()])⁠ exactly as with stats::simulate(). The random generator state is reset to its original value at the end of the call.

Extended contexts

As explained in detail in the loglikelihood.vlmc() documentation and in the dedicated vignette("likelihood", package = "mixvlmc"), the first values of a time series do not in general have a proper context for a VLMC of non zero depth. In order to simulate something meaningful for those values when init is not provided, we rely on the notion of extended context defined in the documents mentioned above. This follows the same logic as using loglikelihood.vlmc() with the parameter initial="extended". All VLMC functions that need to manipulate initial values with no proper context use the same approach.

References

Mächler, M. and Bühlmann, P. (2004) "Variable Length Markov Chains: Methodology, Computing, and Software" Journal of Computational and Graphical Statistics, 13 (2), 435-455, doi:10.1198/1061860043524

See Also

stats::simulate() for details and examples on the random number generator setting

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts, min_size = 5, backend = "C++")
new_rdts <- simulate(model, 500, seed = 0)
head(new_rdts, 10)
## the same simulation as with the R backend
new_rdts_r <- simulate(model, 500, seed = 0, sample = "R")
model_r <- vlmc(rdts, min_size = 5)
identical(new_rdts_r, simulate(model_r, 500, seed = 0))

State space of an object

Description

This function returns the state space of an object for which this is meaningful, such as a discrete time series or a context tree.

Usage

states(x)

## S3 method for class 'ctx_tree'
states(x)

## S3 method for class 'dts'
states(x)

Arguments

x

an object with a state space.

Value

the state space of the object.

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 1, max_depth = 2)
## should be c(0, 1)
states(rdts_ctree)
set.seed(0)
x_dts <- dts(sample(c("A", "B", "C"), 20, replace = TRUE))
## should be c("A", "B", "C")
states(x_dts)

Summary of a VLMC with covariates

Description

This function computes summary statistics of a VLMC with covariates, which are displayed by the associated print() method.

Usage

## S3 method for class 'covlmc'
summary(object, ...)

## S3 method for class 'summary.covlmc'
print(x, ...)

Arguments

object

a fitted VLMC with covariates (a covlmc object).

...

additional arguments (not used).

x

a summary of a VLMC with covariates, as returned by summary().

Value

summary() returns an object of class summary.covlmc, a list with the following components:

print() displays the summary and returns x invisibly.

See Also

covlmc(), contexts.covlmc(), context_number.covlmc(), depth(), covariate_depth()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(1 / 3, 2 / 3, 1)))
)
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 5)
summary(m_cov)

Summary of a context tree

Description

This function computes summary statistics of a context tree, which are displayed by the associated print() method.

Usage

## S3 method for class 'ctx_tree'
summary(object, ...)

## S3 method for class 'summary.ctx_tree'
print(x, ...)

## S3 method for class 'ctx_tree_cpp'
summary(object, ...)

## S3 method for class 'summary.ctx_tree_cpp'
print(x, ...)

Arguments

object

a context tree (a ctx_tree object).

...

additional arguments (not used).

x

a summary of a context tree, as returned by summary().

Value

summary() returns an object of class summary.ctx_tree (and summary.ctx_tree_cpp for a context tree built with the C++ backend), a list with the following components:

print() displays the summary and returns x invisibly.

See Also

ctx_tree(), contexts(), context_number(), depth()

Examples

rdts <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0)
rdts_ctree <- ctx_tree(rdts, min_size = 2, max_depth = 4)
summary(rdts_ctree)
## the components of the summary
unclass(summary(rdts_ctree))

Summary of the model selection of a VLMC with covariates

Description

This function summarises the results of tune_covlmc(). The associated print() method displays the selected model and the characteristics of all the models considered during the selection.

Usage

## S3 method for class 'tune_covlmc'
summary(object, ...)

## S3 method for class 'summary.tune_covlmc'
print(x, ...)

Arguments

object

the results of tune_covlmc() (a tune_covlmc object).

...

additional arguments (not used).

x

a summary of the results of tune_covlmc(), as returned by summary().

Value

summary() returns an object of class summary.tune_covlmc: the results of tune_covlmc() without the saved models (see the save parameter of tune_covlmc()). In particular, its results component is the data frame that describes the models considered during the selection.

print() displays the summary and returns x invisibly.

See Also

tune_covlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 10, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
rdts_tune <- tune_covlmc(rdts, rdts_cov, min_size = 5)
summary(rdts_tune)

Summary of the model selection of a VLMC

Description

This function summarises the results of tune_vlmc(). The associated print() method displays the selected model and the characteristics of all the models considered during the selection.

Usage

## S3 method for class 'tune_vlmc'
summary(object, ...)

## S3 method for class 'summary.tune_vlmc'
print(x, ...)

Arguments

object

the results of tune_vlmc() (a tune_vlmc object).

...

additional arguments (not used).

x

a summary of the results of tune_vlmc(), as returned by summary().

Value

summary() returns an object of class summary.tune_vlmc: the results of tune_vlmc() without the saved models (see the save parameter of tune_vlmc()). In particular, its results component is the data frame that describes the models considered during the selection.

print() displays the summary and returns x invisibly.

See Also

tune_vlmc()

Examples

rdts <- sample(as.factor(c("A", "B", "C")), 100, replace = TRUE)
tune_result <- tune_vlmc(rdts)
summary(tune_result)

Summary of a VLMC

Description

This function computes summary statistics of a VLMC, which are displayed by the associated print() method.

Usage

## S3 method for class 'vlmc'
summary(object, ...)

## S3 method for class 'summary.vlmc'
print(x, ...)

## S3 method for class 'vlmc_cpp'
summary(object, ...)

## S3 method for class 'summary.vlmc_cpp'
print(x, ...)

Arguments

object

a fitted VLMC (a vlmc object).

...

additional arguments (not used).

x

a summary of a VLMC, as returned by summary().

Value

summary() returns an object of class summary.vlmc (and summary.vlmc_cpp for a VLMC built with the C++ backend), a list with the following components:

print() displays the summary and returns x invisibly.

See Also

vlmc(), contexts.vlmc(), context_number(), depth()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts)
summary(model)
## the components of the summary
unclass(summary(model))

Trim a context tree

Description

This function returns a trimmed context tree from which the positions of the contexts in the time series (see the keep_position parameter of ctx_tree()) have been removed.

Usage

trim(ct, ...)

Arguments

ct

a context tree.

...

additional arguments for the trim() methods.

Value

a trimmed context tree.

Examples

## context tree trimming
set.seed(0)
rdts <- sample(as.factor(c("A", "B", "C")), 1000, replace = TRUE)
rdts_tree <- ctx_tree(rdts,
  max_depth = 10, min_size = 5,
  keep_position = TRUE
)
print(object.size(rdts_tree))
rdts_tree <- trim(rdts_tree)
print(object.size(rdts_tree))

Trim a COVLMC

Description

This function returns a trimmed COVLMC from which cached data have been removed.

Usage

## S3 method for class 'covlmc'
trim(ct, keep_model = FALSE, ...)

Arguments

ct

a fitted VLMC with covariates (a covlmc object).

keep_model

specifies whether to keep the internal models (or not). Defaults to FALSE.

...

additional arguments for the trim function.

Details

Called with keep_model set to FALSE (default case), the trimming is maximal and reduces further usability of the model. In particular loglikelihood.covlmc() cannot be used for new data, contexts.covlmc() and model() do not support full model extraction, predict.covlmc(), simulate.covlmc() and prune.covlmc() cannot be used at all, and metrics.covlmc() does not compute the AUC.

Called with keep_model set to TRUE, the trimming process is less complete. In particular internal models are simplified using butcher::butcher() and some additional minor reductions. This saves less memory but enables the use of loglikelihood.covlmc() for new data, of predict.covlmc() and of simulate.covlmc(), as well as full model extraction. prune.covlmc() cannot be used on the trimmed model and metrics.covlmc() does not compute the AUC.

Value

a trimmed covlmc object.

See Also

tune_covlmc()

Examples

pc <- powerconsumption[powerconsumption$week %in% 5:7, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
m_cov <- covlmc(rdts, rdts_cov, min_size = 10, keep_data = TRUE)
print(object.size(m_cov), units = "Mb")
t_m_cov_model <- trim(m_cov, keep_model = TRUE)
print(object.size(t_m_cov_model), units = "Mb")
t_m_cov <- trim(m_cov)
print(object.size(t_m_cov), units = "Mb")
## the fully trimmed model can still be used e.g. to compute the likelihood
## on the original data
logLik(t_m_cov)

Trim a VLMC

Description

This function returns a trimmed VLMC from which the positions of the contexts in the time series (see the keep_match parameter of vlmc()) have been removed.

Usage

## S3 method for class 'vlmc'
trim(ct, ...)

Arguments

ct

a VLMC.

...

additional arguments (not used).

Value

a trimmed VLMC.

Examples

## VLMC trimming is generally useless unless match positions were kept
pc <- powerconsumption[powerconsumption$week %in% 5:6, ]
rdts <- cut(pc$active_power, breaks = 4)
model <- vlmc(rdts, keep_match = TRUE)
print(object.size(model))
model <- trim(model)
## memory use should be reduced
print(object.size(model))
nm_model <- vlmc(rdts)
print(object.size(nm_model))
nm_model <- trim(nm_model)
## no effect when match positions are not kept
print(object.size(nm_model))

Trim a VLMC

Description

This function returns a trimmed VLMC from which the positions of the contexts in the time series (see the keep_match parameter of vlmc()) have been removed.

Usage

## S3 method for class 'vlmc_cpp'
trim(ct, ...)

Arguments

ct

a VLMC.

...

additional arguments (not used).

Details

Trimming with the C++ backend is done directly in the memory managed by Rcpp and cannot be detected at the R level using e.g. utils::object.size().

Value

a trimmed VLMC.

Examples

## VLMC trimming is generally useless unless match positions were kept
pc <- powerconsumption[powerconsumption$week %in% 5:6, ]
rdts <- cut(pc$active_power, breaks = 4)
model <- vlmc(rdts, backend = "C++", keep_match = TRUE)
model <- trim(model)

Fit an optimal Variable Length Markov Chain with Covariates (COVLMC)

Description

This function fits a Variable Length Markov Chain with Covariates (COVLMC) to a discrete time series coupled with a time series of covariates by optimising an information criterion (BIC or AIC).

Usage

tune_covlmc(
  x,
  covariate,
  criterion = c("BIC", "AIC"),
  initial = c("truncated", "specific", "extended"),
  alpha_init = NULL,
  min_size = 5,
  max_depth = 100,
  verbose = 0,
  save = c("best", "initial", "all"),
  trimming = c("full", "partial", "none"),
  best_trimming = c("none", "partial", "full"),
  control = covlmc_control()
)

Arguments

x

an object that can be interpreted as a discrete time series: a numeric, character, factor or logical vector, or a dts object (see dts()). Its state space must contain at least two states.

covariate

a data frame of covariates.

criterion

criterion used to select the best model. Either "BIC" (default) or "AIC" (see details).

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See loglikelihood() for details.

alpha_init

if non NULL, used as the initial cut off parameter (in quantile scale, in (0,1]) to build the initial COVLMC. The default NULL corresponds to 0.5 (see details).

min_size

number >= 1 (default: 5). Tune the minimum number of observations for a context in the growing phase of the context tree (see covlmc() for details).

max_depth

integer >= 0 (default: 100). Longest context considered in growing phase of the initial context tree (see details).

verbose

integer >= 0 (default: 0). Verbosity level of the pruning process. The progress is reported with message(), which can be silenced with suppressMessages().

save

specifies which models are saved during the pruning process. The default value "best" asks the function to keep only the best model according to the criterion. When save="initial" the function keeps in addition the initial (complex) model which is then pruned during the selection process. When save="all", the function returns all the models considered during the selection process. See details for memory occupation.

trimming

specifies the type of trimming used when saving the intermediate models: "full" (default), "partial" or "none" (see the Memory occupation section).

best_trimming

specifies the type of trimming used when saving the best model and the initial one: "none" (default), "partial" or "full" (see the Memory occupation section).

control

a list with control parameters used to fit the models, see covlmc_control().

Details

This function automates the process of fitting a large COVLMC to a discrete time series with covlmc() and of pruning the tree (with cutoff() and prune()) to get an optimal model with respect to an information criterion. To avoid missing long-term dependencies, the function uses the max_depth parameter as an initial guess but then relies on an automatic increase of the value to make sure the initial context tree is only limited by the min_size parameter. The initial value of the alpha parameter of covlmc() is also set to a conservative value (0.5) to avoid prior simplification of the context tree. This can be overridden by setting the alpha_init parameter to a more adapted value.

Once the initial COVLMC is obtained, the cutoff() and prune() functions are used to build all the COVLMC models that could be generated using smaller values of the alpha parameter. The best model is selected from this collection, including the initial complex tree, as the one that minimises the chosen information criterion.

Value

an object of class tune_covlmc, a list with the following components:

Memory occupation

covlmc objects tend to be large and saving all the models during the search for the optimal model can lead to an unreasonable use of memory. To avoid this problem, intermediate models are kept only in trimmed form using trim.covlmc() with keep_model=FALSE. Both the initial model and the best one are saved untrimmed. This default behaviour corresponds to trimming="full". Setting trimming="partial" asks the function to use keep_model=TRUE in trim.covlmc() for intermediate models. Finally, trimming="none" turns off trimming, which is discouraged except for small data sets.

In parallel processing contexts (e.g. using foreach::%dopar%), the results are serialised to be sent back to the main process: as the logistic models keep the data used to fit them (including in the environments attached to their formulas), this can be costly. It is highly recommended to trim all saved models, including the best one and the initial one. This can be done via the best_trimming parameter whose possible values are identical to the ones of trimming.

See Also

covlmc(), cutoff() and prune()

Examples

pc <- powerconsumption[powerconsumption$week %in% 6:7, ]
rdts <- cut(pc$active_power, breaks = c(0, quantile(pc$active_power, probs = c(0.5, 1))))
rdts_cov <- data.frame(day_night = (pc$hour >= 7 & pc$hour <= 17))
rdts_best_model_tune <- tune_covlmc(rdts, rdts_cov)
rdts_best_model_tune
draw(as_covlmc(rdts_best_model_tune))
## details of the pruning process
rdts_best_model_tune$results
## selection with the AIC, keeping all the (trimmed) intermediate models
rdts_aic_tune <- tune_covlmc(rdts, rdts_cov, criterion = "AIC", save = "all")
length(rdts_aic_tune$saved_models$all)

Fit an optimal Variable Length Markov Chain (VLMC)

Description

This function fits a Variable Length Markov Chain (VLMC) to a discrete time series by optimising an information criterion (BIC or AIC).

Usage

tune_vlmc(
  x,
  criterion = c("BIC", "AIC"),
  initial = c("truncated", "specific", "extended"),
  alpha_init = NULL,
  cutoff_init = NULL,
  min_size = 2L,
  max_depth = 100L,
  backend = getOption("mixvlmc.backend", "C++"),
  verbose = 0,
  save = c("best", "initial", "all")
)

Arguments

x

an object that can be interpreted as a discrete time series: a numeric, character, factor or logical vector, or a dts object (see dts()). Its state space must contain at least two states.

criterion

criterion used to select the best model. Either "BIC" (default) or "AIC" (see details).

initial

specifies the likelihood function, more precisely the way the first few observations for which contexts cannot be calculated are integrated in the likelihood. Defaults to "truncated". See loglikelihood() for details.

alpha_init

if non NULL used as the initial cut off parameter (in quantile scale) to build the initial VLMC.

cutoff_init

if non NULL used as the initial cut off parameter (in native scale) to build the initial VLMC. Takes precedence over alpha_init if specified.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context in the growing phase of the initial context tree.

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the initial context tree (see details).

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See vlmc() for details.

verbose

integer >= 0 (default: 0). Verbosity level of the pruning process. The progress is reported with message(), which can be silenced with suppressMessages().

save

specifies which models are saved during the pruning process. The default value "best" asks the function to keep only the best model according to the criterion. When save="initial" the function keeps in addition the initial (complex) model which is then pruned during the selection process. When save="all", the function returns all the models considered during the selection process.

Details

This function automates the process of fitting a large VLMC to a discrete time series with vlmc() and of pruning the tree (with cutoff() and prune()) to get an optimal model with respect to an information criterion. To avoid missing long term dependencies, the function uses the max_depth parameter as an initial guess but then relies on an automatic increase of the value to make sure the initial context tree is only limited by the min_size parameter. The initial value of the cutoff parameter of vlmc() is also set to conservative values (depending on the criterion) to avoid prior simplification of the context tree: in native scale, it is set to 0.25 * log(n) for the BIC (where n is the length of the time series) and to 1 for the AIC. This default value can be overridden using the cutoff_init or alpha_init parameter.

Once the initial VLMC is obtained, the cutoff() and prune() functions are used to build all the VLMC models that could be generated using larger values of the initial cut off parameter. The best model is selected from this collection, including the initial complex tree, as the one that minimises the chosen information criterion.

Value

an object of class tune_vlmc, a list with the following components:

See Also

vlmc(), cutoff() and prune(), as well as as_vlmc(), plot.tune_vlmc() and autoplot.tune_vlmc() to use the results.

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
tune_result <- tune_vlmc(rdts)
tune_result
draw(as_vlmc(tune_result))
summary(tune_result)
## selection with the AIC
tune_result_aic <- tune_vlmc(rdts, criterion = "AIC")
draw(as_vlmc(tune_result_aic))

Fit a Variable Length Markov Chain (VLMC)

Description

This function fits a Variable Length Markov Chain (VLMC) to a discrete time series.

Usage

vlmc(
  x,
  alpha = 0.05,
  cutoff = NULL,
  min_size = 2L,
  max_depth = 100L,
  prune = TRUE,
  keep_match = FALSE,
  backend = getOption("mixvlmc.backend", "C++")
)

Arguments

x

an object that can be interpreted as a discrete time series: a numeric, character, factor or logical vector, or a dts object (see dts()). Its state space must contain at least two states.

alpha

number in (0,1] (default: 0.05) cut off value in quantile scale in the pruning phase.

cutoff

non negative number: cut off value in native (log likelihood ratio) scale in the pruning phase. Defaults to the value obtained from alpha. Takes precedence over alpha if specified.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context in the growing phase of the context tree.

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

prune

logical: specifies whether the context tree should be pruned (default: TRUE).

keep_match

logical: specifies whether to keep the positions of the contexts in the time series (default: FALSE).

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

Details

The VLMC is built using Bühlmann and Wyner's algorithm which consists of fitting a context tree (see ctx_tree()) to a time series and then pruning it in such a way that the conditional distribution of the next state of the time series given the context is significantly different from the distribution given a truncated version of the context.

The construction of the context tree is controlled by min_size and max_depth, exactly as in ctx_tree(). Significance is measured using a likelihood ratio test whose threshold can be specified either in terms of the ratio itself with cutoff or in quantile scale with alpha.

Pruning can be postponed by setting prune=FALSE. Using a combination of cutoff() and prune(), the complexity of the VLMC can then be adjusted. Any VLMC model can be pruned after construction: prune=FALSE is a convenience parameter to avoid setting alpha=1 (which essentially prevents any pruning). Automated model selection is provided by tune_vlmc().

Value

a fitted VLMC model.

Back ends

Two back ends are available to compute context trees:

References

Bühlmann, P. and Wyner, A. J. (1999), "Variable length Markov chains." Ann. Statist. 27 (2) 480-513 doi:10.1214/aos/1018031204

See Also

cutoff(), prune() and tune_vlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts)
draw(model)
depth(model)
## reduce the depth of the model
shallow_model <- vlmc(rdts, max_depth = 3)
draw(shallow_model, prob = FALSE)
## improve probability estimates
robust_model <- vlmc(rdts, min_size = 25)
draw(robust_model, prob = FALSE) ## show the frequencies
draw(robust_model)

Fit a Variable Length Markov Chain (VLMC)

Description

This function fits a Variable Length Markov Chain (VLMC) to a discrete time series.

Usage

## Default S3 method:
vlmc(
  x,
  alpha = 0.05,
  cutoff = NULL,
  min_size = 2L,
  max_depth = 100L,
  prune = TRUE,
  keep_match = FALSE,
  backend = getOption("mixvlmc.backend", "C++")
)

Arguments

x

a numeric, character, factor or logical vector.

alpha

number in (0,1] (default: 0.05) cut off value in quantile scale in the pruning phase.

cutoff

non negative number: cut off value in native (log likelihood ratio) scale in the pruning phase. Defaults to the value obtained from alpha. Takes precedence over alpha if specified.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context in the growing phase of the context tree.

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

prune

logical: specifies whether the context tree should be pruned (default: TRUE).

keep_match

logical: specifies whether to keep the positions of the contexts in the time series (default: FALSE).

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

Details

The VLMC is built using Bühlmann and Wyner's algorithm which consists of fitting a context tree (see ctx_tree()) to a time series and then pruning it in such a way that the conditional distribution of the next state of the time series given the context is significantly different from the distribution given a truncated version of the context.

The construction of the context tree is controlled by min_size and max_depth, exactly as in ctx_tree(). Significance is measured using a likelihood ratio test whose threshold can be specified either in terms of the ratio itself with cutoff or in quantile scale with alpha.

Pruning can be postponed by setting prune=FALSE. Using a combination of cutoff() and prune(), the complexity of the VLMC can then be adjusted. Any VLMC model can be pruned after construction: prune=FALSE is a convenience parameter to avoid setting alpha=1 (which essentially prevents any pruning). Automated model selection is provided by tune_vlmc().

Value

a fitted VLMC model.

Back ends

Two back ends are available to compute context trees:

References

Bühlmann, P. and Wyner, A. J. (1999), "Variable length Markov chains." Ann. Statist. 27 (2) 480-513 doi:10.1214/aos/1018031204

See Also

cutoff(), prune() and tune_vlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
rdts <- cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
)
model <- vlmc(rdts)
draw(model)
depth(model)
## reduce the depth of the model
shallow_model <- vlmc(rdts, max_depth = 3)
draw(shallow_model, prob = FALSE)
## improve probability estimates
robust_model <- vlmc(rdts, min_size = 25)
draw(robust_model, prob = FALSE) ## show the frequencies
draw(robust_model)

Fit a Variable Length Markov Chain (VLMC)

Description

This function fits a Variable Length Markov Chain (VLMC) to a discrete time series.

Usage

## S3 method for class 'dts'
vlmc(
  x,
  alpha = 0.05,
  cutoff = NULL,
  min_size = 2L,
  max_depth = 100L,
  prune = TRUE,
  keep_match = FALSE,
  backend = getOption("mixvlmc.backend", "C++")
)

Arguments

x

a discrete time series represented by a dts object as created by dts().

alpha

number in (0,1] (default: 0.05) cut off value in quantile scale in the pruning phase.

cutoff

non negative number: cut off value in native (log likelihood ratio) scale in the pruning phase. Defaults to the value obtained from alpha. Takes precedence over alpha if specified.

min_size

integer >= 1 (default: 2). Minimum number of observations for a context in the growing phase of the context tree.

max_depth

integer >= 0 (default: 100). Longest context considered in the growing phase of the context tree.

prune

logical: specifies whether the context tree should be pruned (default: TRUE).

keep_match

logical: specifies whether to keep the positions of the contexts in the time series (default: FALSE).

backend

"R" or "C++" (default: as specified by the "mixvlmc.backend" option). Specifies the implementation used to represent the context tree and to build it. See the "Back ends" section.

Details

The VLMC is built using Bühlmann and Wyner's algorithm which consists of fitting a context tree (see ctx_tree()) to a time series and then pruning it in such a way that the conditional distribution of the next state of the time series given the context is significantly different from the distribution given a truncated version of the context.

The construction of the context tree is controlled by min_size and max_depth, exactly as in ctx_tree(). Significance is measured using a likelihood ratio test whose threshold can be specified either in terms of the ratio itself with cutoff or in quantile scale with alpha.

Pruning can be postponed by setting prune=FALSE. Using a combination of cutoff() and prune(), the complexity of the VLMC can then be adjusted. Any VLMC model can be pruned after construction: prune=FALSE is a convenience parameter to avoid setting alpha=1 (which essentially prevents any pruning). Automated model selection is provided by tune_vlmc().

Value

a fitted VLMC model.

Back ends

Two back ends are available to compute context trees:

References

Bühlmann, P. and Wyner, A. J. (1999), "Variable length Markov chains." Ann. Statist. 27 (2) 480-513 doi:10.1214/aos/1018031204

See Also

cutoff(), prune() and tune_vlmc()

Examples

pc <- powerconsumption[powerconsumption$week == 5, ]
power_dts <- dts(cut(pc$active_power,
  breaks = c(0, quantile(pc$active_power, probs = c(0.25, 0.5, 0.75, 1)))
))
model <- vlmc(power_dts)
draw(model)
depth(model)
## reduce the depth of the model
shallow_model <- vlmc(power_dts, max_depth = 3)
draw(shallow_model, prob = FALSE)
## improve probability estimates
robust_model <- vlmc(power_dts, min_size = 25)
draw(robust_model, prob = FALSE) ## show the frequencies
draw(robust_model)