R/np.conmode.R

Defines functions npconmode.default .npConmodeEvaluateLevels .npConmodeLevelBlockWidth .npConmodeNapredictArray .npConmodePadRowOutputs .npConmodeRecordSampleOmissions .npConmodeRecordEvalOmit .npConmodeRecordOmit .npConmodeNapredictRows .npConmodeOmitRows .npConmodeOmitLength .npConmodeSelectedFactor .npConmodeSelect .npConmodeProperProbabilities .npConmodeNormalizeProperControl .npConmodeProjectSimplexVector .npConmodeEffectiveProper npconmode.condbandwidth npconmode.call npconmode.formula .npConmodeValidateCategoricalResponse npconmode

Documented in npconmode npconmode.condbandwidth npconmode.default npconmode.formula

npconmode <-
  function(bws, ...){
    mc <- match.call(expand.dots = FALSE)
    .np_validate_public_dots(mc[["..."]], "npconmode")
    if (!missing(bws) && "na.action" %in% names(mc[["..."]]))
      .np_fit_na_preflight(bws, substitute(list(...))[-1L], environment(), "npconmode")
    args <- .np_formula_dispatch_args(
      NULL, substitute(list(...))[-1L], environment(),
      data.roles = c("txdat", "tydat"),
      call = sys.call(), caller = parent.frame())

    if (!missing(bws)){
      if (is.recursive(bws)){
        if (!is.null(bws$formula) && is.null(args$txdat))
          UseMethod("npconmode",bws$formula)
        else if (!is.null(bws$call) && is.null(args$txdat))
          UseMethod("npconmode",bws$call)
        else if (!is.call(bws))
          UseMethod("npconmode",bws)
        else
          UseMethod("npconmode",NULL)
      } else {
        UseMethod("npconmode", NULL)
      }
    } else {
      UseMethod("npconmode", NULL)
    }
  }

.npConmodeValidateCategoricalResponse <- function(tydat) {
  tydat <- toFrame(tydat)
  if (NCOL(tydat) != 1L)
    stop("'tydat' must consist of one (1) factor or ordered factor response",
         call. = FALSE)
  y <- tydat[[1L]]
  if (!is.factor(y))
    stop("npconmode requires a categorical response: supply 'tydat' as a factor or ordered factor",
         call. = FALSE)
  invisible(TRUE)
}

npconmode.formula <-
  function(bws, data = NULL, newdata = NULL, ..., se = FALSE){
    .np_reject_fit_subset(substitute(list(...))[-1L])
    .np_fit_na_preflight(bws, substitute(list(...))[-1L], environment(), "npconmode", data = data, newdata = newdata)

    se <- npValidateScalarLogical(se, "se")
    dots <- .np_formula_dispatch_args(
      NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE)
    frame.state <- dots[[".np.formula.state", exact = TRUE]]
    dots$.np.formula.state <- NULL
    dots$formula <- NULL

    tt <- terms(bws)
    m <- match(c("formula", "data", "subset", "na.action"),
               names(bws$call), nomatch = 0)
    tmf <- bws$call[c(1,m)]
    tmf[[1]] <- as.name("model.frame")
    tmf[["formula"]] <- tt
    if (!is.null(data))
      tmf[["data"]] <- data
    mf.args <- as.list(tmf)[-1L]
    umf <- tmf <- if (is.null(frame.state))
      .np_bws_formula_model_frame(bws, mf.args, data.override = !is.null(data), overrides = dots) else
        .np_formula_frame_take(frame.state)
    if ("tydat" %in% names(dots)) {
      umf <- tmf <- .np_formula_replace_response(tmf, bws, dots[["tydat"]],
                                                 dots, data.override = !is.null(data))
      dots$tydat <- NULL
      dots$na.action <- NULL
    }
    tt <- attr(tmf, "terms")
    bws <- .np_bws_retain_fit_frame(bws, tmf)
    train.omit <- attr(tmf, "na.action")

    tydat <- tmf[, bws$variableNames[["response"]], drop = FALSE]
    txdat <- tmf[, bws$variableNames[["terms"]], drop = FALSE]
    .npConmodeValidateCategoricalResponse(tydat)

    has.eval <- !is.null(newdata) && !("exdat" %in% names(dots))
    if (has.eval) {
      response <- if (!("eydat" %in% names(dots)))
        .np_diagnostics_response(newdata, tt = tt) else NULL
      has.ey <- !is.null(response)
      eval.tt <- .np_formula_conditional_rhs_terms(bws)
      npValidateNewdataFormula(newdata, eval.tt, include.response = FALSE)
      umf <- .np_diagnostics_model_frame(eval.tt, newdata)
      emf <- umf
      eval.omit <- attr(emf, "na.action")
      if ("eydat" %in% names(dots))
        dots$eydat <- .np_diagnostics_align_response(dots$eydat, emf)
      if (has.ey)
        eydat <- toFrame(.np_diagnostics_align_response(response, emf))

      exdat <- emf[, bws$variableNames[["terms"]], drop = FALSE]
    } else {
      eval.omit <- NULL
    }
    
    cm.args <- list(txdat = txdat, tydat = tydat, se = se)
    if (has.eval) {
      cm.args$exdat <- exdat
      if (has.ey)
        cm.args$eydat <- eydat
    }
    cm.args$bws <- bws
    dots$na.action <- NULL
    ev <- do.call(npconmode, c(cm.args, .np_formula_options(dots, "npconmode.formula")))

    output.omit <- .np_formula_output_action(ev, umf, has.eval, native.restored = TRUE)
    ev <- .npConmodeRecordSampleOmissions(ev, train.omit,
      if (has.eval) eval.omit else ev[["eval.omit", exact = TRUE]])
    ev <- .npConmodePadRowOutputs(ev, output.omit)

    return(ev)
  }

npconmode.call <-
  function(bws, ...) {
    .np_reject_fit_subset(substitute(list(...))[-1L])
    .np_fit_na_preflight(bws, substitute(list(...))[-1L], environment(), "npconmode", native = TRUE)

  .np_reject_native_data(substitute(list(...))[-1L])

    do.call(npconmode, .np_retained_training_args(
      bws, c(txdat = "xdat", tydat = "ydat"), .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE), npconmode.conbandwidth))
  }

npconmode.condbandwidth <-
  function(bws, ...){
    stop("incorrect bandwidth type: expected conditional density bandwidths instead of conditional distribution bandwidths",
         call. = FALSE)
  }

.npConmodeEffectiveProper <- function(bws, proper) {
  if (!is.null(proper)) {
    if (!is.logical(proper) || length(proper) != 1L || is.na(proper))
      stop("'proper' must be TRUE, FALSE, or NULL")
    return(proper)
  }

  reg.spec <- npConditionalRegEngineSpec(
    bws,
    where = "npconmode"
  )
  !identical(reg.spec$reg.engine, "lc")
}

.npConmodeProjectSimplexVector <- function(x) {
  u <- sort(x, decreasing = TRUE)
  cssv <- cumsum(u) - 1
  ind <- seq_along(u)
  keep <- which(u - cssv / ind > 0)
  if (!length(keep))
    return(rep(1 / length(x), length(x)))
  theta <- cssv[max(keep)] / max(keep)
  pmax(x - theta, 0)
}

.npConmodeNormalizeProperControl <- function(proper.control) {
  if (is.null(proper.control))
    return(list())
  if (!is.list(proper.control) || is.data.frame(proper.control))
    stop("'proper.control' must be a list")

  nms <- names(proper.control)
  if (is.null(nms))
    nms <- rep("", length(proper.control))
  bad <- nms == "" | !(nms %in% "tol")
  if (any(bad))
    stop(sprintf("unused argument%s in proper.control: %s",
                 if (sum(bad) == 1L) "" else "s",
                 paste(sQuote(nms[bad]), collapse = ", ")))

  proper.control
}

.npConmodeProperProbabilities <- function(pmat,
                                          levels,
                                          proper = TRUE,
                                          proper.control = list()) {
  if (!is.matrix(pmat) || !is.numeric(pmat))
    stop("internal error: conditional mode probabilities must be a numeric matrix")
  if (ncol(pmat) != length(levels))
    stop("internal error: probability matrix does not match the response support")

  proper.control <- .npConmodeNormalizeProperControl(proper.control)
  tol <- proper.control$tol
  if (is.null(tol))
    tol <- sqrt(.Machine$double.eps)
  if (!is.numeric(tol) || length(tol) != 1L || is.na(tol) || tol < 0)
    stop("'proper.control$tol' must be a non-negative scalar")

  raw <- pmat
  finite.row <- rowSums(is.finite(raw)) == ncol(raw)
  raw.rowsum <- rep(NA_real_, nrow(raw))
  raw.rowsum[finite.row] <- rowSums(raw[finite.row,, drop = FALSE])
  raw.min <- rep(NA_real_, nrow(raw))
  raw.min[finite.row] <- apply(raw[finite.row,, drop = FALSE], 1L, min)
  raw.neg.violation <- ifelse(is.na(raw.min), NA_real_, pmax(-raw.min, 0))

  repaired <- raw
  projection.distance <- rep(NA_real_, nrow(raw))
  invalid.rows <- !finite.row

  if (isTRUE(proper)) {
    for (i in which(finite.row)) {
      x <- raw[i,]
      if (any(x < -tol) || abs(sum(x) - 1) > tol) {
        repaired[i,] <- .npConmodeProjectSimplexVector(x)
      } else {
        repaired[i,] <- pmax(x, 0)
        repaired[i,] <- repaired[i,] / sum(repaired[i,])
      }
      projection.distance[i] <- max(abs(repaired[i,] - raw[i,]))
    }
  } else {
    projection.distance[finite.row] <- 0
  }

  repaired.rows <- isTRUE(proper) & is.finite(projection.distance) & projection.distance > tol
  repaired.rows[is.na(repaired.rows)] <- FALSE

  binary.complement.max <- NA_real_
  if (ncol(repaired) == 2L) {
    ok <- rowSums(is.finite(repaired)) == 2L
    if (any(ok))
      binary.complement.max <- max(abs(repaired[ok, 2L] - (1 - repaired[ok, 1L])))
  }

  colnames(repaired) <- as.character(levels)
  info <- list(
    reason = if (!isTRUE(proper)) "not_requested" else if (any(repaired.rows)) "projected" else "already_proper",
    tol = tol,
    nlevels = ncol(raw),
    invalid.rows = sum(invalid.rows),
    repaired.rows = sum(repaired.rows),
    max.negative.violation.raw = suppressWarnings(max(raw.neg.violation, na.rm = TRUE)),
    max.row.sum.deviation.raw = suppressWarnings(max(abs(raw.rowsum - 1), na.rm = TRUE)),
    max.projection.distance = suppressWarnings(max(projection.distance, na.rm = TRUE)),
    binary.complement.max.deviation = binary.complement.max
  )
  for (nm in c("max.negative.violation.raw", "max.row.sum.deviation.raw", "max.projection.distance")) {
    if (!is.finite(info[[nm]]))
      info[[nm]] <- NA_real_
  }

  list(
    probabilities = repaired,
    raw.probabilities = raw,
    repaired.rows = repaired.rows,
    proper.requested = isTRUE(proper),
    proper.applied = any(repaired.rows),
    proper.info = info
  )
}

.npConmodeSelect <- function(pmat, perr) {
  enrow <- nrow(pmat)
  nlev <- ncol(pmat)
  mdens <- rep(-Inf, enrow)
  mderr <- if (is.null(perr)) NULL else rep(NA_real_, enrow)
  indices <- integer(enrow)
  for (i in seq_len(nlev)) {
    tf <- is.finite(pmat[, i]) & pmat[, i] > 0 & pmat[, i] > mdens
    tf[is.na(tf)] <- FALSE
    indices[tf] <- i
    mdens[tf] <- pmat[tf, i]
    if (!is.null(perr))
      mderr[tf] <- perr[tf, i]
  }
  invalid <- indices == 0L
  mdens[invalid] <- NA_real_
  if (!is.null(perr))
    mderr[invalid] <- NA_real_
  list(indices = indices, condens = mdens, conderr = mderr)
}

.npConmodeSelectedFactor <- function(indices, levels, ordered = FALSE) {
  out <- rep(NA_character_, length(indices))
  valid <- indices > 0L
  out[valid] <- as.character(levels[indices[valid]])
  out <- .np_factor_with_levels(out, levels = as.character(levels), ordered = ordered)
  if (anyNA(levels)) is.na(out) <- !valid
  out
}

.npConmodeOmitLength <- function(omit) {
  if (is.null(omit)) 0L else length(omit)
}

.npConmodeOmitRows <- function(omit) {
  if (!.npConmodeOmitLength(omit)) NA_integer_ else as.vector(omit)
}

.npConmodeNapredictRows <- function(omit, x) {
  if (is.null(x) || !.npConmodeOmitLength(omit))
    return(x)
  if (!is.null(dim(x)) && length(dim(x)) >= 3L)
    return(.npConmodeNapredictArray(omit, x))

  omit <- as.integer(omit)
  keep <- seq_len(NROW(x) + length(omit))[-omit]
  if (is.factor(x)) {
    out <- .np_factor_with_levels(rep(NA_character_, length(x) + length(omit)),
                  levels = levels(x), ordered = is.ordered(x))
    if (anyNA(levels(x))) is.na(out) <- rep.int(TRUE, length(out))
    out[keep] <- x
    if (anyNA(levels(x))) is.na(out)[keep[is.na(x)]] <- TRUE
    attr(out, "na.action") <- NULL
    return(out)
  }
  if (is.data.frame(x)) {
    out <- x[rep(NA_integer_, nrow(x) + length(omit)), , drop = FALSE]
    out[keep, ] <- x
    attr(out, "na.action") <- NULL
    return(out)
  }
  if (is.null(dim(x))) {
    out <- x[rep(NA_integer_, length(x) + length(omit))]
    out[keep] <- x
    attr(out, "na.action") <- NULL
    return(out)
  }
  out <- x[rep(NA_integer_, nrow(x) + length(omit)), , drop = FALSE]
  out[keep, ] <- x
  attr(out, "na.action") <- NULL
  out
}

.npConmodeRecordOmit <- function(obj, omit) {
  obj$omit <- omit
  obj$rows.omit <- .npConmodeOmitRows(omit)
  obj$nobs.omit <- .npConmodeOmitLength(omit)
  obj
}

.npConmodeRecordEvalOmit <- function(obj, omit) {
  obj$eval.omit <- omit
  obj$eval.rows.omit <- .npConmodeOmitRows(omit)
  obj$eval.nobs.omit <- .npConmodeOmitLength(omit)
  obj
}

.npConmodeRecordSampleOmissions <- function(obj, train.omit, eval.omit = NULL) {
  obj$train.rows.omit <- .npConmodeOmitRows(train.omit)
  obj$train.nobs.omit <- .npConmodeOmitLength(train.omit)
  if (isTRUE(obj[["trainiseval", exact = TRUE]]))
    return(.npConmodeRecordOmit(obj, train.omit))
  obj <- .npConmodeRecordEvalOmit(obj, eval.omit)
  .npConmodeRecordOmit(obj, eval.omit)
}

.npConmodePadRowOutputs <- function(obj, omit) {
  if (!.npConmodeOmitLength(omit))
    return(obj)

  n <- length(obj$conmode)
  obj$conmode <- .npConmodeNapredictRows(omit, obj$conmode)
  obj$condens <- .npConmodeNapredictRows(omit, obj$condens)
  obj$conderr <- .npConmodeNapredictRows(omit, obj$conderr)
  if (!is.null(obj$xeval) && NROW(obj$xeval) == n) {
    obj$xeval <- .npConmodeNapredictRows(omit, obj$xeval)
    obj$nobs <- NROW(obj$xeval)
  }
  if (!is.null(obj$yeval) && NROW(obj$yeval) == n)
    obj$yeval <- .npConmodeNapredictRows(omit, obj$yeval)
  if (!is.null(obj$probabilities))
    obj$probabilities <- .npConmodeNapredictRows(omit, obj$probabilities)
  if (!is.null(obj$probability.errors))
    obj$probability.errors <- .npConmodeNapredictRows(omit, obj$probability.errors)
  if (!is.null(obj$probability.repaired.rows))
    obj$probability.repaired.rows <- .npConmodeNapredictRows(omit, obj$probability.repaired.rows)
  if (!is.null(obj$probability.gradients))
    obj$probability.gradients <- .npConmodeNapredictRows(omit, obj$probability.gradients)
  obj
}

.npConmodeNapredictArray <- function(omit, x) {
  if (is.null(x) || !length(omit))
    return(x)
  dx <- dim(x)
  if (is.null(dx) || length(dx) < 3L)
    return(napredict(omit, x))

  keep <- seq_len(dx[1L] + length(omit))[-as.integer(omit)]
  dn <- dimnames(x)
  if (!is.null(dn))
    dn[[1L]] <- NULL
  out <- array(NA_real_,
               dim = c(dx[1L] + length(omit), dx[-1L]),
               dimnames = dn)
  out[keep,,] <- x
  out
}

.npConmodeLevelBlockWidth <- function(enrow, xwidth, nlevels) {
  if (length(enrow) != 1L || is.na(enrow) || enrow < 1L ||
      length(xwidth) != 1L || is.na(xwidth) || xwidth < 0L ||
      length(nlevels) != 1L || is.na(nlevels) || nlevels < 1L)
    stop("internal error: invalid conditional-mode level-block dimensions")

  # Bound the temporary replicated evaluation frame independently of the
  # number of response levels.  The probability and error matrices are public
  # O(n_eval * nlevels) results already required by the estimator; this cap
  # prevents the batching workspace from adding an unbounded copy of them.
  target.cells <- floor((64 * 1024^2) / 8)
  cells.per.row <- max(1, as.double(xwidth) + 3)
  row.cap <- max(1, min(65536, floor(target.cells / cells.per.row)))
  max(1L, min(as.integer(nlevels), as.integer(floor(row.cap / enrow))))
}

.npConmodeEvaluateLevels <- function(bws,
                                      txdat,
                                      tydat,
                                      xeval,
                                      efac,
                                      gradients,
                                      gradient.level.index,
                                      direct.categorical.effects = FALSE,
                                      se = TRUE,
                                      allow.external = FALSE) {
  se <- npValidateScalarLogical(se, "se")
  allow.external <- npValidateScalarLogical(allow.external, "allow.external")
  enrow <- nrow(xeval)
  nlev <- nlevels(efac)
  block.width <- .npConmodeLevelBlockWidth(
    enrow = enrow,
    xwidth = ncol(xeval),
    nlevels = nlev
  )
  pmat <- matrix(NA_real_, enrow, nlev,
                 dimnames = list(NULL, levels(efac)))
  perr <- if (se) matrix(NA_real_, enrow, nlev,
                         dimnames = list(NULL, levels(efac))) else NULL
  pgrad <- if (isTRUE(gradients)) {
    matrix(NA_real_, nrow = enrow, ncol = bws$xndim,
           dimnames = list(NULL, bws$xnames))
  } else {
    NULL
  }

  ordinary.levels <- seq_len(nlev)
  if (isTRUE(gradients))
    ordinary.levels <- ordinary.levels[-gradient.level.index]
  ordinary.blocks <- if (length(ordinary.levels)) {
    starts <- seq.int(1L, length(ordinary.levels), by = block.width)
    lapply(starts, function(start) {
      ordinary.levels[seq.int(start,
                              min(length(ordinary.levels),
                                  start + block.width - 1L))]
    })
  } else {
    list()
  }
  blocks <- if (isTRUE(gradients)) {
    c(ordinary.blocks, list(gradient.level.index))
  } else {
    ordinary.blocks
  }
  empty.rows <- NULL

  for (block in blocks) {
    block.gradients <- isTRUE(gradients) &&
      length(block) == 1L && block[[1L]] == gradient.level.index
    eval.index <- rep.int(seq_len(enrow), times = length(block))
    dens.obj <- npcdens(
      txdat = txdat,
      tydat = tydat,
      exdat = xeval[eval.index,,drop = FALSE],
      eydat = rep(efac[block], each = enrow),
      bws = bws,
      gradients = block.gradients,
      se = se,
      .np_lp_first_se_demand = FALSE,
      .np_conditional_cat_se_demand = FALSE,
      .np_categorical_effects = !isTRUE(direct.categorical.effects),
      .np.require.complete = !allow.external,
      .np.defer.empty.rows = TRUE
    )

    expected <- as.double(enrow) * length(block)
    if (length(dens.obj$condens) != expected ||
        (se && length(dens.obj$conderr) != expected))
      stop("internal error: conditional-mode density block has invalid size")
    flags <- attr(dens.obj, ".np.empty.rows", exact = TRUE)
    if (!is.null(flags)) {
      if (!is.integer(flags) || length(flags) != expected ||
          anyNA(flags) || any(!flags %in% 0:1))
        stop("internal error: conditional-mode empty-row metadata is invalid",
             call. = FALSE)
      if (any(flags == 1L)) {
        block.empty <- integer(enrow)
        block.empty[eval.index[flags == 1L]] <- 1L
        empty.rows <- .npreg_merge_empty_rows(empty.rows, block.empty)
      }
    }
    pmat[, block] <- matrix(dens.obj$condens, nrow = enrow)
    if (se)
      perr[, block] <- matrix(dens.obj$conderr, nrow = enrow)

    if (block.gradients) {
      if (is.null(dens.obj$congrad))
        stop("internal error: conditional-density gradient was not returned")
      pgrad[,] <- dens.obj$congrad
    }
  }

  out <- list(probabilities = pmat, errors = perr, gradients = pgrad)
  if (!is.null(empty.rows)) attr(out, ".np.empty.rows") <- empty.rows
  out
}


npconmode.conbandwidth <-
  function (bws,
            txdat = stop("invoked without training data 'txdat'"),
            tydat = stop("invoked without training data 'tydat'"),
            exdat, eydat,
            proper = NULL,
            proper.control = list(),
            probabilities = FALSE,
            gradients = FALSE,
            level = NULL,
            ..., se = FALSE){
    .np_reject_fit_subset(substitute(list(...))[-1L])
    .np_fit_na_preflight(bws, substitute(list(...))[-1L], environment(), "npconmode", native = TRUE)

  .np_reject_native_data(substitute(list(...))[-1L])


    se <- npValidateScalarLogical(se, "se")
    probabilities <- npValidateScalarLogical(probabilities, "probabilities")
    gradients <- npValidateScalarLogical(gradients, "gradients")
    txdat = toFrame(txdat)
    tydat = toFrame(tydat)
    .np_require_paired_rows(txdat, tydat, "txdat", "tydat")
    bws <- .np_bws_retain_native_training(bws, xdat = txdat, ydat = tydat)

    native.newdata <- .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE)[["newdata", exact = TRUE]]
    if (missing(exdat) && !is.null(native.newdata)) {
      native.eval <- .np_native_newdata_parts(
        native.newdata, list(exdat = bws$xnames), "npconmode")
      exdat <- native.eval$exdat
      if (missing(eydat)) {
        response <- .np_diagnostics_response(native.newdata, ynames = bws$ynames)
        if (!is.null(response)) eydat <- toFrame(response)
      }
    }

    no.ex = missing(exdat)
    no.ey = missing(eydat)

    if (!no.ex)
      exdat = toFrame(exdat)

    if (!no.ey)
      eydat = toFrame(eydat)

    if (!no.ex && !no.ey)
      .np_require_paired_rows(exdat, eydat, "exdat", "eydat")

    ## catch and destroy NA's
    keep.rows <- rep_len(TRUE, nrow(txdat))
    train.omit <- attr(na.omit(data.frame(txdat, tydat)), "na.action")
    if (.npConmodeOmitLength(train.omit) > 0L)
      keep.rows[as.integer(train.omit)] <- FALSE

    if (!any(keep.rows))
      stop("Training data has no rows without NAs")

    txdat <- .np_data_rows(txdat, keep.rows)
    tydat <- .np_data_rows(tydat, keep.rows)

    if (!no.ex){
      keep.eval <- rep_len(TRUE, nrow(exdat))
      eval.df <- data.frame(exdat)
      eval.omit <- attr(na.omit(eval.df), "na.action")
      if (.npConmodeOmitLength(eval.omit) > 0L)
        keep.eval[as.integer(eval.omit)] <- FALSE

      exdat <- .np_data_rows(exdat, keep.eval)

      if (!no.ey)
        eydat <- .np_data_rows(eydat, keep.eval)

      if (!any(keep.eval))
        stop("Evaluation data has no rows without NAs")
    } else {
      eval.omit <- NULL
    }


    tnrow = dim(txdat)[1]
    enrow = if (no.ex) tnrow else dim(exdat)[1]

    if (!no.ey && no.ex)
      stop("npconmode: invalid invocation: 'eydat' provided but not 'exdat'")

    if (bws$yndim != 1 || bws$yncon > 0)
      stop("'tydat' must consist of one (1) discrete variable")

    # Evaluation outcomes own goodness-of-fit diagnostics, never the fitted
    # response support or the probability projection domain.
    efac <- .np_factor_with_levels(
      bws$ydati$all.lev[[1]], levels = bws$ydati$all.lev[[1]],
      ordered = is.ordered(tydat[,1]))

    nlev <- nlevels(efac)
    level.values <- levels(efac)
    if (is.null(level)) {
      gradient.level <- level.values[1L]
    } else {
      if (length(level) != 1L || is.na(level) ||
          !(as.character(level) %in% level.values))
        stop("'level' must identify one response level in the fitted conmode object")
      gradient.level <- as.character(level)
    }
    gradient.level.index <- match(gradient.level, level.values)
    if (isTRUE(gradients)) {
      if (bws$xndim < 1L)
        stop("npconmode class-probability gradients/effects require at least one conditioning variable")
    }
    reg.spec <- npConditionalRegEngineSpec(
      bws,
      where = "npconmode categorical effects"
    )
    direct.categorical.effects <- npGlpCategoricalEffectsRequired(
      regtype.engine = reg.spec$reg.engine,
      degree.engine = reg.spec$degree.engine,
      ncat = bws$xnuno + bws$xnord,
      gradients = gradients
    )
    xeval <- if (no.ex) txdat else exdat
    level.fit <- .npConmodeEvaluateLevels(
      bws = bws,
      txdat = txdat,
      tydat = tydat,
      xeval = xeval,
      efac = efac,
      gradients = gradients,
      gradient.level.index = gradient.level.index,
      direct.categorical.effects = direct.categorical.effects,
      se = se,
      allow.external = !no.ex
    )
    empty.rows <- attr(level.fit, ".np.empty.rows", exact = TRUE)
    pmat <- level.fit$probabilities
    perr <- level.fit$errors
    pgrad <- level.fit$gradients

    proper.effective <- .npConmodeEffectiveProper(bws, proper)
    proper.out <- .npConmodeProperProbabilities(
      pmat,
      levels = levels(efac),
      proper = proper.effective,
      proper.control = proper.control
    )
    if (isTRUE(direct.categorical.effects)) {
      eval.probability <- function(z) {
        endpoint.fit <- .npConmodeEvaluateLevels(
          bws = bws,
          txdat = txdat,
          tydat = tydat,
          xeval = z,
          efac = efac,
          gradients = FALSE,
          gradient.level.index = gradient.level.index,
          se = FALSE,
          allow.external = !no.ex
        )
        empty.rows <<- .npreg_merge_empty_rows(
          empty.rows, attr(endpoint.fit, ".np.empty.rows", exact = TRUE))
        endpoint.proper <- .npConmodeProperProbabilities(
          endpoint.fit$probabilities,
          levels = levels(efac),
          proper = proper.effective,
          proper.control = proper.control
        )
        endpoint.proper$probabilities[, gradient.level.index]
      }
      cat.idx <- which(bws$ixuno | bws$ixord)
      for (jj in cat.idx) {
        frames <- npCategoricalFirstDifferenceFrames(
          exdat = xeval,
          index = jj,
          where = "npconmode"
        )
        pgrad[, jj] <- eval.probability(frames$upper) -
          eval.probability(frames$lower)
      }
    }
    select <- .npConmodeSelect(proper.out$probabilities, perr)
    indices <- select$indices
    mdens <- select$condens
    mderr <- select$conderr
    if (se)
      mderr[proper.out$repaired.rows] <- NA_real_
    cm.args <- list(
      bws = bws,
      xeval = if (no.ex) txdat else exdat,
      conmode = .npConmodeSelectedFactor(indices, efac, ordered = is.ordered(efac)),
      condens = mdens,
      conderr = mderr,
      ntrain = nrow(txdat),
      trainiseval = no.ex,
      proper.requested = proper.out$proper.requested,
      proper.applied = proper.out$proper.applied,
      proper.info = proper.out$proper.info,
      proper.control = proper.control,
      se = se,
      gradients = gradients
    )
    if (isTRUE(probabilities) || isTRUE(gradients)) {
      cm.args$probabilities <- proper.out$probabilities
      cm.args$probability.levels <- efac
      cm.args$probability.errors <- perr
      if (se)
        cm.args$probability.errors[proper.out$repaired.rows, ] <- NA_real_
      cm.args$probability.repaired.rows <- proper.out$repaired.rows
      if (!no.ex) {
        cm.args$xtrain <- txdat
        cm.args$ytrain <- tydat
      }
    }
    if (isTRUE(gradients)) {
      cm.args$probability.gradients <- pgrad
      cm.args$probability.gradient.level <- gradient.level
      cm.args$probability.gradient.names <- bws$xnames
      cm.args$probability.gradient.info <- list(
        target = "class probability",
        response = if (nlev == 2L) "binary" else "multinomial",
        level = gradient.level,
        default.level = level.values[1L],
        semantics = "smooth class-probability gradients/effects for one selected response level"
      )
    }
    if (!(no.ey && !no.ex))
      cm.args$yeval <- if (no.ey) tydat else eydat
    con.mode <- do.call(conmode, cm.args)
    con.mode <- .np_conditional_policy_stamp(con.mode)
    
    score.y <- if (no.ex) tydat[,1] else if (!no.ey) eydat[,1] else NULL
    score.keep <- if (is.null(score.y)) rep_len(FALSE, enrow) else
      !is.na(score.y) & !is.na(con.mode$conmode)
    con.mode$diagnostics.nobs <- sum(score.keep)
    con.mode$diagnostics.sample <- if (!any(score.keep)) "unavailable" else
      if (no.ex) "training" else "evaluation"
    if (any(score.keep)) {
      confusion.matrix <- 
        table(factor(score.y[score.keep], exclude = NULL),
              factor(con.mode$conmode[score.keep],exclude = NULL), dnn=c("Actual", "Predicted"))

      cj <- match(levels(factor(score.y[score.keep], exclude = NULL)),
                  levels(factor(con.mode$conmode[score.keep],exclude = NULL)), nomatch = 0)
      rj <- cj > 0

      t.diag <- cj
      t.diag[rj] <-  diag(confusion.matrix[rj,cj,drop=FALSE])
      
      CCR.overall <- sum(t.diag)/sum(score.keep)
      
      CCR.byoutcome <- t.diag/rowSums(confusion.matrix)
      names(CCR.byoutcome) <- levels(factor(score.y[score.keep], exclude = NULL))

      con.mode$confusion.matrix <- confusion.matrix
      con.mode$CCR.overall <- CCR.overall
      con.mode$CCR.byoutcome <- CCR.byoutcome

      confusion.matrix <- confusion.matrix/sum(score.keep)
      t.diag <- t.diag/sum(score.keep)

      fit.mcfadden <- sum(t.diag) - (sum(confusion.matrix^2)-sum(t.diag^2))
      con.mode$fit.mcfadden <- fit.mcfadden
    }
    con.mode <- .npConmodeRecordSampleOmissions(con.mode, train.omit, eval.omit)
    if (no.ex) {
      con.mode <- .npConmodePadRowOutputs(con.mode, train.omit)
    } else {
      con.mode <- .npConmodePadRowOutputs(con.mode, eval.omit)
    }
    .npreg_finish_empty_rows(con.mode, empty.rows,
      omitted = if (no.ex) train.omit else eval.omit,
      owner = "npconmode", row.labels = rownames(xeval))
  }

npconmode.default <- function(bws, txdat, tydat,
                              nomad = FALSE,
                              proper = NULL,
                              proper.control = list(),
                              probabilities = FALSE,
                              gradients = FALSE,
                              level = NULL,
                              ..., se = FALSE){
  se <- npValidateScalarLogical(se, "se")
  nomad <- npValidateNomadControl(nomad, "nomad")
  probabilities <- npValidateScalarLogical(probabilities, "probabilities")
  gradients <- npValidateScalarLogical(gradients, "gradients")
  sc <- .np_formula_default_call(sys.call(), sys.function(), parent.frame())
  sc.names <- names(sc)

  ## here we check to see if the function was called with tdat =
  ## if it was, we need to catch that and map it to dat =
  ## otherwise the call is passed unadulterated to npudensbw

  bws.named <- any(sc.names == "bws")
  txdat.named <- any(sc.names == "txdat")
  tydat.named <- any(sc.names == "tydat")

  no.bws <- missing(bws)
  no.txdat <- missing(txdat)
  no.tydat <- missing(tydat)
  has.explicit.bws <- (!no.bws) && isa(bws, "conbandwidth")

  ## if bws was passed in explicitly, do not compute bandwidths
    
  if(txdat.named || (bws.named && !no.txdat && !inherits(txdat, "formula"))) {
    if ("data" %in% sc.names)
      .np_data_argument_preflight(substitute(txdat), "txdat", sys.call(), parent.frame(), value = txdat)
    # Keep the caller's vector name; explicit frame/matrix names are authoritative.
    original.name <- if (is.null(dim(txdat)))
      paste(deparse(.np_formula_dot_expression(substitute(txdat), parent.frame())), collapse = "") else NULL
    txdat <- toFrame(txdat)
    if (!is.null(original.name)) names(txdat) <- original.name
  }

  if(tydat.named) {
    if ("data" %in% sc.names)
      .np_data_argument_preflight(substitute(tydat), "tydat", sys.call(), parent.frame(), value = tydat)
    # Keep the caller's vector name; explicit frame/matrix names are authoritative.
    original.name <- if (is.null(dim(tydat)))
      paste(deparse(.np_formula_dot_expression(substitute(tydat), parent.frame())), collapse = "") else NULL
    tydat <- toFrame(tydat)
    if (!is.null(original.name)) names(tydat) <- original.name
  }

  if(!no.tydat) {
    if(!tydat.named) {
      original.name <- if (is.null(dim(tydat)))
        paste(deparse(.np_formula_dot_expression(substitute(tydat), parent.frame())), collapse = "") else NULL
      tydat <- toFrame(tydat)
      if (!is.null(original.name)) names(tydat) <- original.name
    }
    .npConmodeValidateCategoricalResponse(tydat)
  }

  sc.bw <- sc
  
  sc.bw[[1]] <- quote(npcdensbw)
  sc.bw$proper <- NULL
  sc.bw$proper.control <- NULL
  sc.bw$probabilities <- NULL
  sc.bw$gradients <- NULL
  sc.bw$se <- NULL
  sc.bw$level <- NULL
  sc.bw$newdata <- NULL
  sc.bw$exdat <- NULL
  sc.bw$eydat <- NULL

  bws.formula <- (!no.bws) && inherits(bws, "formula")
  if (bws.formula) {
    ib <- match("bws", names(sc.bw), nomatch = 0L)
    if (ib > 0L) names(sc.bw)[ib] <- "formula"
  }

  if(bws.named && !bws.formula){
    sc.bw$bandwidth.compute <- FALSE
  }

  ostxy <- c('txdat','tydat')
  nstxy <- c('xdat','ydat')
  
  m.txy <- match(ostxy, names(sc.bw), nomatch = 0)

  if(any(m.txy > 0)) {
    names(sc.bw)[m.txy] <- nstxy[m.txy > 0]
  }
  sc.bw <- .np_public_dots_filter_call(sc.bw, "npcdensbw")

  formula.input <- .np_formula_dispatch_args(
    NULL, substitute(list(...))[-1L], environment())[["formula", exact = TRUE]]
  training.formula <- if (bws.formula) bws else
    if (!no.txdat && inherits(txdat, "formula")) txdat else formula.input
  frame.state <- if (!has.explicit.bws && inherits(training.formula, "formula"))
    new.env(parent = emptyenv()) else NULL
  if (!is.null(frame.state)) {
    if (length(training.formula) < 3L)
      stop("npconmode requires a categorical response in the formula",
           call. = FALSE)
    response.names <- all.vars(training.formula[[2L]])
    frame.state$validate.training <- function(frame)
      .npConmodeValidateCategoricalResponse(frame[, response.names, drop = FALSE])
    sc.bw$.np.formula.state <- frame.state
    on.exit(rm(list = ls(frame.state, all.names = TRUE), envir = frame.state), add = TRUE)
  }

  use.outer.bandwidth.progress <- !.np_bw_call_uses_nomad_degree_search(
    sc.bw,
    caller_env = parent.frame()
  )

  tbw <- if (!has.explicit.bws) {
    if (use.outer.bandwidth.progress) {
      .np_progress_select_bandwidth_enhanced(
        "Selecting conditional density bandwidth",
        .np_eval_bw_call(sc.bw, caller_env = parent.frame(),
                        native.map = c(bws = "bws", xdat = "txdat", ydat = "tydat"), native.frame = environment(),
                        formula.value = .np_formula_value(formula.input, bws, txdat))
      )
    } else {
        .np_eval_bw_call(sc.bw, caller_env = parent.frame(),
                        native.map = c(bws = "bws", xdat = "txdat", ydat = "tydat"), native.frame = environment(),
                        formula.value = .np_formula_value(formula.input, bws, txdat))
    }
  } else {
        .np_eval_bw_call(sc.bw, caller_env = parent.frame(),
                        native.map = c(bws = "bws", xdat = "txdat", ydat = "tydat"), native.frame = environment(),
                        formula.value = .np_formula_value(formula.input, bws, txdat))
  }

  call.args <- list(bws = tbw)
  if (!is.null(frame.state)) call.args$.np.formula.state <- frame.state
  if (no.bws) {
    if (is.null(frame.state)) {
      call.args$txdat <- txdat
      call.args$tydat <- tydat
    }
  } else {
    if (txdat.named) call.args$txdat <- txdat
    if (tydat.named) call.args$tydat <- tydat
    if ((!bws.named) && (!txdat.named) && (!no.tydat) && (!tydat.named)) {
      call.args <- c(call.args, list(tydat))
    }
  }
  call.args$proper <- proper
  call.args$proper.control <- proper.control
  call.args$probabilities <- probabilities
  call.args$gradients <- gradients
  call.args$se <- se
  call.args$level <- level
  fit.dots <- if (!is.null(tbw[["formula", exact = TRUE]]))
    .np_formula_options(.np_formula_dispatch_args(
      NULL, substitute(list(...))[-1L], environment()), "npconmode.default")
  else .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE)
  if (!is.null(tbw[["formula", exact = TRUE]]))
    call.args <- .np_formula_options(call.args, "npconmode.default")
  do.call(npconmode, c(call.args, fit.dots))
}

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.