#' @title Integrate Benjamin Blonder's `hypervolume` with `dplyr` List-Columns #' @description Wraps S4 `Hypervolume` geometry (`hypervolume` v1.1.2 through v3.x) #' into idiomatic, pipeable `dplyr` (`|>`) verbs using `dplyr::pick()`, grouped #' list-columns, pairwise set-overlap tibbles, and topological hole detection #' (`hypervolume_holes`) over 11-column spreadsheets! #' #' Automatically uses CRAN `hypervolume` if installed, or falls back to a #' deterministic outward-padded hyperbox Monte-Carlo kernel so pipelines run #' anywhere out-of-the-box. # Internal helper: build either a real S4 `hypervolume` object (v3.x or v1.1.2) # or a lightweight deterministic fallback geometry object with identical accessors. .build_hv_object <- function(mat, name = "group", method = "box", samples_per_point = 200L, seed = 42L) { mat <- as.matrix(mat) storage.mode(mat) <- "double" # Drop constant/zero-variance columns only if all rows are identical, or pad by 1e-6 sds <- apply(mat, 2L, stats::sd) sds[is.na(sds) | sds < 1e-9] <- 1e-6 if (requireNamespace("hypervolume", quietly = TRUE)) { ns_exports <- getNamespaceExports("hypervolume") if (method == "box" && "hypervolume_box" %in% ns_exports) { hv <- hypervolume::hypervolume_box(data = mat, name = name, verbose = FALSE) return(list(engine = "hypervolume_s4", s4 = hv, volume = as.numeric(hypervolume::get_volume(hv)), dim = ncol(mat))) } if (method == "gaussian" && "hypervolume_gaussian" %in% ns_exports) { hv <- hypervolume::hypervolume_gaussian(data = mat, name = name, verbose = FALSE) return(list(engine = "hypervolume_s4", s4 = hv, volume = as.numeric(hypervolume::get_volume(hv)), dim = ncol(mat))) } # Compatible with hypervolume v1.1.2 (`hypervolume(data, bandwidth = estimate_bandwidth(data))`) bw <- hypervolume::estimate_bandwidth(mat) bw[is.na(bw) | bw <= 0] <- 1e-3 hv <- hypervolume::hypervolume(data = mat, bandwidth = bw, name = name, verbose = FALSE) return(list(engine = "hypervolume_v1_s4", s4 = hv, volume = as.numeric(hypervolume::get_volume(hv)), dim = ncol(mat))) } # Deterministic kernel-box Monte Carlo hypervolume fallback (zero external C++ deps needed) old_seed <- if (exists(".Random.seed", envir = .GlobalEnv)) get(".Random.seed", envir = .GlobalEnv) else NULL on.exit({ if (!is.null(old_seed)) assign(".Random.seed", old_seed, envir = .GlobalEnv) }, add = TRUE) set.seed(seed) bw <- 1.06 * sds * (nrow(mat)^(-1 / (ncol(mat) + 4))) lo <- apply(mat, 2L, min) - bw hi <- apply(mat, 2L, max) + bw bbox_vol <- prod(pmax(hi - lo, 1e-12)) n_mc <- max(1000L, nrow(mat) * samples_per_point) mc_pts <- matrix(0.0, nrow = n_mc, ncol = ncol(mat)) for (j in seq_len(ncol(mat))) { mc_pts[, j] <- stats::runif(n_mc, min = lo[j], max = hi[j]) } # Point is inside the union of Parzen hyperboxes around observed points if max_j |x_j - p_ij|/bw_j <= 1 inside <- logical(n_mc) for (i in seq_len(nrow(mat))) { cheb <- rep(0.0, n_mc) for (j in seq_len(ncol(mat))) { cheb <- pmax(cheb, abs(mc_pts[, j] - mat[i, j]) / bw[j]) } inside <- inside | (cheb <= 1.0) } est_vol <- bbox_vol * mean(inside) list( engine = "deterministic_parzen_hyperbox", name = name, centers = mat, bw = bw, lo = lo, hi = hi, uniform_points = mc_pts[inside, , drop = FALSE], volume = est_vol, dim = ncol(mat) ) } .test_hv_inclusion <- function(hv_wrap, query_mat) { query_mat <- as.matrix(query_mat) storage.mode(query_mat) <- "double" if (hv_wrap$engine %in% c("hypervolume_s4", "hypervolume_v1_s4")) { return(as.logical(hypervolume::hypervolume_inclusion_test(hv_wrap$s4, query_mat, verbose = FALSE))) } inside <- logical(nrow(query_mat)) centers <- hv_wrap$centers bw <- hv_wrap$bw for (i in seq_len(nrow(centers))) { cheb <- rep(0.0, nrow(query_mat)) for (j in seq_len(ncol(query_mat))) { cheb <- pmax(cheb, abs(query_mat[, j] - centers[i, j]) / bw[j]) } inside <- inside | (cheb <= 1.0) } inside } #' @title Summarise Grouped Data into `hypervolume` List-Columns (`dplyr` Verb) #' @description Works directly after `dplyr::group_by(...)`! Selects numeric feature #' columns via `dplyr::pick(...)`, constructs an n-dimensional hypervolume per group, #' keeps the geometric object in list-column `hv`, and extracts `n_obs`, `dims`, and `volume`. #' @param .data A grouped or ungrouped `data.frame` / `tibble` #' @param ... Tidyselect specification of coordinate columns (e.g. `starts_with("dim")`) #' @param method `"box"`, `"gaussian"`, or `"v1"` #' @param scale_axes Logical; z-score standardize axes before computing geometry #' @export summarise_hypervolume <- function(.data, ..., method = "box", scale_axes = FALSE) { .data |> dplyr::summarise( n_obs = dplyr::n(), hv = { mat <- as.matrix(dplyr::pick(...)) if (scale_axes) { mat <- base::scale(mat) mat[is.na(mat)] <- 0.0 } list(.build_hv_object(mat, method = method)) }, dims = hv[[1L]]$dim, volume = hv[[1L]]$volume, engine = hv[[1L]]$engine, .groups = "drop" ) } #' @title Tag Rows Inside/Outside a Reference Hypervolume (`dplyr::mutate` Verb) #' @description Evaluates `hypervolume_inclusion_test()` inside a `dplyr` pipeline #' to flag whether each row lies inside a certified safe basin (e.g. Fujita-Kato smooth basin). #' @param .data A `data.frame` / `tibble` #' @param ref_hv Either a wrapped hypervolume from `summarise_hypervolume()$hv[[1]]` or S4 `Hypervolume` #' @param ... Tidyselect coordinate columns matching `ref_hv` #' @param .col Output boolean column name #' @export mutate_hypervolume_inclusion <- function(.data, ref_hv, ..., .col = "in_safe_hypervolume") { if (inherits(ref_hv, "Hypervolume")) { ref_hv <- list(engine = "hypervolume_s4", s4 = ref_hv) } .data |> dplyr::mutate( "{.col}" := .test_hv_inclusion(ref_hv, dplyr::pick(...)) ) } #' @title Pairwise Set Overlap Statistics Across Grouped Hypervolumes (`dplyr` Verb) #' @description Computes Jaccard similarity, Sorensen similarity, intersection volume, #' and unique volume fractions (`hypervolume_set` + `hypervolume_overlap_statistics`) #' across every pair of rows in a `summarise_hypervolume()` summary tibble. #' @param .hv_tbl Output tibble from `summarise_hypervolume()` #' @param group_col Unquoted group identifier column #' @export cross_hypervolume_overlap <- function(.hv_tbl, group_col) { g_names <- dplyr::pull(.hv_tbl, {{ group_col }}) hvs <- .hv_tbl$hv n <- length(hvs) if (n < 2L) { stop("Need at least 2 grouped hypervolumes to compute pairwise overlap.") } rows <- list() idx <- 1L for (i in seq_len(n - 1L)) { for (j in (i + 1L):n) { hv1 <- hvs[[i]] hv2 <- hvs[[j]] if (hv1$engine %in% c("hypervolume_s4", "hypervolume_v1_s4")) { hv_set <- hypervolume::hypervolume_set(hv1$s4, hv2$s4, check.memory = FALSE, verbose = FALSE) stats_vec <- hypervolume::hypervolume_overlap_statistics(hv_set) inter_vol <- as.numeric(hypervolume::get_volume(hv_set))["Intersection"] jaccard <- unname(stats_vec["jaccard"]) sorensen <- unname(stats_vec["sorensen"]) u1 <- unname(stats_vec["frac_unique_1"]) u2 <- unname(stats_vec["frac_unique_2"]) } else { # Monte Carlo inclusion cross-estimator on bounding union box lo <- pmin(hv1$lo, hv2$lo) hi <- pmax(hv1$hi, hv2$hi) union_bbox <- prod(pmax(hi - lo, 1e-12)) set.seed(100L + i * 31L + j) pts <- matrix(0.0, nrow = 4000L, ncol = hv1$dim) for (d in seq_len(hv1$dim)) { pts[, d] <- stats::runif(4000L, min = lo[d], max = hi[d]) } in1 <- .test_hv_inclusion(hv1, pts) in2 <- .test_hv_inclusion(hv2, pts) v_inter <- union_bbox * mean(in1 & in2) v_union <- union_bbox * mean(in1 | in2) v1 <- union_bbox * mean(in1) v2 <- union_bbox * mean(in2) inter_vol <- v_inter jaccard <- if (v_union > 0) v_inter / v_union else 0.0 sorensen <- if ((v1 + v2) > 0) (2.0 * v_inter) / (v1 + v2) else 0.0 u1 <- if (v1 > 0) (union_bbox * mean(in1 & !in2)) / v1 else 0.0 u2 <- if (v2 > 0) (union_bbox * mean(in2 & !in1)) / v2 else 0.0 } rows[[idx]] <- tibble::tibble( group_1 = as.character(g_names[[i]]), group_2 = as.character(g_names[[j]]), vol_1 = hv1$volume, vol_2 = hv2$volume, intersection_vol = inter_vol, jaccard = jaccard, sorensen = sorensen, frac_unique_1 = u1, frac_unique_2 = u2 ) idx <- idx + 1L } } dplyr::bind_rows(rows) } #' @title Topological Hole Detection (`hypervolume_holes` -> Tidy `dplyr` Verb) #' @description Wraps Benjamin Blonder's `hypervolume_holes(hv.obs, hv.exp)` to find #' "negative feature space" — forbidden singularity cavities or off-book shell voids #' enclosed inside a naive convex/expected envelope `hv_expected` yet absent from #' the true endogenous observed hypervolume! #' @param .hv_tbl Output tibble from `summarise_hypervolume()` #' @param expected_hv Reference convex/expected hypervolume wrapper #' @export detect_hypervolume_holes_tidy <- function(.hv_tbl, expected_hv) { .hv_tbl |> dplyr::rowwise() |> dplyr::mutate( expected_volume = expected_hv$volume, hole_volume = { if (hv$engine %in% c("hypervolume_s4", "hypervolume_v1_s4") && "hypervolume_holes" %in% getNamespaceExports("hypervolume")) { holes_s4 <- hypervolume::hypervolume_holes( hv.obs = hv$s4, hv.exp = expected_hv$s4, set.check.memory = FALSE, verbose = FALSE ) if (is.null(holes_s4)) 0.0 else as.numeric(hypervolume::get_volume(holes_s4)) } else { pts_exp <- expected_hv$uniform_points if (nrow(pts_exp) == 0L) { 0.0 } else { in_obs <- .test_hv_inclusion(hv, pts_exp) expected_hv$volume * mean(!in_obs) } } }, hole_fraction_of_expected = ifelse(expected_volume > 0, hole_volume / expected_volume, 0.0) ) |> dplyr::ungroup() }