R/ClusterDBCV.R

Defines functions ClusterDBCV

Documented in ClusterDBCV

ClusterDBCV = function(Cls, DataOrDistances, Dimension = NULL,
                       DistanceMethod = "euclidean", Silent = TRUE, ...) {
  # V=ClusterDBCV(Cls,Data)
  #
  # Density-Based Clustering Validation [Moulavi et al., 2014]
  #
  # INPUT
  # Cls[1:n]                 Numeric, character or factor cluster labels; no missing labels
  # DataOrDistances          Data[1:n,1:d], dissimilarities[1:n,1:n] or a dist object
  #
  # OPTIONAL
  # Dimension                Positive integer; required for precomputed distances
  #                          NULL uses ncol(Data); an explicit value must match it
  # DistanceMethod           Distance method; default "euclidean"; ignored for distances
  # Silent                   TRUE suppresses distance progress, not warnings/messages
  # ...                      Further arguments for parallelDist::parDist()
  #                          or stats::dist() if parallelDist is unavailable
  #
  # OUTPUT
  # List V with
  #   DBCV                     Density-based validity in [-1,1]; larger values are better
  #   Object                   List of density, core-distance and MST diagnostics (see DETAILS)
  #
  # DETAILS
  # Label 0 (including character/factor level "0") denotes noise.
  # Uses all-points core distances and mutual-reachability MSTs,
  # without subsampling, with quadratic distance storage. Noise remains
  # in the denominator. Following the dbscan convention, clusters of
  # size < 3 are noise; two retained clusters are required. If an MST
  # has no internal edge, its largest edge defines density sparseness.
  # Prim MST ties use the first index; different tied MSTs can change
  # internal nodes. Undefined scores yield NaN with a warning.
  # No external backend is required. Object contains ClusterLabels,
  # ClusterSizes, Dimension, DensitySparseness, DensitySeparation,
  # ClusterValidity, CoreDistances, InternalNodes, MST and NoiseCount.
  # Cluster-level components follow ClusterLabels; nodes refer to input
  # rows. Core distances for noise are NA. Duplicate points have core
  # distance zero.
  #
  # Author: Michael Thrun, 11/2026
  #
  # [Moulavi et al., 2014] Moulavi, D., Jaskowiak, P. A., Campello, R. J. G. B., Zimek, A., & Sander, J.: Density-Based Clustering Validation, Proceedings of the 2014 SIAM International Conference on Data Mining, pp. 839-847, DOI:10.1137/1.9781611973440.96, 2014.
  #
  Input = internalClusterValidation(Cls, DataOrDistances, "ClusterDBCV",
                                    TRUE, DistanceMethod, Silent, ...)
  DataDists = Input$Data
  Labels = Input$Labels
  DataDimension = Input$Dimension
  Noise = as.character(Cls) == "0"
  Cls = Input$Cls
  Cls[Noise] = 0L
  if (is.null(Dimension)) Dimension = DataDimension
  if (is.null(Dimension) || !is.numeric(Dimension) || length(Dimension) != 1L ||
      !is.finite(Dimension) || Dimension < 1 || Dimension != floor(Dimension))
    stop("ClusterDBCV: Dimension must be a positive integer; supply it for precomputed distances")
  if (!is.null(DataDimension) && Dimension != DataDimension)
    stop("ClusterDBCV: Dimension must equal the number of data columns")
  Sizes = tabulate(Cls, nbins = length(Labels))
  Retained = which(Sizes >= 3L)
  Cls[!Cls %in% Retained] = 0L
  if (length(Retained) < 2L) {
    warning("ClusterDBCV: requires at least two non-noise clusters of at least three observations")
    return(list(DBCV = NaN, Object = NULL))
  }
  ClusterIds = unique(Cls[Cls != 0L])
  Members = lapply(ClusterIds, function(i) which(Cls == i))
  ClusterNo = length(Members)
  CoreDistances = rep(NA_real_, length(Cls))
  InternalNodes = vector("list", ClusterNo)
  Trees = vector("list", ClusterNo)
  Sparseness = numeric(ClusterNo)
  for (i in seq_len(ClusterNo)) {
    Ids = Members[[i]]
    Dists = DataDists[Ids, Ids, drop = FALSE]
    Size = length(Ids)
    # Scaling each inverse-power sum by its nearest-neighbor distance avoids
    # overflow of (1 / distance)^Dimension. A duplicate implies core distance 0.
    diag(Dists) = Inf
    Nearest = apply(Dists, 1L, min)
    Core = numeric(Size)
    Positive = Nearest > 0
    Core[Positive] = Nearest[Positive] *
      (rowSums((Nearest[Positive] / Dists[Positive, , drop = FALSE])^Dimension) /
         (Size - 1L))^(-1 / Dimension)
    CoreDistances[Ids] = Core
    Reachability = pmax(Dists, outer(Core, Core, pmax))

    # Prim's algorithm on the complete mutual-reachability graph. Zero-weight
    # edges are valid; deterministic first-index tie breaking is used.
    Visited = rep(FALSE, Size)
    Visited[1L] = TRUE
    Best = Reachability[1L, ]
    Parent = rep(1L, Size)
    Tree = matrix(0, nrow = Size - 1L, ncol = 3L,
                  dimnames = list(NULL, c("From", "To", "Distance")))
    for (j in seq_len(Size - 1L)) {
      Best[Visited] = Inf
      Next = which.min(Best)
      Tree[j, ] = c(Parent[Next], Next, Best[Next])
      Visited[Next] = TRUE
      Improve = !Visited & Reachability[Next, ] < Best
      Best[Improve] = Reachability[Next, Improve]
      Parent[Improve] = Next
    }
    Degree = tabulate(c(Tree[, 1L], Tree[, 2L]), nbins = Size)
    Internal = which(Degree > 1L)
    InternalEdges = Tree[, 1L] %in% Internal & Tree[, 2L] %in% Internal
    Sparseness[i] = max(Tree[if (any(InternalEdges)) InternalEdges else
                             rep(TRUE, nrow(Tree)), 3L])
    InternalNodes[[i]] = Ids[Internal]
    Tree[, 1:2] = Ids[Tree[, 1:2]]
    Trees[[i]] = Tree
  }
  Separation = matrix(Inf, ClusterNo, ClusterNo)
  for (i in seq_len(ClusterNo - 1L)) {
    for (j in seq.int(i + 1L, ClusterNo)) {
      Left = InternalNodes[[i]]
      Right = InternalNodes[[j]]
      Separation[i, j] = Separation[j, i] = min(pmax(
        DataDists[Left, Right, drop = FALSE],
        outer(CoreDistances[Left], CoreDistances[Right], pmax)))
    }
  }
  NearestSeparation = apply(Separation, 1L, min)
  Validity = (NearestSeparation - Sparseness) / pmax(NearestSeparation, Sparseness)
  Score = sum(lengths(Members) / length(Cls) * Validity)
  if (!is.finite(Score)) {
    warning("ClusterDBCV: density validity is undefined for these distances")
    Score = NaN
  }
  diag(Separation) = 0
  return(list(DBCV = Score,
              Object = list(ClusterLabels = Labels[ClusterIds],
                            ClusterSizes = lengths(Members), Dimension = Dimension,
                            DensitySparseness = Sparseness,
                            DensitySeparation = Separation, ClusterValidity = Validity,
                            CoreDistances = CoreDistances, InternalNodes = InternalNodes,
                            MST = Trees, NoiseCount = sum(Cls == 0L))))
}

Try the FCPS package in your browser

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

FCPS documentation built on Nov. 28, 2026, 9:08 a.m.