R/np.distribution.R

Defines functions npudist.default npudist.dbandwidth npudist.call npudist.formula npudist

Documented in npudist npudist.dbandwidth npudist.default npudist.formula

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

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


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


    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 (!missing(data) && !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 = !missing(data) && !is.null(data), overrides = dots) else
        .np_formula_frame_take(frame.state)
    tt <- attr(tmf, "terms")
    bws <- .np_bws_retain_fit_frame(bws, tmf)

    tdat <- tmf[, .np_formula_term_names(attr(attr(tmf, "terms"),"term.labels")), drop = FALSE]

    has.eval <- !is.null(newdata) && !("edat" %in% names(dots))
    if (has.eval) {
      npValidateNewdataFormula(newdata, tt, include.response = TRUE)
      umf.args <- list(formula = tt, data = newdata)
      umf <- do.call(.np_formula_model_frame, umf.args, envir = parent.frame())
      emf <- umf

      edat <- emf[, .np_formula_term_names(attr(attr(emf, "terms"),"term.labels")), drop = FALSE]
    }
    
    ud.args <- list(tdat = tdat)
    if (has.eval)
      ud.args$edat <- edat
    ud.args$bws <- bws
    dots$na.action <- NULL
    ev <- do.call(npudist, c(ud.args, .np_formula_options(dots, "npudist.formula")))

    ev$omit <- .np_formula_output_action(ev, umf, has.eval)
    ev$rows.omit <- as.vector(ev$omit)
    ev$nobs.omit <- length(ev$rows.omit)

    ev$dist <- napredict(ev$omit, ev$dist)
    if (isTRUE(ev[["se", exact = TRUE]]))
      ev$derr <- napredict(ev$omit, ev$derr)

    return(ev)
  }

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

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

    do.call(npudist, .np_retained_training_args(
      bws, c(tdat = "dat"), .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE), npudist.dbandwidth))
  }

npudist.dbandwidth <-
  function(bws,
           tdat = stop("invoked without training data 'tdat'"),
           edat, ..., se = FALSE){
    .np_reject_fit_subset(substitute(list(...))[-1L])
    .np_fit_na_preflight(bws, substitute(list(...))[-1L], environment(), "npudist", native = TRUE)

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


    se <- npValidateScalarLogical(se, "se")
    ann.se <- se && identical(bws[["type", exact = TRUE]], "adaptive_nn") &&
      bws[["ncon", exact = TRUE]] > 0L
    dots <- .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE)
    fit.start <- proc.time()[3]
    fit.progress.handoff <- isTRUE(dots$.np_fit_progress_handoff)

    native.newdata <- dots[["newdata", exact = TRUE]]
    if (missing(edat) && !is.null(native.newdata)) {
      native.eval <- .np_native_newdata_parts(
        native.newdata, list(edat = bws$xnames), "npudist")
      edat <- native.eval$edat
    }

    no.e = missing(edat)

    tdat.was.vector <- is.atomic(tdat) && is.null(dim(tdat))
    tdat = .np_native_vector_frame_names(toFrame(tdat), tdat.was.vector, bws)
    bws <- .np_bws_retain_native_training(bws, dat = tdat)

    if (!no.e)
      edat = toFrame(edat)

    if (!(no.e || tdat %~% edat ))
      stop("tdat and edat are not similar data frames!")

    if (length(bws$bw) != length(tdat))
      stop("length of bandwidth vector does not match number of columns of 'tdat'")

    beta.kernel <- identical(bws[["ckertype", exact = TRUE]], "beta")
    npValidateBetaKernelSpecification(
      ckertype = bws[["ckertype", exact = TRUE]],
      ckerorder = bws[["ckerorder", exact = TRUE]],
      bwtype = bws[["type", exact = TRUE]],
      ckerbound = bws[["ckerbound", exact = TRUE]],
      ckerlb = bws[["ckerlb", exact = TRUE]],
      ckerub = bws[["ckerub", exact = TRUE]],
      dati = bws[["xdati", exact = TRUE]],
      bw = bws[["bw", exact = TRUE]],
      bandwidth.compute = FALSE,
      where = "beta distribution",
      allow.categorical = TRUE
    )

    if ((any(bws$icon) &&
         !all(vapply(as.data.frame(tdat[, bws$icon]), inherits, logical(1), c("integer", "numeric")))) ||
        (any(bws$iord) &&
         !all(vapply(as.data.frame(tdat[, bws$iord]), inherits, logical(1), "ordered"))) ||
        (any(bws$iuno) &&
         !all(vapply(as.data.frame(tdat[, bws$iuno]), inherits, logical(1), "factor"))))
      stop("supplied bandwidths do not match 'tdat' in type")

    npValidateExtendedNnContinuousBandwidth(bws, where = "npudist")

    if(any(bws$iuno))
      stop("distribution estimation does not support unordered data types")

    tdat = na.omit(tdat)
    train.rows.omit <- unclass(na.action(tdat))
    if (nrow(tdat) == 0L)
      stop("Data has no rows without NAs")
    rows.omit <- train.rows.omit
    eval.rows.omit <- integer(0)

    if (!no.e){
      edat = na.omit(edat)
      eval.rows.omit <- unclass(na.action(edat))
      if (nrow(edat) == 0L)
        stop("Evaluation data has no rows without NAs")
      rows.omit <- eval.rows.omit
    }

    tnrow = nrow(tdat)
    enrow = (if (no.e) tnrow else nrow(edat))

    ## re-assign levels in training and evaluation data to ensure correct
    ## conversion to numeric type.
    
    tdat <- adjustLevels(tdat, bws$xdati)
    
    if (!no.e)
      edat <- adjustLevels(edat, bws$xdati, allowNewCells = TRUE)

    if (!no.e)
      npKernelBoundsCheckEval(edat, bws$icon, bws$ckerlb, bws$ckerub, argprefix = "cker")

    ## grab the evaluation data before it is converted to numeric
    if(no.e)
      teval <- tdat
    else
      teval <- edat

    ## put the unordered, ordered, and continuous data in their own objects
    ## data that is not a factor is continuous.
    
    if (ann.se) ann.training <- tdat
    tdat = toMatrix(tdat)

    tuno = tdat[, bws$iuno, drop = FALSE]
    tcon = tdat[, bws$icon, drop = FALSE]
    tord = tdat[, bws$iord, drop = FALSE]

    if (!no.e){
      edat = toMatrix(edat)

      euno = edat[, bws$iuno, drop = FALSE]
      econ = edat[, bws$icon, drop = FALSE]
      eord = edat[, bws$iord, drop = FALSE]

    } else {
      euno = data.frame()
      eord = data.frame()
      econ = data.frame()
    }

    physical.bw <- .np_physical_bandwidth(bws)
    myopti = list(
      num_obs_train = tnrow,
      num_obs_eval = enrow,
      num_uno = bws$nuno,
      num_ord = bws$nord,
      num_con = bws$ncon,
      int_LARGE_SF = SF_ARB,
      BANDWIDTH_den_extern = switch(bws$type,
        fixed = BW_FIXED,
        generalized_nn = BW_GEN_NN,
        adaptive_nn = BW_ADAP_NN),
      int_MINIMIZE_IO=if (isTRUE(getOption("np.messages"))) IO_MIN_FALSE else IO_MIN_TRUE,
      ckerneval = switch(bws$ckertype,
        gaussian = CKER_GAUSS + bws$ckerorder/2 - 1,
        epanechnikov = CKER_EPAN + bws$ckerorder/2 - 1,
        uniform = CKER_UNI,
        beta = CKER_COORDINATE
),
      ukerneval = switch(bws$ukertype,
        aitchisonaitken = UKER_AIT,
        liracine = UKER_LR),
      okerneval = switch(bws$okertype,
        wangvanryzin = OKER_WANG,
        liracine = OKER_NLR,
        "racineliyan" = OKER_RLY),
      no.e = no.e,
      mcv.numRow = attr(bws$xmcv, "num.row"),
      densOrDist = NP_DO_DIST,
      old.dist = FALSE,
      int_do_tree = if (beta.kernel) DO_TREE_NO else
        npDoTreeOrCategoricalCompress(ncon = bws$ncon,
                                      ncat = bws$nuno + bws$nord,
                                      bws = bws))
    myopti <- c(myopti, npContinuousKernelDescriptorOptions(bws))
    if (beta.kernel)
      myopti <- c(
        myopti,
        categorical.compress = npStrictLogicalOption(
          "np.categorical.compress", TRUE
        )
      )
    cker.bounds.c <- npKernelBoundsMarshal(bws$ckerlb[bws$icon], bws$ckerub[bws$icon])

    myout <- .np_with_nn_radius_context(.np_with_compiled_fit_progress(
      label = "Fitting distribution",
      total = .np_densdist_fit_total(bws = bws, tnrow = tnrow, enrow = enrow),
      handoff = fit.progress.handoff,
      handoff.detail = if (fit.progress.handoff) "starting" else NULL,
      .Call("C_np_density",
            as.double(tuno), as.double(tord), as.double(tcon),
            as.double(euno), as.double(eord), as.double(econ),
            as.double(c(physical.bw[bws$icon], physical.bw[bws$iuno], physical.bw[bws$iord])),
            as.double(bws$xmcv), as.double(attr(bws$xmcv, "pad.num")),
            as.double(bws$nconfac), as.double(bws$ncatfac), as.double(bws$sdev),
            as.integer(myopti),
            as.integer(enrow),
            as.double(cker.bounds.c$lb),
            as.double(cker.bounds.c$ub),
            se && !ann.se,
            PACKAGE = "np")
    ), continuous.names = bws[["xnames", exact = TRUE]][bws[["icon", exact = TRUE]]])
    names(myout)[1] <- "dist"

    if (ann.se)
      myout$derr <- .np_ann_unconditional_se(bws, ann.training, teval, density = FALSE)
    fit.elapsed <- proc.time()[3] - fit.start
    optim.time <- if (!is.null(bws$total.time) && is.finite(bws$total.time)) as.double(bws$total.time) else NA_real_
    total.time <- fit.elapsed + (if (is.na(optim.time)) 0.0 else optim.time)

    ev <- npdistribution(bws=bws, eval=teval, dist = myout$dist,
                         derr = myout$derr, ntrain = tnrow, trainiseval = no.e,
                         rows.omit = rows.omit,
                         train.rows.omit = train.rows.omit,
                         eval.rows.omit = eval.rows.omit,
                         timing = bws$timing, total.time = total.time,
                         optim.time = optim.time, fit.time = fit.elapsed, se = se)
    return(ev)
  }

npudist.default <- function(bws, tdat, ..., se = FALSE){
  se <- npValidateScalarLogical(se, "se")
  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")
  tdat.named <- any(sc.names == "tdat")

  no.bws <- missing(bws)
  no.tdat <- missing(tdat)
  has.explicit.bws <- (!no.bws) && isa(bws, "dbandwidth")
  bws.formula <- (!no.bws) && inherits(bws, "formula")
  direct.formula.tdat <- (!no.tdat) && !tdat.named &&
    inherits(tdat, "formula") && bws.named && !has.explicit.bws

  if (bws.named && no.tdat && bws.formula) {
    sc$`bws` <- NULL
    sc$formula <- bws
    sc.bw <- sc
    sc.bw[[1]] <- quote(npudistbw)
    bws.named <- FALSE
  } else {
    sc.bw <- sc
    sc.bw[[1]] <- quote(npudistbw)
  }

  ## if bws was passed in explicitly, do not compute bandwidths
    
  if(tdat.named) {
    if ("data" %in% sc.names)
      .np_data_argument_preflight(substitute(tdat), "tdat", sys.call(), parent.frame(), value = tdat)
    # Preserve vector syntax before coercion gives it the formal's name.
    original.name <- if (is.null(dim(tdat)))
      paste(deparse(.np_formula_dot_expression(substitute(tdat), parent.frame())), collapse = "") else NULL
    tdat <- toFrame(tdat)
    if (!is.null(original.name)) names(tdat) <- original.name
  }

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

  ostxy <- c('tdat')
  nstxy <- c('dat')
  
  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, "npudistbw")
  formula.input <- .np_formula_dispatch_args(
    NULL, substitute(list(...))[-1L], environment())[["formula", exact = TRUE]]
  frame.state <- if (!has.explicit.bws &&
      ((!no.bws && inherits(bws, "formula")) || direct.formula.tdat ||
       inherits(formula.input, "formula"))) new.env(parent = emptyenv()) else NULL
  if (!is.null(frame.state)) {
    sc.bw$.np.formula.state <- frame.state
    on.exit(rm(list = ls(frame.state, all.names = TRUE), envir = frame.state), add = TRUE)
  }
    
  tbw <- if (!has.explicit.bws) {
    .np_progress_select_bandwidth_enhanced(
      "Selecting distribution bandwidth",
        .np_eval_bw_call(sc.bw, caller_env = parent.frame(),
                        native.map = c(bws = "bws", dat = "tdat"), native.frame = environment(),
                        formula.value = .np_formula_value(formula.input, bws, tdat, "dat"))
    )
  } else {
        .np_eval_bw_call(sc.bw, caller_env = parent.frame(),
                        native.map = c(bws = "bws", dat = "tdat"), native.frame = environment(),
                        formula.value = .np_formula_value(formula.input, bws, tdat, "dat"))
  }

  ## convention: first argument is always dropped, second, if present, propagated
  call.args <- list(bws = tbw, se = se)
  if (!is.null(frame.state)) call.args$.np.formula.state <- frame.state
  if (!no.tdat && !direct.formula.tdat) {
    if (tdat.named) {
      call.args$tdat <- tdat
    } else {
      call.args <- c(call.args, list(tdat))
    }
  }
  if (!has.explicit.bws)
    call.args$.np_fit_progress_handoff <- TRUE
  fit.dots <- if (!is.null(tbw[["formula", exact = TRUE]]))
    .np_formula_options(.np_formula_dispatch_args(
      NULL, substitute(list(...))[-1L], environment()), "npudist.default")
  else .np_formula_dispatch_args(NULL, substitute(list(...))[-1L], environment(), omit.subset = FALSE)
  do.call(npudist, 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.