Skip to content

Fix self-distance and sampling bugs and vectorize .clusterstructure_hopkins() - #1027

Merged
strengejacke merged 2 commits into
easystats:mainfrom
finite-sample:perf/check-clusterstructure-hopkins
Nov 24, 2026
Merged

strengejacke merged 2 commits into
easystats:mainfrom
finite-sample:perf/check-clusterstructure-hopkins

Conversation

@soodoku

@soodoku soodoku commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Problem

.clusterstructure_hopkins() (R/check_clusterstructure.R:107-144) uses a hand-rolled nested R loop (inherited from clustertend) with two correctness bugs and an $O(N^2)$ R-level dispatch bottleneck:

  1. Row-1 self-distance bug (k[i] == 1): minqi is unconditionally initialized to stats::dist(rbind(qq[i, ], x[1, ])) before checking whether qq[i, ] equals x[1, ]. Whenever k[i] == 1 (or qq[i, ] matches x[1, ]), minqi starts at 0 and cannot be improved by any positive distance, leaving minq[i] = 0 and biasing Hopkins' $H$ downward.
  2. Endpoint sampling bias: k <- round(stats::runif(n, 1, nrow(x))) samples boundary indices 1 and nrow(x) with half the probability of interior indices 2:(nrow(x) - 1) instead of sampling uniformly.
  3. $2N^2$ stats::dist(rbind(...)) calls inside nested R loops: Calling stats::dist() on 2-row matrices inside a double loop incurs massive R-level overhead on moderate datasets.

Hand-rolling pairwise distance loops and discrete uniform sampling in R is error-prone around boundary/self-match cases (like j = 1, duplicate rows, and 2-row inputs where drop = FALSE matters). Base R's sample.int() and vectorized stats::dist() handle all supported distance metrics in compiled C without per-pair loop edge cases.

Minimal repro

# Two distinct points: nearest-neighbor distance is sqrt(2) > 0 for every point,
# so Hopkins' H must always be > 0.
x2 <- data.frame(a = c(0, 1), b = c(0, 1))

# Observed on main (50% of seeds sample k == 1 and return H == 0):
mean(vapply(1:50, function(s) {
  set.seed(s)
  check_clusterstructure(x2, standardize = FALSE)$H == 0
}, logical(1)))
#> [1] 0.5

# Expected:
#> [1] 0

Fix

  • Replace round(stats::runif(n, 1, nrow(x))) with sample.int(nr, n) for uniform sampling without replacement.
  • Replace the nested for (i in 1:n) for (j in 2:nrow(x)) stats::dist(rbind(...)) loops with a single vectorized stats::dist(rbind(p, x), method = distance) call, extracting the p-to-x and x-to-x blocks with drop = FALSE and excluding zero distances (dist_xx[dist_xx == 0] <- Inf) uniformly across all rows including row 1 (with a finite guard if all rows are identical).
  • Update seeded expectations in tests/testthat/test-checks.R and add regression tests for row-1 self-distance exclusion and non-Euclidean ("manhattan") distances.

Paired timings (median of 3 runs)

Dataset Before (main) After (vectorized) Speedup
iris[, 1:4] ($N = 150, p = 4$) 0.2860 s 0.0010 s 286x
Random matrix ($N = 250, p = 4$) 0.7380 s 0.0020 s 369x

Verification

  • test-checks.R: PASS (all assertions including check_factorstructure and check_clusterstructure).
  • Revert-check (reverting only R/check_clusterstructure.R): FAIL on the new row-1 self-distance test and updated expectations; restoring R/check_clusterstructure.R: PASS.

@strengejacke
strengejacke requested a lite review from Copilot November 24, 2026 14:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@strengejacke
strengejacke merged commit 532cb84 into easystats:main Nov 24, 2026
8 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants