diff --git a/NAMESPACE b/NAMESPACE index f5292d9..1e5287d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -6,6 +6,7 @@ S3method(print,cv_density_lp) S3method(print,density_lp) S3method(print,density_lp_ppp) S3method(print,domain_lp) +S3method(summary,density_lp) export(cv_density_lp) export(cv_density_lp_ppp) export(density_lp) diff --git a/R/cv.R b/R/cv.R index 43cd2aa..5f4c7d3 100644 --- a/R/cv.R +++ b/R/cv.R @@ -1,5 +1,20 @@ # LOO cross-validation for bandwidth and degree selection ----------------------- +#' Internal constructor for cv_density_lp objects +#' @keywords internal +new_cv_density_lp <- function(m_hat, h_hat, scores, grids, call) { + structure( + list( + m_hat = m_hat, + h_hat = h_hat, + scores = scores, + grids = grids, + call = call + ), + class = "cv_density_lp" + ) +} + #' LOO cross-validation for the local polynomial density estimator #' #' For each pair \eqn{(m, h)} in the grid, computes the leave-one-out @@ -20,7 +35,7 @@ #' @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, -#' - `$m_grid`, `$h_grid`: the grids used. +#' - `$grids`: list containing `$m` and `$h` grids used. #' @seealso [density_lp()], [cv_density_lp_ppp()] #' @export cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { @@ -105,16 +120,15 @@ cv_density_lp <- function(X, h_grid, m_grid = 0:3, domain, N_quad = 500L) { h_grid[idx[2L]] )) } - structure( - list( - m_hat = m_grid[idx[1L]], - h_hat = h_grid[idx[2L]], - scores = scores, - m_grid = m_grid, - h_grid = h_grid, - call = match.call() + new_cv_density_lp( + m_hat = m_grid[idx[1L]], + h_hat = h_grid[idx[2L]], + scores = scores, + grids = list( + m = m_grid, + h = h_grid ), - class = "cv_density_lp" + call = match.call() ) } @@ -143,22 +157,3 @@ cv_density_lp_ppp <- function(pp, h_grid, m_grid = 0:3, N_quad = 500L) { N_quad = N_quad ) } - -#' Print a cv_density_lp object -#' @param x A `"cv_density_lp"` object. -#' @param ... Ignored. -#' @return `x` invisibly. -#' @export -print.cv_density_lp <- function(x, ...) { - score <- x$scores[paste0("m=", x$m_hat), as.character(round(x$h_hat, 6L))] - cat("LOO cross-validation -- local polynomial density\n") - cat(sprintf(" Selected m : %d\n", x$m_hat)) - cat(sprintf(" Selected h : %.6g\n", x$h_hat)) - cat(sprintf(" CV score : %.5g\n", score)) - cat(sprintf( - " Grid : %d degree(s) x %d bandwidth(s)\n", - length(x$m_grid), - length(x$h_grid) - )) - invisible(x) -} diff --git a/R/density_lp.R b/R/density_lp.R index 9737ada..b7a83c5 100644 --- a/R/density_lp.R +++ b/R/density_lp.R @@ -1,5 +1,43 @@ # Grid estimator (exported) ----------------------------------------------------- +#' Internal constructor for density_lp objects +#' @keywords internal +new_density_lp <- function( + estimate, + variance, + t_grid, + X, + h, + m, + domain, + N_quad, + n_fail, + call +) { + structure( + list( + estimate = estimate, + variance = variance, + t_grid = t_grid, + X = X, + params = list( + h = h, + m = m, + domain = domain, + N_quad = N_quad + ), + stats = list( + n_fail = n_fail, + n_obs = nrow(X), + p = nrow(t_grid), + d = ncol(X) + ), + call = call + ), + class = "density_lp" + ) +} + #' Local polynomial density estimation on a grid of target points #' #' @param X Numeric matrix `n x d` of observations. Must be a matrix; no @@ -12,11 +50,7 @@ #' @param N_quad Number of Monte Carlo quadrature points per target point #' (default: 500). #' -#' @return An S3 object of class `"density_lp"` containing: -#' - `$estimate`: numeric vector of length `p` (estimated values), -#' - `$variance`: numeric vector of length `p` (variance estimates), -#' - `$t_grid`: the matrix of target points, -#' - `$h`, `$m`, `$domain`, `$N_quad`: parameters used. +#' @return An S3 object of class `"density_lp"`. #' #' @export density_lp <- function(X, t_grid, h, m = 0L, domain, N_quad = 500L) { @@ -66,17 +100,16 @@ density_lp <- function(X, t_grid, h, m = 0L, domain, N_quad = 500L) { ) } - structure( - list( - estimate = estimate, - variance = variance, - t_grid = t_grid, - h = h, - m = m, - domain = domain, - N_quad = N_quad, - call = match.call() - ), - class = "density_lp" + new_density_lp( + estimate = estimate, + variance = variance, + t_grid = t_grid, + X = X, + h = h, + m = m, + domain = domain, + N_quad = N_quad, + n_fail = n_fail, + call = match.call() ) } diff --git a/R/density_lp_ppp.R b/R/density_lp_ppp.R index c3c7b4a..3378f65 100644 --- a/R/density_lp_ppp.R +++ b/R/density_lp_ppp.R @@ -1,5 +1,21 @@ # spatstat wrapper --------------------------------------------------------------- +#' Internal constructor for density_lp_ppp objects +#' @keywords internal +new_density_lp_ppp <- function(im_obj, params, stats, call) { + structure( + c( + unclass(im_obj), + list( + params = params, + stats = stats, + call = call + ) + ), + class = c("density_lp_ppp", "im") + ) +} + #' Local polynomial density estimation for a spatial point pattern #' #' Convenience wrapper around [density_lp()] for `ppp` objects (spatstat). @@ -13,8 +29,8 @@ #' @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 `im` object (spatstat.geom). Pixels outside `Window(pp)` are -#' `NA`. +#' @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()] #' @importFrom spatstat.geom Window inside.owin im unitname #' @export @@ -68,11 +84,15 @@ density_lp_ppp <- function(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L) { unitname = spatstat.geom::unitname(pp) ) - structure( - c( - unclass(im_obj), - list(h = h, m = as.integer(m), N_quad = as.integer(N_quad), call = mc) + new_density_lp_ppp( + im_obj = im_obj, + params = list( + h = h, + m = as.integer(m), + N_quad = as.integer(N_quad), + domain = dom ), - class = c("density_lp_ppp", "im") + stats = fit$stats, + call = mc ) } diff --git a/R/methods.R b/R/methods.R index 11aea7f..3aaef5d 100644 --- a/R/methods.R +++ b/R/methods.R @@ -7,12 +7,19 @@ #' @export print.density_lp_ppp <- function(x, ...) { cat("Local polynomial density estimate (spatstat)\n") - cat(sprintf(" h : %g\n", x$h)) - cat(sprintf(" m : %d\n", x$m)) - cat(sprintf(" N_quad : %d\n", x$N_quad)) + 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) } @@ -35,18 +42,51 @@ plot.density_lp_ppp <- function(x, ...) { #' @export print.density_lp <- function(x, ...) { cat("Local polynomial density estimate\n") - cat(sprintf(" Domain : %s\n", x$domain$label)) - cat(sprintf(" d : %d\n", x$domain$d)) - cat(sprintf(" h : %g\n", x$h)) - cat(sprintf(" m : %d\n", x$m)) - cat(sprintf(" N_quad : %d\n", x$N_quad)) - cat(sprintf(" Points : %d\n", nrow(x$t_grid))) + 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) { + cat(sprintf( + " Note : %d failure(s) during calculation\n", + x$stats$n_fail + )) + } + invisible(x) +} + +#' Summary of a density_lp object +#' @param object A `"density_lp"` object. +#' @param ... Ignored. +#' @return `object` invisibly. +#' @export +summary.density_lp <- function(object, ...) { + cat("Local Polynomial Density Estimation Summary\n") + cat("-------------------------------------------\n") cat(sprintf( - " Range : [%.5g, %.5g]\n", - min(x$estimate, na.rm = TRUE), - max(x$estimate, na.rm = TRUE) + "Call : %s\n", + paste(deparse(object$call), collapse = "\n") )) - invisible(x) + cat(sprintf( + "Domain : %s (d = %d)\n", + object$params$domain$label, + 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 + )) + 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)) + invisible(object) } #' Plot a density_lp object @@ -59,10 +99,10 @@ print.density_lp <- function(x, ...) { #' @export plot.density_lp <- function( x, - main = paste0("densityLP (h = ", x$h, ", m = ", x$m, ")"), + main = paste0("densityLP (h = ", x$params$h, ", m = ", x$params$m, ")"), ... ) { - d <- x$domain$d + d <- x$stats$d if (d == 1L) { plot( x$t_grid[, 1L], @@ -98,3 +138,24 @@ plot.density_lp <- function( } invisible(x) } + +# S3 methods for "cv_density_lp" ------------------------------------------------ + +#' Print a cv_density_lp object +#' @param x A \code{"cv_density_lp"} object. +#' @param ... Ignored. +#' @return \code{x} invisibly. +#' @export +print.cv_density_lp <- function(x, ...) { + score <- x$scores[paste0("m=", x$m_hat), as.character(round(x$h_hat, 6L))] + cat("LOO cross-validation -- local polynomial density\n") + cat(sprintf(" Selected m : %d\n", x$m_hat)) + cat(sprintf(" Selected h : %.6g\n", x$h_hat)) + cat(sprintf(" CV score : %.5g\n", score)) + cat(sprintf( + " Grid : %d degree(s) x %d bandwidth(s)\n", + length(x$grids$m), + length(x$grids$h) + )) + invisible(x) +} diff --git a/man/cv_density_lp.Rd b/man/cv_density_lp.Rd index 3076221..c2a6b89 100644 --- a/man/cv_density_lp.Rd +++ b/man/cv_density_lp.Rd @@ -22,7 +22,7 @@ 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{$m_grid}, \verb{$h_grid}: the grids used. +\item \verb{$grids}: list containing \verb{$m} and \verb{$h} grids used. } } \description{ diff --git a/man/density_lp.Rd b/man/density_lp.Rd index 34e949a..bd4e03e 100644 --- a/man/density_lp.Rd +++ b/man/density_lp.Rd @@ -23,13 +23,7 @@ implicit conversion from data frames or tibbles is performed.} (default: 500).} } \value{ -An S3 object of class \code{"density_lp"} containing: -\itemize{ -\item \verb{$estimate}: numeric vector of length \code{p} (estimated values), -\item \verb{$variance}: numeric vector of length \code{p} (variance estimates), -\item \verb{$t_grid}: the matrix of target points, -\item \verb{$h}, \verb{$m}, \verb{$domain}, \verb{$N_quad}: parameters used. -} +An S3 object of class \code{"density_lp"}. } \description{ Local polynomial density estimation on a grid of target points diff --git a/man/density_lp_ppp.Rd b/man/density_lp_ppp.Rd index 49b4600..17e87c6 100644 --- a/man/density_lp_ppp.Rd +++ b/man/density_lp_ppp.Rd @@ -20,8 +20,8 @@ density_lp_ppp(pp, h, m = 0L, N_quad = 500L, nx = 128L, ny = 128L) \item{ny}{Number of pixel rows (default 128).} } \value{ -An \code{im} object (spatstat.geom). Pixels outside \code{Window(pp)} are -\code{NA}. +An S3 object of class \code{"density_lp_ppp"}, 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). diff --git a/man/new_cv_density_lp.Rd b/man/new_cv_density_lp.Rd new file mode 100644 index 0000000..82b02a7 --- /dev/null +++ b/man/new_cv_density_lp.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cv.R +\name{new_cv_density_lp} +\alias{new_cv_density_lp} +\title{Internal constructor for cv_density_lp objects} +\usage{ +new_cv_density_lp(m_hat, h_hat, scores, grids, call) +} +\description{ +Internal constructor for cv_density_lp objects +} +\keyword{internal} diff --git a/man/new_density_lp.Rd b/man/new_density_lp.Rd new file mode 100644 index 0000000..c720673 --- /dev/null +++ b/man/new_density_lp.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/density_lp.R +\name{new_density_lp} +\alias{new_density_lp} +\title{Internal constructor for density_lp objects} +\usage{ +new_density_lp( + estimate, + variance, + t_grid, + X, + h, + m, + domain, + N_quad, + n_fail, + call +) +} +\description{ +Internal constructor for density_lp objects +} +\keyword{internal} diff --git a/man/new_density_lp_ppp.Rd b/man/new_density_lp_ppp.Rd new file mode 100644 index 0000000..573a501 --- /dev/null +++ b/man/new_density_lp_ppp.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/density_lp_ppp.R +\name{new_density_lp_ppp} +\alias{new_density_lp_ppp} +\title{Internal constructor for density_lp_ppp objects} +\usage{ +new_density_lp_ppp(im_obj, params, stats, call) +} +\description{ +Internal constructor for density_lp_ppp objects +} +\keyword{internal} diff --git a/man/plot.density_lp.Rd b/man/plot.density_lp.Rd index b8ae560..76f8062 100644 --- a/man/plot.density_lp.Rd +++ b/man/plot.density_lp.Rd @@ -4,7 +4,11 @@ \alias{plot.density_lp} \title{Plot a density_lp object} \usage{ -\method{plot}{density_lp}(x, main = paste0("densityLP (h = ", x$h, ", m = ", x$m, ")"), ...) +\method{plot}{density_lp}( + x, + main = paste0("densityLP (h = ", x$params$h, ", m = ", x$params$m, ")"), + ... +) } \arguments{ \item{x}{A \code{"density_lp"} object.} diff --git a/man/print.cv_density_lp.Rd b/man/print.cv_density_lp.Rd index 5ec6fc2..71f386a 100644 --- a/man/print.cv_density_lp.Rd +++ b/man/print.cv_density_lp.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/cv.R +% Please edit documentation in R/methods.R \name{print.cv_density_lp} \alias{print.cv_density_lp} \title{Print a cv_density_lp object} diff --git a/man/summary.density_lp.Rd b/man/summary.density_lp.Rd new file mode 100644 index 0000000..bfad416 --- /dev/null +++ b/man/summary.density_lp.Rd @@ -0,0 +1,19 @@ +% 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/tests/testthat/test-cv.R b/tests/testthat/test-cv.R index 210edf3..0ec0832 100644 --- a/tests/testthat/test-cv.R +++ b/tests/testthat/test-cv.R @@ -45,12 +45,12 @@ test_that("cv_density_lp: score matrix has correct dimensions", { test_that("cv_density_lp: m_hat is in m_grid", { cv <- make_square_cv() - expect_true(cv$m_hat %in% cv$m_grid) + expect_true(cv$m_hat %in% cv$grids$m) }) test_that("cv_density_lp: h_hat is in h_grid", { cv <- make_square_cv() - expect_true(cv$h_hat %in% cv$h_grid) + expect_true(cv$h_hat %in% cv$grids$h) }) test_that("cv_density_lp: selected score is the minimum finite score", { @@ -72,8 +72,8 @@ test_that("cv_density_lp: grids stored in output match inputs", { domain = domain_from_indicator(is_sq), N_quad = 100L ) - expect_equal(cv$h_grid, h_grid) - expect_equal(cv$m_grid, m_grid) + expect_equal(cv$grids$h, h_grid) + expect_equal(cv$grids$m, m_grid) }) test_that("cv_density_lp: error if X is not a matrix", { diff --git a/tests/testthat/test-density_lp.R b/tests/testthat/test-density_lp.R index 53379b8..f0798ff 100644 --- a/tests/testthat/test-density_lp.R +++ b/tests/testthat/test-density_lp.R @@ -156,8 +156,8 @@ test_that("density_lp: returns 'density_lp' object with correct fields", { expect_s3_class(res, "density_lp") expect_length(res$estimate, 2L) expect_equal(nrow(res$t_grid), 2L) - expect_equal(res$h, 0.4) - expect_equal(res$m, 1L) + expect_equal(res$params$h, 0.4) + expect_equal(res$params$m, 1L) }) test_that("density_lp: estimates are non-negative", { diff --git a/tests/testthat/test-density_lp_ppp.R b/tests/testthat/test-density_lp_ppp.R index a745def..b770bca 100644 --- a/tests/testthat/test-density_lp_ppp.R +++ b/tests/testthat/test-density_lp_ppp.R @@ -8,8 +8,8 @@ test_that("density_lp_ppp: returns a density_lp_ppp object inheriting from im", fit <- density_lp_ppp(pp, h = 0.5, m = 0L, N_quad = 100L, nx = 32L, ny = 32L) expect_s3_class(fit, "density_lp_ppp") expect_s3_class(fit, "im") - expect_equal(fit$h, 0.5) - expect_equal(fit$m, 0L) + 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", { diff --git a/vignettes/cv.Rmd b/vignettes/cv.Rmd index 7fe5cd2..8fab42a 100644 --- a/vignettes/cv.Rmd +++ b/vignettes/cv.Rmd @@ -61,16 +61,16 @@ scores_plot[!is.finite(scores_plot)] <- NA ylim <- range(scores_plot, na.rm = TRUE) -plot(cv_sq$h_grid, scores_plot["m=0", ], +plot(cv_sq$grids$h, scores_plot["m=0", ], type = "b", pch = 16, lwd = 2, col = pal["m=0"], xlab = "h", ylab = "CV score (lower = better)", main = "LOO CV — unit square, f ≡ 1", ylim = ylim ) -lines(cv_sq$h_grid, scores_plot["m=1", ], +lines(cv_sq$grids$h, scores_plot["m=1", ], type = "b", pch = 16, lwd = 2, col = pal["m=1"] ) -lines(cv_sq$h_grid, scores_plot["m=2", ], +lines(cv_sq$grids$h, scores_plot["m=2", ], type = "b", pch = 16, lwd = 2, col = pal["m=2"] ) @@ -140,16 +140,16 @@ scores_bt[!is.finite(scores_bt)] <- NA ylim_bt <- range(scores_bt, na.rm = TRUE) -plot(cv_bt$h_grid, scores_bt["m=0", ], +plot(cv_bt$grids$h, scores_bt["m=0", ], type = "b", pch = 16, lwd = 2, col = pal["m=0"], xlab = "h", ylab = "CV score (lower = better)", main = "LOO CV — unit square, f = Beta(2,5) × Beta(2,5)", ylim = ylim_bt ) -lines(cv_bt$h_grid, scores_bt["m=1", ], +lines(cv_bt$grids$h, scores_bt["m=1", ], type = "b", pch = 16, lwd = 2, col = pal["m=1"] ) -lines(cv_bt$h_grid, scores_bt["m=2", ], +lines(cv_bt$grids$h, scores_bt["m=2", ], type = "b", pch = 16, lwd = 2, col = pal["m=2"] )