R/methods.R

Defines functions .outer_legend plot.dmm print.summary.dmm summary.dmm print.dmm

Documented in plot.dmm print.dmm print.summary.dmm summary.dmm

## Standard S3 methods for the class dmm: print, summary, plot
## =====================================================================


#' Print a drifting Markov model
#'
#' @description Prints the order, the degree, the length, the state space, the number of
#'   parameters, the initial law and the points of support of a drifting Markov model.
#'
#' @param x An object of class \code{dmm}
#' @param digits Default=4. Number of significant digits of the probabilities
#' @param ... Not used
#' @return \code{x}, invisibly
#' @export
#' @seealso \link[drimmR]{fitdmm}, \link[drimmR]{dmm}, \link[drimmR]{summary.dmm}, \link[drimmR]{plot.dmm}
#' @examples
#' data(lambda, package = "drimmR")
#' x <- fitdmm(lambda, 1, 1, c("a", "c", "g", "t"), init.estim = "freq")
#' x
print.dmm <- function(x, digits = 4, ...) {
  cat("Drifting Markov model of order ", x$order, " and degree ", x$degree,
      " (length n = ", x$length, ")\n", sep = "")
  cat("States:", paste(x$states, collapse = " "), "\n")
  cat("Number of parameters:", .nb_param(x), "\n")
  if (x$order > 0L) {
    cat(if (x$order == 1L) "\nInitial law of the first state:\n" else
      paste0("\nInitial law of the ", x$order, " first states:\n"))
    print(signif(x$init, digits))
  }
  cat("\nPoints of support:\n")
  for (i in seq_along(x$matrices)) {
    cat("\n", names(x$matrices)[i], " (position t/n = ", format((i - 1) / x$degree, digits = 3),
        ")\n", sep = "")
    print(signif(x$matrices[[i]], digits))
  }
  invisible(x)
}


#' Summary of a drifting Markov model
#'
#' @description Summarizes a drifting Markov model: its characteristics, the stationary laws
#'   of the states at the beginning, in the middle and at the end of the sequence and, when
#'   sequences are given, their length, log-likelihood, AIC and BIC.
#'
#' @param object An object of class \code{dmm}
#' @param sequences (Optional) A character vector or a list of character vectors
#'   representing one or several sequences
#' @param ... Not used
#' @return An object of class \code{summary.dmm}: a list with the elements \code{order},
#'   \code{degree}, \code{length}, \code{states}, \code{nb.param}, \code{init},
#'   \code{stationary} (matrix of the stationary laws of the states at the positions 0,
#'   \eqn{n/2} and \eqn{n}) and \code{fit} (data frame with the length, log-likelihood, AIC and
#'   BIC of each sequence, or \code{NULL})
#' @export
#' @seealso \link[drimmR]{loglik}, \link[drimmR]{aic}, \link[drimmR]{bic}, \link[drimmR]{getStationaryLaw}
#' @examples
#' data(lambda, package = "drimmR")
#' x <- fitdmm(lambda, 1, 1, c("a", "c", "g", "t"), init.estim = "freq")
#' summary(x, lambda)
summary.dmm <- function(object, sequences = NULL, ...) {
  if (isFALSE(inherits(object, "dmm"))) stop("'object' parameter must be of class 'dmm'")
  positions <- unique(c(0L, object$length %/% 2L, object$length))
  stationary <- if (object$order == 0L) {
    .transition_array(object, positions)[, 1, ]
  } else {
    .stationary_laws(object, positions)
  }
  stationary <- matrix(stationary, nrow = length(positions),
                       dimnames = list(paste0("pos ", positions), object$states))
  fit <- NULL
  if (!is.null(sequences)) {
    sequences <- .check_sequences(sequences)
    ll <- unlist(loglik(object, sequences))
    fit <- data.frame(length = lengths(sequences), loglik = ll,
                      AIC = unlist(aic(object, sequences)),
                      BIC = unlist(bic(object, sequences)))
    rownames(fit) <- if (!is.null(names(sequences))) names(sequences) else
      paste0("sequence ", seq_along(sequences))
  }
  res <- list(order = object$order, degree = object$degree, length = object$length,
              states = object$states, nb.param = .nb_param(object), init = object$init,
              stationary = stationary, fit = fit)
  class(res) <- "summary.dmm"
  res
}


#' @rdname summary.dmm
#' @param x An object of class \code{summary.dmm}
#' @param digits Default=4. Number of significant digits
#' @export
print.summary.dmm <- function(x, digits = 4, ...) {
  cat("Drifting Markov model of order ", x$order, " and degree ", x$degree,
      " (length n = ", x$length, ")\n", sep = "")
  cat("States:", paste(x$states, collapse = " "), "\n")
  cat("Number of parameters:", x$nb.param, "\n")
  cat("\nStationary laws of the states:\n")
  print(signif(x$stationary, digits))
  if (!is.null(x$fit)) {
    cat("\nGoodness of fit:\n")
    print(x$fit, digits = max(digits, 7))
  }
  invisible(x)
}


#' Plot a drifting Markov model
#'
#' @description Plots the transition probabilities, or the stationary laws of the states,
#'   along the sequence.
#'
#' @param x An object of class \code{dmm}
#' @param what Default="transition". If \code{what}="transition", one panel is drawn for each
#'   context (word of length \code{order}), giving the probabilities of the next state along
#'   the sequence; if \code{what}="stationary", the stationary laws of the states are drawn
#'   along the sequence
#' @param contexts (Optional) The contexts (rows of the transition matrices) to draw when
#'   \code{what}="transition"; by default all of them, at most 16
#' @param npoints Default=200. Number of positions at which the curves are evaluated
#' @param ... Graphical parameters passed to \code{\link[graphics]{matplot}}
#' @return Invisibly, a list with the positions and the plotted values (an array
#'   [position, context, state] for \code{what}="transition", a matrix [position, state] for
#'   \code{what}="stationary")
#' @export
#' @importFrom graphics matplot legend par
#' @seealso \link[drimmR]{getTransitionMatrix}, \link[drimmR]{getStationaryLaw}
#' @examples
#' data(lambda, package = "drimmR")
#' x <- fitdmm(lambda, 1, 1, c("a", "c", "g", "t"), init.estim = "freq")
#' plot(x)
#' plot(x, what = "stationary")
plot.dmm <- function(x, what = c("transition", "stationary"), contexts = NULL,
                     npoints = 200, ...) {
  what <- match.arg(what)
  if (!(.is_count(npoints) && npoints >= 2)) stop("'npoints' must be an integer >= 2")
  positions <- unique(round(seq(0, x$length, length.out = npoints)))
  s <- length(x$states)
  cols <- seq_len(s)

  if (what == "stationary") {
    values <- if (x$order == 0L) {
      matrix(.transition_array(x, positions)[, 1, ], ncol = s)
    } else {
      .stationary_laws(x, positions)
    }
    colnames(values) <- x$states
    matplot(positions, values, type = "l", lty = 1, col = cols, xlab = "Position",
            ylab = "Probability", main = "Stationary laws", ...)
    legend("topright", legend = x$states, col = cols, lty = 1, bty = "n")
    return(invisible(list(positions = positions, values = values)))
  }

  values <- .transition_array(x, positions)
  # order 0: a single "context" (the law of the next state does not depend on the past)
  rows <- if (x$order == 0L) "(none)" else rownames(x$matrices$Pi0)
  dimnames(values) <- list(NULL, rows, x$states)
  if (is.null(contexts)) {
    contexts <- utils::head(rows, 16)
    if (length(rows) > 16) message("Only the 16 first contexts are drawn (argument 'contexts')")
  }
  if (!all(contexts %in% rows)) stop("'contexts' must be words of length order (rows of the transition matrices)")
  nc <- length(contexts)
  ncol <- ceiling(sqrt(nc))
  # the legend (next states) is drawn once, in the top outer margin
  op <- par(mfrow = c(ceiling(nc / ncol), ncol), mar = c(4, 4, 2, 1), oma = c(0, 0, 2, 0))
  on.exit(par(op))
  for (ctx in contexts) {
    matplot(positions, values[, ctx, ], type = "l", lty = 1, col = cols,
            ylim = c(0, max(values[, ctx, ])), xlab = "Position", ylab = "Probability",
            main = if (x$order == 0L) "Transition probabilities" else paste("From", ctx), ...)
  }
  .outer_legend(x$states, cols, title = "Next state:")
  invisible(list(positions = positions, values = values[, contexts, , drop = FALSE]))
}


# Horizontal legend in the top outer margin of the current figure
#' @importFrom graphics plot.new
.outer_legend <- function(labels, cols, title = NULL) {
  par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
  plot.new()
  legend("top", legend = labels, col = cols, lty = 1, horiz = TRUE, bty = "n",
         title = title, title.adj = 0, xpd = NA, inset = 0.005)
}

Try the drimmR package in your browser

Any scripts or data that you put into this service are public.

drimmR documentation built on Dec. 2, 2026, 1:07 a.m.