R/render-texture.R

Defines functions haralick.matrix texture.render haralick.net glcm.net

Documented in glcm.net haralick.matrix haralick.net texture.render

.haralick_features <- c("asm", "con", "cor", "den", "dva", "ent", "f12", "f13", "idm", "pro", "sav", "sen", "sha", "sva", "var")

#' Construct network grey-level co-occurrence matrices (GLCMs)
#' @param mtr Numeric gene-by-sample matrix.
#' @param net Network with a named adjacency list in `links`.
#' @param rnm Genes defining one functional gene set or pathway.
#' @param t_level Number of binary grey-level bits.
#' @param min_n Minimum number of mapped genes required for the pathway. The
#'   function returns `NULL` below this threshold; [texture.render()] retains
#'   the pathway row and fills it with `NA` scores.
#' @param by Rank-normalization direction.
#' @param scope Graph scope: `"within-pathway"` uses within-set edges; `"boundary-expanded"` also
#' uses boundary edges to one-hop neighbors.
#' @return A named list with one normalized square GLCM per sample. Matrix
#'   cells contain symmetrized co-occurrence probabilities and sum to one.
#'   Returns `NULL` when fewer than `min_n` pathway genes map; an empty list
#'   indicates insufficient scoped edges.
#' @seealso [haralick.net()], [texture.render()]
#' @examples
#' profiles <- matrix(c(1, 5, 2, 4, 3, 3, 4, 2), nrow = 4,
#'   dimnames = list(letters[1:4], c("sample_1", "sample_2")))
#' net <- list(links = list(a = "b", b = c("a", "c"),
#'   c = c("b", "d"), d = "c"), Ntotal = 3)
#' glcm <- glcm.net(profiles, net, c("a", "b", "c"),
#'   min_n = 3, scope = "within-pathway")
#' names(glcm)
#' @export
glcm.net <- function(mtr, net, rnm, t_level = 3, min_n = 5,
                     by = c("non", "row", "col"), scope = c("within-pathway", "boundary-expanded")) {
  if (length(scope) != 1L) stop("scope must select exactly one score type.", call. = FALSE)
  by <- match.arg(by); scope <- match.arg(scope)
  if (!is.matrix(mtr) || !is.numeric(mtr) || is.null(rownames(mtr)))
    stop("mtr must be a numeric matrix with gene row names.", call. = FALSE)
  if (is.null(net$links) || !is.list(net$links) || is.null(names(net$links)))
    stop("net$links must be a named adjacency list.", call. = FALSE)
  if (length(t_level) != 1L || is.na(t_level) || t_level < 1 ||
      t_level != as.integer(t_level))
    stop("t_level must be one positive integer.", call. = FALSE)
  if (length(min_n) != 1L || is.na(min_n) || min_n < 1 ||
      min_n != as.integer(min_n))
    stop("min_n must be one positive integer.", call. = FALSE)
  rnm <- unique(intersect(rnm, rownames(mtr)))
  if (length(rnm) < min_n) return(NULL)
  rnm_all <- rnm
  if (scope == "boundary-expanded") {
    boundary <- unique(unlist(net$links[rnm], use.names = FALSE))
    rnm_all <- unique(c(rnm, intersect(boundary, rownames(mtr))))
  }
  x <- mtr[rnm_all, , drop = FALSE]; levels <- 2^as.integer(t_level)
  discrete <- matrix(NA_real_, nrow(x), ncol(x), dimnames = dimnames(x))
  scale_rank <- function(z) {
    r <- rank(z, na.last = "keep", ties.method = "min")
    round((levels - 1) * r / max(r, na.rm = TRUE))
  }
  if (by == "non") {
    r <- rank(as.numeric(x), na.last = "keep")
    discrete[] <- round((levels - 1) * r / sum(!is.na(x)))
  } else if (by == "row") discrete[] <- t(apply(x, 1L, scale_rank))
  else discrete[] <- apply(x, 2L, scale_rank)
  edges <- do.call(rbind, lapply(rnm, function(gene) {
    adjacent <- intersect(net$links[[gene]], rnm_all)
    if (length(adjacent)) cbind(gene, adjacent) else NULL
  }))
  if (is.null(edges) || nrow(edges) <= 1L) return(list())
  answer <- lapply(seq_len(ncol(discrete)), function(j) {
    a <- factor(discrete[edges[, 1L], j], levels = 0:(levels - 1L))
    b <- factor(discrete[edges[, 2L], j], levels = 0:(levels - 1L))
    counts <- table(a, b); p <- (counts + t(counts)) / sum(counts + t(counts))
    nz <- which(p > 0)
    if (length(nz) < length(p)) {
      p[-nz] <- 1 / (nrow(edges) * 10 * (length(p) - length(nz)))
      p <- p - (sum(p) - 1) / length(p)
    }
    unclass(p)
  })
  names(answer) <- colnames(discrete); answer
}

#' Calculate Haralick texture features for one functional gene set
#'
#' Calculate texture features from sample-specific grey-level co-occurrence
#' matrices (GLCMs) for a single functional gene set. [glcm.net()] constructs
#' this input; [texture.render()] calls both low-level functions across multiple
#' functional gene sets and assembles the pathway-by-sample result matrices.
#'
#' @param x Named list of square GLCMs, one per sample, for one functional gene
#'   set.
#' @param bind_range Append each feature's range across samples.
#' @param features Unique feature identifiers. The default explicitly lists
#'   all 15 implemented features.
#' @details The calculation follows the established `wvtool` indexing
#'   convention. Although discrete grey levels are labelled `0` through
#'   `G - 1` in the formulas, the `spq` index for sum-based features is formed
#'   from R matrix indices `1` through `G`. Consequently, `sav` is two units
#'   above a strictly zero-based implementation, and `sva` uses the
#'   corresponding scale. This convention is retained for numerical
#'   consistency.
#' @section Haralick features:
#' `features` accepts the following identifiers:
#' \describe{
#'   \item{`asm`}{angular second moment (energy)}
#'   \item{`con`}{contrast}
#'   \item{`cor`}{correlation}
#'   \item{`den`}{difference entropy}
#'   \item{`dva`}{difference variance}
#'   \item{`ent`}{entropy}
#'   \item{`f12`}{first information measure of correlation}
#'   \item{`f13`}{second information measure of correlation}
#'   \item{`idm`}{inverse difference moment (homogeneity)}
#'   \item{`pro`}{cluster prominence}
#'   \item{`sav`}{sum average}
#'   \item{`sen`}{sum entropy}
#'   \item{`sha`}{cluster shade}
#'   \item{`sva`}{sum variance}
#'   \item{`var`}{variance}
#' }
#' @return A numeric feature-by-sample matrix in requested feature order.
#'   When `bind_range = TRUE`, a final `rng` column gives each feature's
#'   across-sample range. Returns `NULL` for an empty GLCM list.
#' @references Haralick RM, Shanmugam K, Dinstein I (1973).
#'   \doi{10.1109/TSMC.1973.4309314}.
#'   Kobayashi K et al. (2015). \doi{10.1007/s10086-015-1507-6}.
#'   Alexeyenko A (2026). \doi{10.64898/2026.07.12.737672}.
#' @seealso [glcm.net()], [texture.render()], [haralick.matrix()]
#' @examples
#' p1 <- matrix(c(0.4, 0.1, 0.1, 0.4), 2)
#' p2 <- matrix(c(0.25, 0.25, 0.25, 0.25), 2)
#' haralick.net(list(sample_1 = p1, sample_2 = p2),
#'   features = c("asm", "con", "idm"))
#' @export
haralick.net <- function(x, bind_range = FALSE, features = c("asm", "con", "cor", "den", "dva", "ent", "f12", "f13",
      "idm", "pro", "sav", "sen", "sha", "sva", "var")) {
  .assert_flag(bind_range, "bind_range")
  bad <- setdiff(features, .haralick_features)
  if (length(bad)) stop("Feature ", bad[[1L]], " is not implemented.", call. = FALSE)
  if (!length(x)) return(NULL)
  out <- matrix(NA_real_, length(features), length(x),
    dimnames = list(features, names(x)))
  for (sample in seq_along(x)) {
    p <- as.matrix(x[[sample]]); n <- nrow(p)
    if (n != ncol(p)) stop("Matrix is not square.", call. = FALSE)
    px <- colSums(p); py <- rowSums(p); i <- seq_len(n)
    mx <- sum(px * i); my <- sum(py * i)
    op <- matrix(i, n, n); oq <- t(op); spq <- op + oq; dpq <- abs(op - oq)
    ent <- -sum(p * log10(p), na.rm = TRUE)
    v <- c(asm = sum(p^2), con = sum(dpq^2 * p), idm = sum(p / (1 + dpq^2)), ent = ent,
      var = sum((op - (mx + my) / 2)^2 * p), sav = sum(spq * p),
      sha = sum((spq - mx - my)^3 * p), pro = sum((spq - mx - my)^4 * p))
    vx <- sum(px * (i - mx)^2); vy <- sum(py * (i - my)^2)
    v["cor"] <- sum((op - mx) * (oq - my) * p) / sqrt(vx * vy)
    ps <- numeric(2L * n - 1L); pd <- numeric(n)
    for (row in i) for (col in i) {
      ps[row + col - 1L] <- ps[row + col - 1L] + p[row, col]
      pd[abs(row - col) + 1L] <- pd[abs(row - col) + 1L] + p[row, col]
    }
    v["sen"] <- sen <- -sum(ps * log10(ps), na.rm = TRUE)
    v["den"] <- den <- -sum(pd * log10(pd), na.rm = TRUE)
    v["dva"] <- sum((dpq - den)^2 * p); v["sva"] <- sum((spq - sen)^2 * p)
    pxpy <- outer(px, py); hxy1 <- -sum(p * log10(pxpy), na.rm = TRUE)
    hx <- -sum(px * log10(px), na.rm = TRUE); hy <- -sum(py * log10(py), na.rm = TRUE)
    v["f12"] <- (hxy1 - ent) / max(hx, hy)
    hxy2 <- -sum(pxpy * log10(pxpy), na.rm = TRUE)
    v["f13"] <- sqrt(1 - exp(-2 * (hxy2 - ent)))
    out[, sample] <- v[features]
  }
  if (bind_range) {
    out <- cbind(out, rng = apply(out, 1L, function(z) diff(range(z))))
  }
  out
}

#' Render a sample matrix as pathway-level texture features
#'
#' From a matrix of continuous gene or protein values, calculate selected
#' Haralick texture features for a collection of pathways. Haralick et al.
#' (1973) developed the method for regular image grids; this implementation
#' evaluates co-occurrence between adjacent nodes in irregular pathway-scale
#' subnetworks extracted from the global network. Subset `fgs` before calling
#' when only some sets are required.
#'
#' @param fgs Named list of functional gene sets whose subnetworks are extracted
#'   from the global network. Subset it before calling when needed.
#' @param mtr Numeric gene-by-sample matrix.
#' @param t_level Number of binary grey-level bits.
#' @param net Network with a named adjacency list in `links`.
#' @param min_ngenes Minimum mapped genes per set.
#' @param norm_dir Rank-normalization direction.
#' @param features Unique requested Haralick feature identifiers. The default
#'   explicitly lists all 15 implemented features.
#' @inheritSection haralick.net Haralick features
#' @param scope Graph scope: `"within-pathway"` uses within-set edges;
#'   `"boundary-expanded"` also uses boundary edges to one-hop neighbors.
#' @param case_sensitive Use case-sensitive identifier matching.
#' @param n_cores Positive integer number of worker processes. Independent
#'   functional gene sets are distributed across workers when greater than one.
#' @param verbose Report progress with [message()].
#' @details Each sample is discretized to `2^t_level` grey levels before a
#'   pathway GLCM is constructed. `norm_dir` controls whether ranking is
#'   performed by gene, by sample, or over the full selected matrix. The
#'   renderer calculates descriptive texture features; it does not calculate
#'   p- or q-values.
#' @return A `nearender_result`. `scores` contains one
#'   pathway-by-sample matrix for every requested Haralick feature, in request
#'   order; `statistics` contains the same master score matrices under the same
#'   names. Pathways below `min_ngenes` retain a row filled with `NA`.
#'   `diagnostics$fgs_network_sizes` reports the number of mapped network
#'   genes for every pathway, while `parameters` records scope,
#'   discretization, normalization direction, case policy, and workers.
#' @references Haralick RM, Shanmugam K, Dinstein I (1973).
#'   \doi{10.1109/TSMC.1973.4309314}.
#'
#'   Kobayashi K et al. (2015). \doi{10.1007/s10086-015-1507-6}.
#'
#'   Alexeyenko A (2026). \doi{10.64898/2026.07.12.737672}.
#' @seealso [glcm.net()], [haralick.net()], [haralick.matrix()],
#'   [spectral.render()], [gsva.render()]
#' @examples
#' profiles <- matrix(c(1, 5, 2, 4, 3, 3, 4, 2), nrow = 4,
#'   dimnames = list(letters[1:4], c("sample_1", "sample_2")))
#' fgs <- list(pathway = c("a", "b", "c"))
#' net <- list(links = list(a = "b", b = c("a", "c"),
#'   c = c("b", "d"), d = "c"), Ntotal = 3)
#' texture <- texture.render(fgs, profiles, net, min_ngenes = 3,
#'   features = c("asm", "con"), scope = "within-pathway",
#'   verbose = FALSE)
#' texture$scores$asm
#' @export
texture.render <- function(fgs, mtr, net, t_level = 3, min_ngenes = 5,
    norm_dir = c("row", "col", "non"), features = c("asm", "con", "cor", "den", "dva", "ent", "f12", "f13",
      "idm", "pro", "sav", "sen", "sha", "sva", "var"),
    scope = c("within-pathway", "boundary-expanded"), case_sensitive = FALSE,
    n_cores = 1L, verbose = TRUE) {
  if (length(scope) != 1L) stop("scope must select exactly one score type.", call. = FALSE)
  scope <- match.arg(scope); norm_dir <- match.arg(norm_dir)
  .assert_flag(case_sensitive, "case_sensitive"); .assert_flag(verbose, "verbose")
  n_cores <- .validate_n_cores(n_cores)
  if (!is.character(features) || !length(features) || anyNA(features) ||
      length(setdiff(features, .haralick_features)) ||
      anyDuplicated(features)) {
    stop("features must contain unique implemented Haralick features.",
      call. = FALSE)
  }
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  fgs_names <- names(fgs)
  net <- as_nearender_network(
    .normalize_network(net, case_sensitive), case_sensitive)
  .assert_compatible_identifiers(fgs = fgs, net = net)
  mtr <- .select_sample_matrix(mtr, NULL, NULL)
  genes <- .canonical_ids(rownames(mtr), case_sensitive)
  if (anyDuplicated(genes)) stop("Matrix gene names collide under the identifier case policy.", call. = FALSE)
  rownames(mtr) <- genes; network_genes <- intersect(genes, names(net$links))
  if (verbose) message("Calculating ", scope, " Haralick texture scores.")
  per_set <- .parallel_lapply(fgs_names, function(nm) haralick.net(glcm.net(mtr, net,
    intersect(network_genes, fgs[[nm]]), t_level, min_ngenes, norm_dir, scope),
    features = features), n_cores = n_cores)
  scores <- stats::setNames(lapply(features, function(feature) {
    z <- matrix(NA_real_, length(fgs_names), ncol(mtr),
      dimnames = list(fgs_names, colnames(mtr)))
    for (k in seq_along(per_set)) if (!is.null(per_set[[k]])) z[k, ] <- per_set[[k]][feature, ]
    z
  }), features)
  mapped <- vapply(fgs, function(z) length(intersect(z, network_genes)),
    integer(1))
  .new_nearender_result(scores, .new_score_info(features, "texture", features,
    mode = scope, parameters = paste0("t_level=", t_level,
      ";norm_dir=", norm_dir),
    citation = "Haralick et al. (1973)"),
    inputs = list(fgs_names = fgs_names, fgs_sizes = lengths(fgs)),
    diagnostics = list(fgs_network_sizes = mapped),
    parameters = list(scope = scope, t_level = t_level,
      min_ngenes = min_ngenes, norm_dir = norm_dir,
      case_sensitive = case_sensitive,
      n_cores = n_cores))
}

#' Compatibility wrapper for texture rendering
#'
#' `haralick.matrix()` forwards to [texture.render()] and emits a deprecation
#' warning. Its former set-selection and combined `all` arguments are not part
#' of this interface.
#'
#' @inheritParams texture.render
#' @return A `nearender_result` returned by [texture.render()].
#' @seealso [texture.render()], [haralick.net()], [glcm.net()]
#' @export
haralick.matrix <- function(fgs, mtr, net, t_level = 3, min_ngenes = 5,
    norm_dir = c("row", "col", "non"), features = c("asm", "con", "cor", "den", "dva", "ent", "f12", "f13",
      "idm", "pro", "sav", "sen", "sha", "sva", "var"),
    scope = c("within-pathway", "boundary-expanded"), case_sensitive = FALSE,
    n_cores = 1L, verbose = TRUE) {
  .Deprecated("texture.render")
  texture.render(fgs = fgs, mtr = mtr, net = net, t_level = t_level,
    min_ngenes = min_ngenes, norm_dir = norm_dir, features = features,
    scope = scope, case_sensitive = case_sensitive, n_cores = n_cores,
    verbose = verbose)
}

Try the NEArender package in your browser

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

NEArender documentation built on Nov. 28, 2026, 5:10 p.m.