R/np.plot.asymptotic.R

Defines functions .np_plot_joint_band_fields .np_plot_plreg_influence .np_plot_plreg_operator .np_plot_plreg_lc_training_operator .np_plot_plreg_check_reconstruction .np_plot_response_residuals .np_plot_scoef_joint_covariance .np_plot_regression_joint_supported .np_plot_regression_joint_covariance .np_plot_regression_capture_operator .np_plot_regression_capture_same_bws .np_plot_regression_capture_supported .np_plot_gaussian_maxima .np_plot_gaussian_calibrate_alphas .np_plot_gaussian_calibrate .np_plot_gaussian_factor_calibrate .np_plot_gaussian_critical .np_plot_gaussian_draws .np_plot_gaussian_integer .np_plot_joint_try .np_plot_joint_unavailable .np_plot_joint_panel_range .np_plot_joint_interval_rows .np_plot_projection_slice

# Subsetting a matrix drops private replay metadata. Preserve the row-owned
# policy explicitly; ordinary matrices remain unchanged.
.np_plot_projection_slice <- function(x, index, columns = seq_len(ncol(x))) {
  out <- x[index,columns,drop=FALSE]
  policy <- attr(x,".np.fit.precision",exact=TRUE)
  if (!is.null(policy)) {
    if (!is.matrix(policy) || !identical(dim(policy),c(nrow(x),2L)) ||
        any(!is.finite(policy)) || any(policy<0))
      stop("invalid accepted precision replay policy",call.=FALSE)
    attr(out,".np.fit.precision") <- policy[index,,drop=FALSE]
  }
  out
}

# A missing joint interval must retain one row per retained plotted center.
# Other interval routes preserve their established omission behavior.
.np_plot_joint_interval_rows <- function(errors, center, joint, type) {
  if (joint && identical(type, "simultaneous"))
    errors[!is.na(center), , drop = FALSE]
  else
    na.omit(errors)
}

.np_plot_joint_panel_range <- function(estimate, err, plotOnEstimate = TRUE) {
  limits <- .np_plot_panel_error_range(estimate, err,
    plot.errors.type = "simultaneous", plotOnEstimate = plotOnEstimate)
  if (all(is.finite(limits))) limits else c(-1, 1)
}

.np_plot_joint_unavailable <- function(message, call. = FALSE) {
  stop(structure(list(message = message, call = NULL),
                 class = c("np_plot_joint_unavailable", "error", "condition")))
}

# Only declared joint-band limitations are recoverable here. Invalid arguments,
# programming errors, invalid covariance objects and interrupts still propagate.
.np_plot_joint_try <- function(expr, unavailable = NULL) {
  expression <- substitute(expr)
  context <- parent.frame()
  tryCatch(eval(expression, context), np_plot_joint_unavailable = function(e) {
    .np_warning(paste0("asymptotic simultaneous variability bands are unavailable: ",
      conditionMessage(e), "; returning NA simultaneous limits and retaining any ",
      "pointwise/Bonferroni intervals."), call. = FALSE)
    unavailable
  })
}

# Finite-grid Gaussian calibration. These helpers have no estimator callers.
.np_plot_gaussian_integer <- function(value, name, maximum = 2^53 - 1) {
  if (!is.numeric(value) || length(value) != 1L || !is.finite(value) ||
      value < 1 || value != floor(value) || value > maximum)
    stop(sprintf("%s must be an integer in [1, %.0f]", name, maximum),
         call. = FALSE)
  if (value <= .Machine$integer.max) as.integer(value) else as.double(value)
}

.np_plot_gaussian_draws <- function(draws, alpha, m) {
  # The simulated statistic is one maximum: its upper tail has mass alpha,
  # irrespective of grid size. This is a probability-scale Monte Carlo target,
  # not an endpoint-accuracy or statistical-coverage guarantee.
  minimum <- ceiling(qnorm(.975)^2 * (1 - alpha) / (.1^2 * alpha))
  draws <- .np_plot_gaussian_integer(draws, "gaussian.draws")
  if (draws < minimum)
    .np_warning(sprintf(paste0("gaussian.draws=%.0f is below the recommended Monte Carlo ",
      "precision count %.0f (alpha=%g, m=%.0f evaluation points). This approximate ",
      "95%% target limits relative simulation error in the maximum's upper-tail ",
      "probability to 10%%; it does not guarantee endpoint accuracy or statistical ",
      "coverage. Increase gaussian.draws for greater precision; retaining the requested count."),
      draws, minimum, alpha, m), call. = FALSE)
  draws
}

# An exact standardized Gaussian maximum lies between the pointwise and
# Bonferroni critical values. Enforce those bounds on its Monte Carlo estimate;
# retain the raw estimate for diagnostics. This does not repair covariance.
.np_plot_gaussian_critical <- function(raw, alpha, m) {
  min(qnorm(alpha / (2 * m), lower.tail = FALSE),
      max(qnorm(alpha / 2, lower.tail = FALSE), raw))
}

# Surface grids use the observation-level factor directly: A %*% e has
# covariance A %*% t(A), without allocating or diagonalizing a g-by-g matrix.
.np_plot_gaussian_factor_calibrate <- function(influence, alpha = 0.05,
                                               draws = 9999L, block = 4096L,
                                               max.bytes = 64 * 1024^2) {
  if (!is.numeric(alpha) || length(alpha) != 1L || !is.finite(alpha) ||
      alpha <= 0 || alpha >= 0.5)
    stop("alpha must lie in (0, 0.5)", call. = FALSE)
  if (!is.matrix(influence) || !is.numeric(influence) ||
      nrow(influence) < 1L || ncol(influence) < 1L || any(!is.finite(influence)))
    stop("Gaussian influence factor must be a finite nonempty numeric matrix",
         call. = FALSE)
  if (!is.numeric(max.bytes) || length(max.bytes) != 1L ||
      !is.finite(max.bytes) || max.bytes <= 0)
    stop("Gaussian memory budget must be positive and finite", call. = FALSE)
  g <- nrow(influence)
  n <- ncol(influence)
  draws <- .np_plot_gaussian_draws(draws, alpha, g)
  block <- .np_plot_gaussian_integer(block, "Gaussian draw block", 1000000L)
  available <- max.bytes - 8 * as.double(g) * n - 24 * draws - 64 * g
  block <- min(block, draws, floor(available / (64 * (as.double(g) + n))))
  if (block < 1)
    .np_plot_joint_unavailable("finite-grid Gaussian influence factor exceeds the plot memory budget",
         call. = FALSE)
  # Row sums avoid a second full factor-sized squared array.
  se <- vapply(seq_len(g), function(i) sqrt(sum(influence[i, ]^2)), numeric(1L))
  if (any(!is.finite(se)))
    stop("Gaussian influence factor has nonfinite variance", call. = FALSE)
  active <- se > 0
  metadata <- list(method = "asymptotic Gaussian", scope = "finite grid within panel",
                   draws = draws, critical = 0, grid.size = g,
                   positive.variance = sum(active), rank = NA_integer_,
                   representation = "observation influence factor")
  if (!any(active)) return(metadata)
  divisor <- ifelse(active, se, 1)
  maxima <- numeric(draws)
  progress <- .np_plot_bootstrap_progress_begin(draws, "Gaussian plot calibration",
                                                 unit = "draw")
  on.exit(.np_plot_progress_end(progress), add = TRUE)
  for (start in seq.int(1L, draws, by = block)) {
    last <- min(draws, start + block - 1L)
    normal <- matrix(rnorm(n * (last - start + 1L)), nrow = n)
    simulated <- (influence %*% normal) / divisor
    maxima[start:last] <- apply(abs(simulated), 2L, max)
    progress <- .np_plot_progress_tick(progress, last)
  }
  metadata$critical.raw <- unname(quantile(maxima, 1 - alpha, type = 1L))
  metadata$critical <- .np_plot_gaussian_critical(metadata$critical.raw, alpha, g)
  metadata
}

.np_plot_gaussian_calibrate <- function(covariance, alpha = 0.05,
                                        draws = 9999L, block = 4096L,
                                        max.bytes = 64 * 1024^2) {
  block <- .np_plot_gaussian_integer(block, "Gaussian draw block", 1000000L)
  if (!is.numeric(alpha) || length(alpha) != 1L || !is.finite(alpha) ||
      alpha <= 0 || alpha >= 0.5)
    stop("alpha must lie in (0, 0.5)", call. = FALSE)
  .np_plot_gaussian_calibrate_alphas(covariance, alpha, draws, block, max.bytes)[[1L]]
}

# One stochastic producer serves all alpha reductions. Reassigning a visible
# seed cannot replay a pending Box-Muller deviate; leave the normal stream live.
.np_plot_gaussian_calibrate_alphas <- function(covariance, alpha,
                                               draws = 9999L, block = 4096L,
                                               max.bytes = 64 * 1024^2) {
  process <- .np_plot_gaussian_maxima(covariance, alpha, draws, block, max.bytes)
  metadata <- process$metadata
  if (!metadata$positive.variance) return(lapply(alpha, function(a) metadata))
  lapply(alpha, function(a) {
    result <- metadata
    result$critical.raw <- unname(quantile(process$maxima, 1 - a, type = 1L))
    result$critical <- .np_plot_gaussian_critical(result$critical.raw, a,
                                                 metadata$grid.size)
    result$rank <- process$rank
    result
  })
}

# Shared bounded producer: validation, symmetric root and normal draw order
# have one owner. Signed scale uncertainty uses the same draws without replay.
.np_plot_gaussian_maxima <- function(covariance, alpha,
                                      draws = 9999L, block = 4096L,
                                      max.bytes = 64 * 1024^2,
                                      reduction = c("absolute", "negative")) {
  reduction <- match.arg(reduction)
  block <- .np_plot_gaussian_integer(block, "Gaussian draw block", 1000000L)
  if (!is.numeric(alpha) || !length(alpha) || any(!is.finite(alpha)) ||
      any(alpha <= 0 | alpha >= 0.5) || anyDuplicated(alpha))
    stop("alpha values must be unique and lie in (0, 0.5)", call. = FALSE)
  if (!is.numeric(max.bytes) || length(max.bytes) != 1L ||
      !is.finite(max.bytes) || max.bytes <= 0)
    stop("Gaussian memory budget must be positive and finite", call. = FALSE)
  if (!is.matrix(covariance) || !is.numeric(covariance) ||
      nrow(covariance) < 1L || nrow(covariance) != ncol(covariance))
    stop("Gaussian covariance must be a nonempty square numeric matrix",
         call. = FALSE)
  g <- nrow(covariance)
  draws <- .np_plot_gaussian_draws(draws, alpha[[1L]], g)
  if (length(alpha) > 1L)
    for (a in alpha[-1L]) .np_plot_gaussian_draws(draws, a, g)
  if (g > 512L || 64 * as.double(g)^2 + 24 * draws + 64 * g > max.bytes)
    .np_plot_joint_unavailable("finite-grid Gaussian covariance exceeds the plot memory/grid budget",
         call. = FALSE)
  if (any(!is.finite(covariance)))
    stop("Gaussian covariance must be finite", call. = FALSE)
  tolerance <- 64 * .Machine$double.eps * g * max(abs(covariance))
  if (max(abs(covariance - t(covariance))) > tolerance)
    stop("Gaussian covariance is materially asymmetric", call. = FALSE)
  variance <- diag(covariance)
  if (any(variance < 0))
    stop("Gaussian covariance has a negative variance", call. = FALSE)
  active <- which(variance > 0)
  zero <- which(variance == 0)
  if (length(zero) && (any(covariance[zero, , drop = FALSE] != 0) ||
                       any(covariance[, zero, drop = FALSE] != 0)))
    stop("zero Gaussian variance requires a zero covariance row and column",
         call. = FALSE)
  metadata <- list(method = "asymptotic Gaussian", scope = "finite grid within panel",
                   draws = draws, critical = 0, grid.size = g,
                   positive.variance = length(active), rank = 0L)
  if (!length(active)) return(list(metadata = metadata, maxima = NULL, rank = 0L))
  s <- sqrt(variance[active])
  correlation <- covariance[active, active, drop = FALSE] / outer(s, s)
  correlation <- (correlation + t(correlation)) / 2
  eig <- eigen(correlation, symmetric = TRUE)
  tolerance <- 64 * .Machine$double.eps * length(active) * max(abs(correlation))
  if (min(eig$values) < -tolerance)
    stop("Gaussian covariance is materially indefinite", call. = FALSE)
  values <- pmax(eig$values, 0)
  # The symmetric square root avoids eigenvector sign conventions. Every
  # column of the normal matrix is one draw in canonical coordinate order.
  root <- tcrossprod(sweep(eig$vectors, 2L, sqrt(values), "*"), eig$vectors)
  block <- min(block, draws, floor((max.bytes - 64 * as.double(g)^2 -
                                     24 * draws) / (64 * g)))
  maxima <- numeric(draws)
  progress <- .np_plot_bootstrap_progress_begin(draws, "Gaussian plot calibration",
                                                 unit = "draw")
  on.exit(.np_plot_progress_end(progress), add = TRUE)
  for (start in seq.int(1L, draws, by = block)) {
    last <- min(draws, start + block - 1L)
    normal <- matrix(rnorm(length(active) * (last - start + 1L)),
                     nrow = length(active))
    simulated <- root %*% normal
    maxima[start:last] <- if (reduction == "absolute") {
      apply(abs(simulated), 2L, max)
    } else {
      negative <- apply(-simulated, 2L, max)
      if (length(zero)) pmax(0, negative) else negative
    }
    progress <- .np_plot_progress_tick(progress, last)
  }
  list(metadata = metadata, maxima = maxima, rank = sum(values > tolerance))
}

# Captured adjoints belong to one complete request, including its native
# constant-weight decisions. Only the observation rows are tiled below.
.np_plot_regression_capture_supported <- function(bws) {
  identical(bws[["type", exact=TRUE]], "fixed") &&
    identical(bws[["ckertype", exact=TRUE]], "gaussian") &&
    isTRUE(bws[["ckerorder", exact=TRUE]] == 2L) &&
    (identical(bws[["ckerbound", exact=TRUE]], "none") ||
     (identical(bws[["ckerbound", exact=TRUE]], "fixed") &&
      isTRUE(bws[["nuno", exact=TRUE]] == 0L) &&
      isTRUE(bws[["nord", exact=TRUE]] == 0L))) &&
    isTRUE(bws[["ncon", exact=TRUE]] > 0L)
}

# Calls and post-publication timing profiles are provenance, not fitted
# geometry. MPI reuse may retain the bandwidth before its coordinator profile
# is attached. Compare every other bandwidth field and attribute exactly;
# training/evaluation ownership is checked separately by each consumer.
# Never evaluate a call to validate a compact fitted operator.
.np_plot_regression_capture_same_bws <- function(left, right) {
  if (!is.list(left) || !is.list(right)) return(FALSE)
  left[["timing.profile"]] <- NULL
  right[["timing.profile"]] <- NULL
  left[["call"]] <- NULL
  right[["call"]] <- NULL
  identical(left, right)
}

.np_plot_regression_capture_operator <- function(fit,bws,x,y,ex,deriv,
                                                 categorical.index,max.bytes) {
  request <- fit[["fit.request", exact=TRUE]]
  if (!.np_plot_regression_capture_supported(bws) ||
      !is.null(categorical.index) || !is.list(request) ||
      !.np_plot_regression_capture_same_bws(request$bws,bws) || !identical(request$xdat,x) ||
      !identical(request$ydat,y) || !identical(request$exdat,ex))
    stop("regression inference capture does not match its fit request",call.=FALSE)
  state <- fit[["fit.inference", exact=TRUE]]
  projection <- fit[["fit.projection", exact=TRUE]]
  spec <- npValidatedConditionalRegSpec(bws,where="regression inference capture",
                                        ncon.field="ncon")
  scalar <- npIsCanonicalLp0Spec(spec,bws$ncon)
  width <- if (scalar) 1L else npLpBasisNcol(spec$basis.engine,spec$degree.engine)
  n <- nrow(x); m <- nrow(ex); d <- bws$ncon
  if (!is.list(state) || length(state)!=4L || !is.list(projection) ||
      length(projection)!=3L ||
      !identical(dim(projection[[1L]]),c(n,as.integer(width))) ||
      !identical(dim(projection[[2L]]),c(m,as.integer(width))) ||
      !identical(dim(state[[1L]]),c(m,as.integer(width*d))) ||
      length(state[[2L]])!=n || length(state[[3L]])!=m ||
      !identical(dim(state[[4L]]),c(3L,ncol(x))))
    stop("invalid compact regression inference state",call.=FALSE)
  direction <- NULL
  if (!is.null(deriv)) {
    order <- rep_len(request$gradient.order,d)
    if (!isTRUE(request$gradients) || length(deriv)!=d || anyNA(deriv) ||
        any(deriv<0L) || sum(deriv>0L)!=1L)
      stop("derivative is absent from the regression inference capture",call.=FALSE)
    direction <- which(deriv>0L)
    if (deriv[direction]!=order[direction])
      stop("derivative order differs from the regression inference capture",call.=FALSE)
  }
  geometry <- .np_plot_lsq_gate_geometry(bws,x,ex,max.bytes=max.bytes)
  attr(geometry,".np.fit.gate") <- state[[4L]]
  operator <- function(evaluation, derivative=NULL, index=NULL) {
    index <- .np_plot_lsq_gate_indices(index,m)
    if (!identical(derivative,deriv) ||
        !identical(evaluation,ex[index,,drop=FALSE]))
      stop("regression inference tile differs from its complete request",call.=FALSE)
    if (!is.null(direction) && scalar)
      return(.np_plot_lsq_gate_derivative(bws,x,ex,s=as.integer(deriv),
        max.bytes=max.bytes,.np.gate=state[[4L]],.np.index=index))
    adjoint <- if (is.null(direction))  .np_plot_projection_slice(projection[[2L]],index) else
      .np_plot_projection_slice(state[[1L]],index,(direction-1L)*width+seq_len(width))
    attr(adjoint,".np.fit.accepted") <- TRUE
    weights <- .np_plot_lsq_gate_weights(bws,geometry,index,max.bytes=max.bytes)
    .Call("C_np_plot_projection_apply",projection[[1L]],adjoint,weights,PACKAGE="np")
  }
  list(operator=operator,residual=state[[2L]])
}

.np_plot_regression_joint_covariance <- function(bws, xdat, ydat, exdat,
                                                residual = NULL, deriv = NULL,
                                                categorical.index = NULL,
                                                factor = FALSE,
                                                block.bytes = 4 * 1024^2,
                                                max.bytes = 64 * 1024^2, fit = NULL) {
  n <- nrow(xdat)
  g <- nrow(exdat)
  ydat <- .np_hat_response(ydat, bws[["ydati", exact = TRUE]])
  if (!is.numeric(block.bytes) || length(block.bytes) != 1L ||
      !is.finite(block.bytes) || block.bytes <= 0 ||
      !is.numeric(max.bytes) || length(max.bytes) != 1L ||
      !is.finite(max.bytes) || max.bytes <= 0)
    stop("joint covariance memory budgets must be positive and finite",
         call. = FALSE)
  spec <- npValidatedConditionalRegSpec(bws, where = "plot joint covariance",
                                         ncon.field = "ncon")
  width <- if (identical(spec$regtype.engine, "lc")) 1 else
    npLpBasisNcol(spec$basis.engine, spec$degree.engine)
  # Conservative workspace allowance includes the unchanged operator's basis,
  # solve, coordinate copies and tree, as well as the plot-owned arrays.
  setup.bytes <- 64 * n * (width + ncol(xdat) + 1) + 128 * width^2
  joint.bytes <- if (factor) 16 * as.double(g) * n else 64 * as.double(g)^2
  available <- min(block.bytes, max.bytes - joint.bytes -
                     16 * n - setup.bytes)
  rows <- floor(available / (64 * as.double(n)))
  if (n < 2L || g < 1L ||
      length(ydat) != n || any(!is.finite(ydat)) ||
      anyNA(xdat) || anyNA(exdat))
    stop("joint covariance has invalid data", call. = FALSE)
  if ((!factor && g > 512L) || rows < 1)
    .np_plot_joint_unavailable("joint covariance exceeds the plot memory/grid budget")
  rows <- min(rows, n, g)
  operator <- function(evaluation, derivative = NULL, index = NULL) {
    npreghat(bws = bws, txdat = xdat, exdat = evaluation, deriv = derivative,
             output = "matrix", .np.require.finite = TRUE)
  }
  captured <- if (!is.null(fit[["fit.inference", exact=TRUE]]))
    .np_plot_regression_capture_operator(fit,bws,xdat,ydat,exdat,deriv,
      categorical.index,max.bytes) else NULL
  z <- if (is.null(captured)) residual else captured$residual
  if (!is.null(captured)) operator <- captured$operator
  if (is.null(z) && bws[["type", exact = TRUE]] %in% c("generalized_nn", "adaptive_nn"))
    z <- .np_plot_response_residuals(bws, xdat, ydat, rows)$residual
  if (is.null(z)) {
  z <- numeric(n)
  for (start in seq.int(1L, n, by = rows)) {
    index <- seq.int(start, min(n, start + rows - 1L))
    hat <- operator(xdat[index, , drop = FALSE])
    ridge <- attr(hat, "ridge.used", exact = TRUE)
    if (is.null(ridge) || length(ridge) != length(index))
      stop("joint covariance requires the influence owner's ridge certificate",
           call. = FALSE)
    for (j in seq_along(index)) {
      i <- index[j]
      if (ridge[j] == 0) {
        weights <- hat[j, -i]
        scale <- max(abs(weights))
        if (scale == 0)
          .np_plot_joint_unavailable("joint covariance has unidentified training residual information",
               call. = FALSE)
        weights <- weights / scale
        z[i] <- sum(weights * (ydat[i] - ydat[-i])) /
          sqrt(sum(weights)^2 + sum(weights^2))
      } else {
        residual.row <- -hat[j, ]
        residual.row[i] <- 1 + residual.row[i]
        scale <- max(abs(residual.row))
        if (scale == 0)
          .np_plot_joint_unavailable("joint covariance has unidentified training residual information",
               call. = FALSE)
        residual.row <- residual.row / scale
        z[i] <- sum(residual.row * ydat) / sqrt(sum(residual.row^2))
      }
    }
  }
  }
  if (length(z) != n || any(!is.finite(z)))
    .np_plot_joint_unavailable("joint covariance normalized residuals are nonfinite", call. = FALSE)
  evaluation.operator <- operator
  if (!is.null(categorical.index)) {
    if (!is.null(deriv))
      stop("joint covariance cannot combine continuous and categorical derivatives",
           call. = FALSE)
    evaluation.operator <- function(evaluation, derivative = NULL, index = NULL) {
      frames <- npCategoricalFirstDifferenceFrames(evaluation, categorical.index,
                                                   "plot joint covariance")
      operator(frames$upper) - operator(frames$lower)
    }
  }
  covariance <- if (factor) NULL else matrix(0, g, g)
  influence <- if (factor) matrix(0, g, n) else NULL
  estimate <- if (!is.null(deriv) || !is.null(categorical.index)) numeric(g) else NULL
  starts <- seq.int(1L, g, by = rows)
  for (a in seq_along(starts)) {
    ia <- seq.int(starts[a], min(g, starts[a] + rows - 1L))
    hat <- evaluation.operator(exdat[ia, , drop = FALSE], deriv, ia)
    if (!is.null(estimate)) estimate[ia] <- drop(hat %*% ydat)
    left <- sweep(hat, 2L, z, "*")
    if (factor) {
      influence[ia, ] <- left
      next
    }
    for (b in seq_len(a)) {
      ib <- seq.int(starts[b], min(g, starts[b] + rows - 1L))
      right <- if (a == b) left else
        sweep(evaluation.operator(exdat[ib, , drop = FALSE], deriv, ib), 2L, z, "*")
      cell <- tcrossprod(left, right)
      covariance[ia, ib] <- cell
      covariance[ib, ia] <- t(cell)
    }
  }
  list(covariance = covariance, residual = z, block.rows = rows,
       estimate = estimate, influence = influence)
}

.np_plot_regression_joint_supported <- function(bws) {
  bws[["type", exact = TRUE]] %in% c("fixed", "generalized_nn", "adaptive_nn") &&
    (isTRUE(bws[["ncon", exact = TRUE]] == 0L) ||
     (bws[["ckertype", exact = TRUE]] %in% c("gaussian", "epanechnikov") &&
      identical(as.integer(bws[["ckerorder", exact = TRUE]]), 2L)))
}

.np_plot_scoef_joint_covariance <- function(bws, xdat, ydat, zdat,
                                           exdat, ezdat, residual,
                                           gradient.index = NULL, factor = FALSE,
                                           block.bytes = 4 * 1024^2,
                                           max.bytes = 64 * 1024^2) {
  n <- nrow(xdat)
  g <- nrow(exdat)
  ydat <- .np_hat_response(ydat, bws[["ydati", exact = TRUE]])
  separate.z <- !is.null(zdat)
  if (!separate.z) zdat <- xdat
  if (is.null(ezdat)) ezdat <- exdat
  spec <- .npscoef_canonical_spec(bws, zdat, where = "plot joint covariance")
  width <- (ncol(xdat) + 1) * if (identical(spec$regtype.engine, "lc")) 1 else
    npLpBasisNcol(spec$basis.engine, spec$degree.engine)
  if (!is.numeric(block.bytes) || length(block.bytes) != 1L ||
      !is.finite(block.bytes) || block.bytes <= 0 ||
      !is.numeric(max.bytes) || length(max.bytes) != 1L ||
      !is.finite(max.bytes) || max.bytes <= 0)
    stop("joint covariance memory budgets must be positive and finite",
         call. = FALSE)
  setup.bytes <- 64 * n * (width + ncol(zdat) + 1) + 128 * width^2
  joint.bytes <- if (factor) 16 * as.double(g) * n else 64 * as.double(g)^2
  available <- min(block.bytes, max.bytes - joint.bytes -
                     16 * n - setup.bytes)
  rows <- floor(available / (64 * as.double(n)))
  if (n < 2L || g < 1L ||
      nrow(zdat) != n || nrow(ezdat) != g ||
      length(ydat) != n || any(!is.finite(ydat)) ||
      anyNA(xdat) || anyNA(exdat) || anyNA(zdat) || anyNA(ezdat))
    stop("joint covariance has invalid data", call. = FALSE)
  if ((!factor && g > 512L) || rows < 1)
    .np_plot_joint_unavailable("joint covariance exceeds the plot memory/grid budget")
  if (!is.null(gradient.index))
    rows <- min(rows, floor(available / (64 * (as.double(n) + width^2))))
  if (rows < 1)
    .np_plot_joint_unavailable("joint coefficient covariance exceeds the plot memory budget", call. = FALSE)
  rows <- min(rows, n, g)
  operator <- function(x, z) {
    args <- list(bws = bws, txdat = xdat, exdat = x,
                 output = "matrix", iterate = FALSE)
    if (separate.z) {
      args$tzdat <- zdat
      args$ezdat <- z
    }
    if (is.null(gradient.index)) {
      hat <- do.call(npscoefhat, args)
    } else {
      args$output <- NULL
      args$tydat <- ydat
      args$se <- FALSE
      args$.np_coefficient_projection <- gradient.index
      state <- do.call(.np_scoef_fit_internal, args)
      hat <- .npscoef_coefficient_projection_block(state, 1L, nrow(x))
    }
    if (any(!is.finite(hat)))
      .np_plot_joint_unavailable("joint covariance requires a finite smooth-coefficient influence map",
           call. = FALSE)
    hat
  }
  z <- residual
  if (length(z) != n || any(!is.finite(z)))
    .np_plot_joint_unavailable("joint covariance smooth-coefficient residuals are nonfinite", call. = FALSE)
  covariance <- if (factor) NULL else matrix(0, g, g)
  influence <- if (factor) matrix(0, g, n) else NULL
  mean <- numeric(g)
  starts <- seq.int(1L, g, by = rows)
  for (a in seq_along(starts)) {
    ia <- seq.int(starts[a], min(g, starts[a] + rows - 1L))
    hat <- operator(exdat[ia, , drop = FALSE], ezdat[ia, , drop = FALSE])
    mean[ia] <- drop(hat %*% ydat)
    left <- sweep(hat, 2L, z, "*")
    if (factor) {
      influence[ia, ] <- left
      next
    }
    for (b in seq_len(a)) {
      ib <- seq.int(starts[b], min(g, starts[b] + rows - 1L))
      right <- if (a == b) left else
        sweep(operator(exdat[ib, , drop = FALSE], ezdat[ib, , drop = FALSE]),
              2L, z, "*")
      cell <- tcrossprod(left, right)
      covariance[ia, ib] <- cell
      covariance[ib, ia] <- t(cell)
    }
  }
  list(covariance = covariance, residual = z, block.rows = rows,
       mean = mean, influence = influence)
}

.np_plot_response_residuals <- function(bws, xdat, ydat, rows,
                                          resx = NULL, projection = NULL,
                                          training.operator = NULL) {
  n <- nrow(xdat)
  partial <- !is.null(projection)
  K <- if (partial) matrix(0, nrow(projection), n) else NULL
  score <- square <- scale <- numeric(n)
  if (!is.null(training.operator) ||
      bws[["type", exact = TRUE]] %in% c("fixed", "adaptive_nn")) {
    # These geometries use the same weights at training coordinates whether
    # evaluation is implicit or explicit. Generalized NN does not.
    operator <- if (!is.null(training.operator)) training.operator else
      function(index) .npreghat_complete(bws, txdat = xdat,
        exdat = xdat[index, , drop = FALSE], output = "matrix")
    progress <- .np_plot_bootstrap_progress_begin(n * (1L + as.integer(partial)),
      "Computing plot training influence", unit = "row")
    on.exit(.np_plot_progress_end(progress), add = TRUE)
    if (partial) {
      K <- projection
      for (start in seq.int(1L, n, by = rows)) {
        index <- seq.int(start, min(n, start + rows - 1L))
        K <- K - projection[, index, drop = FALSE] %*% operator(index)
        progress <- .np_plot_progress_tick(progress, max(index))
      }
    }
    z <- numeric(n)
    for (start in seq.int(1L, n, by = rows)) {
      index <- seq.int(start, min(n, start + rows - 1L))
      E <- -operator(index)
      if (partial) E <- E - resx[index, , drop = FALSE] %*% K
      E[cbind(seq_along(index), index)] <- 1 + E[cbind(seq_along(index), index)]
      scale <- apply(abs(E), 1L, max)
      if (any(!is.finite(scale)) || any(scale == 0))
        .np_plot_joint_unavailable("plot covariance has unidentified training residual information", call. = FALSE)
      E <- E / scale
      z[index] <- drop(E %*% ydat) / sqrt(rowSums(E^2))
      progress <- .np_plot_progress_tick(progress, n * as.integer(partial) + max(index))
    }
    return(list(residual = z, coefficient.map = K))
  }
  spec <- npValidatedConditionalRegSpec(bws, where = "plot response influence", ncon.field = "ncon")
  progress <- .np_plot_bootstrap_progress_begin(n, "Computing plot training influence", unit = "column")
  on.exit(.np_plot_progress_end(progress), add = TRUE)
  # Response-column blocks retain implicit training-evaluation radii. External
  # evaluation at the same coordinates is different for generalized NN.
  for (start in seq.int(1L, n, by = rows)) {
    index <- seq.int(start, min(n, start + rows - 1L))
    response <- matrix(0, n, length(index))
    response[cbind(index, seq_along(index))] <- 1
    # Use the unchanged batched owner's declared capability. Other training
    # maps use canonical scalar response fits, keeping workspace bounded even
    # where the generic hat API would materialize a full training matrix.
    if (.npreghat_native_lp_mean_capability(bws, spec$regtype.engine,
        spec$degree.engine, spec$basis.engine, spec$bernstein.basis.engine,
        integer(bws[["ncon", exact = TRUE]]), FALSE)) {
      Sy <- .npreghat_exact_lp_apply_from_regression_core(bws, txdat = xdat,
        y = response, basis = spec$basis.engine, degree = spec$degree.engine,
        bernstein.basis = spec$bernstein.basis.engine)
    } else {
      Sy <- vapply(seq_along(index), function(j)
        .np_regression_direct(bws, txdat = xdat, tydat = response[, j])$mean,
        numeric(n))
    }
    Sy <- matrix(Sy, n, length(index))
    E <- -Sy
    if (partial) {
      K[, index] <- projection[, index, drop = FALSE] - projection %*% Sy
      E <- E - resx %*% K[, index, drop = FALSE]
    }
    E[cbind(index, seq_along(index))] <- 1 + E[cbind(index, seq_along(index))]
    next.scale <- pmax(scale, apply(abs(E), 1L, max))
    divisor <- ifelse(next.scale > 0, next.scale, 1)
    E <- E / divisor
    score <- score * (scale / divisor) + drop(E %*% ydat[index])
    square <- square * (scale / divisor)^2 + rowSums(E^2)
    scale <- next.scale
    progress <- .np_plot_progress_tick(progress, max(index))
  }
  if (any(!is.finite(square)) || any(square == 0))
    .np_plot_joint_unavailable("plot covariance has unidentified training residual information", call. = FALSE)
  list(residual = score / sqrt(square), coefficient.map = K)
}

.np_plot_plreg_check_reconstruction <- function(fitted, reconstructed, se) {
  if (length(reconstructed) != length(fitted) || length(se) != length(fitted) ||
      any(!is.finite(c(fitted, reconstructed, se))) || any(se < 0))
    stop("partially linear plot influence has invalid fitted values or standard errors", call. = FALSE)
  # A reconstruction difference below 1% of one SE is immaterial on the
  # interval scale. Keep only a representation-level allowance when SE is zero.
  tolerance <- 0.01 * se + 64 * .Machine$double.eps *
    pmax(abs(fitted), abs(reconstructed))
  # Plot callers preserve the curve but withhold uncertainty at unreliable rows.
  abs(reconstructed - fitted) > tolerance
}

.np_plot_plreg_lc_training_operator <- function(bws, xdat) {
  spec <- npValidatedConditionalRegSpec(bws,
    where = "partially linear plot training influence", ncon.field = "ncon")
  if (!identical(bws[["type", exact = TRUE]], "generalized_nn") ||
      !npIsCanonicalLp0Spec(spec, bws[["ncon", exact = TRUE]]) || bws[["ncon", exact = TRUE]] < 1L)
    return(NULL)
  function(index) {
    # The occurrence map preserves implicit-training NN radii in row blocks.
    out <- npksum(bws, txdat = xdat, exdat = xdat[index, , drop = FALSE],
      return.kernel.weights = TRUE, bandwidth.divide = TRUE,
      .np.internal.bandwidth.divide.weights = TRUE,
      .np.internal.eval.train.index = as.integer(index))
    .np_lc_hat_normalize(out$kw, colSums(out$kw))
  }
}

# Compact projections preserve the scalar fit's accepted rank/ridge decision.
# Training fits remain implicit; only their kernel rows are consumed in blocks.
.np_plot_plreg_operator <- function(bws, xdat, ydat, exdat = NULL) {
  spec <- npValidatedConditionalRegSpec(bws,
    where = "partially linear plot influence", ncon.field = "ncon")
  training <- is.null(exdat)
  evaluation <- if (training) xdat else exdat
  if (npIsCanonicalLp0Spec(spec, bws[["ncon", exact = TRUE]]) || bws[["ncon", exact = TRUE]] < 1L) {
    native.training <- if (training) .np_plot_plreg_lc_training_operator(bws, xdat) else NULL
    return(function(index) {
      if (!is.null(native.training)) return(native.training(index))
      .npreghat_complete(bws, txdat = xdat,
        exdat = evaluation[index, , drop = FALSE], output = "matrix")
    })
  }
  fit <- .np_regression_direct(bws, txdat = xdat, tydat = ydat,
                              exdat = exdat, fit.projection = TRUE)
  ingredients <- fit$fit.projection
  if (!is.list(ingredients) || length(ingredients) != 3L)
    stop("accepted plot fit projection is missing", call. = FALSE)
  function(index) {
    kw <- NULL
    if (!isTRUE(ingredients[[3L]])) {
      args <- list(bws = bws, txdat = xdat,
        exdat = evaluation[index, , drop = FALSE],
        return.kernel.weights = TRUE, bandwidth.divide = TRUE,
        .np.internal.bandwidth.divide.weights = TRUE)
      if (training && identical(bws[["type", exact = TRUE]], "generalized_nn"))
        args$.np.internal.eval.train.index <- as.integer(index)
      kw <- do.call(npksum, args)$kw
    }
    .Call("C_np_plot_projection_apply", ingredients[[1L]],
      .np_plot_projection_slice(ingredients[[2L]],index), kw, PACKAGE = "np")
  }
}

.np_plot_plreg_influence <- function(bws, xdat, ydat, zdat, exdat, ezdat,
                                     factor = FALSE, block.bytes = 4 * 1024^2,
                                     max.bytes = 64 * 1024^2, cache = NULL) {
  n <- nrow(xdat); p <- ncol(xdat); g <- nrow(exdat)
  bandwidths <- bws[["bw", exact = TRUE]]
  ydat <- .np_hat_response(ydat, bws[["ydati", exact = TRUE]])
  if (any(!is.finite(c(block.bytes, max.bytes))) ||
      length(block.bytes) != 1L || length(max.bytes) != 1L ||
      block.bytes <= 0 || max.bytes <= 0)
    stop("partially linear plot memory budgets must be positive and finite", call. = FALSE)
  widths <- vapply(bandwidths, function(bw) {
    spec <- npValidatedConditionalRegSpec(bw, where = "partially linear plot influence", ncon.field = "ncon")
    if (identical(spec$regtype.engine, "lc")) 1 else npLpBasisNcol(spec$basis.engine, spec$degree.engine)
  }, numeric(1L))
  width <- max(widths)
  setup <- 64 * n * (width + p + ncol(zdat) + 1) + 128 * (width^2 + p^2) + 64 * g * (p + width + 1)
  retained <- if (factor) 16 * as.double(g) * n else 0
  joint.unavailable <- NULL
  if (factor && max.bytes - setup - retained < 64 * as.double(n)) {
    factor <- FALSE
    retained <- 0
    joint.unavailable <- "partially linear joint influence exceeds the plot memory budget"
  }
  rows <- min(n, floor((max.bytes - setup - retained) / (64 * as.double(n))),
              max(1, floor(block.bytes / (64 * as.double(n)))))
  if (n < 2L || p < 1L || g < 1L || rows < 1 ||
      length(ydat) != n || any(!is.finite(ydat)))
    stop("partially linear plot influence exceeds its data or memory budget", call. = FALSE)
  nuisance.mean <- function(bw, response, evaluation = NULL) {
    # Match the fitted PL estimator's existing categorical-profile owner.
    out <- .np_regression_cat_profile_mean(bw, zdat, response, evaluation)
    if (!is.null(out)) return(as.vector(out))
    .np_regression_direct(bw, txdat = zdat, tydat = response,
                          exdat = evaluation)$mean
  }
  xnum <- function(dat, j, evaluation = FALSE) {
    if (!is.factor(dat[[j]])) return(as.double(dat[[j]]))
    yi <- bandwidths[[j + 1L]][["ydati", exact = TRUE]]
    adjusted <- .np_regression_response_levels(dat[, j, drop = FALSE], yi, allowNewCells = evaluation)
    yi$all.dlev[[1L]][as.integer(adjusted[[1L]])]
  }
  cached <- if (is.null(cache)) NULL else cache$training
  rx <- if (is.null(cached)) matrix(0, n, p) else cached$rx
  re <- matrix(0, g, p); formation <- numeric(p)
  for (j in seq_len(p)) {
    x <- xnum(xdat, j)
    if (is.null(cached)) {
      sx <- nuisance.mean(bandwidths[[j + 1L]], x)
      rx[, j] <- x - sx
      formation[j] <- .np_plreg_residual_formation_error(x, sx)
    }
    lx <- nuisance.mean(bandwidths[[j + 1L]], x, ezdat)
    re[, j] <- xnum(exdat, j, TRUE) - lx
  }
  if (is.null(cached)) {
    qrR <- qr(rx, tol = .Machine$double.eps)
    .np_plreg_check_residualized_rank(qrR, p, "partially linear plot influence", formation)
    # R^+ without an n-by-n identity or normal-equation inversion.
    B <- matrix(0, p, n)
    B[qrR$pivot, ] <- backsolve(qr.R(qrR), t(qr.Q(qrR)))
    yz <- bandwidths[["yzbw", exact = TRUE]]
    training <- .np_plot_response_residuals(yz, zdat, ydat, rows, rx, B,
      training.operator = .np_plot_plreg_operator(yz, zdat, ydat))
    K <- training$coefficient.map
    z <- training$residual
    if (!is.null(cache)) cache$training <- list(rx = rx, K = K, z = z)
  } else {
    K <- cached$K
    z <- cached$z
  }
  operator <- .np_plot_plreg_operator(
    bandwidths[["yzbw", exact = TRUE]], zdat, ydat, ezdat)
  influence <- if (factor) matrix(0, g, n) else NULL
  se <- mean <- numeric(g)
  for (start in seq.int(1L, g, by = rows)) {
    index <- seq.int(start, min(g, start + rows - 1L))
    H <- operator(index) + re[index, , drop = FALSE] %*% K
    mean[index] <- drop(H %*% ydat)
    A <- sweep(H, 2L, z, "*")
    se[index] <- sqrt(rowSums(A^2))
    if (factor) influence[index, ] <- A
  }
  list(mean = mean, se = se, influence = influence, residual = z, block.rows = rows,
       joint.unavailable = joint.unavailable)
}

# Calibration can be unavailable while some requested marginal bands still exist.
# Used by the density integration and partially linear availability contract.
.np_plot_joint_band_fields <- function(object, calibration = NULL, errors = NULL,
                                       component = NULL) {
  if (is.null(component)) {
    if (!is.null(calibration)) object$band.calibration <- calibration
    if (!is.null(errors)) object$band.errors <- errors
  } else {
    if (!is.null(calibration)) object$band.calibration[[component]] <- calibration
    if (!is.null(errors)) object$band.errors[[component]] <- errors
  }
  object
}

Try the np package in your browser

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

np documentation built on Nov. 25, 2026, 1:06 a.m.