From 53549f9ba1eb0c56412d948c11944d3737e06e37 Mon Sep 17 00:00:00 2001 From: Nicolas Klutchnikoff Date: Thu, 30 Apr 2026 14:23:48 +0200 Subject: [PATCH 1/3] refactor: unify API around pp_lp and as_pp_lp --- .Rbuildignore | 1 + NAMESPACE | 18 ++- R/cv.R | 112 +++++++++++------- R/density_lp.R | 145 ++++++++++++++++++++---- R/density_lp_ppp.R | 89 ++++----------- R/domain.R | 37 ++++-- R/domain_sector.R | 20 +++- R/methods.R | 208 ++++++++++++---------------------- R/pp_lp.R | 117 +++++++++++++++++++ man/as_pp_lp.Rd | 39 +++++++ man/cv_density_lp.Rd | 37 +++--- man/cv_density_lp_ppp.Rd | 14 +-- man/density_lp.Rd | 58 ++++++---- man/density_lp_ppp.Rd | 17 +-- man/domain_from_indicator.Rd | 4 +- man/plot.density_lp.Rd | 25 ---- man/plot.density_lp_ppp.Rd | 19 ---- man/pp_lp.Rd | 38 +++++++ man/print.cv_density_lp.Rd | 19 ---- man/print.density_lp.Rd | 19 ---- man/print.density_lp_ppp.Rd | 19 ---- man/summary.cv_density_lp.Rd | 19 ---- man/summary.density_lp.Rd | 19 ---- man/summary.density_lp_ppp.Rd | 19 ---- 24 files changed, 617 insertions(+), 495 deletions(-) create mode 100644 R/pp_lp.R create mode 100644 man/as_pp_lp.Rd delete mode 100644 man/plot.density_lp.Rd delete mode 100644 man/plot.density_lp_ppp.Rd create mode 100644 man/pp_lp.Rd delete mode 100644 man/print.cv_density_lp.Rd delete mode 100644 man/print.density_lp.Rd delete mode 100644 man/print.density_lp_ppp.Rd delete mode 100644 man/summary.cv_density_lp.Rd delete mode 100644 man/summary.density_lp.Rd delete mode 100644 man/summary.density_lp_ppp.Rd diff --git a/.Rbuildignore b/.Rbuildignore index 52000ce..8693d3a 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -17,3 +17,4 @@ ^README\.Rmd$ ^README\.html$ ^CITATION\.cff$ +^memory$ diff --git a/NAMESPACE b/NAMESPACE index 5abc8e7..5e121c5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,14 +1,27 @@ # Generated by roxygen2: do not edit by hand +S3method(as_pp_lp,matrix) +S3method(as_pp_lp,pp_lp) +S3method(as_pp_lp,ppp) +S3method(cv_density_lp,data.frame) +S3method(cv_density_lp,matrix) +S3method(cv_density_lp,pp_lp) +S3method(cv_density_lp,ppp) +S3method(density_lp,data.frame) +S3method(density_lp,matrix) +S3method(density_lp,pp_lp) +S3method(density_lp,ppp) S3method(plot,density_lp) S3method(plot,density_lp_ppp) S3method(print,cv_density_lp) S3method(print,density_lp) S3method(print,density_lp_ppp) S3method(print,domain_lp) +S3method(print,pp_lp) S3method(summary,cv_density_lp) S3method(summary,density_lp) S3method(summary,density_lp_ppp) +export(as_pp_lp) export(cv_density_lp) export(cv_density_lp_ppp) export(density_lp) @@ -17,17 +30,14 @@ export(domain_Rd) export(domain_from_indicator) export(domain_from_owin) export(domain_sector) +export(pp_lp) export(rfactory) importFrom(Rcpp,sourceCpp) -importFrom(grDevices,grey) -importFrom(graphics,image) importFrom(spatstat.geom,Window) importFrom(spatstat.geom,area.owin) importFrom(spatstat.geom,im) -importFrom(spatstat.geom,inside.owin) importFrom(spatstat.geom,intersect.owin) importFrom(spatstat.geom,owin) -importFrom(spatstat.geom,unitname) importFrom(spatstat.random,runifpoint) importFrom(stats,integrate) importFrom(stats,runif) diff --git a/R/cv.R b/R/cv.R index bc7f360..e4b602d 100644 --- a/R/cv.R +++ b/R/cv.R @@ -27,34 +27,75 @@ new_cv_density_lp <- function(m_hat, h_hat, scores, grids, call) { #' where \eqn{\|H_0^{(X_i)}\|^2 = (B_{X_i}^{-1})_{11}} is the self-influence #' scalar returned as a byproduct of the C++ pipeline. #' -#' @param X Numeric matrix `n x d` of observations. +#' @param x Observations. Can be a numeric \code{matrix}, a \code{spatstat.geom::ppp} +#' object, or a \code{pp_lp} object. #' @param h_grid Numeric vector of bandwidth values (all > 0). -#' @param m_grid Integer vector of polynomial degrees (default `0:3`). -#' @param domain An `"domain_lp"` object. -#' @param N_quad Number of quadrature points per evaluation (default 500). -#' @return An S3 object of class `"cv_density_lp"` containing: -#' - `$m_hat`, `$h_hat`: selected degree and bandwidth, -#' - `$scores`: matrix `|m_grid| x |h_grid|` of CV scores, -#' - `$grids`: list containing `$m` and `$h` grids used. -#' @seealso [density_lp()], [cv_density_lp_ppp()] +#' @param m_grid Integer vector of polynomial degrees (default \code{0:3}). +#' @param N_quad Number of quadrature (Monte Carlo) points used to approximate +#' the normalising integral (default 500). +#' @param ... Additional arguments passed to methods. +#' +#' @return An S3 object of class \code{"cv_density_lp"} with fields: +#' \describe{ +#' \item{m_hat}{Selected polynomial degree.} +#' \item{h_hat}{Selected bandwidth.} +#' \item{scores}{Matrix of CV scores (rows = degrees, columns = bandwidths).} +#' \item{grids}{List with \code{$m} and \code{$h} grids used.} +#' } +#' @seealso [density_lp()] #' @examples #' set.seed(1) #' X <- matrix(runif(30 * 2), ncol = 2) -#' dom <- domain_Rd(2) +#' dom <- domain_Rd(2L) #' cv <- cv_density_lp(X, h_grid = c(0.2, 0.4), m_grid = 0:1, domain = dom, N_quad = 100L) #' print(cv) -#' +#' summary(cv) +#' @export +cv_density_lp <- function(x, h_grid, m_grid = 0:3, N_quad = 500L, ...) { + UseMethod("cv_density_lp") +} + +#' @export +cv_density_lp.matrix <- function( + x, + h_grid, + m_grid = 0:3, + N_quad = 500L, + domain, + ... +) { + pp <- pp_lp(x, domain) + cv_density_lp(pp, h_grid = h_grid, m_grid = m_grid, N_quad = N_quad, ...) +} + #' @export -cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { - check_X(X) - check_domain(domain, ncol(X)) +cv_density_lp.data.frame <- function( + x, + h_grid, + m_grid = 0:3, + N_quad = 500L, + domain, + ... +) { + pp <- pp_lp(as.matrix(x), domain) + cv_density_lp(pp, h_grid = h_grid, m_grid = m_grid, N_quad = N_quad, ...) +} + +#' @export +cv_density_lp.ppp <- function(x, h_grid, m_grid = 0:3, N_quad = 500L, ...) { + pp <- as_pp_lp(x) + cv_density_lp(pp, h_grid = h_grid, m_grid = m_grid, N_quad = N_quad, ...) +} + +#' @export +cv_density_lp.pp_lp <- function(x, h_grid, m_grid = 0:3, N_quad = 500L, ...) { check_h_grid(h_grid) check_m_grid(m_grid) check_N_quad(N_quad) m_grid <- as.integer(m_grid) - n <- nrow(X) - d <- ncol(X) + n <- x$n + d <- x$d scores <- matrix( NA_real_, @@ -64,9 +105,8 @@ cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { ) n_fail <- matrix(0L, length(m_grid), length(h_grid)) - sampler <- domain$sampler_factory() - # We transpose X once for C++ (d x n) - Xt <- t(X) + sampler <- x$domain$sampler_factory() + Xt <- t(x$X) for (ih in seq_along(h_grid)) { h <- h_grid[ih] @@ -75,7 +115,7 @@ cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { s_list <- vector("list", n) n_total_vec <- integer(n) for (i in seq_len(n)) { - t_i <- X[i, , drop = TRUE] + t_i <- x$X[i, , drop = TRUE] s <- tryCatch(sampler(N_quad, t_i, h), error = function(e) NULL) if (is.null(s)) { s_list[[i]] <- matrix(0, d, 0) @@ -90,10 +130,8 @@ cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { m <- m_grid[im] alphas <- build_alphas(m, d) - # Call the optimized C++ backend for the full observation loop log_loo <- cv_lp_fixed_h_m_cpp(Xt, s_list, n_total_vec, h, alphas) - # Track failures (infinite scores) n_fail[im, ih] <- sum(!is.finite(log_loo)) scores[im, ih] <- -mean(log_loo) } @@ -141,32 +179,26 @@ cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { #' LOO cross-validation for a spatial point pattern #' -#' Convenience wrapper around [cv_density_lp()] for `ppp` objects. The domain -#' is derived automatically from `Window(pp)`. +#' This function is now an alias for [cv_density_lp()] when called on a \code{ppp} +#' object. #' #' @param pp A `ppp` object (spatstat.geom). #' @param h_grid Numeric vector of bandwidth values (all > 0). #' @param m_grid Integer vector of polynomial degrees (default `0:3`). #' @param N_quad Number of quadrature points per evaluation (default 500). -#' @return An S3 object of class `"cv_density_lp"` (see [cv_density_lp()]). -#' @seealso [cv_density_lp()], [density_lp_ppp()] +#' @param ... Additional arguments passed to [cv_density_lp()]. +#' @return An S3 object of class \code{"cv_density_lp"} (see [cv_density_lp()]). #' @examples +#' \donttest{ #' set.seed(1) -#' pp <- spatstat.geom::ppp(runif(30), runif(30), window = spatstat.geom::owin()) +#' pp <- spatstat.geom::ppp(runif(50), runif(50), window = spatstat.geom::owin()) #' cv <- cv_density_lp_ppp(pp, h_grid = c(0.2, 0.4), m_grid = 0:1, N_quad = 100L) #' print(cv) -#' -#' @importFrom spatstat.geom Window +#' } #' @export -cv_density_lp_ppp <- function(pp, h_grid, m_grid = 0:3, N_quad = 500L) { - stopifnot(inherits(pp, "ppp")) - X <- cbind(pp$x, pp$y) - dom <- domain_from_owin(spatstat.geom::Window(pp)) - cv_density_lp( - X, - h_grid = h_grid, - m_grid = m_grid, - domain = dom, - N_quad = N_quad - ) +cv_density_lp_ppp <- function(pp, h_grid, m_grid = 0:3, N_quad = 500L, ...) { + if (!inherits(pp, "ppp")) { + stop("cv_density_lp_ppp requires a 'ppp' object from spatstat.geom") + } + cv_density_lp(pp, h_grid = h_grid, m_grid = m_grid, N_quad = N_quad, ...) } diff --git a/R/density_lp.R b/R/density_lp.R index 3f864e5..bd5b731 100644 --- a/R/density_lp.R +++ b/R/density_lp.R @@ -38,40 +38,93 @@ new_density_lp <- function( ) } -#' Local polynomial density estimation on a grid of target points +#' Local polynomial density estimation #' -#' @param X Numeric matrix `n x d` of observations. Must be a matrix; no -#' implicit conversion from data frames or tibbles is performed. -#' @param t_grid Numeric matrix `p x d` of target points. +#' @param x Observations. Can be a numeric \code{matrix}, a \code{spatstat.geom::ppp} +#' object, or a \code{pp_lp} object. #' @param h Bandwidth (scalar > 0). -#' @param m Polynomial degree (integer >= 0). -#' @param domain An `"domain_lp"` object describing the support of the density -#' (see [domain_Rd()], [domain_from_indicator()], [domain_sector()]). -#' @param N_quad Number of Monte Carlo quadrature points per target point -#' (default: 500). +#' @param m Polynomial degree (integer >= 0, default 0). +#' @param t_grid Numeric matrix \code{p x d} of target points. If \code{NULL}, +#' it is automatically generated from the bounding box of \code{x}. +#' @param N_quad Number of quadrature (Monte Carlo) points used to approximate +#' the normalising integral (default 500). +#' @param ... Additional arguments passed to methods or for grid generation +#' (\code{nx}, \code{ny} for 2D). #' -#' @return An S3 object of class `"density_lp"`. +#' @return An S3 object of class \code{"density_lp"}. In 2D, it also inherits +#' from \code{spatstat.geom::im}. #' #' @examples +#' # 2D estimation on the unit square #' set.seed(1) #' X <- matrix(runif(50 * 2), ncol = 2) -#' t_grid <- as.matrix(expand.grid( -#' x = seq(0.1, 0.9, length.out = 5), -#' y = seq(0.1, 0.9, length.out = 5) -#' )) -#' dom <- domain_Rd(2) -#' fit <- density_lp(X, t_grid = t_grid, h = 0.3, m = 1L, domain = dom, N_quad = 100L) +#' dom <- domain_Rd(2L) +#' fit <- density_lp(X, h = 0.3, m = 1L, domain = dom, nx = 10L, ny = 10L, N_quad = 100L) #' print(fit) +#' summary(fit) #' +#' # 1D estimation with plot +#' set.seed(2) +#' X1 <- matrix(runif(50), ncol = 1) +#' t1 <- matrix(seq(0.1, 0.9, length.out = 20), ncol = 1) +#' fit1 <- density_lp(X1, h = 0.3, domain = domain_Rd(1L), t_grid = t1, N_quad = 100L) +#' plot(fit1) +#' +#' @export +density_lp <- function(x, h, m = 0L, t_grid = NULL, N_quad = 500L, ...) { + UseMethod("density_lp") +} + +#' @export +density_lp.matrix <- function( + x, + h, + m = 0L, + t_grid = NULL, + N_quad = 500L, + domain, + ... +) { + pp <- pp_lp(x, domain) + obj <- density_lp(pp, h = h, m = m, t_grid = t_grid, N_quad = N_quad, ...) + + # If t_grid was provided manually but is a regular grid, we could try to promote to im. + # For now, let's ensure that if it's already a density_lp from pp_lp, we don't break it. + obj +} + +#' @export +density_lp.data.frame <- function( + x, + h, + m = 0L, + t_grid = NULL, + N_quad = 500L, + domain, + ... +) { + pp <- pp_lp(as.matrix(x), domain) + density_lp(pp, h = h, m = m, t_grid = t_grid, N_quad = N_quad, ...) +} + +#' @importFrom spatstat.geom im #' @export -density_lp <- function(X, t_grid, h, m = 0L, domain, N_quad = 500L) { - check_X(X) - check_t_grid(t_grid, ncol(X)) - check_domain(domain, ncol(X)) +density_lp.ppp <- function(x, h, m = 0L, t_grid = NULL, N_quad = 500L, ...) { + pp <- as_pp_lp(x) + density_lp(pp, h = h, m = m, t_grid = t_grid, N_quad = N_quad, ...) +} + +#' @export +density_lp.pp_lp <- function(x, h, m = 0L, t_grid = NULL, N_quad = 500L, ...) { check_h(h) check_m(m) check_N_quad(N_quad) + if (is.null(t_grid)) { + t_grid <- .make_auto_grid(x, ...) + } + check_t_grid(t_grid, x$d) + p <- nrow(t_grid) estimate <- numeric(p) variance <- numeric(p) @@ -80,11 +133,11 @@ density_lp <- function(X, t_grid, h, m = 0L, domain, N_quad = 500L) { for (i in seq_len(p)) { res <- tryCatch( density_lp_point( - X = X, + X = x$X, t = t_grid[i, ], h = h, m = m, - domain = domain, + domain = x$domain, N_quad = N_quad ), error = function(e) NULL @@ -111,16 +164,58 @@ density_lp <- function(X, t_grid, h, m = 0L, domain, N_quad = 500L) { ) } - new_density_lp( + obj <- new_density_lp( estimate = estimate, variance = variance, t_grid = t_grid, - X = X, + X = x$X, h = h, m = as.integer(m), - domain = domain, + domain = x$domain, N_quad = as.integer(N_quad), n_fail = n_fail, call = match.call() ) + + # Harmonization for 2D (spatstat compatibility) + if (x$d == 2L && !is.null(attr(t_grid, "grid_info"))) { + info <- attr(t_grid, "grid_info") + values <- rep(NA_real_, info$nx * info$ny) + values[info$inside] <- obj$estimate + im_obj <- spatstat.geom::im( + t(matrix(values, nrow = info$nx, ncol = info$ny)), + xcol = info$xcol, + yrow = info$yrow + ) + obj <- structure( + c(unclass(obj), unclass(im_obj)), + class = c("density_lp", "im") + ) + } + + obj +} + +.make_auto_grid <- function(x, nx = 128L, ny = 128L, ...) { + if (x$d == 2L) { + xcol <- seq(x$bbox[1, 1], x$bbox[2, 1], length.out = nx) + yrow <- seq(x$bbox[1, 2], x$bbox[2, 2], length.out = ny) + grid <- as.matrix(expand.grid(x = xcol, y = yrow)) + inside <- x$domain$is_in_domain(grid[, 1], grid[, 2]) + t_grid <- grid[inside, , drop = FALSE] + attr(t_grid, "grid_info") <- list( + nx = nx, + ny = ny, + xcol = xcol, + yrow = yrow, + inside = inside + ) + return(t_grid) + } else { + # For d > 2, we could implement a default, but it's risky. + # For now, require t_grid if not 2D, or use a coarse grid. + stop( + "Automatic grid generation is currently only supported for d = 2. Please provide t_grid." + ) + } } diff --git a/R/density_lp_ppp.R b/R/density_lp_ppp.R index 8c3f914..a443a44 100644 --- a/R/density_lp_ppp.R +++ b/R/density_lp_ppp.R @@ -18,10 +18,8 @@ new_density_lp_ppp <- function(im_obj, params, stats, call) { #' Local polynomial density estimation for a spatial point pattern #' -#' Convenience wrapper around [density_lp()] for `ppp` objects (spatstat). -#' The evaluation grid and the domain are derived automatically from -#' `Window(pp)`. The result is a `spatstat.geom::im` pixel image, fully -#' compatible with the spatstat plotting and analysis ecosystem. +#' This function is now an alias for [density_lp()] when called on a `ppp` +#' object. #' #' @param pp A `ppp` object (spatstat.geom). #' @param h Bandwidth (scalar > 0). @@ -29,76 +27,29 @@ new_density_lp_ppp <- function(im_obj, params, stats, call) { #' @param N_quad Number of quadrature points per target point (default 500). #' @param nx Number of pixel columns (default 128). #' @param ny Number of pixel rows (default 128). -#' @return An S3 object of class `"density_lp_ppp"`, which also inherits from -#' `spatstat.geom::im`. Pixels outside `Window(pp)` are `NA`. -#' @seealso [density_lp()], [domain_from_owin()] +#' @param ... Additional arguments passed to [density_lp()]. +#' @return An S3 object of class \code{"density_lp"}, which also inherits from +#' \code{spatstat.geom::im}. Pixels outside \code{Window(pp)} are \code{NA}. +#' @seealso [density_lp()] #' @examples +#' \donttest{ #' set.seed(1) #' pp <- spatstat.geom::ppp(runif(50), runif(50), window = spatstat.geom::owin()) #' fit <- density_lp_ppp(pp, h = 0.3, m = 1L, N_quad = 100L, nx = 20L, ny = 20L) #' print(fit) -#' -#' @importFrom spatstat.geom Window inside.owin im unitname +#' } #' @export -density_lp_ppp <- function(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L) { - stopifnot(inherits(pp, "ppp")) - check_h(h) - check_m(m) - check_N_quad(N_quad) - stopifnot(is.numeric(nx), nx >= 2L) - stopifnot(is.numeric(ny), ny >= 2L) - - win <- spatstat.geom::Window(pp) - dom <- domain_from_owin(win) - - # Regular grid over the bounding box - grid_x <- seq(win$xrange[1L], win$xrange[2L], length.out = nx) - grid_y <- seq(win$yrange[1L], win$yrange[2L], length.out = ny) - t_all <- as.matrix(expand.grid(x = grid_x, y = grid_y)) - - # Keep only grid points inside the window - inside <- spatstat.geom::inside.owin(t_all[, 1L], t_all[, 2L], w = win) - t_grid <- t_all[inside, , drop = FALSE] - - if (nrow(t_grid) == 0L) { - stop("No grid points fall inside Window(pp). Try increasing nx or ny.") +density_lp_ppp <- function( + pp, + h, + m = 0L, + N_quad = 500L, + nx = 128L, + ny = 128L, + ... +) { + if (!inherits(pp, "ppp")) { + stop("density_lp_ppp requires a 'ppp' object from spatstat.geom") } - - mc <- match.call() - - X <- cbind(pp$x, pp$y) - fit <- density_lp( - X, - t_grid = t_grid, - h = h, - m = m, - domain = dom, - N_quad = N_quad - ) - - # Fill full nx*ny grid (NA outside window), then reshape for im - # expand.grid fills x fastest: point (grid_x[j], grid_y[i]) has index (i-1)*nx+j - # im(mat, xcol, yrow) expects mat[i,j] = value at (xcol[j], yrow[i]) - # => mat_im = t(matrix(values, nrow = nx, ncol = ny)) - values <- rep(NA_real_, nx * ny) - values[inside] <- fit$estimate - - im_obj <- spatstat.geom::im( - t(matrix(values, nrow = nx, ncol = ny)), - xcol = grid_x, - yrow = grid_y, - unitname = spatstat.geom::unitname(pp) - ) - - new_density_lp_ppp( - im_obj = im_obj, - params = list( - h = h, - m = as.integer(m), - N_quad = as.integer(N_quad), - domain = dom - ), - stats = fit$stats, - call = mc - ) + density_lp(pp, h = h, m = m, N_quad = N_quad, nx = nx, ny = ny, ...) } diff --git a/R/domain.R b/R/domain.R index 61a8a5f..08da2a8 100644 --- a/R/domain.R +++ b/R/domain.R @@ -1,9 +1,23 @@ # Domain objects "domain_lp" ---------------------------------------------------- #' @keywords internal -new_domain_lp <- function(d, sampler_factory, label, call) { +new_domain_lp <- function( + d, + sampler_factory, + is_in_domain, + label, + call, + bbox = NULL +) { structure( - list(d = d, sampler_factory = sampler_factory, label = label, call = call), + list( + d = d, + sampler_factory = sampler_factory, + is_in_domain = is_in_domain, + label = label, + call = call, + bbox = bbox + ), class = "domain_lp" ) } @@ -32,10 +46,11 @@ domain_Rd <- function(d) { stopifnot(is.numeric(d), length(d) == 1L, is.finite(d), d >= 1, d == floor(d)) d <- as.integer(d) - is_in <- function(...) rep(TRUE, length(..1)) + is_in_domain <- function(...) rep(TRUE, length(..1)) new_domain_lp( d, - function() sampler_rejection(is_in), + sampler_factory = function() sampler_rejection(is_in_domain), + is_in_domain = is_in_domain, label = "R^d", call = match.call() ) @@ -48,8 +63,8 @@ domain_Rd <- function(d) { #' `d` is inferred from `length(formals(is_in_domain))`. #' @return An `"domain_lp"` object. #' @examples -#' is_in <- function(x, y) x^2 + y^2 <= 1 -#' dom <- domain_from_indicator(is_in) +#' is_in_domain <- function(x, y) x^2 + y^2 <= 1 +#' dom <- domain_from_indicator(is_in_domain) #' print(dom) #' @export domain_from_indicator <- function(is_in_domain) { @@ -58,7 +73,8 @@ domain_from_indicator <- function(is_in_domain) { stopifnot(d >= 1L) new_domain_lp( d, - function() sampler_rejection(is_in_domain), + sampler_factory = function() sampler_rejection(is_in_domain), + is_in_domain = is_in_domain, label = "analytic domain", call = match.call() ) @@ -80,10 +96,13 @@ domain_from_indicator <- function(is_in_domain) { #' @export domain_from_owin <- function(win) { stopifnot(inherits(win, "owin")) + bbox <- matrix(c(win$xrange, win$yrange), nrow = 2L, byrow = FALSE) new_domain_lp( 2L, - function() sampler_owin(win), + sampler_factory = function() sampler_owin(win), + is_in_domain = function(x, y) spatstat.geom::inside.owin(x, y, win), label = paste0("spatstat owin (", win$type, ")"), - call = match.call() + call = match.call(), + bbox = bbox ) } diff --git a/R/domain_sector.R b/R/domain_sector.R index 9af3a58..f60e286 100644 --- a/R/domain_sector.R +++ b/R/domain_sector.R @@ -10,11 +10,14 @@ #' @export domain_sector <- function(k) { stopifnot(is.numeric(k), length(k) == 1L, is.finite(k), k > 0) + bbox <- matrix(c(0, 1, 0, 1), nrow = 2L, byrow = FALSE) new_domain_lp( 2L, - function() sampler_sector(k), + sampler_factory = function() sampler_sector(k), + is_in_domain = function(x, y) (x >= 0) & (x <= 1) & (y >= 0) & (y <= x^k), label = paste0("polynomial sector D_", k), - call = match.call() + call = match.call(), + bbox = bbox ) } @@ -61,10 +64,11 @@ sampler_sector <- function(k) { # Rejection sampling (efficient: domain is monotone in x) y_lo <- max(0, ty - h) y_hi <- ty + h - accepted <- matrix(NA_real_, 2L, 0L) + chunks <- list() + n_accepted <- 0L max_iter <- 1000L iter <- 0L - while (ncol(accepted) < N_quad) { + while (n_accepted < N_quad) { iter <- iter + 1L if (iter > max_iter) { stop(sprintf( @@ -80,12 +84,16 @@ sampler_sector <- function(k) { h )) } - need <- ceiling(2 * (N_quad - ncol(accepted))) + need <- ceiling(2 * (N_quad - n_accepted)) x <- runif(need, x_lo, x_hi) y <- runif(need, y_lo, y_hi) ok <- (y >= 0) & (y <= x^k) - accepted <- cbind(accepted, rbind(x[ok] - tx, y[ok] - ty)) + if (any(ok)) { + chunks[[length(chunks) + 1L]] <- rbind(x[ok] - tx, y[ok] - ty) + n_accepted <- n_accepted + sum(ok) + } } + accepted <- do.call(cbind, chunks) list( points = accepted[, seq_len(N_quad), drop = FALSE], n_total = round(N_quad * (2 * h)^2 / vol) diff --git a/R/methods.R b/R/methods.R index 0973a55..97d705e 100644 --- a/R/methods.R +++ b/R/methods.R @@ -1,53 +1,26 @@ -# S3 methods for "density_lp_ppp" ----------------------------------------------- - -#' Print a density_lp_ppp object -#' @param x A `"density_lp_ppp"` object. -#' @param ... Ignored. -#' @return `x` invisibly. -#' @export -print.density_lp_ppp <- function(x, ...) { - cat("Local polynomial density estimate (spatstat)\n") - cat(sprintf(" Points : %d\n", x$stats$n_obs)) - cat(sprintf(" h : %g\n", x$params$h)) - cat(sprintf(" m : %d\n", x$params$m)) - cat(sprintf(" N_quad : %d\n", x$params$N_quad)) - cat(sprintf(" Grid : %d x %d pixels\n", length(x$xcol), length(x$yrow))) - rng <- range(x$v, na.rm = TRUE) - cat(sprintf(" Range : [%.5g, %.5g]\n", rng[1L], rng[2L])) - if (!is.null(x$stats$n_fail) && x$stats$n_fail > 0L) { - cat(sprintf( - " Note : %d failure(s) during calculation\n", - x$stats$n_fail - )) - } - invisible(x) -} - -#' Plot a density_lp_ppp object -#' @param x A `"density_lp_ppp"` object. -#' @param ... Passed to [spatstat.geom::plot.im()]. -#' @return `x` invisibly. -#' @export -plot.density_lp_ppp <- function(x, ...) { - NextMethod() - invisible(x) -} - # S3 methods for "density_lp" --------------------------------------------------- -#' Print a density_lp object -#' @param x A `"density_lp"` object. -#' @param ... Ignored. -#' @return `x` invisibly. +#' @rdname density_lp #' @export print.density_lp <- function(x, ...) { - cat("Local polynomial density estimate\n") - cat(sprintf(" Points : %d\n", x$stats$p)) - cat(sprintf(" h : %g\n", x$params$h)) - cat(sprintf(" m : %d\n", x$params$m)) - rng <- range(x$estimate, na.rm = TRUE) - cat(sprintf(" Range : [%.5g, %.5g]\n", rng[1L], rng[2L])) - if (x$stats$n_fail > 0L) { + if (inherits(x, "im")) { + cat("Local polynomial density estimate (2D, spatstat-compatible)\n") + cat(sprintf(" Points : %d\n", x$stats$n_obs)) + cat(sprintf(" h : %g\n", x$params$h)) + cat(sprintf(" m : %d\n", x$params$m)) + cat(sprintf(" Grid : %d x %d pixels\n", length(x$xcol), length(x$yrow))) + rng <- range(x$v, na.rm = TRUE) + cat(sprintf(" Range : [%.5g, %.5g]\n", rng[1L], rng[2L])) + } else { + cat("Local polynomial density estimate\n") + cat(sprintf(" d : %d\n", x$stats$d)) + cat(sprintf(" Points : %d\n", x$stats$p)) + cat(sprintf(" h : %g\n", x$params$h)) + cat(sprintf(" m : %d\n", x$params$m)) + rng <- range(x$estimate, na.rm = TRUE) + cat(sprintf(" Range : [%.5g, %.5g]\n", rng[1L], rng[2L])) + } + if (!is.null(x$stats$n_fail) && x$stats$n_fail > 0L) { cat(sprintf( " Note : %d failure(s) during calculation\n", x$stats$n_fail @@ -56,10 +29,8 @@ print.density_lp <- function(x, ...) { invisible(x) } -#' Summary of a density_lp object -#' @param object A `"density_lp"` object. -#' @param ... Ignored. -#' @return `object` invisibly. +#' @rdname density_lp +#' @param object A \code{"density_lp"} object (for \code{summary}). #' @export summary.density_lp <- function(object, ...) { cat("Local Polynomial Density Estimation Summary\n") @@ -74,108 +45,80 @@ summary.density_lp <- function(object, ...) { object$stats$d )) cat(sprintf("Observations : n = %d\n", object$stats$n_obs)) - cat(sprintf( - "Grid points : p = %d (%d success, %d failure)\n", - object$stats$p, - object$stats$p - object$stats$n_fail, - object$stats$n_fail - )) + if (inherits(object, "im")) { + cat(sprintf( + "Grid : %d x %d pixels (%d evaluated, %d failure)\n", + length(object$xcol), + length(object$yrow), + object$stats$p - object$stats$n_fail, + object$stats$n_fail + )) + } else { + cat(sprintf( + "Grid points : p = %d (%d success, %d failure)\n", + object$stats$p, + object$stats$p - object$stats$n_fail, + object$stats$n_fail + )) + } cat("\nParameters:\n") cat(sprintf(" Bandwidth (h) : %g\n", object$params$h)) cat(sprintf(" Degree (m) : %d\n", object$params$m)) cat(sprintf(" Quadrature : %d MC points\n", object$params$N_quad)) cat("\nResults (estimate):\n") - print(summary(object$estimate)) + if (inherits(object, "im")) { + print(summary(as.vector(object$v), na.rm = TRUE)) + } else { + print(summary(object$estimate, na.rm = TRUE)) + } invisible(object) } -#' Plot a density_lp object -#' @param x A `"density_lp"` object. -#' @param main Plot title (default: bandwidth and degree). -#' @param ... Passed to the underlying plot function. -#' @return `x` invisibly. -#' @importFrom grDevices grey -#' @importFrom graphics image +#' @rdname density_lp #' @export -plot.density_lp <- function( - x, - main = paste0("densityLP (h = ", x$params$h, ", m = ", x$params$m, ")"), - ... -) { - d <- x$stats$d - if (d == 1L) { - plot( - x$t_grid[, 1L], - x$estimate, - type = "l", - xlab = "t", - ylab = "Estimated density", - main = main, - ... - ) - } else if (d == 2L) { - xs <- sort(unique(x$t_grid[, 1L])) - ys <- sort(unique(x$t_grid[, 2L])) - if (length(xs) * length(ys) == nrow(x$t_grid)) { - Z <- matrix(x$estimate, nrow = length(xs), ncol = length(ys)) - image(xs, ys, Z, xlab = "x", ylab = "y", main = main, ...) - } else { - warning("plot.density_lp: irregular grid, falling back to scatter plot.") +plot.density_lp <- function(x, ...) { + if (inherits(x, "im")) { + # Dispatch to spatstat.geom::plot.im + NextMethod() + } else { + d <- x$stats$d + if (d == 1L) { plot( x$t_grid[, 1L], - x$t_grid[, 2L], - col = grey(1 - x$estimate / max(x$estimate, na.rm = TRUE)), - pch = 15, - cex = 0.5, - xlab = "x", - ylab = "y", - main = main, + x$estimate, + type = "l", + xlab = "t", + ylab = "Estimated density", ... ) + } else { + warning( + "plot.density_lp: no default graphical method for d = ", + d, + ". Using scatter plot." + ) + plot(x$t_grid, col = "blue", pch = 16, ...) } - } else { - warning("plot.density_lp: no graphical method for d = ", d, ".") } invisible(x) } -#' Summary of a density_lp_ppp object -#' @param object A `"density_lp_ppp"` object. -#' @param ... Ignored. -#' @return `object` invisibly. +# Alias methods for backward compatibility -------------------------------------- + #' @export -summary.density_lp_ppp <- function(object, ...) { - cat("Local Polynomial Density Estimation Summary (spatstat)\n") - cat("-------------------------------------------------------\n") - cat(sprintf( - "Call : %s\n", - paste(deparse(object$call), collapse = "\n") - )) - cat(sprintf("Domain : %s\n", object$params$domain$label)) - cat(sprintf("Observations : n = %d\n", object$stats$n_obs)) - cat(sprintf( - "Grid : %d x %d pixels\n", - length(object$xcol), - length(object$yrow) - )) - cat("\nParameters:\n") - cat(sprintf(" Bandwidth (h) : %g\n", object$params$h)) - cat(sprintf(" Degree (m) : %d\n", object$params$m)) - cat(sprintf(" Quadrature : %d MC points\n", object$params$N_quad)) - if (!is.null(object$stats$n_fail) && object$stats$n_fail > 0L) { - cat(sprintf(" Note : %d failure(s)\n", object$stats$n_fail)) - } - cat("\nResults (estimate):\n") - print(summary(as.vector(object$v), na.rm = TRUE)) - invisible(object) -} +print.density_lp_ppp <- function(x, ...) print.density_lp(x, ...) + +#' @export +summary.density_lp_ppp <- function(object, ...) summary.density_lp(object, ...) + +#' @export +plot.density_lp_ppp <- function(x, ...) plot.density_lp(x, ...) + # S3 methods for "cv_density_lp" ------------------------------------------------ -#' Summary of a cv_density_lp object -#' @param object A `"cv_density_lp"` object. -#' @param ... Ignored. -#' @return `object` invisibly. +#' @rdname cv_density_lp +#' @param object A \code{"cv_density_lp"} object (for \code{summary}). #' @export summary.cv_density_lp <- function(object, ...) { row_idx <- which(object$grids$m == object$m_hat) @@ -199,10 +142,7 @@ summary.cv_density_lp <- function(object, ...) { invisible(object) } -#' Print a cv_density_lp object -#' @param x A \code{"cv_density_lp"} object. -#' @param ... Ignored. -#' @return \code{x} invisibly. +#' @rdname cv_density_lp #' @export print.cv_density_lp <- function(x, ...) { row_idx <- which(x$grids$m == x$m_hat) diff --git a/R/pp_lp.R b/R/pp_lp.R new file mode 100644 index 0000000..2a1f9d9 --- /dev/null +++ b/R/pp_lp.R @@ -0,0 +1,117 @@ +#' Unified Point Pattern for Local Polynomial Estimation +#' +#' Creates a unified object containing observations, a domain, and a bounding box. +#' This object serves as the standard input for estimation functions in the +#' \code{densityLP} package. +#' +#' @param X A matrix of observations (n x d). +#' @param domain A \code{domain_lp} object. +#' @param bbox A bounding box (matrix 2 x d, rows = min/max). If \code{NULL}, +#' it is inferred from the domain or the data. +#' @return An object of class \code{"pp_lp"} with fields \code{$X}, \code{$domain}, +#' \code{$bbox}, \code{$d}, and \code{$n}. +#' @examples +#' X <- matrix(runif(40), 20, 2) +#' dom <- domain_Rd(2L) +#' pp <- pp_lp(X, dom) +#' print(pp) +#' @export +pp_lp <- function(X, domain, bbox = NULL) { + check_X(X) + stopifnot(inherits(domain, "domain_lp")) + + d <- ncol(X) + if (domain$d != d) { + stop(sprintf( + "Dimension mismatch: X has %d columns but domain is for d = %d", + d, + domain$d + )) + } + + if (is.null(bbox)) { + bbox <- .get_bbox(X, domain) + } + + structure( + list( + X = X, + domain = domain, + bbox = bbox, + d = d, + n = nrow(X) + ), + class = "pp_lp" + ) +} + +#' @rdname pp_lp +#' @param x A \code{"pp_lp"} object. +#' @param ... Ignored. +#' @export +print.pp_lp <- function(x, ...) { + cat(sprintf("Unified Point Pattern (d = %d)\n", x$d)) + cat(sprintf(" Observations : n = %d\n", x$n)) + cat(sprintf(" Domain : %s\n", x$domain$label)) + cat(" Bounding Box :\n") + print(x$bbox) + invisible(x) +} + +#' Convert an object to a pp_lp object +#' +#' @param x An object to convert. Can be a \code{matrix}, a \code{pp_lp}, or a +#' \code{spatstat.geom::ppp}. +#' @param ... Additional arguments (e.g. \code{domain} for the matrix method). +#' @return An object of class \code{"pp_lp"}. +#' @examples +#' X <- matrix(runif(40), 20, 2) +#' dom <- domain_Rd(2L) +#' pp <- as_pp_lp(X, domain = dom) +#' print(pp) +#' @export +as_pp_lp <- function(x, ...) { + UseMethod("as_pp_lp") +} + +#' @rdname as_pp_lp +#' @export +as_pp_lp.pp_lp <- function(x, ...) { + x +} + +#' @rdname as_pp_lp +#' @param domain A \code{domain_lp} object (required for the matrix method). +#' @param bbox A bounding box matrix (optional). +#' @export +as_pp_lp.matrix <- function(x, domain, bbox = NULL, ...) { + pp_lp(x, domain, bbox) +} + +#' @rdname as_pp_lp +#' @importFrom spatstat.geom Window +#' @export +as_pp_lp.ppp <- function(x, ...) { + X <- matrix(c(x$x, x$y), ncol = 2L) + win <- spatstat.geom::Window(x) + domain <- domain_from_owin(win) + bbox <- matrix(c(win$xrange, win$yrange), nrow = 2L, byrow = FALSE) + pp_lp(X, domain, bbox) +} + +.get_bbox <- function(X, domain) { + if (!is.null(domain$bbox)) { + return(domain$bbox) + } + + ranges <- apply(X, 2, range) + extents <- ranges[2, ] - ranges[1, ] + margin <- 0.05 + bbox <- rbind( + ranges[1, ] - margin * extents, + ranges[2, ] + margin * extents + ) + colnames(bbox) <- colnames(X) + rownames(bbox) <- c("min", "max") + bbox +} diff --git a/man/as_pp_lp.Rd b/man/as_pp_lp.Rd new file mode 100644 index 0000000..e8c169f --- /dev/null +++ b/man/as_pp_lp.Rd @@ -0,0 +1,39 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pp_lp.R +\name{as_pp_lp} +\alias{as_pp_lp} +\alias{as_pp_lp.pp_lp} +\alias{as_pp_lp.matrix} +\alias{as_pp_lp.ppp} +\title{Convert an object to a pp_lp object} +\usage{ +as_pp_lp(x, ...) + +\method{as_pp_lp}{pp_lp}(x, ...) + +\method{as_pp_lp}{matrix}(x, domain, bbox = NULL, ...) + +\method{as_pp_lp}{ppp}(x, ...) +} +\arguments{ +\item{x}{An object to convert. Can be a \code{matrix}, a \code{pp_lp}, or a +\code{spatstat.geom::ppp}.} + +\item{...}{Additional arguments (e.g. \code{domain} for the matrix method).} + +\item{domain}{A \code{domain_lp} object (required for the matrix method).} + +\item{bbox}{A bounding box matrix (optional).} +} +\value{ +An object of class \code{"pp_lp"}. +} +\description{ +Convert an object to a pp_lp object +} +\examples{ +X <- matrix(runif(40), 20, 2) +dom <- domain_Rd(2L) +pp <- as_pp_lp(X, domain = dom) +print(pp) +} diff --git a/man/cv_density_lp.Rd b/man/cv_density_lp.Rd index 4e76e5c..7242e99 100644 --- a/man/cv_density_lp.Rd +++ b/man/cv_density_lp.Rd @@ -1,28 +1,39 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/cv.R +% Please edit documentation in R/cv.R, R/methods.R \name{cv_density_lp} \alias{cv_density_lp} +\alias{summary.cv_density_lp} +\alias{print.cv_density_lp} \title{LOO cross-validation for the local polynomial density estimator} \usage{ -cv_density_lp(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) +cv_density_lp(x, h_grid, m_grid = 0:3, N_quad = 500L, ...) + +\method{summary}{cv_density_lp}(object, ...) + +\method{print}{cv_density_lp}(x, ...) } \arguments{ -\item{X}{Numeric matrix \verb{n x d} of observations.} +\item{x}{Observations. Can be a numeric \code{matrix}, a \code{spatstat.geom::ppp} +object, or a \code{pp_lp} object.} \item{h_grid}{Numeric vector of bandwidth values (all > 0).} \item{m_grid}{Integer vector of polynomial degrees (default \code{0:3}).} -\item{domain}{An \code{"domain_lp"} object.} +\item{N_quad}{Number of quadrature (Monte Carlo) points used to approximate +the normalising integral (default 500).} -\item{N_quad}{Number of quadrature points per evaluation (default 500).} +\item{...}{Additional arguments passed to methods.} + +\item{object}{A \code{"cv_density_lp"} object (for \code{summary}).} } \value{ -An S3 object of class \code{"cv_density_lp"} containing: -\itemize{ -\item \verb{$m_hat}, \verb{$h_hat}: selected degree and bandwidth, -\item \verb{$scores}: matrix \verb{|m_grid| x |h_grid|} of CV scores, -\item \verb{$grids}: list containing \verb{$m} and \verb{$h} grids used. +An S3 object of class \code{"cv_density_lp"} with fields: +\describe{ +\item{m_hat}{Selected polynomial degree.} +\item{h_hat}{Selected bandwidth.} +\item{scores}{Matrix of CV scores (rows = degrees, columns = bandwidths).} +\item{grids}{List with \code{$m} and \code{$h} grids used.} } } \description{ @@ -39,11 +50,11 @@ scalar returned as a byproduct of the C++ pipeline. \examples{ set.seed(1) X <- matrix(runif(30 * 2), ncol = 2) -dom <- domain_Rd(2) +dom <- domain_Rd(2L) cv <- cv_density_lp(X, h_grid = c(0.2, 0.4), m_grid = 0:1, domain = dom, N_quad = 100L) print(cv) - +summary(cv) } \seealso{ -\code{\link[=density_lp]{density_lp()}}, \code{\link[=cv_density_lp_ppp]{cv_density_lp_ppp()}} +\code{\link[=density_lp]{density_lp()}} } diff --git a/man/cv_density_lp_ppp.Rd b/man/cv_density_lp_ppp.Rd index 14654e4..558117e 100644 --- a/man/cv_density_lp_ppp.Rd +++ b/man/cv_density_lp_ppp.Rd @@ -4,7 +4,7 @@ \alias{cv_density_lp_ppp} \title{LOO cross-validation for a spatial point pattern} \usage{ -cv_density_lp_ppp(pp, h_grid, m_grid = 0:3, N_quad = 500L) +cv_density_lp_ppp(pp, h_grid, m_grid = 0:3, N_quad = 500L, ...) } \arguments{ \item{pp}{A \code{ppp} object (spatstat.geom).} @@ -14,21 +14,21 @@ cv_density_lp_ppp(pp, h_grid, m_grid = 0:3, N_quad = 500L) \item{m_grid}{Integer vector of polynomial degrees (default \code{0:3}).} \item{N_quad}{Number of quadrature points per evaluation (default 500).} + +\item{...}{Additional arguments passed to \code{\link[=cv_density_lp]{cv_density_lp()}}.} } \value{ An S3 object of class \code{"cv_density_lp"} (see \code{\link[=cv_density_lp]{cv_density_lp()}}). } \description{ -Convenience wrapper around \code{\link[=cv_density_lp]{cv_density_lp()}} for \code{ppp} objects. The domain -is derived automatically from \code{Window(pp)}. +This function is now an alias for \code{\link[=cv_density_lp]{cv_density_lp()}} when called on a \code{ppp} +object. } \examples{ +\donttest{ set.seed(1) -pp <- spatstat.geom::ppp(runif(30), runif(30), window = spatstat.geom::owin()) +pp <- spatstat.geom::ppp(runif(50), runif(50), window = spatstat.geom::owin()) cv <- cv_density_lp_ppp(pp, h_grid = c(0.2, 0.4), m_grid = 0:1, N_quad = 100L) print(cv) - } -\seealso{ -\code{\link[=cv_density_lp]{cv_density_lp()}}, \code{\link[=density_lp_ppp]{density_lp_ppp()}} } diff --git a/man/density_lp.Rd b/man/density_lp.Rd index 1abc14d..85e9ed8 100644 --- a/man/density_lp.Rd +++ b/man/density_lp.Rd @@ -1,42 +1,60 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/density_lp.R +% Please edit documentation in R/density_lp.R, R/methods.R \name{density_lp} \alias{density_lp} -\title{Local polynomial density estimation on a grid of target points} +\alias{print.density_lp} +\alias{summary.density_lp} +\alias{plot.density_lp} +\title{Local polynomial density estimation} \usage{ -density_lp(X, t_grid, h, m = 0L, domain, N_quad = 500L) +density_lp(x, h, m = 0L, t_grid = NULL, N_quad = 500L, ...) + +\method{print}{density_lp}(x, ...) + +\method{summary}{density_lp}(object, ...) + +\method{plot}{density_lp}(x, ...) } \arguments{ -\item{X}{Numeric matrix \verb{n x d} of observations. Must be a matrix; no -implicit conversion from data frames or tibbles is performed.} - -\item{t_grid}{Numeric matrix \verb{p x d} of target points.} +\item{x}{Observations. Can be a numeric \code{matrix}, a \code{spatstat.geom::ppp} +object, or a \code{pp_lp} object.} \item{h}{Bandwidth (scalar > 0).} -\item{m}{Polynomial degree (integer >= 0).} +\item{m}{Polynomial degree (integer >= 0, default 0).} -\item{domain}{An \code{"domain_lp"} object describing the support of the density -(see \code{\link[=domain_Rd]{domain_Rd()}}, \code{\link[=domain_from_indicator]{domain_from_indicator()}}, \code{\link[=domain_sector]{domain_sector()}}).} +\item{t_grid}{Numeric matrix \code{p x d} of target points. If \code{NULL}, +it is automatically generated from the bounding box of \code{x}.} -\item{N_quad}{Number of Monte Carlo quadrature points per target point -(default: 500).} +\item{N_quad}{Number of quadrature (Monte Carlo) points used to approximate +the normalising integral (default 500).} + +\item{...}{Additional arguments passed to methods or for grid generation +(\code{nx}, \code{ny} for 2D).} + +\item{object}{A \code{"density_lp"} object (for \code{summary}).} } \value{ -An S3 object of class \code{"density_lp"}. +An S3 object of class \code{"density_lp"}. In 2D, it also inherits +from \code{spatstat.geom::im}. } \description{ -Local polynomial density estimation on a grid of target points +Local polynomial density estimation } \examples{ +# 2D estimation on the unit square set.seed(1) X <- matrix(runif(50 * 2), ncol = 2) -t_grid <- as.matrix(expand.grid( - x = seq(0.1, 0.9, length.out = 5), - y = seq(0.1, 0.9, length.out = 5) -)) -dom <- domain_Rd(2) -fit <- density_lp(X, t_grid = t_grid, h = 0.3, m = 1L, domain = dom, N_quad = 100L) +dom <- domain_Rd(2L) +fit <- density_lp(X, h = 0.3, m = 1L, domain = dom, nx = 10L, ny = 10L, N_quad = 100L) print(fit) +summary(fit) + +# 1D estimation with plot +set.seed(2) +X1 <- matrix(runif(50), ncol = 1) +t1 <- matrix(seq(0.1, 0.9, length.out = 20), ncol = 1) +fit1 <- density_lp(X1, h = 0.3, domain = domain_Rd(1L), t_grid = t1, N_quad = 100L) +plot(fit1) } diff --git a/man/density_lp_ppp.Rd b/man/density_lp_ppp.Rd index 904fcf3..79a46a8 100644 --- a/man/density_lp_ppp.Rd +++ b/man/density_lp_ppp.Rd @@ -4,7 +4,7 @@ \alias{density_lp_ppp} \title{Local polynomial density estimation for a spatial point pattern} \usage{ -density_lp_ppp(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L) +density_lp_ppp(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L, ...) } \arguments{ \item{pp}{A \code{ppp} object (spatstat.geom).} @@ -18,24 +18,25 @@ density_lp_ppp(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L) \item{nx}{Number of pixel columns (default 128).} \item{ny}{Number of pixel rows (default 128).} + +\item{...}{Additional arguments passed to \code{\link[=density_lp]{density_lp()}}.} } \value{ -An S3 object of class \code{"density_lp_ppp"}, which also inherits from +An S3 object of class \code{"density_lp"}, which also inherits from \code{spatstat.geom::im}. Pixels outside \code{Window(pp)} are \code{NA}. } \description{ -Convenience wrapper around \code{\link[=density_lp]{density_lp()}} for \code{ppp} objects (spatstat). -The evaluation grid and the domain are derived automatically from -\code{Window(pp)}. The result is a \code{spatstat.geom::im} pixel image, fully -compatible with the spatstat plotting and analysis ecosystem. +This function is now an alias for \code{\link[=density_lp]{density_lp()}} when called on a \code{ppp} +object. } \examples{ +\donttest{ set.seed(1) pp <- spatstat.geom::ppp(runif(50), runif(50), window = spatstat.geom::owin()) fit <- density_lp_ppp(pp, h = 0.3, m = 1L, N_quad = 100L, nx = 20L, ny = 20L) print(fit) - +} } \seealso{ -\code{\link[=density_lp]{density_lp()}}, \code{\link[=domain_from_owin]{domain_from_owin()}} +\code{\link[=density_lp]{density_lp()}} } diff --git a/man/domain_from_indicator.Rd b/man/domain_from_indicator.Rd index 70dd5fa..cd336f0 100644 --- a/man/domain_from_indicator.Rd +++ b/man/domain_from_indicator.Rd @@ -18,7 +18,7 @@ An \code{"domain_lp"} object. Domain defined by an indicator function } \examples{ -is_in <- function(x, y) x^2 + y^2 <= 1 -dom <- domain_from_indicator(is_in) +is_in_domain <- function(x, y) x^2 + y^2 <= 1 +dom <- domain_from_indicator(is_in_domain) print(dom) } diff --git a/man/plot.density_lp.Rd b/man/plot.density_lp.Rd deleted file mode 100644 index 76f8062..0000000 --- a/man/plot.density_lp.Rd +++ /dev/null @@ -1,25 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{plot.density_lp} -\alias{plot.density_lp} -\title{Plot a density_lp object} -\usage{ -\method{plot}{density_lp}( - x, - main = paste0("densityLP (h = ", x$params$h, ", m = ", x$params$m, ")"), - ... -) -} -\arguments{ -\item{x}{A \code{"density_lp"} object.} - -\item{main}{Plot title (default: bandwidth and degree).} - -\item{...}{Passed to the underlying plot function.} -} -\value{ -\code{x} invisibly. -} -\description{ -Plot a density_lp object -} diff --git a/man/plot.density_lp_ppp.Rd b/man/plot.density_lp_ppp.Rd deleted file mode 100644 index bcdbefa..0000000 --- a/man/plot.density_lp_ppp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{plot.density_lp_ppp} -\alias{plot.density_lp_ppp} -\title{Plot a density_lp_ppp object} -\usage{ -\method{plot}{density_lp_ppp}(x, ...) -} -\arguments{ -\item{x}{A \code{"density_lp_ppp"} object.} - -\item{...}{Passed to \code{\link[spatstat.geom:plot.im]{spatstat.geom::plot.im()}}.} -} -\value{ -\code{x} invisibly. -} -\description{ -Plot a density_lp_ppp object -} diff --git a/man/pp_lp.Rd b/man/pp_lp.Rd new file mode 100644 index 0000000..8819027 --- /dev/null +++ b/man/pp_lp.Rd @@ -0,0 +1,38 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pp_lp.R +\name{pp_lp} +\alias{pp_lp} +\alias{print.pp_lp} +\title{Unified Point Pattern for Local Polynomial Estimation} +\usage{ +pp_lp(X, domain, bbox = NULL) + +\method{print}{pp_lp}(x, ...) +} +\arguments{ +\item{X}{A matrix of observations (n x d).} + +\item{domain}{A \code{domain_lp} object.} + +\item{bbox}{A bounding box (matrix 2 x d, rows = min/max). If \code{NULL}, +it is inferred from the domain or the data.} + +\item{x}{A \code{"pp_lp"} object.} + +\item{...}{Ignored.} +} +\value{ +An object of class \code{"pp_lp"} with fields \code{$X}, \code{$domain}, +\code{$bbox}, \code{$d}, and \code{$n}. +} +\description{ +Creates a unified object containing observations, a domain, and a bounding box. +This object serves as the standard input for estimation functions in the +\code{densityLP} package. +} +\examples{ +X <- matrix(runif(40), 20, 2) +dom <- domain_Rd(2L) +pp <- pp_lp(X, dom) +print(pp) +} diff --git a/man/print.cv_density_lp.Rd b/man/print.cv_density_lp.Rd deleted file mode 100644 index 71f386a..0000000 --- a/man/print.cv_density_lp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{print.cv_density_lp} -\alias{print.cv_density_lp} -\title{Print a cv_density_lp object} -\usage{ -\method{print}{cv_density_lp}(x, ...) -} -\arguments{ -\item{x}{A \code{"cv_density_lp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{x} invisibly. -} -\description{ -Print a cv_density_lp object -} diff --git a/man/print.density_lp.Rd b/man/print.density_lp.Rd deleted file mode 100644 index 1b42359..0000000 --- a/man/print.density_lp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{print.density_lp} -\alias{print.density_lp} -\title{Print a density_lp object} -\usage{ -\method{print}{density_lp}(x, ...) -} -\arguments{ -\item{x}{A \code{"density_lp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{x} invisibly. -} -\description{ -Print a density_lp object -} diff --git a/man/print.density_lp_ppp.Rd b/man/print.density_lp_ppp.Rd deleted file mode 100644 index 7d6245b..0000000 --- a/man/print.density_lp_ppp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{print.density_lp_ppp} -\alias{print.density_lp_ppp} -\title{Print a density_lp_ppp object} -\usage{ -\method{print}{density_lp_ppp}(x, ...) -} -\arguments{ -\item{x}{A \code{"density_lp_ppp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{x} invisibly. -} -\description{ -Print a density_lp_ppp object -} diff --git a/man/summary.cv_density_lp.Rd b/man/summary.cv_density_lp.Rd deleted file mode 100644 index 9d2fc87..0000000 --- a/man/summary.cv_density_lp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{summary.cv_density_lp} -\alias{summary.cv_density_lp} -\title{Summary of a cv_density_lp object} -\usage{ -\method{summary}{cv_density_lp}(object, ...) -} -\arguments{ -\item{object}{A \code{"cv_density_lp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{object} invisibly. -} -\description{ -Summary of a cv_density_lp object -} diff --git a/man/summary.density_lp.Rd b/man/summary.density_lp.Rd deleted file mode 100644 index bfad416..0000000 --- a/man/summary.density_lp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{summary.density_lp} -\alias{summary.density_lp} -\title{Summary of a density_lp object} -\usage{ -\method{summary}{density_lp}(object, ...) -} -\arguments{ -\item{object}{A \code{"density_lp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{object} invisibly. -} -\description{ -Summary of a density_lp object -} diff --git a/man/summary.density_lp_ppp.Rd b/man/summary.density_lp_ppp.Rd deleted file mode 100644 index 0d91efd..0000000 --- a/man/summary.density_lp_ppp.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/methods.R -\name{summary.density_lp_ppp} -\alias{summary.density_lp_ppp} -\title{Summary of a density_lp_ppp object} -\usage{ -\method{summary}{density_lp_ppp}(object, ...) -} -\arguments{ -\item{object}{A \code{"density_lp_ppp"} object.} - -\item{...}{Ignored.} -} -\value{ -\code{object} invisibly. -} -\description{ -Summary of a density_lp_ppp object -} From 7df95f8f7da45c0445e9edda8bd281f1f04b3ca3 Mon Sep 17 00:00:00 2001 From: Nicolas Klutchnikoff Date: Thu, 30 Apr 2026 14:23:54 +0200 Subject: [PATCH 2/3] refactor: optimize .data.frame methods and consolidate internal calls --- R/alphas.R | 2 +- R/rfactory.R | 13 ++++--------- R/samplers.R | 2 +- R/utils.R | 21 ++++++++++----------- 4 files changed, 16 insertions(+), 22 deletions(-) diff --git a/R/alphas.R b/R/alphas.R index 43582c8..5d9f234 100644 --- a/R/alphas.R +++ b/R/alphas.R @@ -13,7 +13,7 @@ build_alphas <- function(m, d) { stopifnot(is.numeric(m), length(m) == 1L, m >= 0, m == floor(m)) stopifnot(is.numeric(d), length(d) == 1L, d >= 1, d == floor(d)) - grid <- do.call(expand.grid, rep(list(seq.int(0L, m)), d)) + grid <- do.call(expand.grid, rep(list(0:m), d)) valid <- rowSums(grid) <= m alphas <- matrix(as.integer(as.matrix(grid[valid, , drop = FALSE])), ncol = d) diff --git a/R/rfactory.R b/R/rfactory.R index 7095bc2..14716dc 100644 --- a/R/rfactory.R +++ b/R/rfactory.R @@ -52,11 +52,6 @@ rfactory <- function(f, is_in_domain = NULL, box, M = NULL, N_pilot = 2000L) { coord_names <- names(formals(f)) - .call_fn <- function(fn, mat) { - args <- lapply(seq_len(d), function(j) mat[, j]) - do.call(fn, args) - } - .sample_box <- function(n) { mat <- matrix(runif(n * d), n, d) sweep(sweep(mat, 2L, upper - lower, "*"), 2L, lower, "+") @@ -64,9 +59,9 @@ rfactory <- function(f, is_in_domain = NULL, box, M = NULL, N_pilot = 2000L) { if (is.null(M)) { pilots <- .sample_box(N_pilot) - fvals <- .call_fn(f, pilots) + fvals <- call_on_columns(f, pilots) if (!is.null(is_in_domain)) { - fvals <- fvals * .call_fn(is_in_domain, pilots) + fvals <- fvals * call_on_columns(is_in_domain, pilots) } if (max(fvals) <= 0) { stop("All pilot values are zero or negative. Check `box` and `f`.") @@ -98,13 +93,13 @@ rfactory <- function(f, is_in_domain = NULL, box, M = NULL, N_pilot = 2000L) { } cands <- .sample_box(batch) if (!is.null(is_in_domain)) { - cands <- cands[.call_fn(is_in_domain, cands), , drop = FALSE] + cands <- cands[call_on_columns(is_in_domain, cands), , drop = FALSE] } if (nrow(cands) == 0L) { next } - fvals <- .call_fn(f, cands) + fvals <- call_on_columns(f, cands) if (any(fvals > M)) { warning( "some fvals exceed M: M is underestimated, sample may be biased." diff --git a/R/samplers.R b/R/samplers.R index 96e3c87..ae831bc 100644 --- a/R/samplers.R +++ b/R/samplers.R @@ -26,7 +26,7 @@ sampler_rejection <- function(is_in_domain) { d <- length(t) U <- matrix(runif(N_quad * d, -h, h), N_quad, d) X <- U + t[col(U)] - ok <- do.call(is_in_domain, lapply(seq_len(d), function(j) X[, j])) + ok <- call_on_columns(is_in_domain, X) pts <- t(U[ok, , drop = FALSE]) if (ncol(pts) == 0L) { stop( diff --git a/R/utils.R b/R/utils.R index 9c41d54..8d061d6 100644 --- a/R/utils.R +++ b/R/utils.R @@ -2,11 +2,8 @@ #' @keywords internal check_X <- function(X) { - if (!is.matrix(X)) { - stop("`X` must be a numeric matrix (n x d). Use `as.matrix(X)` if needed.") - } - if (!is.numeric(X)) { - stop("`X` must be a numeric matrix.") + if (!is.numeric(as.matrix(X))) { + stop("`X` must be numeric.") } if (anyNA(X)) { stop("`X` contains missing values (NA).") @@ -18,12 +15,6 @@ check_X <- function(X) { #' @keywords internal check_t_grid <- function(t_grid, d) { - if (!is.matrix(t_grid)) { - stop("`t_grid` must be a numeric matrix (p x d).") - } - if (!is.numeric(t_grid)) { - stop("`t_grid` must be a numeric matrix.") - } if (ncol(t_grid) != d) { stop( "`t_grid` must have ", @@ -35,6 +26,9 @@ check_t_grid <- function(t_grid, d) { "." ) } + if (!is.numeric(as.matrix(t_grid))) { + stop("`t_grid` must be numeric.") + } if (anyNA(t_grid)) { stop("`t_grid` contains missing values (NA).") } @@ -112,3 +106,8 @@ check_domain <- function(domain, d) { ) } } + +#' @keywords internal +call_on_columns <- function(fn, mat) { + do.call(fn, lapply(seq_len(ncol(mat)), function(j) mat[, j])) +} From 36df4ca7504a84a64a5945c829ccb789dfe3efc1 Mon Sep 17 00:00:00 2001 From: Nicolas Klutchnikoff Date: Thu, 30 Apr 2026 14:23:58 +0200 Subject: [PATCH 3/3] test: update suite for unified API and internal refactorings --- tests/testthat/test-alphas.R | 2 +- tests/testthat/test-cv.R | 14 ++-- tests/testthat/test-density_lp.R | 37 +++++++--- tests/testthat/test-density_lp_ppp.R | 103 +++++++++++++++------------ tests/testthat/test-domain.R | 8 +-- tests/testthat/test-samplers.R | 69 ++++++++++-------- 6 files changed, 136 insertions(+), 97 deletions(-) diff --git a/tests/testthat/test-alphas.R b/tests/testthat/test-alphas.R index 8a15cc7..1b12919 100644 --- a/tests/testthat/test-alphas.R +++ b/tests/testthat/test-alphas.R @@ -30,7 +30,7 @@ test_that("build_alphas : ordre correct (degre croissant, puis lex)", { expect_equal( bloc, bloc[ - do.call(order, lapply(seq_len(ncol(bloc)), function(j) bloc[, j])), + call_on_columns(order, bloc), , drop = FALSE ] diff --git a/tests/testthat/test-cv.R b/tests/testthat/test-cv.R index 9b29110..f50048c 100644 --- a/tests/testthat/test-cv.R +++ b/tests/testthat/test-cv.R @@ -78,15 +78,11 @@ test_that("cv_density_lp: grids stored in output match inputs", { expect_equal(cv$grids$m, m_grid) }) -test_that("cv_density_lp: error if X is not a matrix", { - expect_error( - cv_density_lp( - as.data.frame(matrix(1, 10, 2)), - h_grid = 0.3, - domain = domain_Rd(2L) - ), - "matrix" - ) +test_that("cv_density_lp: allows data.frame and error if input is a list", { + X_df <- as.data.frame(matrix(runif(20), 10, 2)) + dom <- domain_Rd(2L) + expect_no_error(cv_density_lp(X_df, h_grid = 0.3, domain = dom)) + expect_error(cv_density_lp(as.list(X_df), h_grid = 0.3, domain = dom)) }) test_that("cv_density_lp: error if h_grid contains non-positive value", { diff --git a/tests/testthat/test-density_lp.R b/tests/testthat/test-density_lp.R index 79dec00..8066cc9 100644 --- a/tests/testthat/test-density_lp.R +++ b/tests/testthat/test-density_lp.R @@ -103,24 +103,42 @@ test_that("plot.density_lp: returns x invisibly for d=2", { domain = domain_Rd(2L), N_quad = 200L ) - expect_identical(withVisible(plot(res))$visible, FALSE) + # manual grid doesn't have grid_info, defaults to scatter with warning + expect_warning( + expect_identical(withVisible(plot(res))$visible, FALSE), + "Using scatter plot" + ) }) # ── Input validation ─────────────────────────────────────────────────────────── -test_that("density_lp: error if X is not a matrix", { +test_that("density_lp: allows data.frame and error if input is a list", { + X_df <- as.data.frame(matrix(runif(20), 10, 2)) + dom <- domain_Rd(2L) + expect_no_error( + density_lp(X_df, t_grid = matrix(0.5, 1, 2), h = 0.3, m = 1, domain = dom) + ) expect_error( density_lp( - as.data.frame(matrix(0, 10, 2)), - matrix(0.5, 1, 2), + as.list(X_df), + t_grid = matrix(0.5, 1, 2), h = 0.3, m = 1, - domain = domain_Rd(2L) - ), - "matrix" + domain = dom + ) ) }) +test_that("density_lp: automatic grid generation in 2D returns im object", { + set.seed(1L) + X <- matrix(runif(40), 20, 2) + dom <- domain_Rd(2L) + res <- density_lp(X, h = 0.3, m = 0L, domain = dom, nx = 10, ny = 10) + expect_s3_class(res, "im") + expect_s3_class(res, "density_lp") + expect_equal(dim(res$v), c(10, 10)) +}) + test_that("density_lp: error on dimension mismatch between X and t_grid", { X <- matrix(runif(20), 10, 2) t_grid <- matrix(0.5, 1, 3) # d=3 != 2 @@ -132,10 +150,9 @@ test_that("density_lp: error on dimension mismatch between X and t_grid", { test_that("density_lp: error on domain dimension mismatch", { X <- matrix(runif(20), 10, 2) - t_grid <- matrix(0.5, 1, 2) expect_error( - density_lp(X, t_grid, h = 0.3, m = 1, domain = domain_Rd(3L)), - "dimension" + density_lp(X, h = 0.3, m = 1, domain = domain_Rd(3L)), + "Dimension mismatch" ) }) diff --git a/tests/testthat/test-density_lp_ppp.R b/tests/testthat/test-density_lp_ppp.R index b770bca..ce67f9d 100644 --- a/tests/testthat/test-density_lp_ppp.R +++ b/tests/testthat/test-density_lp_ppp.R @@ -1,77 +1,90 @@ -# ── density_lp_ppp ──────────────────────────────────────────────────────────── +# ── density_lp.ppp ──────────────────────────────────────────────────────────── -test_that("density_lp_ppp: returns a density_lp_ppp object inheriting from im", { +test_that("density_lp.ppp: returns density_lp and im classes", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") set.seed(1L) - pp <- spatstat.random::runifpoint(100L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 100L, nx = 32L, ny = 32L) - expect_s3_class(fit, "density_lp_ppp") + r <- sqrt(runif(80L)) + theta <- runif(80L) * 2 * pi + pp <- spatstat.geom::ppp( + r * cos(theta), + r * sin(theta), + window = spatstat.geom::disc() + ) + fit <- density_lp(pp, h = 0.4, m = 1L, nx = 32L, ny = 32L) + expect_s3_class(fit, "density_lp") expect_s3_class(fit, "im") - expect_equal(fit$params$h, 0.5) - expect_equal(fit$params$m, 0L) }) -test_that("print.density_lp_ppp: returns x invisibly and produces output", { +test_that("density_lp.ppp: print method output matches 2D", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") - set.seed(7L) - pp <- spatstat.random::runifpoint(100L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 100L, nx = 32L, ny = 32L) - expect_output(print(fit), "spatstat") + set.seed(2L) + pp <- spatstat.geom::ppp( + runif(100L), + runif(100L), + window = spatstat.geom::owin() + ) + fit <- density_lp(pp, h = 0.5, nx = 32L, ny = 32L) + expect_output(print(fit), "spatstat-compatible") expect_identical(withVisible(print(fit))$visible, FALSE) }) -test_that("density_lp_ppp: pixel matrix dimensions match nx and ny", { +test_that("density_lp.ppp: respects nx and ny", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") - set.seed(2L) + set.seed(3L) + pp <- spatstat.geom::ppp( + runif(50L), + runif(50L), + window = spatstat.geom::owin() + ) nx <- 20L ny <- 25L - pp <- spatstat.random::runifpoint(100L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 100L, nx = nx, ny = ny) + fit <- density_lp(pp, h = 0.4, nx = nx, ny = ny) + expect_equal(length(fit$xcol), nx) + expect_equal(length(fit$yrow), ny) expect_equal(dim(fit$v), c(ny, nx)) }) -test_that("density_lp_ppp: pixels outside window are NA", { +test_that("density_lp.ppp: error on non-positive bandwidth", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") - set.seed(3L) - pp <- spatstat.random::runifpoint(100L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 100L, nx = 32L, ny = 32L) - # Disc bounding box [-1,1]^2: corner pixels are outside the disc - expect_true(is.na(fit$v[1L, 1L])) - expect_true(any(is.na(fit$v))) + pp <- spatstat.geom::ppp(0.5, 0.5, window = spatstat.geom::owin()) + expect_error(density_lp(pp, h = -0.1), "positive") }) -test_that("density_lp_ppp: non-NA estimates are non-negative (m = 0)", { +test_that("density_lp.ppp: m=0 behaves correctly", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") set.seed(4L) - pp <- spatstat.random::runifpoint(150L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 150L, nx = 32L, ny = 32L) - expect_true(all(fit$v[!is.na(fit$v)] >= 0)) + pp <- spatstat.geom::ppp( + runif(100L), + runif(100L), + window = spatstat.geom::owin() + ) + fit <- density_lp(pp, h = 0.3, m = 0L, nx = 20L, ny = 20L) + expect_true(all(fit$v >= 0, na.rm = TRUE)) }) -test_that("density_lp_ppp: integral is approximately 1 for uniform data", { +test_that("density_lp.ppp: NA outside the window", { skip_if_not_installed("spatstat.geom") - skip_if_not_installed("spatstat.random") - set.seed(5L) - pp <- spatstat.random::runifpoint(300L, win = spatstat.geom::disc()) - fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 200L, nx = 64L, ny = 64L) - int_val <- sum(fit$v, na.rm = TRUE) * fit$xstep * fit$ystep - expect_gt(int_val, 0.5) - expect_lt(int_val, 1.8) + # Circular window + win <- spatstat.geom::disc(radius = 0.5, centre = c(0.5, 0.5)) + pp <- spatstat.geom::ppp(0.5, 0.5, window = win) + fit <- density_lp(pp, h = 0.2, nx = 32L, ny = 32L) + # Corner (0,0) is outside the disc + expect_true(is.na(fit$v[1L, 1L])) }) -test_that("density_lp_ppp: error if input is not a ppp", { +test_that("density_lp_ppp alias: error if input is not a ppp", { expect_error(density_lp_ppp(matrix(1, 10, 2), h = 0.3), "ppp") }) -test_that("density_lp_ppp: error if h <= 0", { +test_that("density_lp.ppp: integration on unit square close to 1", { skip_if_not_installed("spatstat.geom") skip_if_not_installed("spatstat.random") - set.seed(6L) - pp <- spatstat.random::runifpoint(50L, win = spatstat.geom::disc()) - expect_error(density_lp_ppp(pp, h = -0.1)) + set.seed(101L) + pp <- spatstat.random::runifpoint(1000L, win = spatstat.geom::owin()) + fit <- density_lp(pp, h = 0.3, nx = 50L, ny = 50L) + # Area of pixel + area <- (fit$xcol[2L] - fit$xcol[1L]) * (fit$yrow[2L] - fit$yrow[1L]) + int_val <- sum(fit$v, na.rm = TRUE) * area + expect_gt(int_val, 0.5) + expect_lt(int_val, 1.5) }) diff --git a/tests/testthat/test-domain.R b/tests/testthat/test-domain.R index 3827fed..34d2e6e 100644 --- a/tests/testthat/test-domain.R +++ b/tests/testthat/test-domain.R @@ -93,8 +93,8 @@ test_that("check_domain: error on dimension mismatch", { # ── check_X / check_t_grid ───────────────────────────────────────────────────── -test_that("check_X: error if not a matrix", { - expect_error(check_X(as.data.frame(matrix(1, 3, 2))), "matrix") +test_that("check_X: allows numeric data.frame", { + expect_no_error(check_X(as.data.frame(matrix(1, 3, 2)))) }) test_that("check_X: error if not numeric", { @@ -111,8 +111,8 @@ test_that("check_X: error if zero rows", { expect_error(check_X(matrix(numeric(0), 0, 2)), "one observation") }) -test_that("check_t_grid: error if not a matrix", { - expect_error(check_t_grid(c(0.5, 0.5), d = 2L), "matrix") +test_that("check_t_grid: allows numeric data.frame", { + expect_no_error(check_t_grid(as.data.frame(matrix(0.5, 3, 2)), d = 2L)) }) test_that("check_t_grid: error on dimension mismatch", { diff --git a/tests/testthat/test-samplers.R b/tests/testthat/test-samplers.R index d4061f7..6d070ca 100644 --- a/tests/testthat/test-samplers.R +++ b/tests/testthat/test-samplers.R @@ -3,54 +3,61 @@ test_that("sampler_rejection: points have correct dimension", { set.seed(1L) is_in <- function(...) rep(TRUE, length(..1)) - s <- sampler_rejection(is_in)(100L, t = c(0.5, 0.5), h = 0.3) - expect_equal(nrow(s$points), 2L) - expect_true(ncol(s$points) > 0L) + s <- sampler_rejection(is_in) + res <- s(100L, t = c(0.5, 0.5), h = 0.3) + expect_equal(nrow(res$points), 2L) + expect_true(ncol(res$points) > 0L) }) test_that("sampler_rejection: n_total equals N_quad", { set.seed(2L) is_in <- function(...) rep(TRUE, length(..1)) - s <- sampler_rejection(is_in)(200L, t = c(0.5, 0.5), h = 0.3) - expect_equal(s$n_total, 200L) + s <- sampler_rejection(is_in) + res <- s(200L, t = c(0.5, 0.5), h = 0.3) + expect_equal(res$n_total, 200L) }) test_that("sampler_rejection: all points lie in [-h, h]^d", { set.seed(3L) h <- 0.4 is_in <- function(...) rep(TRUE, length(..1)) - s <- sampler_rejection(is_in)(300L, t = c(0.5, 0.5), h = h) - expect_true(all(abs(s$points) <= h + 1e-9)) + s <- sampler_rejection(is_in) + res <- s(300L, t = c(0.5, 0.5), h = h) + expect_true(all(abs(res$points) <= h + 1e-9)) }) test_that("sampler_rejection: points respect domain constraint", { set.seed(4L) is_in <- function(x, y) x^2 + y^2 <= 1 - s <- sampler_rejection(is_in)(300L, t = c(0, 0), h = 0.5) - pts_global <- sweep(t(s$points), 2L, c(0, 0), "+") + s <- sampler_rejection(is_in) + res <- s(300L, t = c(0, 0), h = 0.5) + pts_global <- sweep(t(res$points), 2L, c(0, 0), "+") expect_true(all(rowSums(pts_global^2) <= 1 + 1e-9)) }) test_that("sampler_rejection: error when V(h) is empty", { is_in <- function(...) rep(FALSE, length(..1)) - expect_error(sampler_rejection(is_in)(100L, t = c(0.5, 0.5), h = 0.3)) + s <- sampler_rejection(is_in) + expect_error(s(100L, t = c(0.5, 0.5), h = 0.3)) }) # ── sampler_sector ───────────────────────────────────────────────────────────── test_that("sampler_sector: returns exactly N_quad points of dimension 2", { set.seed(10L) - s <- sampler_sector(2)(300L, t = c(0.5, 0.1), h = 0.2) - expect_equal(nrow(s$points), 2L) - expect_equal(ncol(s$points), 300L) + s <- sampler_sector(2) + res <- s(300L, t = c(0.5, 0.1), h = 0.2) + expect_equal(nrow(res$points), 2L) + expect_equal(ncol(res$points), 300L) }) test_that("sampler_sector: points lie within D_k", { set.seed(11L) k <- 2 t_pt <- c(0.5, 0.1) - s <- sampler_sector(k)(300L, t = t_pt, h = 0.2) - pts <- sweep(t(s$points), 2L, t_pt, "+") + s <- sampler_sector(k) + res <- s(300L, t = t_pt, h = 0.2) + pts <- sweep(t(res$points), 2L, t_pt, "+") x <- pts[, 1L] y <- pts[, 2L] expect_true(all(x >= 0 - 1e-9 & x <= 1 + 1e-9)) @@ -60,12 +67,14 @@ test_that("sampler_sector: points lie within D_k", { test_that("sampler_sector: n_total > N_quad near apex (small volume)", { set.seed(12L) N <- 200L - s <- sampler_sector(2)(N, t = c(0.05, 0.01), h = 0.1) - expect_gt(s$n_total, N) + s <- sampler_sector(2) + res <- s(N, t = c(0.05, 0.01), h = 0.1) + expect_gt(res$n_total, N) }) test_that("sampler_sector: error when x range is empty", { - expect_error(sampler_sector(2)(100L, t = c(-0.5, 0), h = 0.3)) + s <- sampler_sector(2) + expect_error(s(100L, t = c(-0.5, 0), h = 0.3)) }) # ── sampler_owin ─────────────────────────────────────────────────────────── @@ -74,9 +83,10 @@ test_that("sampler_owin: returns N points of dimension 2", { skip_if_not_installed("spatstat.geom") set.seed(20L) win <- spatstat.geom::owin(c(0, 1), c(0, 1)) - s <- sampler_owin(win)(100L, t = c(0.5, 0.5), h = 0.3) - expect_equal(nrow(s$points), 2L) - expect_equal(ncol(s$points), 100L) + s <- sampler_owin(win) + res <- s(100L, t = c(0.5, 0.5), h = 0.3) + expect_equal(nrow(res$points), 2L) + expect_equal(ncol(res$points), 100L) }) test_that("sampler_owin: n_total equals N_quad for full box", { @@ -85,9 +95,10 @@ test_that("sampler_owin: n_total equals N_quad for full box", { win <- spatstat.geom::owin(c(0, 1), c(0, 1)) h <- 0.3 t_pt <- c(0.5, 0.5) - s <- sampler_owin(win)(200L, t = t_pt, h = h) + s <- sampler_owin(win) + res <- s(200L, t = t_pt, h = h) # Full box [0.2, 0.8]^2 is inside [0,1]^2 -> vol = (2h)^2 -> n_total = N - expect_equal(s$n_total, 200L) + expect_equal(res$n_total, 200L) }) test_that("sampler_owin: n_total > N_quad at boundary (clipped box)", { @@ -97,10 +108,11 @@ test_that("sampler_owin: n_total > N_quad at boundary (clipped box)", { h <- 0.3 t_pt <- c(0.1, 0.5) # box clips at x=0 N <- 200L - s <- sampler_owin(win)(N, t = t_pt, h = h) + s <- sampler_owin(win) + res <- s(N, t = t_pt, h = h) # x range: [0, 0.4], width = 0.4 < 2h = 0.6 -> vol < (2h)^2 # n_total = round(N * (2h)^2 / vol) > N - expect_gt(s$n_total, N) + expect_gt(res$n_total, N) }) test_that("sampler_owin: points lie within the owin", { @@ -109,9 +121,10 @@ test_that("sampler_owin: points lie within the owin", { win <- spatstat.geom::owin(c(0, 1), c(0, 1)) t_pt <- c(0.5, 0.5) h <- 0.4 - s <- sampler_owin(win)(150L, t = t_pt, h = h) - pts_x <- s$points[1L, ] + t_pt[1L] - pts_y <- s$points[2L, ] + t_pt[2L] + s <- sampler_owin(win) + res <- s(150L, t = t_pt, h = h) + pts_x <- res$points[1L, ] + t_pt[1L] + pts_y <- res$points[2L, ] + t_pt[2L] expect_true(all(pts_x >= 0 - 1e-9 & pts_x <= 1 + 1e-9)) expect_true(all(pts_y >= 0 - 1e-9 & pts_y <= 1 + 1e-9)) })