code
stringlengths
1
13.8M
GetRowCol <- function(Index, dim1, dim2) { Col1 <- ceiling(Index / dim1) Row1 <- Index - (Col1 - 1) * dim1 return(c(Row1, Col1)) }
context("mz_bbox") test_that("mz_bbox gets bounding box for vector tiles", { bbox <- mz_bbox(ca_tiles) expect_is(bbox, "data.frame") expect_true(setequal( names(bbox), c("min_lon", "min_lat", "max_lon", "max_lat") )) sdlon <- -117.1534 sdlat <- 32.80151 saclon <- -121.4668 saclat <- 38.57873 expect_lt(bbox$min_lon, sdlon) expect_gt(bbox$max_lon, sdlon) expect_lt(bbox$min_lat, sdlat) expect_gt(bbox$max_lat, sdlat) expect_lt(bbox$min_lon, saclon) expect_gt(bbox$max_lon, saclon) expect_lt(bbox$min_lat, saclat) expect_gt(bbox$max_lat, saclat) }) test_that("mz_bbox gets bounding box for isochrones", { bbox <- mz_bbox(marina_walks) expect_is(bbox, "data.frame") expect_true(setequal( names(bbox), c("min_lon", "min_lat", "max_lon", "max_lat") )) marinalon <- -122.3151 marinalat <- 37.86613 expect_lt(bbox$min_lon, marinalon) expect_gt(bbox$max_lon, marinalon) expect_lt(bbox$min_lat, marinalat) expect_gt(bbox$max_lat, marinalat) }) test_that("mz_bbox gets bounding box for search results", { bbox <- mz_bbox(oakland_public) coords <- mz_coordinates(oakland_public) within <- function(lon, lat, bbox) { expect_lte(bbox$min_lon, lon) expect_gte(bbox$max_lon, lon) expect_lte(bbox$min_lat, lat) expect_gte(bbox$max_lat, lat) } Map(function(x, y) within(x, y, bbox), coords$lon, coords$lat) }) test_that("mz_bbox works for sf and sp objects", { oakland_sf <- as_sf(oakland_public) oakland_sp <- as_sp(oakland_public) expect_is(mz_bbox(oakland_sf), "mz_bbox") expect_is(mz_bbox(oakland_sp), "mz_bbox") })
knitr::opts_chunk$set(fig.width = 4, fig.align = 'center', echo = TRUE, warning = FALSE, message = FALSE, eval = FALSE, tidy = FALSE)
setMethod("getQuan", "PcaClassic", function(obj) [email protected]) PcaClassic <- function (x, ...) UseMethod("PcaClassic") PcaClassic.formula <- function (formula, data = NULL, subset, na.action, ...) { cl <- match.call() mt <- terms(formula, data = data) if (attr(mt, "response") > 0) stop("response not allowed in formula") mf <- match.call(expand.dots = FALSE) mf$... <- NULL mf[[1]] <- as.name("model.frame") mf <- eval.parent(mf) if (.check_vars_numeric(mf)) stop("PCA applies only to numerical variables") na.act <- attr(mf, "na.action") mt <- attr(mf, "terms") attr(mt, "intercept") <- 0 x <- model.matrix(mt, mf) res <- PcaClassic.default(x, ...) cl[[1]] <- as.name("PcaClassic") res@call <- cl res } PcaClassic.default <- function(x, k=ncol(x), kmax=ncol(x), scale=FALSE, signflip=TRUE, crit.pca.distances=0.975, trace=FALSE, ...) { cl <- match.call() if(missing(x)){ stop("You have to provide at least some data") } data <- as.matrix(x) n <- nrow(data) p <- ncol(data) Xsvd <- .classPC(data, scale=scale, signflip=signflip, scores=TRUE) if(Xsvd$rank == 0) { stop("All data points collapse!") } myrank <- Xsvd$rank if(is.logical(scale) && !scale) Xsvd$scale <- vector('numeric', p) + 1 if(trace) { cat("\nDimension of the input matrix x:\n", dim(x)) cat("\nInput parameters [k, kmax, rank(x)]: ", k, kmax, Xsvd$rank, "\n") } kmax <- max(min(kmax, Xsvd$rank),1) if((k <- floor(k)) < 0) k <- 0 else if(k > kmax) { warning(paste("The number of principal components k = ", k, " is larger then kmax = ", kmax, "; k is set to ", kmax,".", sep="")) k <- kmax } if(k != 0) k <- min(k, ncol(data)) else { test <- which(Xsvd$eigenvalues/Xsvd$eigenvalues[1] <= 1.E-3) k <- if(length(test) != 0) min(min(Xsvd$rank, test[1]), kmax) else min(Xsvd$rank, kmax) cumulative <- cumsum(Xsvd$eigenvalues[1:k])/sum(Xsvd$eigenvalues) if(cumulative[k] > 0.8) { k <- which(cumulative >= 0.8)[1] } if(trace) cat("\n k, kmax, rank, p: ", k, kmax, Xsvd$rank, ncol(data), "\n") if(trace) cat("The number of principal components is defined by the algorithm. It is set to ", k,".\n", sep="") } if(trace) cat("\nTo be used [k, kmax, ncol(data), rank(data)]=",k, kmax, ncol(data), Xsvd$rank, "\n") loadings <- Xsvd$loadings[, 1:k, drop=FALSE] eigenvalues <- as.vector(Xsvd$eigenvalues[1:k]) center <- as.vector(Xsvd$center) scores <- Xsvd$scores[, 1:k, drop=FALSE] scale <- Xsvd$scale eig0 <- as.vector(Xsvd$eigenvalues) totvar0 <- sum(eig0) if(is.list(dimnames(data)) && !is.null(dimnames(data)[[1]])) { dimnames(scores)[[1]] <- dimnames(data)[[1]] } else { dimnames(scores)[[1]] <- 1:n } dimnames(scores)[[2]] <- as.list(paste("PC", seq_len(ncol(scores)), sep = "")) dimnames(loadings) <- list(colnames(data), paste("PC", seq_len(ncol(loadings)), sep = "")) cl[[1]] <- as.name("PcaClassic") res <- new("PcaClassic", call=cl, rank=myrank, loadings=loadings, eigenvalues=eigenvalues, center=center, scale=scale, scores=scores, k=k, n.obs=n, eig0=eig0, totvar0=totvar0) res <- pca.distances(res, data, Xsvd$rank, crit.pca.distances) return(res) }
rc.qc<-function(ramclustObj=NULL, qc.tag="QC", remove.qc = FALSE, npc=4, scale="pareto", outfile.basename ="ramclustQC", view.hist = TRUE ){ if(is.null(ramclustObj)) { stop("must supply ramclustObj as input. i.e. ramclustObj = RC", '\n') } if(is.null(qc.tag)) { stop("qc.tag = NULL; qc.tag must be defined to enable QC variance examination.", '\n') } if(is.null(outfile.basename)) { outfile.basename <- "ramclustQC" } do.sets <- c("MSdata", "SpecAbund") if(is.null(ramclustObj$SpecAbund)) { do.sets <- do.sets[!(do.sets %in% "SpecAbund")] } do.sets.rows <- sapply( c(do.sets, "phenoData"), FUN = function(x) { nrow(ramclustObj[[x]]) }) if(!sd(do.sets.rows) == 0) { stop("number of rows in MSdata, SpecAbund, and phenoData sets are not identical.") } if(length(qc.tag) == 1) { qc <- grepl(qc.tag[1], ramclustObj$phenoData$sample.names) } if(length(qc.tag) == 2) { qc <- grepl(qc.tag[1], ramclustObj$phenoData[[qc.tag[2]]]) } if(length(which(qc)) == 0) { stop("no QC samples found using the qc.tag ", "'", qc.tag, "'", '\n') } dir.create("QC") if(!is.null(ramclustObj$SpecAbund)) { if(!is.null(ramclustObj$cmpd.use)) { cmpd.use <- ramclustObj$cmpd.use } else { cmpd.use <- rep(TRUE, length(ramclustObj$ann)) } } if(!is.null(ramclustObj$clrt)) { pdf(file=paste("QC/", "ramclust_clustering_diagnostic.pdf", sep=""), useDingbats=FALSE, width=8, height=8) o<-order(ramclustObj$clrt[cmpd.use]) c<-cor(ramclustObj$SpecAbund[,cmpd.use][,o]) d<-diag(as.matrix((c[2:(nrow(c)), 1:ncol(c)-1]))) hist(d, breaks=50, main="") title(main="histogram of pearson's r for each cluster to its adjacent cluster (by time)", cex.main=0.8, sub=paste("skew =", round(e1071::skewness(d), digits=3), " :values near zero are better", '\n', 'WARNING:metabolic relationships will confound interpretation of this plot'), cex.sub=0.6) gplots::heatmap.2(c^2, trace="none", dendrogram="none", Rowv=FALSE, Colv=FALSE, main="pearsons r^2, clusters sorted by rt", cex.main=0.5, cexRow=0.02 + 1/log10(length(o)), cexCol=0.02 + 1/log10(length(o))) dev.off() } qc <- which(qc) cols<-rep(8, nrow(ramclustObj$phenoData)) cols[qc]<-2 for(x in do.sets) { if(x == "SpecAbund") { td <- ramclustObj[[x]][,cmpd.use] } else { td <- ramclustObj[[x]] } if(min(dim(td)) < npc) {npc <- min(dim(td))} PCA<-pcaMethods::pca(td, scale=scale, nPcs=npc, center=TRUE) sc<-PCA@scores write.csv(sc, file = paste0("QC/", outfile.basename, "_", x, "_pcascores.csv")) pdf(file = paste0("QC/", outfile.basename, "_", x, "_qc_diagnostic.pdf"), useDingbats=FALSE, width=8, height=8) ld<-PCA@loadings for(i in 1:(ncol(sc)-1)) { plot(sc[,i], sc[,i+1], col=cols, pch=19, main=paste( "PCA analysis:", x, if(x == "SpecAbund") { "(compounds)" } else {"(features)"} ), xlab=paste("PC", i, ":: r^2 =", round(PCA@R2[i], digits=2), ":: QC(rel sd) = ", round(sd(sc[qc,i])/sd(sc[,i]), digits=2) ), ylab=paste("PC", i+1, ":: r^2 =", round(PCA@R2[i+1], digits=2), ":: QC(rel sd) = ", round(sd(sc[qc,i+1])/sd(sc[,i+1]), digits=2) ) ) legend(qc.tag, text.col=2, x="topright", bty="n") } sds<-apply(td[qc,], 2, FUN="sd", na.rm=TRUE) means<-apply(td[qc,], 2, FUN="mean", na.rm=TRUE) cvs<-sds/means if(x == "MSdata") { ramclustObj$qc.cv.feature <- cvs ramclustObj$qc.cv.feature.msdata <- cvs if(!is.null(ramclustObj$MSMSdata)) { sds<-apply(ramclustObj$MSMSdata[qc,], 2, FUN="sd", na.rm=TRUE) means<-apply(ramclustObj$MSMSdata[qc,], 2, FUN="mean", na.rm=TRUE) msms.cvs<-sds/means ramclustObj$qc.cv.feature.msmsdata <- msms.cvs cvs <- pmin(ramclustObj$qc.cv.feature.msdata, msms.cvs) ramclustObj$qc.cv.feature <- cvs } } else { ramclustObj$qc.cv.cmpd <- cvs } qs<-quantile(cvs, probs=seq(0,1,0.2), na.rm=TRUE) hist(cvs, breaks=50, main="") title(paste("histogram of", x, "CVs from QC samples"), line=2.7) title("20% quantiles in red on top axis", col.main =2, cex.main=0.7, line=2) axis(side=3, col=2, col.ticks=2, col.axis=2, round(qs, digits=3), labels=TRUE, las=2, cex.axis=0.4) dev.off() if(view.hist) { hist(cvs, breaks=50, main="") title(paste("histogram of", x, "CVs from QC samples"), line=2.7) title("20% quantiles in red on top axis", col.main =2, cex.main=0.7, line=2) axis(side=3, col=2, col.ticks=2, col.axis=2, round(qs, digits=3), labels=TRUE, las=2, cex.axis=0.4) } if(x == "SpecAbund") { out <- data.frame( "cmpd" = ramclustObj$cmpd[cmpd.use], "annotation" = ramclustObj$ann[cmpd.use], "rt" = ramclustObj$clrt[cmpd.use], "rdsd" = ramclustObj$clrtsd[cmpd.use], "mean.int" = means, "cv" = cvs ) } else { out <- data.frame( "mz" = ramclustObj$fmz, "rt" = ramclustObj$frt, "mean.int" = means, "cv" = cvs ) if(length(ramclustObj$labels) > 0) { out <- data.frame( out, "feature" = ramclustObj$labels, "cluster" = ramclustObj$featclus ) } } write.csv(out, file = paste0("QC/", outfile.basename, "_", x, "_cv_summar.csv")) } if(remove.qc) { ramclustObj$qc <- list() for(x in c("phenoData", do.sets)) { ramclustObj$qc[[x]] <- ramclustObj[[x]][qc,] ramclustObj[[x]] <- ramclustObj[[x]][-qc,] } } ramclustObj$history$qc.summary <- paste( "Variance in quality control samples was described using the", "rc.qc function within ramclustR. Summary statistics are provided", "including the relative standard deviation of QC samples to all", "samples in PCA space, as well as the relative standard deviation", "of each feature/compound in QC samples, plotted as a histogram.", if(!is.null(ramclustObj$cmpd.use)) {" Only compounds which passed the CV filter are reported."} ) return(ramclustObj) }
api_historicals_options <- function(RH, chain_symbol, type, strike_price, expiration_date, interval = NULL, span = NULL) { dta <- api_instruments_options(RH, method = "symbol", chain_symbol = chain_symbol, type = type, strike_price = strike_price, expiration_date = expiration_date) url <- paste0(api_endpoints("historicals_options"), dta$id, "/?interval=", interval, "&span=", span) token <- paste("Bearer", RH$tokens.access_token) dta <- GET(url, add_headers("Accept" = "application/json", "Content-Type" = "application/json", "Authorization" = token)) dta <- mod_json(dta, "fromJSON") dta <- dta$data_points dta <- dta %>% dplyr::mutate_at("begins_at", lubridate::ymd_hms) %>% dplyr::mutate_at(c("open_price", "close_price", "high_price", "low_price", "volume"), as.numeric) return(dta) }
source("ESEUR_config.r") pal_col=rainbow(3) q1=read.csv(paste0(ESEUR_dir, "regression/Q1_udd.csv.xz"), as.is=TRUE) q10=read.csv(paste0(ESEUR_dir, "regression/Q10_udd.csv.xz"), as.is=TRUE) udd=merge(q1, q10) plot(udd$age, udd$insts, log="y", col=point_col, xaxs="i", xlim=c(0, max(udd$age)), xlab="Age (days)", ylab="Installations\n") i_mod=glm(insts ~ age, data=udd, family=poisson) i_pred=predict(i_mod, newdata=data.frame(age=1:6000), type="link", se.fit=TRUE) lines(exp(i_pred$fit), col=pal_col[1]) lines(exp(i_pred$fit+1.96*i_pred$se.fit), col=pal_col[2]) lines(exp(i_pred$fit-1.96*i_pred$se.fit), col=pal_col[2]) lines(loess.smooth(udd$age, udd$insts, family="gaussian", span=0.2), col=pal_col[3])
if (Sys.getenv("RunAllRcppTests") != "yes") exit_file("Set 'RunAllRcppTests' to 'yes' to run.") Rcpp::sourceCpp("cpp/S4.cpp") setClass("track", representation(x="numeric", y="numeric")) tr <- new( "track", x = 2, y = 2 ) expect_equal(S4_methods(tr), list( TRUE, TRUE, FALSE, 2.0, 2.0 ), info = "slot management" ) S4_getslots( tr ) expect_equal( tr@x, 10.0 , info = "slot('x') = 10" ) expect_equal( tr@y, 20.0 , info = "slot('y') = 20" ) expect_error( S4_setslots( tr ), info = "slot does not exist" ) expect_error( S4_setslots_2( tr ), info = "slot does not exist" ) setClass("track", representation(x="numeric", y="numeric")) tr <- new( "track", x = 2, y = 3 ) expect_equal( S4_get_slot_x( tr ), 2, info = "S4( SEXP )" ) expect_error( S4_get_slot_x( list( x = 2, y = 3 ) ), info = "not S4" ) expect_error( S4_get_slot_x( structure( list( x = 2, y = 3 ), class = "track" ) ), info = "S3 is not S4" ) tr <- S4_ctor( "track" ) expect_true( inherits( tr, "track" ) ) expect_equal( tr@x, numeric(0) ) expect_equal( tr@y, numeric(0) ) expect_error( S4_ctor( "someclassthatdoesnotexist" ) ) setClass("track", representation(x="numeric", y="numeric")) setClass("trackCurve", representation(smooth = "numeric"), contains = "track") tr1 <- new( "track", x = 2, y = 3 ) tr2 <- new( "trackCurve", x = 2, y = 3, smooth = 5 ) expect_true( S4_is_track( tr1 ), info = 'track is track' ) expect_true( S4_is_track( tr2 ), info = 'trackCurve is track' ) expect_true( !S4_is_trackCurve( tr1 ), info = 'track is not trackCurve' ) expect_true( S4_is_trackCurve( tr2 ), info = 'trackCurve is trackCurve' ) setClass("track", representation(x="numeric", y="numeric")) setClass("trackCurve", representation(smooth = "numeric"), contains = "track") tr1 <- new( "track", x = 2, y = 3 ) expect_equal( S4_get_slot_x(tr1), 2, info="Vector( SlotProxy ) ambiguity" ) x <- 1:10 attr( x, "foo" ) <- "bar" expect_equal( S4_get_attr_x(x), "bar", info="Vector( AttributeProxy ) ambiguity" ) setClass( "Foo", contains = "character", representation( x = "numeric" ) ) foo <- S4_dotdata( new( "Foo", "bla", x = 10 ) ) expect_equal( as.character( foo) , "foooo" ) setClass("Foo", list(data="integer")) foo <- new("Foo", data=1:3) expect_equal( S4_proxycoerce(foo), c(1, 2, 3) )
peakTrough <- function(spec, freqBounds=c(10, 30), dbMin=-15, smooth=5, plot=FALSE) { if(max(spec[, 1] > 1e3)) { message(paste0('Expected kHz, but frequency units appear to be in hertz.', 'Converting before calculation, note that result is in kHz.')) spec[, 1] <- spec[, 1] / 1e3 } peak2 <- 0; peak2dB <- dbMin trough <- 0; troughdB <- dbMin peak3 <- 0; peak3dB <- dbMin trough2 <- 0; trough2dB <- dbMin spec[,2] <- spec[,2] - max(spec[,2], na.rm = TRUE) extend <- floor(smooth/2) spec[,2] <- roll_mean(c(rep(spec[1,2], extend), spec[,2], rep(spec[nrow(spec), 2], extend)), smooth) wherePeak <- which.max(spec[-1*c(1, nrow(spec)), 2]) + 1 peak <- spec[wherePeak, 1] peakdB <- spec[wherePeak, 2] if(length(peak)==0) { peak <- 0; peakdB <- dbMin } before <- spec[c(1, 1:nrow(spec)-1), 2] after <- spec[c(2:nrow(spec), nrow(spec)), 2] isPeak <- (spec[, 2] > before) & (spec[, 2] >= after) inRange1 <- ((spec[, 1] >= (peak + freqBounds[1])) & (spec[, 1] <= (peak + freqBounds[2]))) | ((spec[, 1] <= (peak - freqBounds[1])) & (spec[, 1] >= (peak - freqBounds[2]))) notPeak1 <- spec[, 1] != peak inDbRange <- spec[, 2] >= dbMin peak2Spec <- spec[isPeak & inRange1 & notPeak1 & inDbRange, ] if(length(peak2Spec)==2) { peak2Spec <- matrix(peak2Spec, ncol=2) } if(nrow(peak2Spec) > 0) { wherePeak2 <- which.max(peak2Spec[, 2]) peak2 <- peak2Spec[wherePeak2, 1] peak2dB <- peak2Spec[wherePeak2, 2] inRange2 <- (peak2Spec[, 1] >= (peak2 + freqBounds[1])) | (peak2Spec[, 1] <= (peak2 - freqBounds[1])) notPeak2 <- peak2Spec[, 1] != peak2 peak3Spec <- peak2Spec[inRange2 & notPeak2, ] if(length(peak3Spec)==2) { peak3Spec <- matrix(peak3Spec, ncol=2) } if(nrow(peak3Spec) > 0) { wherePeak3 <- which.max(peak3Spec[, 2]) peak3 <- peak3Spec[wherePeak3, 1] peak3dB <- peak3Spec[wherePeak3, 2] } } allPeaks <- sort(c(peak, peak2, peak3)) allPeaks <- allPeaks[allPeaks != 0] if(length(allPeaks)==2) { inTrough <- (spec[, 1] > allPeaks[1]) & (spec[, 1] < allPeaks[2]) troughMat <- spec[inTrough, ] if(length(troughMat) == 2) { troughMat <- matrix(troughMat, ncol = 2) } whereTrough <- which.min(troughMat[, 2]) trough <- troughMat[whereTrough, 1] troughdB <- troughMat[whereTrough, 2] } else if(length(allPeaks)==3) { inTrough <- (spec[, 1] > allPeaks[1]) & (spec[, 1] < allPeaks[2]) troughMat <- spec[inTrough, ] if(length(troughMat) == 2) { troughMat <- matrix(troughMat, ncol = 2) } whereFirst <- which.min(troughMat[, 2]) first <- troughMat[whereFirst, 1] firstdB <- troughMat[whereFirst, 2] inTrough2 <- (spec[, 1] > allPeaks[2]) & (spec[, 1] < allPeaks[3]) troughMat <- spec[inTrough2, ] if(length(troughMat) == 2) { troughMat <- matrix(troughMat, ncol = 2) } whereSecond <- which.min(troughMat[, 2]) second <- troughMat[whereSecond, 1] seconddB <- troughMat[whereSecond, 2] if(firstdB <= seconddB) { trough <- first troughdB <- firstdB trough2 <- second trough2dB <- seconddB } else { trough <- second troughdB <- seconddB trough2 <- first trough2dB <- firstdB } } peakToPeak2 <- ifelse(peak2==0, 0, abs(peak-peak2)) peakToPeak3 <- ifelse(peak3==0, 0, abs(peak-peak3)) peak2ToPeak3 <- ifelse((peak3==0) | (peak2==0), 0, abs(peak2-peak3)) if(plot) { specDf <- data.frame(Freq = spec[, 1], dB = spec[, 2]) freqLines <- sort(peak + c(freqBounds, -1*freqBounds)) graphDf <- data.frame(Freq = c(peak, peak2, peak3, trough, trough2), dB = c(max(specDf$dB), peak2dB, peak3dB, troughdB, trough2dB), Type = c('Highest Peak', 'Second Peak', 'Third Peak', 'Trough / Notch', 'Trough / Notch')) g <- ggplot() + geom_line(data=specDf, aes_string(x='Freq', y='dB')) + geom_vline(xintercept=freqLines, color='goldenrod1') + geom_hline(yintercept=dbMin, color='blue') + geom_point(data=graphDf, aes_string(x='Freq', y='dB', color='Type'), size=3) + coord_cartesian(xlim=range(specDf$Freq), ylim=range(specDf$dB)) + scale_x_continuous(breaks=seq(0,500,20)) + labs(title='Finding Peaks and Troughs', x='Frequency (kHz)', y='Relative dB') + geom_rect(aes(xmin=c(freqLines[1], freqLines[3]), xmax=c(freqLines[2], freqLines[4]), ymin=dbMin, ymax=0, fill='a'), alpha=.1) + geom_rect(aes(xmin=c(-5, freqLines[2], freqLines[4]), xmax=c(freqLines[1], freqLines[3], 150), ymin=dbMin, ymax=0, fill='b'), alpha=.15) + geom_rect(aes(xmin=c(freqLines[1], freqLines[3]), xmax=c(freqLines[2], freqLines[4]), ymin=-130, ymax=dbMin, fill='c'), alpha=.1) + scale_fill_manual(values=c('green', 'blue', 'yellow'), labels=c('Range to Search', 'dB Range', 'Frequency Range'), name='') + theme(plot.title=element_text(hjust=.5)) suppressWarnings(print(g)) } tryCatch({ structure(list(peak = peak, peak2 = peak2, peak3 = peak3, trough = trough, trough2 = trough2, peakToPeak2 = peakToPeak2, peakToPeak3 = peakToPeak3, peak2ToPeak3 = peak2ToPeak3), row.names=c(NA, -1), class='data.frame') }, error = function(e) { message('peakTrough failed with error:\n', e$message) data.frame(peak = NA, peak2 = NA, peak3 = NA, trough = NA, trough2 = NA, peakToPeak2 = NA, peakToPeak3 = NA, peak2ToPeak3 = NA) }) }
calcEm <- function(conc = NULL, calc.method = calcEm_HoribaPitot, analyte = NULL, ..., data = NULL, fun.name = "calcEm", force = FALSE, this.call = NULL){ dots <- quos(...) if(is.null(this.call)) this.call <- match.call() settings <- calcChecks(fun.name, ..., data = data) conc <- getPEMSElement(!!enquo(conc), data, ref.name="conc") temp <- attr(conc, "name") if(!force){ if(length(grep("^conc.", temp))<1) checkIfMissing(if.missing = settings$if.missing, reply = paste("'", temp, "' should be concentration, \n\tdenoted conc.[analyte]", sep=""), suggest = "select suitable input or force if sure ?calcEm", if.warning = NULL, fun.name = fun.name) } temp <- gsub("^conc.", "", temp) if(is.null(analyte)) analyte <- temp if(!force){ if(temp != analyte) checkIfMissing(if.missing = settings$if.missing, reply = "Input type does not match assigned 'analyte'", suggest = "select suitable input or force if sure ?calcEm", if.warning = NULL, fun.name = fun.name) } if(is.function(calc.method)){ if("output" %in% names(dots)) dots[[which(names(dots)=="output")]]<-NULL em <- eval_tidy(quo(calc.method(conc=conc, data=data, fun.name=fun.name, analyte=analyte, this.call=this.call, !!!dots))) return(pemsOutput(em, output = settings$output, data = data, fun.name = fun.name, this.call = this.call)) } checkIfMissing(if.missing = settings$if.missing, reply = "could not run calc.method!", suggest = "check ?calcEm if reason unclear", if.warning = "returning NULL", fun.name = fun.name) return(NULL) } calcEm_HoribaPitot <- function(conc = NULL, time = local.time, exflow = exh.flow.rate, extemp = exh.temp, express = exh.press, analyte = NULL, delay = NULL, mm = NULL, ..., force = force, data = NULL, fun.name = "calcEm_HoribaPitot", this.call = NULL){ settings <- calcChecks(fun.name, ..., data = data) time <- getPEMSElement(!!enquo(time), data, if.missing="return") exflow <- getPEMSElement(!!enquo(exflow), data, if.missing="return") extemp <- getPEMSElement(!!enquo(extemp), data, if.missing="return") express <- getPEMSElement(!!enquo(express), data, if.missing="return") tempGet <- function(..., id=NULL, data=NULL, default=NULL){ extra.args <- list(...) if(id %in% names(extra.args)) return(extra.args[[id]]) if(!is.null(data)){ if(isPEMS(data)) if(id %in% names(getPEMSConstants(data))) return(getPEMSConstants(data)[[id]]) if(id %in% names(data)) return(data[[id]]) } if(!is.null(default)){ if(id %in% names(default)) return(default[[id]]) } return(NULL) } if(is.null(mm)) mm <- tempGet(..., id=paste("mm.", analyte[1], sep=""), data=data, default=ref.chem) if(is.null(mm) & analyte[1]=="hc"){ mm.h <- tempGet(..., id="mm.h", data=data, default=ref.chem) alpha.exhaust.hc <- tempGet(..., id="alpha.exhaust.hc", data=data, default=ref.chem) mm.c <- tempGet(..., id="mm.c", data=data, default=ref.chem) temp <- mm.h * alpha.exhaust.hc + mm.c thc.c6 <- tempGet(..., id="thc.c6", data=data, default=ref.chem) mm <- temp * thc.c6 } if(is.null(delay)) delay <- tempGet(..., id=paste("delay.", analyte[1], sep=""), data=data) conc <- convertUnits(conc, to = "vol%", if.missing = settings$if.missing, unit.convesions = settings$unit.conversions) exflow <- convertUnits(exflow, to = "L/min", if.missing = settings$if.missing, unit.convesions = settings$unit.conversions) if(delay[1]>=1){ conc <- c(conc[(floor(delay[1])+1): length(conc)], rep(NA, floor(delay[1]))) } em <- conc * mm * exflow * (1/60) * (1/100) * (1/22.415) * (273.15/293.15) em <- pems.element(em, name=paste("em.", analyte[1], sep=""), units="g/s") pemsOutput(em, output = settings$output, data = data, fun.name = fun.name, this.call = this.call) }
'dse14t'
distsampOpen <- function(lambdaformula, gammaformula, omegaformula, pformula, data, keyfun=c("halfnorm", "exp", "hazard", "uniform"), output=c("abund", "density"), unitsOut=c("ha", "kmsq"), mixture=c("P", "NB", "ZIP"), K, dynamics=c("constant", "autoreg", "notrend", "trend", "ricker", "gompertz"), fix=c("none", "gamma", "omega"), immigration=FALSE, iotaformula = ~1, starts, method="BFGS", se=TRUE, ...) { if(!is(data, "unmarkedFrameDSO")) stop("Data is not of class unmarkedFrameDSO.") keyfun <- match.arg(keyfun) if(!keyfun %in% c("halfnorm", "exp", "hazard", "uniform")) stop("keyfun must be 'halfnorm', 'exp', 'hazard', or 'uniform'") if(keyfun == "uniform"){ if(!missing(pformula)){ warning("pformula is ignored when using a uniform key function") } pformula <- ~1 } output <- match.arg(output) unitsOut <- match.arg(unitsOut) db <- [email protected] w <- diff(db) tlength <- data@tlength survey <- data@survey unitsIn <- data@unitsIn mixture <- match.arg(mixture) dynamics <- match.arg(dynamics) if((identical(dynamics, "constant") || identical(dynamics, "notrend")) & immigration) stop("You can not include immigration in the constant or notrend models") if(identical(dynamics, "notrend") & !identical(lambdaformula, omegaformula)) stop("lambdaformula and omegaformula must be identical for notrend model") fix <- match.arg(fix) formlist <- mget(c("lambdaformula", "gammaformula", "omegaformula", "pformula", "iotaformula")) check_no_support(formlist) formula <- as.formula(paste(unlist(formlist), collapse=" ")) D <- getDesign(data, formula) y <- D$y Xlam <- D$Xlam Xgam <- D$Xgam Xom <- D$Xom Xsig <- D$Xp Xiota<- D$Xiota delta <- D$delta; go.dims <- D$go.dims deltamax <- max(delta, na.rm=TRUE) M <- nrow(y) T <- data@numPrimary J <- ncol(getY(data)) / T Xlam.offset <- D$Xlam.offset Xgam.offset <- D$Xgam.offset Xom.offset <- D$Xom.offset Xsig.offset <- D$Xp.offset Xiota.offset<- D$Xiota.offset y <- array(y, c(M, J, T)) yt <- apply(y, c(1,3), function(x) { if(all(is.na(x))) return(NA) else return(sum(x, na.rm=TRUE)) }) ytna <- apply(is.na(y), c(1,3), all) ytna <- matrix(ytna, nrow=M) ytna[] <- as.integer(ytna) first <- apply(!ytna, 1, function(x) min(which(x))) last <- apply(!ytna, 1, function(x) max(which(x))) first1 <- which(first==1)[1] if(missing(K)) { K <- max(y, na.rm=T) + 20 warning("K was not specified and was set to ", K, ".") } if(K <= max(y, na.rm = TRUE)) stop("specified K is too small. Try a value larger than any observation") k <- 0:K lk <- length(k) lfac.k <- lgamma(k+1) kmyt <- array(0, c(lk, T, M)) lfac.kmyt <- array(0, c(M, T, lk)) fin <- array(NA, c(M, T, lk)) for(i in 1:M) { for(t in 1:T) { fin[i,t,] <- k - yt[i,t] >= 0 if(sum(ytna[i,t])==0) { kmyt[,t,i] <- k - yt[i,t] lfac.kmyt[i,t, ] <- lgamma(kmyt[,t,i] + 1) } } } ua <- getUA(data) u <- ua$u; a <- ua$a if(length(D$removed.sites)>0){ u <- ua$u[-D$removed.sites,] a <- ua$a[-D$removed.sites,] } switch(survey, line = A <- rowSums(a) * 2, point = A <- rowSums(a)) switch(unitsIn, m = A <- A / 1e6, km = A <- A) switch(unitsOut, ha = A <- A * 100, kmsq = A <- A) if(output=='abund'){ A <- rep(1, M) } lamParms <- colnames(Xlam) gamParms <- colnames(Xgam) omParms <- colnames(Xom) nAP <- ncol(Xlam) nGP <- ncol(Xgam) nOP <- ncol(Xom) nDP <- ifelse(keyfun == "uniform", 0, ncol(Xsig)) detParms <- character(0) if(keyfun != "uniform") detParms <- colnames(Xsig) nIP <- ifelse(immigration, ncol(Xiota), 0) iotaParms <- character(0) if(immigration) iotaParms <- colnames(Xiota) if(identical(fix, "gamma")) { if(!identical(dynamics, "constant")) stop("dynamics must be constant when fixing gamma or omega") if(nGP > 1){ stop("gamma covariates not allowed when fix==gamma") }else { nGP <- 0 gamParms <- character(0) } } else if(identical(dynamics, "notrend")) { if(nGP > 1){ stop("gamma covariates not allowed when dyamics==notrend") } else { nGP <- 0 gamParms <- character(0) } } if(identical(fix, "omega")) { if(!identical(dynamics, "constant")) stop("dynamics must be constant when fixing gamma or omega") if(nOP > 1) stop("omega covariates not allowed when fix==omega") else { nOP <- 0 omParms <- character(0) } } else if(identical(dynamics, "trend")) { if(nOP > 1) stop("omega covariates not allowed when dynamics='trend'") else { nOP <- 0 omParms <- character(0) } } nP <- nAP + nGP + nOP + nDP + nIP + (mixture!="P") + (keyfun == "hazard") if(!missing(starts) && length(starts) != nP) stop(paste("The number of starting values should be", nP)) nbParm <- character(0) if(identical(mixture,"NB")) nbParm <- "alpha" else if(identical(mixture, "ZIP")) nbParm <- "psi" scaleParm <- character(0) if(identical(keyfun, "hazard")) scaleParm <- "scale" paramNames <- c(lamParms, gamParms, omParms, detParms, iotaParms, scaleParm, nbParm) I <- cbind(rep(k, times=lk), rep(k, each=lk)) I1 <- I[I[,1] <= I[,2],] lik_trans <- .Call("get_lik_trans", I, I1, PACKAGE="unmarked") beta_ind <- matrix(NA, 7, 2) beta_ind[1,] <- c(1, nAP) beta_ind[2,] <- c(1, nGP) + nAP beta_ind[3,] <- c(1, nOP) + nAP + nGP beta_ind[4,] <- c(1, nDP) + nAP + nGP + nOP beta_ind[5,] <- c(1, nIP) + nAP + nGP + nOP + nDP beta_ind[6,] <- c(1, 1) + nAP + nGP + nOP + nDP + nIP beta_ind[7,] <- c(1, 1) + nAP + nGP + nOP + nDP + nIP + (keyfun == "hazard") fin <- fin*1 u <- t(u) yperm <- aperm(y, c(1,3,2)) nll <- function(parms) { .Call("nll_distsampOpen", yperm, yt, Xlam, Xgam, Xom, Xsig, Xiota, parms, beta_ind - 1, Xlam.offset, Xgam.offset, Xom.offset, Xsig.offset, Xiota.offset, ytna, lk, mixture, first - 1, last - 1, first1 - 1, M, T, delta, dynamics, survey, fix, go.dims, immigration, I, I1, lik_trans$Ib, lik_trans$Ip, a, u, w, db, keyfun, lfac.k, kmyt, lfac.kmyt, fin, A, PACKAGE = "unmarked") } if(missing(starts)){ starts <- rep(0, nP) if(keyfun != "uniform") starts[beta_ind[4,1]] <- log(mean(w)) } fm <- optim(starts, nll, method=method, hessian=se, ...) ests <- fm$par names(ests) <- paramNames covMat <- invertHessian(fm, nP, se) fmAIC <- 2*fm$value + 2*nP lamEstimates <- unmarkedEstimate(name = "Abundance", short.name = "lam", estimates = ests[1:nAP], covMat = as.matrix(covMat[1:nAP,1:nAP]), invlink = "exp", invlinkGrad = "exp") estimateList <- unmarkedEstimateList(list(lambda=lamEstimates)) gamName <- switch(dynamics, constant = "gamConst", autoreg = "gamAR", notrend = "", trend = "gamTrend", ricker="gamRicker", gompertz = "gamGomp") if(!(identical(fix, "gamma") | identical(dynamics, "notrend"))){ estimateList@estimates$gamma <- unmarkedEstimate(name = ifelse(identical(dynamics, "constant") | identical(dynamics, "autoreg"), "Recruitment", "Growth Rate"), short.name = gamName, estimates = ests[(nAP+1) : (nAP+nGP)], covMat = as.matrix(covMat[(nAP+1) : (nAP+nGP), (nAP+1) : (nAP+nGP)]), invlink = "exp", invlinkGrad = "exp") } if(!(identical(fix, "omega") | identical(dynamics, "trend"))) { if(identical(dynamics, "constant") | identical(dynamics, "autoreg") | identical(dynamics, "notrend")){ estimateList@estimates$omega <- unmarkedEstimate( name="Apparent Survival", short.name = "omega", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)], covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP), (nAP+nGP+1) : (nAP+nGP+nOP)]), invlink = "logistic", invlinkGrad = "logistic.grad") } else if(identical(dynamics, "ricker")){ estimateList@estimates$omega <- unmarkedEstimate(name="Carrying Capacity", short.name = "omCarCap", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)], covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP), (nAP+nGP+1) : (nAP+nGP+nOP)]), invlink = "exp", invlinkGrad = "exp") } else{ estimateList@estimates$omega <- unmarkedEstimate(name="Carrying Capacity", short.name = "omCarCap", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)], covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP), (nAP+nGP+1) : (nAP+nGP+nOP)]), invlink = "exp", invlinkGrad = "exp") } } if(keyfun != "uniform"){ estimateList@estimates$det <- unmarkedEstimate( name = "Detection", short.name = "sigma", estimates = ests[(nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP)], covMat = as.matrix(covMat[(nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP), (nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP)]), invlink = "exp", invlinkGrad = "exp") } if(immigration) { estimateList@estimates$iota <- unmarkedEstimate( name="Immigration", short.name = "iota", estimates = ests[(nAP+nGP+nOP+nDP+1) :(nAP+nGP+nOP+nDP+nIP)], covMat = as.matrix(covMat[(nAP+nGP+nOP+nDP+1) : (nAP+nGP+nOP+nDP+nIP), (nAP+nGP+nOP+nDP+1) : (nAP+nGP+nOP+nDP+nIP)]), invlink = "exp", invlinkGrad = "exp") } if(identical(keyfun, "hazard")) { estimateList@estimates$scale <- unmarkedEstimate(name = "Hazard-rate(scale)", short.name = "scale", estimates = ests[nAP+nGP+nOP+nDP+nIP+1], covMat = as.matrix(covMat[nAP+nGP+nOP+nDP+nIP+1, nAP+nGP+nOP+nDP+nIP+1]), invlink = "exp", invlinkGrad = "exp") } if(identical(mixture, "NB")) { estimateList@estimates$alpha <- unmarkedEstimate(name = "Dispersion", short.name = "alpha", estimates = ests[nP], covMat = as.matrix(covMat[nP, nP]), invlink = "exp", invlinkGrad = "exp") } if(identical(mixture, "ZIP")) { estimateList@estimates$psi <- unmarkedEstimate(name = "Zero-inflation", short.name = "psi", estimates = ests[nP], covMat = as.matrix(covMat[nP, nP]), invlink = "logistic", invlinkGrad = "logistic.grad") } umfit <- new("unmarkedFitDSO", fitType = "distsampOpen", call = match.call(), formula = formula, formlist = formlist, data = data, sitesRemoved=D$removed.sites, estimates = estimateList, AIC = fmAIC, opt = fm, negLogLike = fm$value, nllFun = nll, K = K, mixture = mixture, dynamics = dynamics, fix = fix, immigration=immigration, keyfun=keyfun, unitsOut=unitsOut) return(umfit) }
invert.auto <- function(observed, invert.options, return.samples = TRUE, save.samples = NULL, quiet=FALSE, parallel=TRUE, parallel.cores=NULL, parallel.output = '/dev/null') { if (parallel == TRUE) { testForPackage("parallel") } else { message("Running in serial mode. Better performance can be achived with `parallel=TRUE`.") } ngibbs.max <- invert.options$ngibbs.max if (is.null(ngibbs.max)) { ngibbs.max <- 1e6 message("ngibbs.max not provided. ", "Setting default to ", ngibbs.max) } ngibbs.min <- invert.options$ngibbs.min if (is.null(ngibbs.min)) { ngibbs.min <- 5000 message("ngibbs.min not provided. ", "Setting default to ", ngibbs.min) } ngibbs.step <- invert.options$ngibbs.step if (is.null(ngibbs.step)) { ngibbs.step <- 1000 message("ngibbs.step not provided. ", "Setting default to ", ngibbs.step) } nchains <- invert.options$nchains if (is.null(nchains)) { nchains <- 3 message("nchains not provided. ", "Setting default to ", nchains) } inits.function <- invert.options$inits.function if (is.null(inits.function)) { stop("invert.options$inits.function is required but missing.") } if (is.null(invert.options$do.lsq)) { invert.options$do.lsq <- FALSE message("do.lsq not provided. ", "Setting default to ", invert.options$do.lsq) } if (invert.options$do.lsq) { testForPackage("minpack.lm") } iter_conv_check <- invert.options$iter_conv_check if (is.null(iter_conv_check)) { iter_conv_check <- 15000 message("iter_conv_check not provided. ", "Setting default to ", iter_conv_check) } threshold <- invert.options$threshold if (is.null(threshold)) { threshold <- 1.1 message("threshold not provided. ", "Setting default to ", threshold) } calculate.burnin <- invert.options$calculate.burnin if (is.null(calculate.burnin)) { calculate.burnin <- TRUE message("calculate.burnin not provided. ", "Setting default to ", calculate.burnin) } if (parallel) { maxcores <- parallel::detectCores() if (is.null(parallel.cores)) { parallel.cores <- maxcores - 1 } else { if (!is.numeric(parallel.cores) | parallel.cores %% 1 != 0) { stop("Invalid argument to 'parallel.cores'. Must be integer or NULL") } else if (parallel.cores > maxcores) { warning(sprintf("Requested %1$d cores but only %2$d cores available. ", parallel.cores, maxcores), "Using only available cores.") parallel.cores <- maxcores } } cl <- parallel::makeCluster(parallel.cores, "FORK", outfile = parallel.output) on.exit(parallel::stopCluster(cl), add = TRUE) parallel::clusterSetRNGStream(cl) message(sprintf("Running %d chains in parallel. ", nchains), "Progress bar unavailable") } invert.function <- function(x) { invert.options$inits <- x$inits invert.options$resume <- x$resume samps <- invert.custom(observed = observed, invert.options = invert.options, quiet = quiet, return.resume = TRUE, runID = x$runID) return(samps) } runID_list <- seq_len(nchains) inputs <- list() for (i in seq_len(nchains)) { inputs[[i]] <- list(runID = runID_list[i], inits = inits.function(), resume = NULL) } if (!is.null(invert.options$run_first)) { if (parallel) { first <- parallel::parLapply(cl, inputs, invert.options$run_first) } else { first <- list() for (i in seq_len(nchains)) { first[[i]] <- invert.options$run_first(inputs[[i]]) } } } invert.options$ngibbs <- ngibbs.min i.ngibbs <- ngibbs.min if (parallel) { output.list <- parallel::parLapply(cl, inputs, invert.function) } else { output.list <- list() for (i in seq_along(inputs)) { print(sprintf("Running chain %d of %d", i, nchains)) output.list[[i]] <- invert.function(inputs[[i]]) } } resume <- lapply(output.list, '[[', 'resume') out <- process_output(output.list = output.list, iter_conv_check = iter_conv_check, save.samples = save.samples, threshold = threshold, calculate.burnin = calculate.burnin) invert.options$ngibbs <- ngibbs.step while (!out$finished & i.ngibbs < ngibbs.max) { if (!quiet) { message(sprintf("Running iterations %d to %d", i.ngibbs, i.ngibbs + ngibbs.step)) } inits <- lapply(out$samples, getLastRow) inputs <- list() for (i in seq_len(nchains)) { inputs[[i]] <- list(runID = runID_list[i], inits = inits[[i]], resume = resume[[i]]) } if (parallel) { output.list <- parallel::parLapply(cl, inputs, invert.function) } else { output.list <- list() for (i in seq_along(inputs)) { message(sprintf('Running chain %d of %d', i, nchains)) output.list[[i]] <- invert.function(inputs[[i]]) } } i.ngibbs <- i.ngibbs + ngibbs.step resume <- lapply(output.list, '[[', 'resume') out <- process_output(output.list = output.list, prev_out = out, iter_conv_check = iter_conv_check, save.samples = save.samples, threshold = threshold, calculate.burnin = calculate.burnin) } if (i.ngibbs > ngibbs.max & !out$finished) { warning("Convergence was not achieved, and max iterations exceeded. ", "Returning results as 'NA'.") } if (!return.samples) { out$samples <- c('Samples not returned' = NA) } return(out) } getLastRow <- function(samps, exclude.cols = ncol(samps)) { cols <- seq_len(ncol(samps)) cols <- cols[-exclude.cols] last_row <- samps[nrow(samps), cols] return(last_row) } combineChains <- function(samps1, samps2) { stopifnot(length(samps1) == length(samps2)) nchains <- length(samps1) sampsfinal <- list() for (i in seq_len(nchains)) { sampsfinal[[i]] <- rbind(samps1[[i]], samps2[[i]]) } stopifnot(length(sampsfinal) == length(samps1)) out <- PEcAn.assim.batch::makeMCMCList(sampsfinal) return(out) } process_output <- function(output.list, prev_out = NULL, iter_conv_check, save.samples, threshold, calculate.burnin) { samples.current <- lapply(output.list, "[[", "results") deviance_list.current <- lapply(output.list, "[[", "deviance") n_eff_list.current <- lapply(output.list, "[[", "n_eff") rm(output.list) out <- list() if (is.null(prev_out)) { out$samples <- PEcAn.assim.batch::makeMCMCList(samples.current) out$deviance_list <- deviance_list.current out$n_eff_list <- n_eff_list.current } else { out$samples <- combineChains(prev_out$samples, samples.current) out$deviance_list <- mapply(c, prev_out$deviance_list, deviance_list.current, SIMPLIFY = F) out$n_eff_list <- mapply(c, prev_out$n_eff_list, n_eff_list.current, SIMPLIFY = F) } rm(prev_out) if (!is.null(save.samples)) { saveRDS(out, file = save.samples) } out$nsamp <- coda::niter(out$samples) nburn <- min(floor(out$nsamp/2), iter_conv_check) burned_samples <- window(out$samples, start = nburn) check_initial <- check.convergence(burned_samples, threshold = threshold, autoburnin = FALSE) if (check_initial$error) { warning("Could not calculate Gelman diag. Assuming no convergence.") out$finished <- FALSE return(out) } if (!check_initial$converged) { message("Convergence was not achieved. Continuing sampling.") out$finished <- FALSE return(out) } else { message("Passed initial convergence check.") } if (calculate.burnin) { burn <- PEcAn.assim.batch::autoburnin(out$samples, return.burnin = TRUE, method = 'gelman.plot') out$burnin <- burn$burnin if (out$burnin == 1) { message("Robust convergence check in autoburnin failed. ", "Resuming sampling.") out$finished <- FALSE return(out) } else { message("Converged after ", out$nsamp, "iterations.") out$results <- summary_simple(do.call(rbind, burn$samples)) } } else { message("Skipping robust convergece check (autoburnin) because ", "calculate.burnin == FALSE.") out$burnin <- nburn out$results <- summary_simple(do.call(rbind, burned_samples)) } message("Burnin = ", out$burnin) out$finished <- TRUE return(out) }
SimPhase123=function(DoseStart,Dose,PE,PT,Hypermeans,Hypervars,Contour,PiLim,ProbLim,NET,NF,Accrue12,Time12,cohort,betaA,ProbC,betaC,Family,alpha,Nmax,Accrue,Twait,NLookSwitch,NLook,Sup,Fut,nSims){ Doselog = log(Dose)-mean(log(Dose)) Dose1=(Dose-mean(Dose))/sd(Dose) PH123=matrix(rep(NA,4*nSims),nrow=nSims) PH12=matrix(rep(NA,4*nSims),nrow=nSims) B=2000 for(h in 1:nSims){ if(h%%100==0){ cat(h, "Simulations Finished ") } Phase12 = RunAdaptiveEffToxTrial(DoseStart,Doselog, Hypermeans, Hypervars, Contour, PiLim, ProbLim, cohort, NET, NF, B, 1, PE, PT ) Opt=Phase12[[1]][1] Phase12=Phase12[[3]] Phase12[,1]=Phase12[,1]+1 ACC1=cumsum(rexp(NET,Accrue12)) Grab = rep(NA,NET/cohort) for(m in 1:length(Grab)){Grab[m]=ACC1[m*3]} for(m in 1:length(Grab)){ACC1[((m-1)*cohort+1):((m-1)*cohort+cohort)]=rep(Grab[m],cohort)} Phase12 = cbind(Phase12,ACC1) Z=SimPhase3(Dose1,Phase12,PE,PT,Hypermeans,Hypervars,betaA,ProbC,betaC,Family,alpha,Nmax,Opt,Accrue,Time12,Twait,NLookSwitch,NLook,Sup,Fut) Z123=Z[[1]] Z12=Z[[2]] PH123[h,]=Z123 PH12[h,]=Z12 } Z=as.list(c(0,0)) Z[[1]]=PH123 Z[[2]]=PH12 return(Z) }
library(lumberjack) logfile <- tempfile() data(women) start_log(women, logger=simple$new(verbose=FALSE)) women[1,1] <- 2*women[1,1] women$ratio <- women$height/women$weight dump_log(women, "simple", file=logfile)
NULL Milo <- function(..., graph=list(), nhoodDistances=Matrix(0L, sparse=TRUE), nhoods=Matrix(0L, sparse=TRUE), nhoodCounts=Matrix(0L, sparse=TRUE), nhoodIndex=list(), nhoodExpression=Matrix(0L, sparse=TRUE), .k=NULL){ old <- S4Vectors:::disableValidity() if (!isTRUE(old)) { S4Vectors:::disableValidity(TRUE) on.exit(S4Vectors:::disableValidity(old)) } if(length(list(...)) == 0){ milo <- .emptyMilo() } else if(is(unlist(...), "SingleCellExperiment")){ milo <- .fromSCE(unlist(...)) } milo } .fromSCE <- function(sce, assayName="logcounts"){ out <- new("Milo", sce, graph=list(), nhoods=Matrix(0L, sparse=TRUE), nhoodDistances=NULL, nhoodCounts=Matrix(0L, sparse=TRUE), nhoodIndex=list(), nhoodExpression=Matrix(0L, sparse=TRUE), .k=NULL) reducedDims(out) <- reducedDims(sce) altExps(out) <- list() out } .emptyMilo <- function(...){ out <- new("Milo", graph=list(), nhoods=Matrix(0L, sparse=TRUE), nhoodDistances=NULL, nhoodCounts=Matrix(0L, sparse=TRUE), nhoodIndex=list(), nhoodExpression=Matrix(0L, sparse=TRUE), .k=NULL) reducedDims(out) <- SimpleList() altExps(out) <- SimpleList() colData(out) <- DataFrame() if (objectVersion(out) >= "1.11.3"){ colPairs(out) <- SimpleList() rowPairs(out) <- SimpleList() } out } setValidity("Milo", function(object){ if (!is(object@nhoodCounts, "matrixORMatrix")){ "@nhoodCounts must be matrix format" } else{ TRUE } if(!is(object@nhoodDistances, "listORNULL")){ "@nhoodDistances must be a list of matrices" } else{ TRUE } if(!is(object@nhoodExpression, "matrixORMatrix")){ "@nhoodExpression must be a matrix format" } else{ TRUE } if (!is_igraph(object@graph)){ if(typeof(object@graph) != "list"){ "@graph must be of type list or igraph" } } else{ TRUE } })
tbl <- dplyr::tribble( ~dates, ~rows, ~col_1, ~col_2, ~col_3, ~col_4, "2018-02-10", "1", 767.6, 928.1, 382.0, 674.5, "2018-02-10", "2", 403.3, 461.5, 15.1, 242.8, "2018-02-10", "3", 686.4, 54.1, 282.7, 56.3, "2018-02-10", "4", 662.6, 148.8, 984.6, 928.1, "2018-02-11", "5", 198.5, 65.1, 127.4, 219.3, "2018-02-11", "6", 132.1, 118.1, 91.2, 874.3, "2018-02-11", "7", 349.7, 307.1, 566.7, 542.9, "2018-02-11", "8", 63.7, 504.3, 152.0, 724.5, "2018-02-11", "9", 105.4, 729.8, 962.4, 336.4, "2018-02-11", "10", 924.2, 424.6, 740.8, 104.2 ) check_suggests <- function() { skip_if_not_installed("rvest") skip_if_not_installed("xml2") } selection_value <- function(html, key) { selection <- paste0("[", key, "]") html %>% rvest::html_nodes(selection) %>% rvest::html_attr(key) } test_that("the `row_group_order()` function works correctly", { html_tbl <- tbl %>% gt(rowname_col = "rows", groupname_col = "dates") %>% row_group_order(groups = c("2018-02-11", "2018-02-10")) dt_row_groups_get(data = html_tbl) %>% expect_equal(c("2018-02-11", "2018-02-10")) expect_error( tbl %>% gt(rowname_col = "rows", groupname_col = "dates") %>% row_group_order(groups = c(TRUE, FALSE)) ) expect_error( tbl %>% gt(rowname_col = "rows", groupname_col = "dates") %>% row_group_order(groups = c("2018-02-13", "2018-02-10")) ) }) test_that("styling at various locations is kept when using `row_group_order()`", { summary_tbl <- tbl %>% gt(rowname_col = "rows", groupname_col = "dates") %>% summary_rows( groups = TRUE, columns = everything(), fns = list("sum") ) %>% grand_summary_rows( columns = everything(), fns = list("sum") ) summary_tbl_styled_1 <- summary_tbl %>% tab_style( style = cell_text(style = "italic", weight = "bold"), locations = list( cells_summary(), cells_stub_summary(), cells_grand_summary(), cells_stub_grand_summary() ) ) %>% render_as_html() %>% xml2::read_html() summary_tbl_styled_2 <- summary_tbl %>% tab_style( style = cell_text(style = "italic", weight = "bold"), locations = list( cells_summary(), cells_stub_summary(), cells_grand_summary(), cells_stub_grand_summary() ) ) %>% row_group_order(groups = c("2018-02-11", "2018-02-10")) %>% render_as_html() %>% xml2::read_html() summary_tbl_styled_1 %>% selection_value("style") %>% expect_equal(rep("font-style: italic; font-weight: bold;", 15)) summary_tbl_styled_2 %>% selection_value("style") %>% expect_equal(rep("font-style: italic; font-weight: bold;", 15)) })
.qp.update <- function (ppt,qp,theta,gn,gnge,ppe,ppg,fd,fdge,kd,kr,pgg,alpha1,alpha2,alpha3,darray,x,n,model){ alpha1.t<-qp*alpha1 alpha1.t[alpha1.t<1 & model==1]<-1 qp.star <- .rdirichlet.MCMCpack(1, alpha1.t) e.t<-1-exp(qp.star[1]*log(1-ppt)) g.t<-1-exp(qp.star[2]*log(1-ppt)) ge.t<-1-exp(qp.star[3]*log(1-ppt)) gg.t<-1-exp(qp.star[4]*log(1-ppt)) if(model[2]==1){ gn.star <- sample(9,1,replace=T)-1 fd.t<-c(runif(1,0,1-sqrt(1-g.t)),array(0,gn.star)) fr.t<-c(0,array(sqrt(1-((1-g.t)/(1-fd.t[1])^2)^(1/gn.star)),gn.star)) } else { gn.star <-0 fd.t <-c(0,0) fr.t <-c(0,0) } if(model[3]==1){ alpha2.t<-c(log(ppe),log(ppg))/log(1-exp(qp[3]*log(1-ppt)))*alpha2 +1 ge<-.rdirichlet.MCMCpack(1,c(1,1)) ppe.star<-exp(ge[1]*log(ge.t)) ppg.star<-exp(ge[2]*log(ge.t)) gnge.star <- sample(9,1,replace=T)-1 fdge.t<-c(runif(1,0,1-sqrt(1-ppg.star)),array(0,gnge.star)) frge.t<-c(0,array(sqrt(1-((1-ppg.star)/(1-fdge.t[1])^2)^(1/gnge.star)),gnge.star)) } else { ge<-c(0,0) ppe.star <-0 ppg.star <-0 gnge.star<-0 fdge.t<-c(0,0) frge.t<-c(0,0) } if(model[4]==1){ kd.star <- sample(9,1,replace=T)-1 if(kd.star==0){ kr.star <- sample(8,1,replace=T) } if(kd.star>0){ kr.star <- sample(9-kd.star,1,replace=T)-1 } if(kd.star>0 & kr.star>0){ alpha3.t<-pgg*alpha3+1 pgg.star<-.rdirichlet.MCMCpack(1,c(1,1)) ppd.star<-exp(pgg.star[1]*log(gg.t)) ppr.star<-exp(pgg.star[2]*log(gg.t)) } if(kd.star==0){ ppr.star<-gg.t ppd.star<-0 } if(kr.star==0){ ppd.star<-gg.t ppr.star<-0 } frgg.t<-c(array(0,kd.star),array((ppr.star)^(1/2/kr.star),kr.star)) fdgg.t<-c(array(1-sqrt(1-ppd.star^(1/kd.star)),kd.star),array(0,kr.star)) } else{ kd.star<-0 kr.star<-0 pgg.star<-c(0,0) ppd.star<-0 ppr.star<-0 frgg.t<-c(0,0) fdgg.t<-c(0,0) } temp<-drgegggne(fd.t,fr.t,fdgg.t,frgg.t,fdge.t,frge.t,ppe.star,e.t) theta.t<-temp[,3]/(temp[,2]+temp[,3]) log.post.old <- .logMCMC.post(x,n,theta[darray]) log.post.star <- .logMCMC.post(x,n,theta.t[darray]) alpha1.tt<-qp.star*alpha1 alpha1.tt[alpha1.tt<1 & model==1]<-1 log.jump <- sum(log(.ddirichlet.MCMCpack(qp[model==1],alpha1.tt[model==1]))) - sum(log(.ddirichlet.MCMCpack(qp.star[model==1],alpha1.t[model==1]))) alpha2.tt<-ge*alpha2+1 if(kd.star>0 & kr.star>0){ alpha3.tt<-pgg.star*alpha3+1 } r <- exp (log.post.star - log.post.old + log.jump) if(runif(1)<r){ qp<-qp.star theta<-theta.t ppe<-ppe.star ppg<-ppg.star if(kd.star>0 & kr.star>0) { pgg<-pgg.star } kd<-kd.star kr<-kr.star gn<-gn.star fd<-fd.t gnge<-gnge.star fdge<-fdge.t } list (qp=qp,theta=theta,gn=gn,gnge=gnge,ppe=ppe,ppg=ppg,fd=fd,fdge=fdge,kd=kd,kr=kr,pgg=pgg) }
skip_on_cran()
print.summary.multicut <- function(x, cut, sort, digits, ...) { if (missing(cut)) cut <- getOption("ocoptions")$cut if (missing(digits)) digits <- max(3L, getOption("digits") - 3L) if (missing(sort)) sort <- getOption("ocoptions")$sort xx <- .summary_opticut(x, cut=cut, sort=sort, multi=TRUE) Missing <- nrow(x$summary) - nrow(xx) tmp <- if (nrow(xx) > 1L) "Species models" else "Species model" TXT <- paste0(tmp, " with logLR >= ", format(cut, digits = digits), ":") cat("Multivariate multticut results, dist = ", if (is.function(x$dist)) attr(x$dist, "dist") else x$dist, "\n", sep="") cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n\n", TXT, "\n", sep = "") print(format.data.frame(xx, digits=digits), ...) if (Missing) cat(Missing, "species not shown\n") cat("\n") invisible(x) }
cov.lo <- function(para, map, data, ref, model, nsample, V, bet0, outcome){ data$'(Intercept)' <- 1 g <- gfunction.lo(para, map, ref) g.the <- gfunction.the.lo(para, map, ref) g.alp <- gfunction.alp.lo(para, map, ref) g.bet <- gfunction.bet.lo(para, map, ref) nmodel <- length(map$bet) nlam <- max(map$lam) n <- nrow(data) m <- nrow(ref) r <- m/n lam <- para[map$lam] pr <- as.vector(1/(1+g %*% lam)) pr <- pr/sum(pr) pr0 <- 1/n J.tt <- -(t(g) %*% (g * pr)) * r nthe <- length(g.the) J.tthe <- matrix(0, nrow = nlam, ncol = nthe) for(i in 1:nthe){ J.tthe[, i] <- t(g.the[[i]]) %*% pr * r } nalp <- length(g.alp) if(nalp > 0){ J.talp <- matrix(0, nrow = nlam, ncol = nalp) for(i in 1:nalp){ J.talp[, i] <- t(g.alp[[i]]) %*% pr * r } } nbet <- length(g.bet) J.tbet <- matrix(0, nrow = nlam, ncol = nbet) for(i in 1:nbet){ J.tbet[, i] <- t(g.bet[[i]]) %*% pr * r } the <- para[map$the] fx <- as.matrix(data[, names(the), drop = FALSE]) elin <- as.vector(exp(fx %*% the)) yh <- elin/(1+elin) J.the <- t(fx) %*% (fx * (yh * (1-yh) * pr0)) suppressMessages(Sigma0 <- Sigma0.lo(para, map, ref, model, nsample, outcome)) J.bet <- solve(Sigma0)/n np <- length(para) Jv <- matrix(0, nrow = np, ncol = np) Iv <- matrix(0, nrow = np, ncol = np) Jv[map$lam, map$lam] <- J.tt Jv[map$lam, map$the] <- J.tthe Jv[map$the, map$lam] <- t(J.tthe) if(nalp > 0){ Jv[map$lam, map$all.alp] <- J.talp Jv[map$all.alp, map$lam] <- t(J.talp) } Jv[map$lam, map$all.bet] <- J.tbet Jv[map$all.bet, map$lam] <- t(J.tbet) Jv[map$the, map$the] <- J.the Jv[map$all.bet, map$all.bet] <- J.bet Iv[map$lam, map$lam] <- -J.tt Iv[map$the, map$the] <- J.the Iv[map$all.bet, map$all.bet] <- J.bet vcov <- solve(Jv) %*% Iv %*% solve(Jv)/n vcov Jv0 <- -hess.lo(para, map, data, ref, solve(V), bet0, outcome)/n Iv0 <- matrix(0, nrow = np, ncol = np) Iv0[map$lam, map$lam] <- -Jv0[map$lam, map$lam] Iv0[map$the, map$the] <- Jv0[map$the, map$the] Iv0[map$all.bet, map$all.bet] <- Jv0[map$all.bet, map$all.bet] vcov0 <- solve(Jv0) %*% Iv0 %*% solve(Jv0)/n vcov0 }
be.zeroinfl <- function(object, data, dist=c("poisson", "negbin", "geometric"), alpha=0.05, trace=FALSE){ if(class(object)!="zeroinfl") stop("object must be zeroinfl\n") dist <- match.arg(dist) fit <- object rhs1 <- attr(fit$terms$count, "term.labels") rhs2 <- attr(fit$terms$zero, "term.labels") nj <- length(rhs1)*length(rhs2) j <- 1 if(trace) { cat("Initial model\n") print(summary(fit)) } RET <- matrix(NA, nrow=nj, ncol=3) colnames(RET) <- c("loglik", "BIC", "AIC") while(T){ if(trace) cat("\nstep", j, "\n") coef <- summary(fit)$coef d <- dim(coef$count)[1] if(dist!="negbin") count.pval <- coef$count[-1,4] else count.pval <- coef$count[-c(1,d),4] zero.pval <- coef$zero[-1,4] nc <- length(count.pval) nz <- length(zero.pval) if(dist!="negbin") count.order <- order(coef$count[-1,4], decreasing=TRUE) else count.order <- order(coef$count[-c(1,d),4], decreasing=TRUE) zero.order <- order(coef$zero[-1,4], decreasing=TRUE) rhs1 <- attr(fit$terms$count, "term.labels") rhs2 <- attr(fit$terms$zero, "term.labels") kc <- 1 kz <- 1 count.max <- count.pval[count.order[kc]] zero.max <- zero.pval[zero.order[kz]] if(is.na(count.max) && is.na(zero.max)) break else if(is.na(zero.max)) zero.max <- 0 else if(is.na(count.max)) count.max <- 0 if(count.max > zero.max) if(count.max > alpha){ newid <- count.order[kc] if(dist!="negbin") dropvar <- rownames(coef$count)[-1][newid] else dropvar <- rownames(coef$count)[-c(1,d)][newid] if(trace) cat("drop variable in count component: ", rhs1[newid],"\n") rhs1 <- rhs1[-newid] kc <- kc + 1 } else break else if(zero.max > alpha){ newid <- zero.order[kc] dropvar <- rownames(coef$zero)[-1][newid] if(trace) cat("drop variable in zero component: ", rhs2[newid],"\n") rhs2 <- rhs2[-newid] } else break if(length(rhs1)==0) rhs1tmp <- 1 else { rhs1tmp <- rhs1[1] if(length(rhs1) > 1) for(i in 2:length(rhs1)) rhs1tmp <- paste(rhs1tmp, "+", rhs1[i]) } if(length(rhs2)==0) rhs2tmp <- 1 else { rhs2tmp <- rhs2[1] if(length(rhs2) > 1) for(i in 2:length(rhs2)) rhs2tmp <- paste(rhs2tmp, "+", rhs2[i]) } res <- deparse(terms(fit$terms$count)[[2]]) out <- paste(res, "~", rhs1tmp, "|", rhs2tmp) environment(out) <- parent.frame() fit <- try(zeroinfl(eval(parse(text=out)), data=data, dist=dist)) if(inherits(fit, "try-error")) break if(trace){ print(summary(fit)) cat("\nloglik of zero-inflated model", logLik(fit), "\n") cat("\nBIC of zero-inflated model", AIC(fit, k=log(dim(data)[1]))) cat("\nAIC of zero-inflated model", AIC(fit)) } RET[j,1] <- logLik(fit) RET[j,2] <- AIC(fit, k=log(dim(data)[1])) RET[j,3] <- AIC(fit) j <- j + 1 } if(trace) print(RET[complete.cases(RET),]) return(fit) }
print_uncertainty_nd <- function(model,T,type="pn",lower=NULL,upper=NULL, resolution=20, nintegpoints=400,cex.lab=1,cex.contourlab=1,cex.axis=1, nlevels=10,levels=NULL, xdecal=3,ydecal=3, option="mean",pairs=NULL,...){ d <- model@d mynames <- colnames(model@X) if ( (resolution>40) & is.null(pairs) ) resolution <- 40 if(is.null(lower)) lower <- rep(0,times=d) if(is.null(upper)) upper <- rep(1,times=d) if (d==1){ print("Error in print_uncertainty_nd, number of dimension is equal to 1. Please use print_uncertainty_1d instead") return(0) } if (d==2){ print("Error in print_uncertainty_nd, number of dimension is equal to 2. Please use print_uncertainty_2d instead") return(0) } sub.d <- d-2 integration.tmp <- matrix(sobol(n=nintegpoints, dim = sub.d),ncol=sub.d) sbis <- c(1:resolution^2) numrow <- resolution^2 * nintegpoints integration.base <- matrix(c(0),nrow=numrow,ncol=sub.d) for(i in 1:sub.d){ col.i <- as.numeric(integration.tmp[,i]) my.mat <- expand.grid(col.i,sbis) integration.base[,i] <- my.mat[,1] } s <- seq(from=0,to=1,length=resolution) sbis <- c(1:nintegpoints) s.base <- expand.grid(sbis,s,s) s.base <- s.base[,c(2,3)] prediction.points <- matrix(c(0),nrow=numrow,ncol=d) if(type=="vorob"){ print("Vorob'ev plot not available in n dimensions.") print("We switch to a pn plot.") type <- "pn" } if(is.null(pairs)) par(mfrow=c(d-1,d-1)) for (d1 in 1:(d-1)){ for (d2 in 1:d){ if(d2!=d1){ if((d2 < d1) & is.null(pairs)){ plot.new() }else{ if(is.null(pairs) || all(pairs==c(d1,d2)) ){ myindex <- 1 for (ind in 1:d){ if(ind==d1){ prediction.points[,ind] <- lower[ind] + s.base[,1] * ( upper[ind] - lower[ind] ) scale.x <- lower[ind] + s * ( upper[ind] - lower[ind] ) name.x <- mynames[d1] }else if(ind==d2){ prediction.points[,ind] <- lower[ind] + s.base[,2] * ( upper[ind] - lower[ind] ) scale.y <- lower[ind] + s * ( upper[ind] - lower[ind] ) name.y <- mynames[d2] }else{ prediction.points[,ind] <- lower[ind] + integration.base[,myindex] * ( upper[ind] - lower[ind] ) myindex <- myindex + 1 } } pred <- predict_nobias_km(object=model,newdata=prediction.points,type="UK",low.memory=TRUE) pn <- excursion_probability(mn = pred$mean,sn = pred$sd,T = T) if(type=="pn") { myvect <- pn zlim <- c(0,1) }else if(type=="sur"){ myvect <- pn * (1-pn) zlim <- c(0,0.25) }else if(type=="timse"){ sk <- pred$sd mk <- pred$mean if(length(T)==1){ Wn <- 1/sqrt(2*pi*sk^2) * exp(-0.5*((mk-T)/sk)^2) }else{ weight0 <- 1/sqrt(2*pi*sk^2) Wn <- 0 for(i in 1:length(T)){ Ti <- T[i] Wn <- Wn + weight0 * exp(-0.5*((mk-Ti)/sk)^2) } } myvect <- sk^2 * Wn zlim <- NULL }else if(type=="imse"){ sk <- pred$sd myvect <- sk^2 zlim <- NULL }else{ myvect <- pn zlim <- c(0,1) } myvect <- matrix(myvect,nrow=nintegpoints) if (option == "mean") {myvect <- colMeans(myvect) }else if(option == "max"){myvect <- apply(X=myvect,MARGIN=2,FUN=max) }else if(option == "min"){myvect <- apply(X=myvect,MARGIN=2,FUN=min) }else{myvect <- colMeans(myvect)} mymatrix <- matrix(myvect, nrow=resolution,ncol=resolution) if(is.null(zlim)) zlim <- c(min(mymatrix),max(mymatrix)) image(x=scale.x,y=scale.y,z=mymatrix,zlim=zlim,col=grey.colors(10), xlab="",ylab="",cex.axis=cex.axis,axes=TRUE,...) mtext(name.x, side=1, line=xdecal,cex=cex.lab ) mtext(name.y, side=2, line=ydecal,cex=cex.lab ) if(!is.null(levels)){ contour(x=scale.x,y=scale.y,z=mymatrix,add=TRUE,labcex=cex.contourlab,levels=levels) } else { contour(x=scale.x,y=scale.y,z=mymatrix,add=TRUE,labcex=cex.contourlab,nlevels=nlevels) } } } } } } return(mean(myvect)) }
"dataGasSensor"
get_node_df_ws <- function(graph) { fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } if (graph_contains_node_selection(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "There is no selection of nodes available.") } graph$nodes_df %>% dplyr::filter(id %in% graph$node_selection$node) }
connListTwoDimensions = function(dimensions) { dimensions=as.integer(dimensions) if(!is.vector(dimensions) || length(dimensions)>2 || (!is.numeric(dimensions) && !is.integer(dimensions))) { stop("dimensions has to be a numeric vector of length 2") } if(dimensions[1]<2 || dimensions[2]<2) { stop("Each dimension has to have at least length 2") } conn = .Call("conn2Dim", dimensions, PACKAGE="PMA") nodeNumbers = matrix(0:(dimensions[1]*dimensions[2]-1), nrow=dimensions[1]) connList =list(nodes=nodeNumbers, conn=conn) class(connList) = "connListObj" return(connList) } is.connListObj = function(obj) { if(class(obj)!="connListObj") { stop("Object does not have the right class") } if(!is.integer(obj$nodes)) { stop("The nodes part has to be a vector of integers") } if(!(length(obj$conn)==length(obj$nodes))) { stop("The length of the conn part does not correspond to the number of nodes") } for(i in 1:length(obj$nodes)) { if(!(is.null(obj$conn[[i]]) || is.integer(obj$conn[[i]]))) { stop("All elements of the conn part have to be null or integer vectors") } } for(i in 1:length(obj$nodes)) { if(sum(!is.element(obj$conn[[i]], obj$nodes))>0) { stop(paste("Node",i,"has a connection to a non-existing node")) } } return(TRUE) } FLSA = function(y, lambda1=0, lambda2=NULL, connListObj = NULL, splitCheckSize=1e9, verbose=FALSE, thr=10e-10, maxGrpNum=4*length(y)) { splitCheckSize=as.integer(splitCheckSize) if(is.null(connListObj)) { if(is.vector(y)) { solObj = .Call("FLSA",y, PACKAGE="PMA") if(!is.null(lambda2)) { resLambda1Is0 = FLSAOneDimExplicitSolution(solObj,lambda2) if(lambda1!=0) { res = softThresholding(resLambda1Is0,lambda1) return(res) } else { return(resLambda1Is0) } } else { return(solObj) } } else if(is.matrix(y)) { connListObj = connListTwoDimensions(dim(y)) if(!is.null(lambda2)) { lambda2 = checkLambda2(lambda2) res=.Call("FLSAGeneralMain", connListObj, as.vector(y), lambda2, splitCheckSize, verbose, thr, as.integer(maxGrpNum), PACKAGE="PMA") res= array(res, dim=c(length(lambda2), dim(y))) myDimNames = list(lambda2, 1:(dim(y)[1]), 1:(dim(y)[2])) dimnames(res) = myDimNames if(lambda1!=0) { res = softThresholding(res, lambda1) } } else { res=.Call("FLSAGeneralMain", connListObj, as.vector(y), lambda2, splitCheckSize, verbose,thr, as.integer(maxGrpNum), PACKAGE="PMA") } return(res) } } else { if(!is.null(lambda2)) { lambda2=checkLambda2(lambda2) } if(length(connListObj$nodes)!=length(y)) { stop("y has to have the same number of nodes as connListObj") } res=.Call("FLSAGeneralMain", connListObj, as.vector(y), lambda2, splitCheckSize, verbose, thr, as.integer(maxGrpNum), PACKAGE="PMA") if(!is.null(lambda2) && (lambda1!=0)) { res = softThresholding(res, lambda1) } return(res) } } FLSAGetSolution = function(solObj, lambda2, lambda1=0, dim=NULL) { lambda2 = checkLambda2(lambda2) if(class(solObj)=="FLSA") { res = FLSAOneDimExplicitSolution(solObj, lambda2) if(lambda1!=0) { res = softThresholding(res, lambda1) } return(res) } else if(class(solObj)=="FLSAGeneral") { nodes = as.integer(which(solObj$InitialNodeMap>=0)-1) res = .Call("FLSAGeneralExplicitSolution",solObj,nodes, lambda2, PACKAGE="PMA") if(!is.null(dim)) { if(prod(dim)!=length(nodes)) { stop("Dimensions are not compatible with solObj") } res = array(res, dim=c(length(lambda2),dim)) } if(lambda1!=0) { res = softThresholding(res,lambda1) } return(res) } else { stop("solObj is not of class FLSA or FLSAGeneral") } } checkLambda2 = function(lambda2) { if(!is.numeric(lambda2)) { stop("lambda2 has to be a numeric vector") } if(sum(lambda2<0)>0) { stop("lambda2 has to be non-negative") } lambda2 = sort(unique(lambda2)) return(lambda2) } FLSAOneDimExplicitSolution = function(solObj, lambda2) { lambda2 = checkLambda2(lambda2) return(.Call("FLSAexplicitSolution",solObj, lambda2, PACKAGE="PMA")) } softThresholding = function(solMat, lambda1) { if(!is.numeric(lambda1)) { stop("lambda1 has to be a numeric vector") } if(sum(lambda1<0)>0) { stop("lambda1 has to be non-negative") } lambda1 = sort(unique(lambda1)) oldDim = dim(solMat) newDim = c(length(lambda1), oldDim) oldDimNames = dimnames(solMat) if(is.null(oldDimNames)) { oldDimNames = vector("list",2) } newDimNames = c(list(lambda1), oldDimNames) res = array(dim=newDim, dimnames = newDimNames) if(length(oldDim)==2) { for(i in 1:length(lambda1)) { foo = abs(solMat)-lambda1[i] foo[foo<0]=0 res[i,,] = sign(solMat) * foo } } else if(length(oldDim)==3) { for(i in 1:length(lambda1)) { foo = abs(solMat)-lambda1[i] foo[foo<0]=0 res[i,,,] = sign(solMat) * foo } } else { stop("Wrong dimension of solMat; please inform the maintainer of this package") } return(res) }
.onLoad <- function(...) { shiny::registerInputHandler("f7DatePicker.date", function(f7DatePicker.data, ...) { if (is.null(f7DatePicker.data) || length(f7DatePicker.data) < 1) { NULL } else { f7DatePicker.date <- unlist(f7DatePicker.data) if (is.numeric(f7DatePicker.date)) { f7DatePicker.date <- as.POSIXct(f7DatePicker.date / 1000, tz = "UTC", origin = "1970-01-01") } else { f7DatePicker.date <- as.POSIXct(f7DatePicker.date, format = "%Y-%m-%dT%H:%M:%S", tz = "UTC") } as.Date(f7DatePicker.date, tz = Sys.timezone()) } }, force = TRUE) }
expected <- eval(parse(text="c(FALSE, FALSE, FALSE)")); test(id=0, code={ argv <- eval(parse(text="list(structure(1:3, .Label = c(\"1\", \"2\", NA), class = \"factor\"), structure(1:3, .Label = c(\"1\", \"2\", NA), class = \"factor\"))")); do.call(`!=`, argv); }, o=expected);
context("implementation [log-likelihood and coefficients]") source_files <- dir(system.file("PlackettLuce0", package = "PlackettLuce"), full.names = TRUE) for (file0 in source_files) source(file0) source_files <- dir(system.file("Reference_Implementations", package = "PlackettLuce"), full.names = TRUE) for (file0 in source_files) source(file0) coef_tol <- 1e-06 loglik_tol <- 1e-12 logLik_poisson.gnm <- function(x) { n <- nlevels(x$eliminate) ll <- logLik(x) + n attr(ll, "df") <- attr(ll, "df") - n ll } R <- matrix(c(1, 2, 0, 0, 4, 1, 2, 3, 2, 1, 1, 1, 1, 2, 3, 0, 2, 1, 1, 0, 1, 0, 3, 2), nrow = 6, byrow = TRUE) colnames(R) <- c("apple", "banana", "orange", "pear") R <- as.rankings(R) if (require("Matrix") & requireNamespace("igraph") & requireNamespace("RSpectra")) { model0 <- PlackettLuce0(rankings = R) model1 <- PlackettLuce(rankings = R, npseudo = 0) test_that("coef match legacy code [fake partial rankings with ties]", { expect_equal(as.vector(coef(model0)), as.vector(coef(model1)), tolerance = coef_tol) }) test_that("logLik matches legacy code [fake partial rankings with ties]", { expect_equal(logLik(model0), logLik(model1), tolerance = loglik_tol) }) dat <- poisson_rankings(R, aggregate = FALSE, as.data.frame = TRUE) test_that("null deviance matches glm [fake partial rankings with ties]", { model2 <- glm(y ~ -1 + z, family = poisson, data = dat) expect_equal(-2*model1$null.loglik, model2$deviance) expect_equal(model1$df.null, model2$df.residual) }) } M <- matrix(c(1, 2, 3, 1, 1, 4, 2, 1, 2, 3, 4, 3), nrow = 6, byrow = TRUE) R <- as.rankings(M, "ordering") mod1 <- PlackettLuce(R, npseudo = 0) dat <- poisson_rankings(R, aggregate = FALSE, as.data.frame = TRUE) if (require(gnm) & require(BradleyTerry2)){ mod2 <- gnm(y ~ -1 + X, family = poisson, eliminate = z, data = dat, constrain = 1) BT_data <- data.frame(p1 = factor(M[,1]), p2 = factor(M[,2])) mod3 <- BTm(rep(1, 6), p1, p2, data = BT_data) test_that("estimates match gnm, BTm [fake paired comparisons]", { expect_equal(unname(coef(mod1)[-1]), unname(coef(mod2)[-1]), tolerance = coef_tol) expect_equal(unname(coef(mod2)[-1]), unname(coef(mod3)), tolerance = coef_tol) }) test_that("logLik matches gnm, BTm [fake paired comparisons]", { expect_equal(logLik(mod1), logLik(mod3), check.attributes = FALSE, tolerance = 1e-12) expect_equal(attr(logLik(mod3), "df"), attr(logLik_poisson.gnm(mod2), "df")) expect_equal(logLik(mod3), logLik_poisson.gnm(mod2), check.attributes = FALSE,tolerance = 1e-12) }) mod5 <- glm(y ~ -1 + z, family = poisson, data = dat) test_that("null deviance matches glm, BTm [fake paired comparisons]", { expect_equal(-2*mod1$null.loglik, mod3$null.deviance) expect_equal(-2*mod1$null.loglik, mod5$deviance) expect_equal(mod1$df.null, mod3$df.null) expect_equal(mod1$df.null, mod5$df.residual) }) } if (require(BradleyTerry2)){ icehockey2 <- subset(icehockey, result != 0.5) mod_BT <- BTm(outcome = result, player1 = visitor, player2 = opponent, id = "team", data = icehockey2) R <- matrix(0, nrow = nrow(icehockey2), ncol = nlevels(icehockey2$visitor)) R[cbind(seq_len(nrow(icehockey2)), icehockey2$visitor)] <- 2 - icehockey2$result R[cbind(seq_len(nrow(icehockey2)), icehockey2$opponent)] <- icehockey2$result + 1 mod_PL <- PlackettLuce(R, npseudo = 0) test_that("estimates match BTm [icehockey]", { expect_equal(unname(coef(mod_BT)), unname(coef(mod_PL))[-1], tolerance = coef_tol) }) test_that("log-likelihood matches BTm [icehockey]", { expect_equal(logLik(mod_BT), logLik(mod_PL), check.attributes = FALSE, tolerance = loglik_tol) expect_equal(attr(logLik(mod_BT), "df"), attr(logLik(mod_PL), "df")) }) } M <- matrix(c(1, 2, 0, 0, 3, 1, 4, 0, 1, 4, 0, 0, 2, 1, 4, 3, 2, 3, 4, 0, 1, 2, 3, 0), nrow = 6, byrow = TRUE) gamma <- PL(M) lambda <- log(c(gamma/sum(gamma))) lambda <- lambda - lambda[1] R <- as.rankings(M, "ordering") mod1 <- PlackettLuce(R, npseudo = 0) if (require(gnm)){ dat <- dat <- poisson_rankings(R, aggregate = FALSE, as.data.frame = TRUE) mod2 <- gnm(y ~ -1 + X, family = poisson, eliminate = z, data = dat, constrain = 1) test_that("coef match Hunter's MM, gnm [fake partial rankings no ties]", { expect_equal(unname(coef(mod1))[-1], unname(coef(mod2))[-1], tolerance = coef_tol) expect_equal(unname(c(coef(mod1))), lambda, tolerance = coef_tol) }) test_that("logLik matches gnm [fake partial rankings no ties]", { expect_equal(logLik(mod1), logLik_poisson.gnm(mod2), check.attributes = FALSE, tolerance = loglik_tol) }) } if (require(StatRank)){ data(Data.Nascar) gamma <- PL(Data.Nascar) lambda <- log(c(gamma/sum(gamma))) lambda <- lambda - lambda[1] R <- as.rankings(Data.Nascar, input = "ordering") mod1 <- PlackettLuce(R, npseudo = 0) dat <- PlackettLuce:::poisson_rankings(R, aggregate = FALSE, as.data.frame = TRUE) mod2 <- gnm(y ~ -1 + X, family = poisson, eliminate = z, data = dat, constrain = 1) test_that("coef match Hunter's MM, gnm [nascar]", { expect_equal(unname(coef(mod1))[-1], unname(coef(mod2))[-1], tolerance = coef_tol) expect_equal(unname(c(coef(mod1))), lambda, tolerance = coef_tol, check.attributes = FALSE) }) test_that("logLik matches gnm [nascar]", { expect_equal(logLik(mod1), logLik_poisson.gnm(mod2), check.attributes = FALSE, tolerance = loglik_tol) }) }
grfx <- function(n, G, incidence = NULL, saveIncidence = FALSE, output = "matrix", stdnorms = NULL, warn = TRUE){ d <- nrow(G) if(d > 1 && all(G == G[1,1])) warning("variance-covariance matrix 'G' may have caused 'chol.default(G)' error. If so, consider subtracting 0.0001 from the covariances to make correlations < 1 or >-1") Mg <- as(chol(G), "dtCMatrix") if(is.null(incidence)){ if(any(ls(envir = globalenv() ) == "nadiv_prev_Mincidence")){ if(warn) warning("using previous incidence matrix") } else{ if(saveIncidence){ nadiv_prev_Mincidence <<- Diagonal(n, 1) } else{ nadiv_prev_Mincidence <- Diagonal(n, 1) } if(warn) warning("Incidence matrix used = Identity matrix") } } else{ if(saveIncidence){ nadiv_prev_Mincidence <<- chol(incidence) } else{ nadiv_prev_Mincidence <- chol(incidence) } } M <- suppressMessages(kronecker(nadiv_prev_Mincidence, Mg)) if(is.null(stdnorms)){ Z <- Matrix(rnorm(n*d), nrow = 1) } else{ if(length(stdnorms) != n*d) stop("length(stdnorms) must be equal to 'n' times the order of 'G'") Z <- Matrix(stdnorms, nrow = 1) } X <- Matrix((Z %*% M)@x, ncol = d, byrow = TRUE) return(as(X, output)) }
interUniform<-function(AngleLower, AngleUpper) { uniformLAD<-function(LeafAngle) { (2/pi)*rep(1, length(LeafAngle)) } pi180<-pi/180.0 fraction<-integrate(uniformLAD, lower=AngleLower*pi180, upper=AngleUpper*pi180) fraction[[1]] }
"ACMx" <- function(y,order=c(1,1),X=NULL,cond.dist="po",ini=NULL){ beta=NULL; k=0; withX=FALSE; nT=length(y) if(!is.null(X)){ withX=TRUE if(!is.matrix(X))X=as.matrix(X) T1=dim(X)[1] if(nT > T1)nT=T1 if(nT < T1){T1=nT; X=X[1:T1,]} k=dim(X)[2] m1=glm(y~X,family=poisson) m11=summary(m1) beta=m11$coefficients[-1,1]; se.beta=m11$coefficients[-1,2] glmresi=m1$residuals } mm=glm(y[2:nT]~y[1:(nT-1)],family=poisson) m22=summary(mm) ome=m22$coefficients[1,1]; se.ome=m22$coefficients[1,2] p=order[1]; q=order[2]; S=1.0*10^(-6); params=NULL; loB=NULL; upB=NULL if(cond.dist=="po"){ if(withX){ params=c(params,beta=beta); loB=c(loB,beta=beta-2*abs(beta)); upB=c(upB,beta=beta+2*abs(beta)) } params=c(params,omega=ome); loB=c(loB,omega=S); upB=c(upB,omega=ome+10*ome) if(p > 0){ a1=rep(0.05,p); params=c(params,alpha=a1); loB=c(loB,alpha=rep(S,p)); upB=c(upB,alpha=rep(0.5,p)) } if(q > 0){ b1=rep(0.5,q) params=c(params,gamma=b1); loB=c(loB,gamma=rep(S,q)); upB=c(upB,gamma=rep(1-S,q)) } cat("Initial estimates: ",params,"\n") cat("loB: ",loB,"\n") cat("upB: ",upB,"\n") fit=nlminb(start = params, objective= poX, lower=loB, upper=upB, PCAxY=y, PCAxX=X, PCAxOrd=order, control=list(rel.tol=1e-6)) epsilon = 0.0001 * fit$par npar=length(params) Hessian = matrix(0, ncol = npar, nrow = npar) for (i in 1:npar) { for (j in 1:npar) { x1 = x2 = x3 = x4 = fit$par x1[i] = x1[i] + epsilon[i]; x1[j] = x1[j] + epsilon[j] x2[i] = x2[i] + epsilon[i]; x2[j] = x2[j] - epsilon[j] x3[i] = x3[i] - epsilon[i]; x3[j] = x3[j] + epsilon[j] x4[i] = x4[i] - epsilon[i]; x4[j] = x4[j] - epsilon[j] Hessian[i, j] = (poX(x1,PCAxY=y,PCAxX=X,PCAxOrd=order)-poX(x2,PCAxY=y,PCAxX=X,PCAxOrd=order) -poX(x3,PCAxY=y,PCAxX=X,PCAxOrd=order)+poX(x4,PCAxY=y,PCAxX=X,PCAxOrd=order))/ (4*epsilon[i]*epsilon[j]) } } cat("Maximized log-likehood: ",-poX(fit$par,PCAxY=y,PCAxX=X,PCAxOrd=order),"\n") se.coef = sqrt(diag(solve(Hessian))) tval = fit$par/se.coef matcoef = cbind(fit$par, se.coef, tval, 2*(1-pnorm(abs(tval)))) dimnames(matcoef) = list(names(tval), c(" Estimate", " Std. Error", " t value", "Pr(>|t|)")) cat("\nCoefficient(s):\n") printCoefmat(matcoef, digits = 6, signif.stars = TRUE) est=fit$par; ist=1 bb=rep(1,length(y)); y1=y if(withX){beta=est[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1 ome=est[icnt] p=order[1]; q=order[2]; nT=length(y) if(p > 0){a1=est[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } r1=ome if(q > 0){g1=est[(icnt+1):(icnt+q)] r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } rate=bb[ist:nT]*r1 resi=y[ist:nT]-rate sresi=resi/sqrt(rate) } if(cond.dist=="nb"){ if(is.null(ini)){ if(withX){ params=c(params,beta=rep(0.4,k)); loB=c(loB,beta=rep(-3,k)); upB=c(upB,beta=rep(2,k)) } params=c(params,omega=ome); loB=c(loB,omega=S); upB=c(upB,omega=ome+6*se.ome) if(p > 0){ a1=rep(0.05,p); params=c(params,alpha=a1); loB=c(loB,alpha=rep(S,p)); upB=c(upB,alpha=rep(0.5,p)) } if(q > 0){ b1=rep(0.7,q) params=c(params,gamma=b1); loB=c(loB,gamma=rep(S,q)); upB=c(upB,gamma=rep(1-S,q)) } } else{ se.ini=abs(ini/10); jst= k if(withX){ params=c(params,beta=ini[1:k]); loB=c(loB,beta=ini[1:k]-4*se.ini[1:k]); upB=c(upB,beta=ini[1:k]+4*se.ini[1:k]) } jst=k+1 params=c(params,omega=ini[jst]); loB=c(loB,omega=ini[jst]-3*se.ini[jst]); upB=c(upB,omega=ini[jst]+3*se.ini[jst]) if(p > 0){a1=ini[(jst+1):(jst+p)]; params=c(params,alpha=a1); loB=c(loB,alpha=rep(S,p)) upB=c(upB,alpha=a1+3*se.ini[(jst+1):(jst+p)]); jst=jst+p } if(q > 0){ b1=ini[(jst+1):(jst+q)] params=c(params,gamma=b1); loB=c(loB,gamma=rep(S,q)); upB=c(upB,gamma=rep(1-S,q)) } } meanY=mean(y); varY=var(y); th1=meanY^2/(varY-meanY)*2; if(th1 < 0)th1=meanY*0.1 params=c(params,theta=th1); loB=c(loB,theta=0.5); upB=c(upB,theta=meanY*1.5) cat("initial estimates: ",params,"\n") cat("loB: ",loB,"\n") cat("upB: ",upB,"\n") fit=nlminb(start = params, objective= nbiX, lower=loB, upper=upB, PCAxY=y,PCAxX=X,PCAxOrd=order, control=list(rel.tol=1e-6)) epsilon = 0.0001 * fit$par npar=length(params) Hessian = matrix(0, ncol = npar, nrow = npar) for (i in 1:npar) { for (j in 1:npar) { x1 = x2 = x3 = x4 = fit$par x1[i] = x1[i] + epsilon[i]; x1[j] = x1[j] + epsilon[j] x2[i] = x2[i] + epsilon[i]; x2[j] = x2[j] - epsilon[j] x3[i] = x3[i] - epsilon[i]; x3[j] = x3[j] + epsilon[j] x4[i] = x4[i] - epsilon[i]; x4[j] = x4[j] - epsilon[j] Hessian[i, j] = (nbiX(x1,PCAxY=y,PCAxX=X,PCAxOrd=order)-nbiX(x2,PCAxY=y,PCAxX=X,PCAxOrd=order) -nbiX(x3,PCAxY=y,PCAxX=X,PCAxOrd=order)+nbiX(x4,PCAxY=y,PCAxX=X,PCAxOrd=order))/ (4*epsilon[i]*epsilon[j]) } } cat("Maximized log-likehood: ",-nbiX(fit$par,PCAxY=y,PCAxX=X,PCAxOrd=order),"\n") se.coef = sqrt(diag(solve(Hessian))) tval = fit$par/se.coef matcoef = cbind(fit$par, se.coef, tval, 2*(1-pnorm(abs(tval)))) dimnames(matcoef) = list(names(tval), c(" Estimate", " Std. Error", " t value", "Pr(>|t|)")) cat("\nCoefficient(s):\n") printCoefmat(matcoef, digits = 6, signif.stars = TRUE) est=fit$par bb=rep(1,length(y)); y1=y if(withX){beta=est[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1 ome=est[icnt] p=order[1]; q=order[2]; nT=length(y) if(p > 0){a1=est[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } if(q > 0){g1=est[(icnt+1):(icnt+q)]; icnt=icnt+q r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } rate=bb[ist:nT]*r1 resi=y[ist:nT]-rate theta=est[icnt+1] pb=theta/(theta+rate) v1=theta*(1-pb)/(pb^2) sresi=resi/sqrt(v1) } if(cond.dist=="dp"){ if(withX){ params=c(params,beta=beta); loB=c(loB,beta=beta-2*abs(beta)); upB=c(upB,beta=beta+2*abs(beta)) } params=c(params,omega=ome*0.3); loB=c(loB,omega=S); upB=c(upB,omega=ome+4*se.ome) if(p > 0){ a1=rep(0.05,p); params=c(params,alpha=a1); loB=c(loB,alpha=rep(S,p)); upB=c(upB,alpha=rep(1-S,p)) } if(q > 0){ b1=rep(0.6,q) params=c(params,gamma=b1); loB=c(loB,gamma=rep(S,q)); upB=c(upB,gamma=rep(1-S,q)) } meanY=mean(y); varY = var(y); t1=meanY/varY params=c(params,theta=t1); loB=c(loB,theta=S); upB=c(upB,theta=2) cat("initial estimates: ",params,"\n") cat("loB: ",loB,"\n") cat("upB: ",upB,"\n") fit=nlminb(start = params, objective= dpX, lower=loB, upper=upB,PCAxY=y,PCAxX=X,PCAxOrd=order, control=list(rel.tol=1e-6)) epsilon = 0.0001 * fit$par npar=length(params) Hessian = matrix(0, ncol = npar, nrow = npar) for (i in 1:npar) { for (j in 1:npar) { x1 = x2 = x3 = x4 = fit$par x1[i] = x1[i] + epsilon[i]; x1[j] = x1[j] + epsilon[j] x2[i] = x2[i] + epsilon[i]; x2[j] = x2[j] - epsilon[j] x3[i] = x3[i] - epsilon[i]; x3[j] = x3[j] + epsilon[j] x4[i] = x4[i] - epsilon[i]; x4[j] = x4[j] - epsilon[j] Hessian[i, j] = (dpX(x1,PCAxY=y,PCAxX=X,PCAxOrd=order)-dpX(x2,PCAxY=y,PCAxX=X,PCAxOrd=order) -dpX(x3,PCAxY=y,PCAxX=X,PCAxOrd=order)+dpX(x4,PCAxY=y,PCAxX=X,PCAxOrd=order))/ (4*epsilon[i]*epsilon[j]) } } cat("Maximized log-likehood: ",-dpX(fit$par,PCAxY=y,PCAxX=X,PCAxOrd=order),"\n") se.coef = sqrt(diag(solve(Hessian))) tval = fit$par/se.coef matcoef = cbind(fit$par, se.coef, tval, 2*(1-pnorm(abs(tval)))) dimnames(matcoef) = list(names(tval), c(" Estimate", " Std. Error", " t value", "Pr(>|t|)")) cat("\nCoefficient(s):\n") printCoefmat(matcoef, digits = 6, signif.stars = TRUE) est=fit$par bb=rep(1,length(y)); y1=y if(withX){beta=est[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1 ome=est[icnt] p=order[1]; q=order[2]; nT=length(y) if(p > 0){a1=est[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } if(q > 0){g1=est[(icnt+1):(icnt+q)]; icnt=icnt+q r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } theta=est[icnt+1] rate=bb[ist:nT]*r1 resi=y[ist:nT]-rate v1=rate/theta sresi=resi/sqrt(rate) } ACMx <- list(data=y,X=X,estimates=est,residuals=resi,sresi=sresi) } "nbiX" <- function(par,PCAxY,PCAxX,PCAxOrd){ y <- PCAxY; X <- PCAxX; order <- PCAxOrd withX = F; k = 0 if(!is.null(X)){ withX=T; k=dim(X)[2] } bb=rep(1,length(y)); y1=y if(withX){beta=par[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1 ome=par[icnt] p=order[1]; q=order[2]; nT=length(y) if(p > 0){a1=par[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } if(q > 0){g1=par[(icnt+1):(icnt+q)]; icnt=icnt+q r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } theta=par[icnt+1] rate=bb[ist:nT]*r1 pb=theta/(theta+rate) lnNBi=dnbinom(y[ist:nT],size=theta,prob=pb,log=T) nbiX <- -sum(lnNBi) } "poX" <- function(par,PCAxY,PCAxX,PCAxOrd){ y <- PCAxY; X <- PCAxX; order <- PCAxOrd withX = F; k=0 if(!is.null(X)){ withX=T; k=dim(X)[2] } bb=rep(1,length(y)); y1=y if(withX){beta=par[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1; ist=1; nT=length(y); nobe=nT ome=par[icnt]; rate=rep(ome,nobe) p=order[1]; q=order[2] if(p > 0){a1=par[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } r1=rate if(q > 0){g1=par[(icnt+1):(icnt+q)] r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } rate=bb[ist:nT]*r1 lnPoi=dpois(y[ist:nT],rate,log=T) poX <- -sum(lnPoi) } "dpX" <- function(par,PCAxY,PCAxX,PCAxOrd){ y <- PCAxY; X <- PCAxX; order <- PCAxOrd withX=F; k = 0 if(!is.null(X)){ withX=TRUE; k=dim(X)[2] } bb=rep(1,length(y)); y1=y if(withX){beta=par[1:k]; bb=exp(X%*%matrix(beta,k,1))} icnt=k+1 ome=par[icnt] p=order[1]; q=order[2]; nT=length(y) if(p > 0){a1=par[(icnt+1):(icnt+p)]; icnt=icnt+p nobe=nT-p; rate=rep(ome,nobe); ist=p+1 for (i in 1:p){ rate=rate+a1[i]*y1[(ist-i):(nT-i)] } } if(q > 0){g1=par[(icnt+1):(icnt+q)]; icnt=icnt+q r1=filter(rate,g1,"r",init=rep(mean(y/bb),q)) } theta=par[icnt+1] rate=bb[ist:nT]*r1 yy=y[ist:nT] rate1 = rate*theta cinv=1+(1-theta)/(12*rate1)*(1+1/rate1) lcnt=-log(cinv) lpd=lcnt+0.5*log(theta)-rate1 idx=c(1:nobe)[yy > 0] tp=length(idx) d1=apply(matrix(yy[idx],tp,1),1,factorialOwn) lpd[idx]=lpd[idx]-d1-yy[idx]+yy[idx]*log(yy[idx])+theta*yy[idx]*(1+log(rate[idx])-log(yy[idx])) dpX <- -sum(lpd) } "factorialOwn" <- function(n,log=T){ x=c(1:n) if(log){ x=log(x) y=cumsum(x) } else{ y=cumprod(x) } y[n] }
after_join_all <- function(x, y, by_user, by_time, mode = 'inner', ...){ types <- c( 'first-first', 'first-firstafter', 'lastbefore-firstafter', 'any-firstafter', 'any-any' ) by_type <- function(type){ after_join(x, y, by_user = by_user, by_time = by_time, mode = mode, type = type) %>% dplyr::mutate(!!type := 'Y') } join_fun <- match.fun(paste0(mode, '_join')) all_types <- types %>% purrr::map(by_type) join_fun(x, y, by = by_user) %>% Reduce(dplyr::left_join, all_types, init = .) %>% dplyr::filter_at(dplyr::vars(dplyr::one_of(types)), dplyr::any_vars(!is.na(.))) }
order_snormal1 <- function(size,k,mu,sigma,nu,tau,n,alpha=0.05,...){ sample <- qST1(initial_order(size,k,n),mu,sigma,nu,tau,...) pdf <- factorial(size)*cumprod(dST1(sample,mu,sigma,nu,tau,...))[size] if(size>5){ return(list(sample=sample,pdf=pdf,ci_median=interval_median(size,sample,alpha))) } cat("---------------------------------------------------------------------------------------------\n") cat("We cannot report the confidence interval. The size of the sample is less or equal than five.\n") return(list(sample=sample,pdf=pdf)) }
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "tanSearch" set.seed(2) training <- LPH07_1(100, factors = TRUE, class = TRUE) testing <- LPH07_1(100, factors = TRUE, class = TRUE) trainX <- training[, -ncol(training)] trainY <- training$Class rec_cls <- recipe(Class ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl2 <- trainControl(method = "LOOCV", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl3 <- trainControl(method = "none", classProbs = TRUE, summaryFunction = twoClassSummary) cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random") set.seed(849) test_class_cv_model <- train(trainX, trainY, method = "tanSearch", trControl = cctrl1, metric = "ROC") test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)]) test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rand <- train(trainX, trainY, method = "tanSearch", trControl = cctrlR, tuneLength = 4) set.seed(849) test_class_loo_model <- train(trainX, trainY, method = "tanSearch", trControl = cctrl2, metric = "ROC") set.seed(849) test_class_none_model <- train(trainX, trainY, method = "tanSearch", trControl = cctrl3, tuneGrid = test_class_cv_model$bestTune, metric = "ROC") test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)]) test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob") test_levels <- levels(test_class_cv_model) if(!all(levels(trainY) %in% test_levels)) cat("wrong levels") test_class_predictors1 <- predictors(test_class_cv_model) test_class_imp <- varImp(test_class_cv_model) tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) sInfo <- sessionInfo() timestamp_end <- Sys.time() save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
AssignItem = R6Class("AssignItem", inherit = Item, public = list( initialize = function(decl, value){ assertR6(decl, "VarDecl") assertNull(decl$getValue()) assertR6(value, "Expression") private$.decl = decl private$.e = value }, id = function(){ return(private$.decl$getId()$getName()) }, getValue = function(){ return(private$.e) }, setValue = function(val){ assertR6(val, "Expression") private$.e = val }, getDecl = function(){ return(private$.decl) }, setDecl = function(decl){ assertR6(decl, "VarDecl") private$.decl = decl }, c_str = function(){ return(sprintf("%s = %s;\n", private$.decl$getId()$getName(), private$.e$c_str())) }, getDeleteFlag = function(){ return(private$.delete_flag) }, delete = function(){ private$.delete_flag = TRUE helperDeleteItem("AssignItem") } ), private = list( .decl = NULL, .e = NULL, .delete_flag = FALSE ))
"fitted.drc" <- function(object, ...) { predict(object, ...) }
NULL show_line_types <- function() { lt <- c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash") d <- data.frame(lt = factor(lt, levels = lt)) ggplot() + scale_x_continuous(name="", limits=c(0,1), breaks=NULL) + scale_linetype_identity() + geom_segment(data=d, mapping=aes(x=0, xend=1, y=lt, yend=lt, linetype=lt))+ labs(title = "Line types available in R", y = "")+ theme(axis.text.y = element_text(face="bold", color="black")) }
"puerto_rico_icd"
foo <- function() { 1 }
[ { "title": "BLATting the internet: the most frequent gene?", "href": "https://nsaunders.wordpress.com/2014/01/24/blatting-the-internet-the-most-frequent-gene/" }, { "title": "2013-10 Automatic Conversion of Tables to LongForm Dataframes", "href": "http://stattech.wordpress.fos.auckland.ac.nz/2013-10-automatic-conversion-of-tables-to-longform-dataframes/" }, { "title": "Log File Analysis with R", "href": "http://www.r-chart.com/2012/02/log-file-analysis-with-r.html" }, { "title": "Tuning LaplacesDemon", "href": "http://wiekvoet.blogspot.com/2014/10/tuning-laplacesdemon.html" }, { "title": "The Social Dynamics of the R Core Team", "href": "http://www.johnmyleswhite.com/notebook/2012/08/12/the-social-dynamics-of-the-r-core-team/" }, { "title": "Estimating ODE’s parameters", "href": "https://web.archive.org/web/http://anotherrblog.blogspot.com/2013/07/estimating-odes-parameters.html" }, { "title": "Computing for Data Analysis Returns", "href": "http://simplystatistics.org/2012/12/14/computing-for-data-analysis-returns/" }, { "title": "Statistical Models with a Point of View: First vs. Third Person", "href": "http://joelcadwell.blogspot.com/2015/06/statistical-models-with-point-of-view.html" }, { "title": "Clustering analysis and its implementation in R", "href": "http://onetipperday.sterding.com/2012/04/clustering-analysis-2.html" }, { "title": "Reminder: useR! 2011 abstracts, earlybird registration deadline April 1", "href": "http://blog.revolutionanalytics.com/2011/03/reminder-user-2011-abstracts-earlybird-registration-deadline-april-1.html" }, { "title": "Migrating from SPSS/Excel to R", "href": "https://psychwire.wordpress.com/2011/07/10/migrating-from-spssexcel-to-r/" }, { "title": "Images as x-axis labels (updated)", "href": "http://jcarroll.com.au/2016/06/03/images-as-x-axis-labels-updated/" }, { "title": "R, drug development and the FDA", "href": "http://blog.revolutionanalytics.com/2013/08/r-drug-development-and-the-fda.html" }, { "title": "My first… web application with Shiny", "href": "http://www.milanor.net/blog/my-first-web-application-with-shiny/" }, { "title": "Here’s an improved system.time function for R", "href": "http://userprimary.net/posts/2006/05/14/heres-an-improved-systemtime-function-for-r/" }, { "title": "When the “reorder” function just isn’t good enough…", "href": "https://rforwork.info/2013/05/06/when-the-reorder-function-just-isnt-good-enough/" }, { "title": "(Semi-)automating the R markdown to blogger workflow", "href": "https://web.archive.org/web/http://metvurst.blogspot.com/2013/01/automating-r-markdown-to-blogger.html" }, { "title": "The animation package", "href": "http://sgsong.blogspot.com/2009/12/animation-package.html" }, { "title": "Where’s Waldo? Image Analysis in R", "href": "http://blog.revolutionanalytics.com/2012/05/wheres-waldo-image-analysis-in-r.html" }, { "title": "Wanted: A Perfect Scatterplot (with Marginals)", "href": "http://www.win-vector.com/blog/2015/06/wanted-a-perfect-scatterplot-with-marginals/" }, { "title": "Quantitative link strength for APE cophyloplot", "href": "https://rtricks.wordpress.com/2009/11/17/quantitative-link-strength-for-ape-cophyloplot/" }, { "title": "The making of cricket package yorkr – Part 3", "href": "https://gigadom.wordpress.com/2016/03/17/the-making-of-cricket-package-yorkr-part-3/" }, { "title": "Probabilistic Momentum with Intraday data", "href": "https://systematicinvestor.wordpress.com/2014/03/31/probabilistic-momentum-with-intraday-data/" }, { "title": "Web-Scraper for Google Scholar Updated!", "href": "http://thebiobucket.blogspot.com/2012/08/web-scraper-for-google-scholar-updated.html" }, { "title": "Personal CRAN-repository", "href": "http://gforge.se/2012/11/personal-cran-repository/" }, { "title": "Better decision tree graphics for rpart via party and partykit", "href": "http://blog.nguyenvq.com/blog/2012/05/29/better-decision-tree-graphics-for-rpart-via-party-and-partykit/" }, { "title": "Exponentiation of a matrix (including pseudoinverse)", "href": "http://menugget.blogspot.com/2012/03/exponentiation-of-matrix-including.html" }, { "title": "How many pages in Scott Walker Recall Petition PDF files?", "href": "http://franklincenterhq.org/3049/how-many-pages-in-scott-walker-recall-petition-pdf-files/" }, { "title": "The Zebra Of Riemann", "href": "https://aschinchon.wordpress.com/2014/07/13/the-zebra-of-riemann/" }, { "title": "Converting MATLAB and R date and time values", "href": "http://lukemiller.org/index.php/2011/02/converting-matlab-and-r-date-and-time-values/" }, { "title": "Revisiting MPs’ Expenses", "href": "https://blog.ouseful.info/2013/04/02/revisiting-mps-expenses/" }, { "title": "Reorder factor levels", "href": "http://quantitative-ecology.blogspot.com/2007/10/reorder-factor-levels.html" }, { "title": "Fantasy football (oops, soccer)", "href": "http://www.rcasts.com/2010/12/fantasy-football-oops-soccer.html" }, { "title": "Tapply on steroids – by (climate trends in Scottish seasons)", "href": "https://scottishsnow.wordpress.com/2015/03/20/tapply-on-steroids-by-climate-trends-in-scottish-seasons/" }, { "title": "A Quick and Dirty Guide to Exploratory Data Visualization", "href": "http://r-datameister.blogspot.com/2013/07/a-quick-and-dirty-guide-to-exploratory.html" }, { "title": "New R IDE", "href": "http://quantitativeecology.blogspot.com/2011/03/new-r-ide.html" }, { "title": "Reducing Respondent Burden: Item Sampling", "href": "http://joelcadwell.blogspot.com/2013/01/reducing-respondent-burden-item-sampling.html" }, { "title": "Rchievement of the day", "href": "https://wkmor1.wordpress.com/2011/08/16/rchievement-of-the-day/" }, { "title": "DataCamp for Business – New & Improved", "href": "https://www.datacamp.com/community/blog/datacamp-for-business-new-improved" }, { "title": "Lists of English Words", "href": "http://www.bytemining.com/2010/10/lists-of-english-words/" }, { "title": "Yet another R report generator, and more!", "href": "http://biostatmatt.com/archives/1000" }, { "title": "Give your R charts that Wes Anderson style", "href": "http://blog.revolutionanalytics.com/2014/03/give-your-r-charts-that-wes-anderson-style.html" }, { "title": "Display googleVis charts within RStudio", "href": "http://www.magesblog.com/2013/11/display-googlevis-charts-within-rstudio.html" }, { "title": "Throw some, throw some STATS on that map…(Part 1)", "href": "http://spatioanalytics.com/2013/07/12/throw-some-throw-some-stats-on-that-map-part-1/" }, { "title": "R IDE and debugger now available for 64-bit Windows; Webinar Tuesday", "href": "https://web.archive.org/web/http://blog.revolution-computing.com/2010/02/r-ide-and-debugger-now-available-for-64bit-windows-webinar-tuesday.html" }, { "title": "Spurious correlations and the Lasso", "href": "https://sieste.wordpress.com/2012/05/13/spurious-correlations-and-the-lasso/" }, { "title": "Introduction to my New IKReporting Package", "href": "https://quantstrattrader.wordpress.com/2015/03/09/introduction-to-my-new-ikreporting-package/" }, { "title": "Win Books and T-shirts in Our DataScience.LA Meetup Raffles, Powered by R and dplyr!", "href": "http://datascience.la/win-books-and-t-shirts-in-our-datascience-la-meetup-raffles-powered-by-r-and-dplyr/" }, { "title": "2 New (Draft) Chapters for Intro Fish Science with R", "href": "https://web.archive.org/web/https://fishr.wordpress.com/2014/11/16/2-new-draft-chapters-for-intro-fish-science-with-r/" }, { "title": "Access all UCSC wiggle tracks from R and your terminal", "href": "http://zvfak.blogspot.com/2011/02/access-all-ucsc-wiggle-tracks-from-r.html" } ]
cv.nfeaturesLDA = function( data = matrix(rnorm(600), 60), cl = gl(3, 20), k = 5, cex.rg = c(0.5, 3), col.av = c('blue', 'red'), ... ) { requireNamespace('MASS') nmax = min(ncol(data), ani.options('nmax')) cl = as.factor(cl) dat = data.frame(data, cl) N = nrow(dat) n = sample(N) dat = dat[n, ] kf = cumsum(c(1, kfcv(k, N))) aovF = function(x, cl) { qr.obj <- qr(model.matrix(~cl)) qty.obj <- qr.qty(qr.obj, x) tab <- table(factor(cl)) dfb <- length(tab) - 1 dfw <- sum(tab) - dfb - 1 ms.between <- apply(qty.obj[2:(dfb + 1), , drop = FALSE]^2, 2, sum)/dfb ms.within <- apply(qty.obj[-(1:(dfb + 1)), , drop = FALSE]^2, 2, sum)/dfw Fstat <- ms.between/ms.within } acc = matrix(nrow = k, ncol = nmax) loc = cbind(rep(1:nmax, each = k), rep(1:k, nmax)) op = par(mfrow = c(1, 2)) for (j in 1:nmax) { for (i in 2:(k + 1)) { dev.hold() idx = kf[i - 1]:(kf[i] - 1) trdat = dat[-idx, ] slct = order(aovF( as.matrix(trdat[, -ncol(trdat)]), trdat[, ncol(trdat)] ), decreasing = TRUE) <= j fit = MASS::lda(as.formula(paste( colnames(dat)[ncol(dat)], '~', paste(colnames(dat)[-ncol(dat)][slct], collapse = '+') )), data = dat) pred = predict(fit, dat[idx, ], dimen = 2) acc[i - 1, j] = mean(dat[idx, ncol(dat)] == pred$class) plot( 1, xlim = c(1, nmax), ylim = c(0, k), type = 'n', ylab = 'Fold', xlab = 'Number of Features', yaxt = 'n', panel.first = grid() ) axis(2, 1:k) axis(2, 0, expression(bar(p))) if ((j - 1) * k + i - 1 < nmax * k) text(matrix(loc[-(1:((j - 1) * k + i - 1)), ], ncol = 2), '?') points(matrix(loc[1:((j - 1) * k + i - 1), ], ncol = 2), cex = c(acc)^2 * diff(cex.rg) + min(cex.rg), col = col.av[1], ...) points( 1:nmax, rep(0, nmax), col = col.av[2], ..., cex = apply(acc, 2, mean, na.rm = TRUE) * diff(cex.rg) + min(cex.rg) ) styl.pch = as.integer(dat[idx, ncol(dat)]) styl.col = 2 - as.integer(dat[idx, ncol(dat)] == pred$class) plot(pred$x, pch = styl.pch, col = styl.col) legend('topright', legend = c('correct', 'wrong'), fill = 1:2, bty = 'n', cex = 0.8) legend('bottomleft', legend = levels(dat[idx, ncol(dat)])[unique(styl.pch)], pch = unique(styl.pch), bty = 'n', cex = 0.8) ani.pause() } } par(op) rownames(acc) = paste('Fold', 1:k, sep = '') colnames(acc) = 1:nmax nf = which.max(apply(acc, 2, mean)) names(nf) = NULL invisible(list(accuracy = acc, optimum = nf)) }
context("Test logger functions.") rm(list = ls()) test_that("logging works", { expect_true({ log_info("the stuff") TRUE }) expect_warning({ log_warn("some stuff") }, regexp = "some stuff") expect_error({ log_fatal("other stuff") }, regexp = "other stuff") }) rm(list = ls()) closeAllConnections()
global_handle <- function(entrace = TRUE, prompt_install = TRUE) { check_bool(entrace) check_bool(prompt_install) global_entrace(entrace) global_prompt_install(prompt_install) invisible(NULL) } global_prompt_install <- function(enable = TRUE) { check_bool(enable) if (getRversion() <= "4.0") { return(invisible(NULL)) } poke_global_handlers( enable, packageNotFoundError = hnd_prompt_install ) } hnd_prompt_install <- function(cnd) { if (!rlang::is_interactive()) { return(rlang::zap()) } if (!rlang::is_string(cnd$package) || is.null(findRestart("retry_loadNamespace"))) { return(rlang::zap()) } rlang::check_installed(cnd$package) invokeRestart("retry_loadNamespace") } environment(hnd_prompt_install) <- baseenv() try_fetch <- function(expr, ...) { frame <- environment() catch <- value <- NULL delayedAssign("catch", return(value), frame, frame) throw <- function(x) { value <<- x catch } .External(ffi_try_fetch, frame) } handler_call <- quote(function(cnd) { { .__handler_frame__. <- TRUE .__setup_frame__. <- frame } out <- handlers[[i]](cnd) if (!inherits(out, "rlang_zap")) throw(out) }) catch_cnd <- function(expr, classes = "condition") { stopifnot(is_character(classes)) handlers <- rep_named(classes, list(identity)) eval_bare(rlang::expr( tryCatch(!!!handlers, { force(expr) return(NULL) }) )) } cnd_muffle <- function(cnd) { restart <- switch(cnd_type(cnd), message = "muffleMessage", warning = "muffleWarning", interrupt = "resume", "rlang_muffle" ) if (!is_null(findRestart(restart))) { invokeRestart(restart) } FALSE } if (getRversion() < "4.0") { utils::globalVariables("globalCallingHandlers") } poke_global_handlers <- function(enable, ...) { check_bool(enable) handlers <- list2(...) if (enable) { inject(globalCallingHandlers(!!!handlers)) } else { inject(drop_global_handlers(!!!handlers)) } } drop_global_handlers <- function(...) { to_pop <- list(...) handlers <- globalCallingHandlers() for (i in seq_along(to_pop)) { if (loc <- detect_index(handlers, identical, to_pop[[i]])) { if (is_string(names(to_pop)[[i]], names(handlers)[[loc]])) { handlers[[loc]] <- NULL } } } globalCallingHandlers(NULL) globalCallingHandlers(handlers) }
listStabilityMeasures = function() { l = list( data.frame(Name = "stabilityDavis", Corrected = FALSE, Adjusted = FALSE, Minimum = 0, Maximum = 1, stringsAsFactors = FALSE), list("stabilityDice", FALSE, FALSE, 0, 1), list("stabilityHamming", FALSE, FALSE, 0, 1), list("stabilityIntersectionCount", TRUE, TRUE, NA, 1), list("stabilityIntersectionGreedy", TRUE, TRUE, NA, 1), list("stabilityIntersectionMBM", TRUE, TRUE, NA, 1), list("stabilityIntersectionMean", TRUE, TRUE, NA, 1), list("stabilityJaccard", FALSE, FALSE, 0, 1), list("stabilityKappa", TRUE, FALSE, -1, 1), list("stabilityLustgarten", TRUE, FALSE, -1, 1), list("stabilityNogueira", TRUE, FALSE, -1, 1), list("stabilityNovovicova", FALSE, FALSE, 0, 1), list("stabilityOchiai", FALSE, FALSE, 0, 1), list("stabilityPhi", TRUE, FALSE, -1, 1), list("stabilitySechidis", FALSE, TRUE, NA, NA), list("stabilitySomol", TRUE, FALSE, 0, 1), list("stabilityUnadjusted", TRUE, FALSE, -1, 1), list("stabilityWald", TRUE, FALSE, "1-p", 1), list("stabilityYu", TRUE, TRUE, NA, 1), list("stabilityZucknick", FALSE, TRUE, 0, 1) ) do.call(rbind, l) }
getYear <- function(x, format, ...) UseMethod("getYear") getYear.default <- function(x, format, ...) stop("'getYear' can only be used on objects of a date/time class") getYear.Date <- getYear.POSIXct <- getYear.POSIXlt <- function(x, format="%Y", ...) format(x=x, format=format, ...) getMonth <- function(x, format, ...) UseMethod("getMonth") getMonth.default <- function(x, format, ...) stop("'getMonth' can only be used on objects of a date/time class") getMonth.Date <- getMonth.POSIXct <- getMonth.POSIXlt <- function(x, format="%m", ...) format(x=x, format=format) getDay <- function(x, format, ...) UseMethod("getDay") getDay.default <- function(x, format, ...) stop("'getDay' can only be used on objects of a date/time class") getDay.Date <- getDay.POSIXct <- getDay.POSIXlt <- function(x, format="%d", ...) format(x=x, format=format) getHour <- function(x, format, ...) UseMethod("getHour") getHour.default <- function(x, format, ...) stop("'getHour' can only be used on objects of a date/time class") getMin <- function(x, format, ...) UseMethod("getMin") getMin.default <- function(x, format, ...) stop("'getMin' can only be used on objects of a date/time class") getSec <- function(x, format, ...) UseMethod("getSec") getSec.default <- function(x, format, ...) stop("'getSec' can only be used on objects of a date/time class")
svychu <- function(formula, design, ...) { if( !( 'g' %in% names(list(...)) ) ) stop( "g= parameter must be specified" ) warning("The svychu function is experimental and is subject to changes in later versions.") if( !is.na( list(...)[["g"]] ) && !( list(...)[["g"]] <= 1 & list(...)[["g"]] >= 0 ) ) stop( "g= must be in the [0, 1] interval." ) if( 'type_thresh' %in% names( list( ... ) ) && !( list(...)[["type_thresh"]] %in% c( 'relq' , 'abs' , 'relm' ) ) ) stop( 'type_thresh= must be "relq" "relm" or "abs". see ?svychu for more detail.' ) if( length( attr( terms.formula( formula ) , "term.labels" ) ) > 1 ) stop( "convey package functions currently only support one variable in the `formula=` argument" ) UseMethod("svychu", design) } svychu.survey.design <- function(formula, design, g, type_thresh="abs", abs_thresh=NULL, percent = .60, quantiles = .50, na.rm = FALSE, thresh = FALSE, ...){ if (is.null(attr(design, "full_design"))) stop("you must run the ?convey_prep function on your linearized survey design object immediately after creating it with the svydesign() function.") if( type_thresh == "abs" & is.null( abs_thresh ) ) stop( "abs_thresh= must be specified when type_thresh='abs'" ) if ("logical" %in% class(attr(design, "full_design"))) full_design <- design else full_design <- attr(design, "full_design") h <- function( y , thresh , g ) if (g==0) ifelse( y != 0 , ifelse( y <= thresh , log( thresh / y ) , 0 ) , 0 ) else ifelse( y <= thresh , ( 1 - ( y / thresh )^g ) / g , 0 ) ht <- function( y , thresh , g ) if (g==0) ifelse( y != 0 , ifelse( y <= thresh , 1/thresh , 0 ) , 0 ) else ifelse( y <= thresh , (y^g / thresh^(g + 1) ) , 0 ) incvar <- model.frame(formula, design$variables, na.action = na.pass)[[1]] if(na.rm){ nas<-is.na(incvar) design<-design[!nas,] if (length(nas) > length(design$prob))incvar <- incvar[!nas] else incvar[nas] <- 0 } w <- 1/design$prob if( any( incvar[w > 0] <= 0 , na.rm = TRUE ) ){ nps<-incvar <= 0 design<-design[!nps,] if (length(nps) > length(design$prob))incvar <- incvar[!nps] else incvar[nps] <- 0 w <- 1/design$prob } if( is.null( names( design$prob ) ) ) ind <- as.character( seq( length( design$prob ) ) ) else ind <- names(design$prob) N <- sum(w) if ("logical" %in% class(attr(design, "full_design"))) full_design <- design else full_design <- attr(design, "full_design") incvec <- model.frame(formula, full_design$variables, na.action = na.pass)[[1]] if(na.rm){ nas<-is.na(incvec) full_design<-full_design[!nas,] if (length(nas) > length(full_design$prob)) incvec <- incvec[!nas] else incvec[nas] <- 0 } wf <- 1/full_design$prob if( any( incvec[wf > 0] <= 0 , na.rm = TRUE ) ){ warning("keeping strictly positive incomes only.") nps <- incvec <= 0 full_design<-full_design[!nps,] if (length(nps) > length(full_design$prob)) incvec <- incvec[!nps] else incvec[nps] <- 0 wf <- 1/full_design$prob } if( is.null( names( full_design$prob ) ) ) ncom <- as.character( seq( length( full_design$prob ) ) ) else ncom <- names(full_design$prob) htot <- h_fun(incvar, w) if (sum(1/design$prob==0) > 0) ID <- 1*(1/design$prob!=0) else ID <- 1 * ( ncom %in% ind ) if( type_thresh == 'relq' ){ ARPT <- svyarpt(formula = formula, full_design, quantiles=quantiles, percent=percent, na.rm=na.rm, ...) th <- coef(ARPT) arptlin <- attr(ARPT, "lin") rval <- sum(w*h(incvar,th,g))/N ahat <- sum(w*ht(incvar,th,g))/N chulin <-ID*( h( incvec , th , g ) - rval ) / N + ( ahat * arptlin ) if ( g == 0 ) { estimate <- contrastinf( quote(1 - exp(-watts) ) , list( watts = list( value = rval , lin = chulin ) ) ) rval <- estimate$value chulin <- estimate$lin rm(estimate) } } if( type_thresh == 'relm'){ th <- percent*sum(incvec*wf)/sum(wf) rval <- sum(w*h(incvar,th,g))/N ahat <- sum(w*ht(incvar,th,g))/N chulin <-ID*( h( incvec , th , g ) - rval + ( ( percent * incvec ) - th ) * ahat ) / N if ( g == 0 ) { estimate <- contrastinf( quote(1 - exp(-watts) ) , list( watts = list( value = rval , lin = chulin ) ) ) rval <- estimate$value chulin <- estimate$lin rm(estimate) } } if( type_thresh == 'abs' ){ th <- abs_thresh rval <- sum( w*h( incvar , th , g ) ) / N chulin <- ID*( h( incvec , th , g ) - rval ) / N if ( g == 0 ) { estimate <- contrastinf( quote(1 - exp(-watts) ) , list( watts = list( value = rval , lin = chulin ) ) ) rval <- estimate$value chulin <- estimate$lin rm(estimate) } } variance <- survey::svyrecvar(chulin/full_design$prob, full_design$cluster, full_design$strata, full_design$fpc, postStrata = full_design$postStrata) colnames( variance ) <- rownames( variance ) <- names( rval ) <- strsplit( as.character( formula )[[2]] , ' \\+ ' )[[1]] class(rval) <- c( "cvystat" , "svystat" ) attr(rval, "var") <- variance attr(rval, "statistic") <- paste0("chu",g) attr(rval, "lin") <- chulin if(thresh) attr(rval, "thresh") <- th rval } svychu.svyrep.design <- function(formula, design, g, type_thresh="abs", abs_thresh=NULL, percent = .60, quantiles = .50, na.rm = FALSE, thresh = FALSE,...) { if (is.null(attr(design, "full_design"))) stop("you must run the ?convey_prep function on your replicate-weighted survey design object immediately after creating it with the svrepdesign() function.") if( type_thresh == "abs" & is.null( abs_thresh ) ) stop( "abs_thresh= must be specified when type_thresh='abs'" ) if ("logical" %in% class(attr(design, "full_design"))) full_design <- design else full_design <- attr(design, "full_design") h <- function( y , thresh , g ) if (g==0) ifelse( y != 0 , ifelse( y <= thresh , log( thresh / y ) , 0 ) , 0 ) else ifelse( y <= thresh , ( 1 - ( y / thresh )^g ) / g , 0 ) ComputeCHU <- function( y , w , thresh , g ){ N <- sum(w) if (g == 0) { 1 - exp( -sum( w * h( y , thresh , g ) ) / N ) } else { sum( w * h( y , thresh , g ) ) / N } } df <- model.frame(design) incvar <- model.frame(formula, design$variables, na.action = na.pass)[[1]] if(na.rm){ nas<-is.na(incvar) design<-design[!nas,] df <- model.frame(design) incvar <- incvar[!nas] } ws <- weights(design, "sampling") if( any(incvar[ ws > 0 ] <= 0 , na.rm = TRUE ) ){ nps<-incvar <= 0 design<-design[!nps,] df <- model.frame(design) incvar <- incvar[!nps] ws <- weights(design, "sampling") } df_full<- model.frame(full_design) incvec <- model.frame(formula, full_design$variables, na.action = na.pass)[[1]] if(na.rm){ nas<-is.na(incvec) full_design<-full_design[!nas,] df_full <- model.frame(full_design) incvec <- incvec[!nas] } wsf <- weights(full_design,"sampling") if( any(incvec[ wsf > 0 ] <= 0 , na.rm = TRUE ) ){ warning("keeping strictly positive incomes only.") nps<-incvec <= 0 full_design<-full_design[!nps,] df_full <- model.frame(full_design) incvec <- incvec[!nps] wsf <- weights(full_design,"sampling") } names(incvec) <- names(wsf) <- row.names(df_full) ind<- row.names(df) if(type_thresh=='relq') th <- percent * computeQuantiles( incvec, wsf, p = quantiles) if(type_thresh=='relm') th <- percent*sum(incvec*wsf)/sum(wsf) if(type_thresh=='abs') th <- abs_thresh rval <- ComputeCHU(incvar, ws, thresh = th , g = g) wwf <- weights(full_design, "analysis") qq <- apply(wwf, 2, function(wi){ names(wi)<- row.names(df_full) wd<-wi[ind] incd <- incvec[ind] ComputeCHU( incd, wd, thresh = th , g = g )} ) if(anyNA(qq))variance <- NA else variance <- survey::svrVar(qq, design$scale, design$rscales, mse = design$mse, coef = rval) variance <- as.matrix( variance ) colnames( variance ) <- rownames( variance ) <- names( rval ) <- strsplit( as.character( formula )[[2]] , ' \\+ ' )[[1]] class(rval) <- c( "cvystat" , "svrepstat" ) attr(rval, "var") <- variance attr(rval, "statistic") <- paste0("chu",g) attr(rval, "lin") <- NA if(thresh) attr(rval, "thresh") <- th rval } svychu.DBIsvydesign <- function (formula, design, ...){ if (!( "logical" %in% class(attr(design, "full_design"))) ){ full_design <- attr( design , "full_design" ) full_design$variables <- getvars( formula, attr( design , "full_design" )$db$connection, attr( design , "full_design" )$db$tablename, updates = attr( design , "full_design" )$updates, subset = attr( design , "full_design" )$subset ) attr( design , "full_design" ) <- full_design rm( full_design ) } design$variables <- getvars( formula, design$db$connection, design$db$tablename, updates = design$updates, subset = design$subset ) NextMethod("svychu", design) }
make_planar_pair <- function(x, y = NULL, epsg = 3857) { if (is.null(epsg) || isFALSE(epsg)) { return(list(x = x, y = y)) } x_is_ll <- isTRUE(sf::st_is_longlat(x)) y_is_ll <- isTRUE(sf::st_is_longlat(y)) x_crs <- sf::st_crs(x) y_crs <- sf::st_crs(y) if (is.null(x_crs) || is.na(x_crs)) { cli::cli_warn('Planarizing skipped. {.arg x} missing CRS.') return(list(x = x, y = y)) } if ((is.null(y_crs) || is.na(y_crs)) & !is.null(y)) { cli::cli_warn('Planarizing skipped. {.arg y} missing CRS.') return(list(x = x, y = y)) } if (!is.null(y)) { if (!x_is_ll && !y_is_ll) { if (x_crs != y_crs) { y <- sf::st_transform(y, x_crs) } } else if (!x_is_ll) { y <- sf::st_transform(y, x_crs) } else if (!y_is_ll) { x <- sf::st_transform(x, y_crs) } else { x <- sf::st_transform(x, epsg) y <- sf::st_transform(y, epsg) } } else { if (x_is_ll) { x <- sf::st_transform(x, epsg) } } list(x = x, y = y) }
options.validation <- function(options){ if(is.null(options$id.str)){ warning("options$id.str is NULL") } if(!any(options$method %in% 1:3)){ stop("method should be 1 (AdaJoint), 2 (AdaJoint2), or 3 (ARTP)") } if(!is.numeric(options$huge.gene.size) || options$huge.gene.size < 0){ stop("huge.gene.size should be non-negative integer") } if(!is.numeric(options$huge.chr.size) || options$huge.chr.size < 0){ stop("huge.chr.size should be non-negative integer") } if(is.null(options$nperm)){ stop("nperm cannot be NULL") } if(!is.null(options$nperm) && options$nperm < 1000){ warning("nperm is too small") } if(!is.null(options$excluded.regions)){ excluded.regions <- options$excluded.regions tmp <- (c("data.frame", "matrix") %in% class(excluded.regions)) if(!any(tmp)){ msg <- "options$excluded.regions should be either a data frame or a matrix" stop(msg) }else{ if("matrix" %in% class(excluded.regions)){ excluded.regions <- as.data.frame(excluded.regions) } } header1 <- c('Chr', 'Pos', 'Radius') header2 <- c('Chr', 'Start', 'End') if(all(header1 %in% colnames(excluded.regions))){ excluded.regions <- excluded.regions[, header1, drop = FALSE] if(!any(c('integer', 'numeric') %in% class(excluded.regions$Pos))){ msg <- 'options$excluded.regions should have integer Pos' stop(msg) } if(!any(c('integer', 'numeric') %in% class(excluded.regions$Radius))){ msg <- 'options$excluded.regions should have integer Radius' stop(msg) } }else{ if(all(header2 %in% colnames(excluded.regions))){ excluded.regions <- excluded.regions[, header2, drop = FALSE] if(!any(c('integer', 'numeric') %in% class(excluded.regions$Start))){ msg <- 'options$excluded.regions should have integer Start' stop(msg) } if(!any(c('integer', 'numeric') %in% class(excluded.regions$End))){ msg <- 'options$excluded.regions should have integer End' stop(msg) } }else{ msg <- 'Invalid options$excluded.regions. Please refer to ?ARTP2::options' stop(msg) } } } if(options$snp.miss.rate > .1 && !options$turn.off.filters){ msg <- paste0("options$snp.miss.rate = ", options$snp.miss.rate, " might be too large") warning(msg) } if(options$inspect.snp.n <= 0){ stop("options$inspect.snp.n should be a positive integer") } if(options$inspect.snp.percent < 0 || options$inspect.snp.percent > 1){ stop("option$inspect.snp.percent should be in [0, 1]") } if(options$inspect.gene.n <= 0){ stop("options$inspect.gene.n should be a positive integer") } if(options$inspect.gene.percent < 0 || options$inspect.gene.percent > 1){ stop("option$inspect.gene.percent should be in [0, 1]") } if(length(intersect(options$excluded.snps, options$selected.snps)) > 0){ stop("Some SNPs are specified in both options$excluded.snps and options$selected.snps") } if(!is.null(options$excluded.subs) && !is.null(options$selected.subs)){ if(intersect(options$excluded.subs, options$selected.subs) > 0){ stop("Some subject IDs are specified in both options$excluded.subs and options$selected.subs") } } if(options$gene.R2 <= 0){ stop("gene.R2 should be in (0, 1]") } if(options$chr.R2 <= 0){ stop("chr.R2 should be in (0, 1]") } if(options$huge.gene.R2 <= 0){ stop("huge.gene.R2 should be in (0, 1]") } if(options$huge.chr.R2 <= 0){ stop("huge.chr.R2 should be in (0, 1]") } }
reactlog_module_ui <- function(include_refresh = TRUE, id = "reactlog_module") { ns <- shiny::NS(id) shiny::tagList( if (isTRUE(include_refresh)) shiny::actionButton( ns("refresh"), "", icon = shiny::icon("refresh"), class = "btn-sm btn-warning" ), shiny::uiOutput(ns("iframe")) ) } reactlog_module_server <- function( id = "reactlog_module", width = "100%", height = 600, ... ) { assert_shiny_version() shiny::moduleServer( id, function(input, output, session) { ns <- shiny::NS(id) output$iframe <- shiny::renderUI({ input$refresh test_mode_txt <- if (isTRUE(getOption("shiny.testmode"))) { "&test=1" } else { "" } random_id <- ns(paste0( "reactlog_iframe_", as.hexmode(floor(stats::runif(1, 1, 16^7))) )) htmltools::tagList( htmltools::tags$iframe( id = random_id, width = width, height = height, ... ), htmltools::tags$script(htmltools::HTML(paste0(" (function() { var src = 'reactlog?w=' + window.escape(window.Shiny.shinyapp.config.workerId) + '&s=' + window.escape(window.Shiny.shinyapp.config.sessionId) + '", test_mode_txt, "'; $(' })() "))) ) }) } ) } shiny_version_required <- function() { desc_file <- system.file("DESCRIPTION", package = "reactlog") suggests <- read.dcf(desc_file)[1, "Suggests"] pkgs <- strsplit(suggests, ",")[[1]] shiny_version <- gsub("[^.0-9]", "", pkgs[grepl("^shiny ", pkgs)]) package_version(shiny_version) } test_shiny_version <- function() { tryCatch({ utils::packageVersion("shiny") >= shiny_version_required() }, error = function() { FALSE }) } assert_shiny_version <- function() { if (!test_shiny_version()) { stop("`shiny` v", shiny_version_required, " or greater must be installed") } }
lipsitz.test <- function (model, g = 10) { oldmodel <- model if (class(oldmodel) == "polr") { yhat <- as.data.frame(fitted(oldmodel)) } else if (class(oldmodel) == "clm") { predprob <- oldmodel$model[, 2:ncol(oldmodel$model), drop = F] yhat <- as.data.frame(predict(oldmodel, newdata = predprob, type = "prob")$fit) } else warning("Model is not of class polr or clm. Test may fail.") formula <- formula(oldmodel$terms) DNAME <- paste("formula: ", deparse(formula)) METHOD <- "Lipsitz goodness of fit test for ordinal response models" obs <- oldmodel$model[1] if (g < 6) warning("g < 6. Running this test when g < 6 is not recommended.") if (g >= nrow(obs) / (5 * ncol(yhat))) warning("g >= n/5c. Running this test when g >= n/5c is not recommended.") yhat$score <- apply(sapply(1:ncol(yhat), function(i) { yhat[, i] * i }), 1, sum) yhat$tmp <- 1:nrow(yhat) yhat <- yhat[order(yhat$score), ] cutyhats <- cut(1:nrow(yhat), breaks = g, include.lowest = T) cutyhats <- cutyhats[order(yhat$tmp)] yhat <- yhat[order(yhat$tmp), ] yhat$score <- NULL yhat$tmp <- NULL dfobs <- data.frame(obs, cutyhats) dfobsmelt <- melt(dfobs, id.vars = 2) observed <- cast(dfobsmelt, cutyhats ~ value, length) if (g != nrow(observed)) { warning(paste("Not possible to compute", g, "rows. There might be too few observations.")) } oldmodel$model <- cbind(oldmodel$model, cutyhats = dfobs$cutyhats) oldmodel$model$grp <- as.factor(vapply(oldmodel$model$cutyhats, function(x) which(observed[, 1] == x), 1)) newmodel <- update(oldmodel, . ~ . + grp, data = oldmodel$model) if (class(oldmodel) == "polr") { LRstat <- oldmodel$deviance - newmodel$deviance } else if (class(oldmodel) == "clm") { LRstat <- abs(-2 * (newmodel$logLik - oldmodel$logLik)) } PARAMETER <- g - 1 PVAL <- 1 - pchisq(LRstat, PARAMETER) names(LRstat) <- "LR statistic" names(PARAMETER) <- "df" structure(list(statistic = LRstat, parameter = PARAMETER, p.value = PVAL, method = METHOD, data.name = DNAME, newmoddata = oldmodel$model, predictedprobs = yhat), class = "htest") }
UTM_zone_hemisphere <- function(x, y) { value1 <- (floor((x + 180) / 6) %% 60) + 1 value2 <- ifelse(y > 0, "north", "south") value3 <- paste0(value1," +",value2) return(value3) }
agent_returnSpeciesResultData <- function(xmlResultData) { allSpecies<-list() for(species in 2:xmlSize(xmlResultData[[1]])) { speciesResult<-NULL speciesName<-xmlAttrs(xmlResultData[[1]][[species]])[1] headers<-strsplit(xmlAttrs(xmlResultData[[1]][[species]])[[2]],",") if(length(xmlResultData[[1]][[species]])>0) { result<- toString(xmlResultData[[1]][[species]][[1]]) result<- strsplit(result,";") for(agent in 1:length(result[[1]])) { if(agent>1) { result[[1]][agent]<- substr(result[[1]][agent], 2, nchar(result[[1]][agent])) } resultsSplit<-strsplit(result[[1]][agent],",") resultRow<-read.csv(textConnection(resultsSplit[[1]]),header=F) speciesResult<-rbind(speciesResult,t(resultRow)) } colnames(speciesResult)<-headers[[1]] } else { speciesResult<-rbind(speciesResult,headers[[1]]) speciesResult<-rbind(speciesResult,headers[[1]]) colnames(speciesResult)<-headers[[1]] speciesResult<-speciesResult[0,] } specieslist <- list() specieslist[[speciesName]]<-speciesResult allSpecies<-append(allSpecies,specieslist) } return(allSpecies) }
nd.extremal <- function(A, out.dist=TRUE, k=ceiling(nrow(A)/5)){ if ((!is.list(A))||(length(A)<=1)){ stop("* nd.extremal : input 'A' should be a list of length larger than 1.") } listA = list_transform(A, NIflag="not") k = as.integer(k) if ((length(as.vector(k))!=1)||(k<1)||(k>=nrow(listA[[1]]))){ stop("* nd.extremal : parameter 'k' should be [1, } N = length(listA) mat_eigs = array(0,c(N,k)) mat_dist = array(0,c(N,N)) for (i in 1:N){ L = as.matrix(laplacian_unnormalized(listA[[i]])) mat_eigs[i,] = as.vector(RSpectra::eigs(L,k)$values) } for (i in 1:(N-1)){ eig1 = mat_eigs[i,] for (j in (i+1):N){ eig2 = mat_eigs[j,] numerator = sum((eig1-eig2)^2) denominator = min(sum(eig1^2),sum(eig2^2)) if (denominator==0){ solution = NA } else { solution = sqrt(numerator/denominator) } mat_dist[i,j] = solution mat_dist[j,i] = solution } } if (out.dist){ mat_dist = as.dist(mat_dist) } result = list() result$D= mat_dist result$spectra = mat_eigs return(result) }
standard_routes <- function() { dat <- wmata_api( path = "TrainPositions/StandardRoutes", query = list(contentType = "json"), flatten = TRUE, level = 1 ) dat$TrackCircuits <- lapply(dat$TrackCircuits, FUN = tibble::as_tibble) tibble::as_tibble(dat) }
setClassUnion("DateTime", c("Date", "POSIXct"))
context("Encodings") test_that("Encodings work on Windows", { input <- "César Moreira Nuñez" reference <- c("césar", "moreira", "nuñez") reference_enc <- c("UTF-8", "unknown", "UTF-8") output_n1 <- tokenize_ngrams(input, n = 1, simplify = TRUE) output_words <- tokenize_words(input, simplify = TRUE) output_skip <- tokenize_skip_ngrams(input, n = 1, k = 0, simplify = TRUE) expect_equal(output_n1, reference) expect_equal(output_words, reference) expect_equal(output_skip, reference) expect_equal(Encoding(output_n1), reference_enc) expect_equal(Encoding(output_words), reference_enc) expect_equal(Encoding(output_skip), reference_enc) })
NM2winNM <- function(x, pos, maxbp, winsize = 100L, depr = TRUE) { if( depr ){ myMsg <- "The function NM2winNM was deprecated in vcfR version 1.6.0. If you use this function and would like to advocate for its persistence, please contact the maintainer of vcfR. The maintainer can be contacted at maintainer('vcfR')" stop(myMsg) } .NM2winNM(x, pos, maxbp, winsize) } z.score <- function(x){ winave <- apply(x, MARGIN=2, mean, na.rm=TRUE) winsd <- apply(x, MARGIN=2, stats::sd, na.rm=TRUE) zsc <- sweep(x, MARGIN=2, STATS=winave, FUN="-") zsc <- sweep(zsc, MARGIN=2, STATS=winsd, FUN="/") zsc } windowize.NM <- function(x, pos, starts, ends, summary="mean", depr = TRUE){ if( depr ){ myMsg <- "The function windowizeNM was deprecated in vcfR version 1.6.0. If you use this function and would like to advocate for its persistence, please contact the maintainer of vcfR. The maintainer can be contacted at maintainer('vcfR')" stop(myMsg) } .windowize_NM(x, pos, starts, ends, summary=summary) }
gLRT3 <- function(A, k=2, rho=0, gamma=0, EMstep=TRUE, ICMstep=TRUE, tol=1e-06, maxiter=1000, inf=Inf) { A[A[,2]==inf,2] = Inf if(ncol(A) == 3 && all(A[,2] >= A[,1]) && length(unique(A[,3])) == k && all(A[,3]>=0) && all(A[,3]< k) ) { AA = A[,-3] trt = A[,3] est = ModifiedEMICM(AA, EMstep=EMstep, ICMstep=ICMstep, tol=tol, maxiter=maxiter) tiny = .Machine$double.eps*100 est$sigma = ifelse(abs(est$sigma) < tiny, 0, est$sigma) est$sigma = ifelse(abs(1.0 - est$sigma) < tiny, 1.0, est$sigma) cens = CensorType(AA, inf=inf) temp = cens temp[temp != 4] = 5 counts = table(c(0, 0, trt), c(5, 4, temp)) counts[1,] = counts[1,] - 1 u = Teststat3(trt, k, cens, counts, est, rho=rho, gamma=gamma, c0=1) v = Var3(trt, k, cens, counts, est, rho=rho, gamma=gamma, c0=1) chisq = Chisqstat3(u, v, counts) chisqstat = chisq[1] df = chisq[2] p = 1-pchisq(chisqstat, df) } else { stop("Please Verify data format, } out = data.frame() class(out) = "glrt3" out$method = "Generalized log-rank test (Zhao, Zhao, Sun, and Kim, 2008)" out$u = u out$var = v out$chisq = chisqstat out$df = df out$p = p out }
execute_function <- function(object, requri, objectname="FUN"){ if(!is.function(object)){ stop(objectname, "is not a function.") } fnargs <- req$post(); dotargs <- parse_dots(fnargs[["..."]]); fnargs["..."] <- NULL; fnargs <- lapply(fnargs, parse_arg); fileargs <- structure(lapply(req$files(), function(x){as.expression(basename(x$name))}), names=names(req$files())); fnargs <- c(fnargs, fileargs); argn <- lapply(names(fnargs), as.name); names(argn) <- names(fnargs); exprargs <- sapply(fnargs, is.expression); if(length(exprargs) > 0){ argn[names(fnargs[exprargs])] <-lapply(fnargs[exprargs], function(z){if(length(z)) z[[1]] else substitute()}); fnargs[exprargs] <- NULL } argn <- c(argn, dotargs) mycall <- as.call(c(list(as.name(objectname)), argn)); fnargs <- c(fnargs, structure(list(object), names=objectname)); session_eval(mycall, fnargs, storeval=TRUE, format=requri[1]) }
genotyping_global_error <- function(x, ploidy, restricted = TRUE, error = 0.01, th.prob = 0.95) { if(restricted){ x1 <- x[1:(ploidy+1)] if(sum(x1 > th.prob) == 1){ x2 <- x[ploidy + 2:3] id <- segreg_poly(ploidy, dP = x2[1], dQ = x2[2]) > 0 x3 <- x1[id] o <- which.max(x3) x3[o] <- 1-error x3[-o] <- error/(sum(id)-1) x1[match(names(x3), names(x1))] <- x3 return(x1) } return(x1) } else { x1 <- x[1:(ploidy+1)] if(sum(x1 > th.prob) == 1){ o <- which.max(x1) x1[o] <- 1-error x1[-o] <- error/(length(x1)-1) return(x1) } return(x1) } } est_full_hmm_with_global_error <- function(input.map, error = NULL, tol = 10e-4, restricted = TRUE, th.prob = 0.95, verbose = FALSE) { if (!inherits(input.map, "mappoly.map")) { stop(deparse(substitute(input.map)), " is not an object of class 'mappoly.map'") } output.seq <- input.map mrk.names <- get(input.map$info$data.name, pos = 1)$mrk.names[input.map$maps[[1]]$seq.num] if(!mappoly::is.prob.data(get(input.map$info$data.name, pos = 1))){ geno.temp <- get(input.map$info$data.name, pos = 1)$geno.dose[mrk.names,] ind.names <- get(input.map$info$data.name, pos = 1)$ind.names gen <- vector("list", length(ind.names)) names(gen) <- ind.names mrk <- ind <- NULL dp <- get(input.map$info$data.name, pos = 1)$dosage.p1[input.map$maps[[1]]$seq.num] dq <- get(input.map$info$data.name, pos = 1)$dosage.p2[input.map$maps[[1]]$seq.num] names(dp) <- names(dq) <- mrk.names d.pq <- data.frame(dp = dp, dq = dq) d.pq$mrk <- mrk.names for(i in names(gen)) { a <- matrix(0, nrow(geno.temp), input.map$info$ploidy+1, dimnames = list(mrk.names, 0:input.map$info$ploidy)) for(j in rownames(a)){ if(geno.temp[j,i] == input.map$info$ploidy+1){ a[j,] <- segreg_poly(ploidy = input.map$info$ploidy, dP = dp[j], dQ = dq[j]) } else { a[j,geno.temp[j,i]+1] <- 1 } } a <- as.data.frame(a) a$mrk <- rownames(a) a.temp <- t(merge(a, d.pq, sort = FALSE)[,-c(1)]) if(!is.null(error)) a.temp <- apply(a.temp, 2, genotyping_global_error, ploidy = input.map$info$ploidy, restricted = restricted, error = error, th.prob = th.prob) else a.temp <- a.temp[1:(input.map$info$ploidy+1), ] colnames(a.temp) <- a[,1] gen[[i]] <- a.temp } } else { geno.temp <- subset(get(input.map$info$data.name, pos = 1)$geno, mrk%in%mrk.names) ind.names <- get(input.map$info$data.name, pos = 1)$ind.names gen <- vector("list", length(ind.names)) names(gen) <- ind.names mrk <- ind <- NULL d.pq <- data.frame(dp = get(input.map$info$data.name, pos = 1)$dosage.p1[input.map$maps[[1]]$seq.num], dq = get(input.map$info$data.name, pos = 1)$dosage.p2[input.map$maps[[1]]$seq.num]) d.pq$mrk <- mrk.names for(i in names(gen)) { a <- subset(geno.temp, ind%in%i) a <- a[match(mrk.names, a$mrk),] a.temp <- t(merge(a, d.pq, sort = FALSE)[,-c(1:2)]) if(!is.null(error)) a.temp <- apply(a.temp, 2, genotyping_global_error, ploidy = input.map$info$ploidy, restricted = restricted, error = error, th.prob = th.prob) else a.temp <- a.temp[1:(input.map$info$ploidy+1), ] colnames(a.temp) <- a[,1] gen[[i]] <- a.temp } } if (verbose) cat(" ---------------------------------------------- INFO: running HMM using full transition space: this operation may take a while. -----------------------------------------------\n") for(i in 1:length(input.map$maps)) { YP <- input.map$maps[[i]]$seq.ph$P YQ <- input.map$maps[[i]]$seq.ph$Q map <- poly_hmm_est(ploidy = as.numeric(input.map$info$ploidy), n.mrk = as.numeric(input.map$info$n.mrk), n.ind = as.numeric(length(gen)), p = as.numeric(unlist(YP)), dp = as.numeric(cumsum(c(0, sapply(YP, function(x) sum(length(x)))))), q = as.numeric(unlist(YQ)), dq = as.numeric(cumsum(c(0, sapply(YQ, function(x) sum(length(x)))))), g = as.double(unlist(gen)), rf = as.double(input.map$maps[[i]]$seq.rf), verbose = verbose, tol = tol) output.seq$maps[[i]]$seq.rf <- map$rf output.seq$maps[[i]]$loglike <- map$loglike } return(output.seq) }
context("genome_join") library(dplyr) x1 <- tibble(id = 1:4, chromosome = c("chr1", "chr1", "chr2", "chr2"), start = c(100, 200, 300, 400), end = c(150, 250, 350, 450)) x2 <- tibble(id = 1:4, chromosome = c("chr1", "chr2", "chr2", "chr1"), start = c(140, 210, 400, 300), end = c(160, 240, 415, 320)) test_that("Can join genomes on chromosomes and intervals", { skip_if_not_installed("IRanges") j <- genome_inner_join(x1, x2, by = c("chromosome", "start", "end")) expect_equal(j$chromosome.x, j$chromosome.y) expect_equal(j$chromosome.x, c("chr1", "chr2")) expect_equal(j$id.x, c(1, 4)) expect_equal(j$id.y, c(1, 3)) expect_equal(colnames(j), c("id.x", "chromosome.x", "start.x", "end.x", "id.y", "chromosome.y", "start.y", "end.y")) x3 <- x1 x3$chromosome <- "chr1" x4 <- x2 x4$chromosome <- "chr1" j2 <- genome_inner_join(x3, x4, by = c("chromosome", "start", "end")) expect_equal(nrow(j2), 4) expect_equal(j2$id.x, 1:4) expect_equal(j2$id.y, c(1, 2, 4, 3)) j3 <- genome_left_join(x1, x2, by = c("chromosome", "start", "end")) expect_equal(nrow(j3), 4) expect_equal(sum(is.na(j3$start.x)), 0) expect_equal(sum(is.na(j3$start.y)), 2) expect_true(all(j3$chromosome.x == j3$chromosome.y, na.rm = TRUE)) j4 <- genome_right_join(x1, x2, by = c("chromosome", "start", "end")) expect_equal(nrow(j4), 4) expect_equal(sum(is.na(j4$start.x)), 2) expect_true(all(j4$chromosome.x == j4$chromosome.y, na.rm = TRUE)) }) test_that("genome_join throws an error if not given three columns", { skip_if_not_installed("IRanges") expect_error(genome_inner_join(x1, x2, by = c("start", "end")), "three columns") })
streaks=function(y){ n = length(y) where = c(0, y, 0) == 0 location.zeros = (0:(n+1))[where] streak.lengths = diff(location.zeros) - 1 streak.lengths[streak.lengths > 0] }
.onAttach <- function(libname, pkgname){ if (check_v8_major_version() < 6L) { packageStartupMessage( "Warning: v8 Engine is version ", V8::engine_info()[["version"]], " but version >=6 is required for full functionality. Some rmapshaper", " functions, notably ms_clip() and ms_erase(), may not work. See", " https://github.com/jeroen/V8 for help installing a modern version", " of v8 on your operating system.") } }
tam_mml_mfr_inits_beta <- function(Y, formulaY, dataY, G, group, groups, nstud, pweights, ridge, beta.fixed, xsi.fixed, constraint, ndim, beta.inits, tp, gresp, pid0) { nullY <- is.null(Y) if ( ! is.null( formulaY ) ){ formulaY <- stats::as.formula( formulaY ) Y <- stats::model.matrix( formulaY, dataY )[,-1] nullY <- FALSE } if (! nullY){ Y <- as.matrix(Y) nreg <- ncol(Y) if ( is.null( colnames(Y) ) ){ colnames(Y) <- paste("Y", 1:nreg, sep="") } if ( ! nullY ){ Y <- cbind(1,Y) colnames(Y)[1] <- "Intercept" } } else { Y <- matrix( 1, nrow=nstud, ncol=1 ) nreg <- 0 } if ( G > 1 & nullY ){ Y <- matrix( 0, nstud, G ) colnames(Y) <- paste("group", groups, sep="") for (gg in 1:G){ Y[,gg] <- 1*(group==gg) } nreg <- G - 1 } if (tp>1){ if ( nrow(gresp) !=nrow(Y) ){ Ypid <- rowsum( Y, pid0 ) Y <- Ypid / Ypid[,1] } } W <- crossprod(Y * pweights, Y ) if (ridge > 0){ diag(W) <- diag(W) + ridge } YYinv <- solve(W) if ( is.null(beta.fixed) & ( is.null(xsi.fixed) ) ){ beta.fixed <- matrix( c(1,1,0), nrow=1) if ( ndim > 1){ for ( dd in 2:ndim){ beta.fixed <- rbind( beta.fixed, c( 1, dd, 0 ) ) } } } if( ! is.matrix(beta.fixed) ){ if ( ! is.null(beta.fixed) ){ if ( ! beta.fixed ){ beta.fixed <- NULL } } } beta <- matrix(0, nrow=nreg+1, ncol=ndim) if ( ! is.null( beta.inits ) ){ beta[ beta.inits[,1:2] ] <- beta.inits[,3] } res <- list(Y=Y, nullY=nullY, formulaY=formulaY, nreg=nreg, W=W, YYinv=YYinv, beta.fixed=beta.fixed, beta=beta) return(res) }
totCophI <- function(tree){ if (!inherits(tree, "phylo")) stop("The input tree must be in phylo-format.") n <- length(tree$tip.label) if(n == 1 || n==2) {return(0)} nv_vec <- get.subtreesize(tree)[(n+2):(n+tree$Nnode)] tci_val <- sapply(nv_vec, function(x) choose(x,2)) return(sum(tci_val)) }
predict.coxph.penal <- function(object, newdata, type=c("lp", "risk", "expected", "terms"), se.fit=FALSE, terms=names(object$assign), collapse, safe=FALSE, ...) { type <- match.arg(type) n <- object$n pterms <- object$pterms if (!any(pterms==2) || (missing(newdata) && se.fit==FALSE && type!='terms')) NextMethod('predict',object,...) else { termname <- names(object$pterms) sparsename <- termname[object$pterms==2] nvar <- length(termname) na.action <- object$na.action object$na.action <- NULL if (missing(newdata) && (se.fit || type=='terms')) { x <- object[['x']] if (is.null(x)) { temp <- coxph.getdata(object, y=TRUE, x=TRUE, stratax=TRUE) if (is.null(object$y)) object$y <- temp$y if (is.null(object$strata)) object$strata <- temp$strata x <- temp$x } xvar <- match(sparsename, dimnames(x)[[2]]) indx <- as.numeric(as.factor(x[,xvar])) object$x <- x[, -xvar, drop=FALSE] } if (nvar==1) { if (!missing(newdata)) { n <- nrow(as.data.frame(newdata)) pred <- rep(0,n) se <- rep(0,n) } else { if (se.fit) se <- sqrt(object$fvar[indx]) pred <- object$linear.predictor } if (type=='risk') pred <- exp(pred) if (type=='expected') { pred <- object$y[,ncol(object$y)] -object$residuals se.fit=FALSE } } else { oldTerms <- object$terms temp <- attr(object$terms, 'term.labels') object$terms <- object$terms[-match(sparsename, temp)] pred <- NextMethod('predict',object,terms=terms,...) object$terms<- oldTerms if (se.fit) { se <- pred$se.fit pred <- pred$fit } if (type=='terms' && missing(newdata)) { spterm <- object$frail[indx] spstd <- sqrt(object$fvar[indx]) if (nvar==2) { if (xvar==2) { pred <- cbind(pred, spterm) if (se.fit) se <- cbind(se, spstd) } else { pred <- cbind(spterm, pred) if (se.fit) se <- cbind(spstd, se) } } else { first <- if (xvar==1) 0 else 1:(xvar-1) secnd <- if (xvar==nvar) 0 else (xvar+1):nvar pred <- cbind(pred[,first], spterm, pred[,secnd]) if (se.fit) se <- cbind(se[,first], spstd, se[,secnd]) } dimnames(pred) <- list(dimnames(x)[[1]], termname) if (se.fit) dimnames(se) <- dimnames(pred) } } if (missing(newdata) && !is.null(na.action)) { pred <- naresid(na.action, pred) if (is.matrix(pred)) n <- nrow(pred) else n <- length(pred) if(se.fit) se <- naresid(na.action, se) } if (!missing(collapse)) { if (length(collapse) != n) stop("Collapse vector is the wrong length") pred <- drop(rowsum(pred, collapse)) if (se.fit) se <- sqrt(drop(rowsum(se^2, collapse))) } if (se.fit) list(fit=pred, se.fit=se) else pred } }
parse_Rd <- function(file, srcfile = NULL, encoding = "unknown", verbose = FALSE, fragment = FALSE, warningCalls = TRUE, macros = file.path(R.home("share"), "Rd", "macros", "system.Rd"), permissive = FALSE) { if(is.character(file)) { file0 <- file if(file == "") { file <- stdin() } else { if (missing(srcfile)) srcfile <- srcfile(file) } } else file0 <- "<connection>" lines <- readLines(file, warn = FALSE) if(is.character(macros)) macros <- initialRdMacros(macros = macros) lines[lines == "\\non_function{}"] <- "" enc <- grep("\\encoding{", lines, fixed = TRUE, useBytes=TRUE, value=TRUE) enc <- grep("^[[:space:]]*\\\\encoding\\{([^}]*)\\}.*", enc, value = TRUE) if(length(enc)) { if(length(enc) > 1L) warning(file0, ": multiple \\encoding lines, using the first", domain = NA, call. = warningCalls) enc <- enc[1L] enc <- sub("^[[:space:]]*\\\\encoding\\{([^}]*)\\}.*", "\\1", enc) if(verbose) message("found encoding ", enc, domain = NA) encoding <- if(enc %in% c("UTF-8", "utf-8", "utf8")) "UTF-8" else enc } if (length(encoding) != 1L || encoding == "unknown") encoding <- "" if (!inherits(srcfile, "srcfile")) srcfile <- srcfile(file0) basename <- basename(srcfile$filename) srcfile$encoding <- encoding srcfile$Enc <- "UTF-8" if (encoding == "ASCII") { if (anyNA(iconv(lines, "", "ASCII"))) stop(file0, ": non-ASCII input and no declared encoding", domain = NA, call. = warningCalls) } else { if (encoding != "UTF-8") lines <- iconv(lines, encoding, "UTF-8", sub = "byte") bytes <- charToRaw(lines[1L]) if(identical(as.integer(bytes[1L : 3L]), c(0xefL, 0xbbL, 0xbfL))) lines[1L] <- rawToChar(bytes[-(1L : 3L)]) } tcon <- file() writeLines(lines, tcon, useBytes = TRUE) on.exit(close(tcon)) warndups <- config_val_to_logical(Sys.getenv("_R_WARN_DUPLICATE_RD_MACROS_", "FALSE")) result <- if(permissive) withCallingHandlers(.External2(C_parseRd, tcon, srcfile, "UTF-8", verbose, basename, fragment, warningCalls, macros, warndups), warning = function(w) if (grepl("unknown macro", conditionMessage(w))) tryInvokeRestart("muffleWarning")) else .External2(C_parseRd, tcon, srcfile, "UTF-8", verbose, basename, fragment, warningCalls, macros, warndups) result <- expandDynamicFlags(result) if (permissive) permissify(result) else result } print.Rd <- function(x, deparse = FALSE, ...) { cat(as.character.Rd(x, deparse = deparse), sep = "") invisible(x) } as.character.Rd <- function(x, deparse = FALSE, ...) { ZEROARG <- c("\\cr", "\\dots", "\\ldots", "\\R", "\\tab") TWOARG <- c("\\section", "\\subsection", "\\item", "\\enc", "\\method", "\\S3method", "\\S4method", "\\tabular", "\\if", "\\href") USERMACROS <- c("USERMACRO", "\\newcommand", "\\renewcommand") EQN <- c("\\deqn", "\\eqn", "\\figure") modes <- c(RLIKE = 1L, LATEXLIKE = 2L, VERBATIM = 3L, INOPTION = 4L, COMMENTMODE = 5L, UNKNOWNMODE = 6L) tags <- c(RCODE = 1L, TEXT = 2L, VERB = 3L, COMMENT = 5L, UNKNOWN = 6L) state <- c(braceDepth = 0L, inRString = 0L) needBraces <- FALSE inEqn <- 0L pr <- function(x, quoteBraces) { tag <- attr(x, "Rd_tag") if (is.null(tag) || tag == "LIST") tag <- "" if (is.list(x)) { savestate <- state state <<- c(0L, 0L) needBraces <<- FALSE if (tag == "Rd") { result <- character() for (i in seq_along(x)) result <- c(result, pr(x[[i]], quoteBraces)) } else if (startsWith(tag, " if (deparse) { dep <- deparseRdElement(x[[1L]][[1L]], c(state, modes["LATEXLIKE"], inEqn, as.integer(quoteBraces))) result <- c(tag, dep[[1L]]) } else result <- c(tag, x[[1L]][[1L]]) for (i in seq_along(x[[2L]])) result <- c(result, pr(x[[2L]][[i]], quoteBraces)) result <- c(result, " } else if (tag %in% ZEROARG) { result <- tag needBraces <<- TRUE } else if (tag %in% TWOARG) { result <- tag for (i in seq_along(x)) result <- c(result, pr(x[[i]], quoteBraces)) } else if (tag %in% EQN) { result <- tag inEqn <<- 1L result <- c(result, pr(x[[1L]], quoteBraces)) inEqn <<- 0L if (length(x) > 1L) result <- c(result, pr(x[[2L]], quoteBraces)) } else { result <- tag if (!is.null(option <- attr(x, "Rd_option"))) result <- c(result, "[", pr(option, quoteBraces), "]") result <- c(result, "{") for (i in seq_along(x)) result <- c(result, pr(x[[i]], quoteBraces)) result <- c(result, "}") } if (state[1L]) result <- pr(x, TRUE) state <<- savestate } else if (tag %in% USERMACROS) { result <- c() } else { if (deparse) { dep <- deparseRdElement(as.character(x), c(state, tags[tag], inEqn, as.integer(quoteBraces))) result <- dep[[1L]] state <<- dep[[2L]][1L:2L] } else { if (inherits(x, "Rd")) class(x) <- setdiff(class(x), "Rd") result <- as.character(x) } if (needBraces) { if (grepl("^[[:alpha:]]", result)) result <- c("{}", result) needBraces <<- FALSE } } result } if (is.null(attr(x, "Rd_tag"))) attr(x, "Rd_tag") <- "Rd" pr(x, quoteBraces = FALSE) } deparseRdElement <- function(element, state) .Call(C_deparseRd, element, state) permissify <- function(Rd) { tags <- RdTags(Rd) oldclass <- class(Rd) oldsrcref <- utils::getSrcref(Rd) oldtag <- attr(Rd, "Rd_tag") i <- 0 while (i < length(tags)) { i <- i+1 if (tags[i] == "UNKNOWN") { Rd[[i]] <- tagged(Rd[[i]], "TEXT", utils::getSrcref(Rd[[i]])) while (i < length(tags)) { if (tags[i+1] == "LIST") { Rd <- c(Rd[seq_len(i)], list(tagged("{", "TEXT", utils::getSrcref(Rd[[i+1]]))), permissify(Rd[[i+1]]), list(tagged("}", "TEXT", utils::getSrcref(Rd[[i+1]]))), Rd[seq_along(Rd)[-seq_len(i+1)]]) tags <- RdTags(Rd) i <- i+3 } else if (tags[i+1] == "TEXT" && grepl("^ *$", Rd[[i+1]])) i <- i + 1 else break } } else if (is.recursive(Rd[[i]])) Rd[[i]] <- permissify(Rd[[i]]) } class(Rd) <- oldclass attr(Rd, "srcref") <- oldsrcref attr(Rd, "Rd_tag") <- oldtag Rd }
project = function(x, xmin, xmax) { pmin(pmax(x, xmin), xmax) } logSumExp = function(a, b) { A = max(a,b) B = min(a,b) A + log1p(exp(B-A)) } fdsa = function(x, N, model=c("gk", "gh"), logB=FALSE, theta0, batch_size=100, alpha=1, gamma=0.49, a0=1, c0=NULL, A=100, theta_min=c(-Inf,ifelse(logB, -Inf, 1E-5),-Inf,0), theta_max=c(Inf,Inf,Inf,Inf), silent=FALSE, plotEvery=100) { if (!is.numeric(x)) stop("x must be numeric (a vector of observations)") if (!silent) { oldask = par(ask=FALSE) } cnames = c("A", ifelse(logB, "log B", "B"), "g", ifelse(model[1]=="gk", "k", "h"), "estimated log likelihood") if (model[1] == "gk") { if (logB) { get_log_densities = function(x, theta) dgk(batch, theta[1], exp(theta[2]), theta[3], theta[4], log=TRUE) } else { get_log_densities = function(x, theta) dgk(batch, theta[1], theta[2], theta[3], theta[4], log=TRUE) } } else { if (logB) { get_log_densities = function(x, theta) dgh(batch, theta[1], exp(theta[2]), theta[3], theta[4], log=TRUE) } else { get_log_densities = function(x, theta) dgh(batch, theta[1], theta[2], theta[3], theta[4], log=TRUE) } } nobs = length(x) batch_size = min(batch_size, nobs) nm_ratio = nobs/batch_size theta = theta0 estimates = matrix(nrow=N+1, ncol=5) colnames(estimates) = cnames estimates[1,] = c(theta, NA) if (missing(c0)) { batch = x[sample(nobs, 100, replace=TRUE)] density_sample = get_log_densities(batch, theta0) c0 = stats::sd(density_sample) / sqrt(batch_size) c0 = pmin(c0, (theta_max - theta_min)/2) } else if (any(c0 > (theta_max-theta_min)/2)) { stop("c0 too large compared to parameter constraints") } if (!silent) { prog_bar = progress::progress_bar$new(total = N, format = "[:bar] :percent eta: :eta") } for (t in seq(0,N-1)) { at = a0*(t+1+A)^-alpha ct = c0*(t+1)^-gamma indices = sample(nobs, batch_size) batch = x[indices] gt = rep(0,4) for (i in 1:4) { delta = rep(0,4) delta[i] = 1 theta1 = project(theta+ct*delta, theta_min, theta_max) theta2 = project(theta-ct*delta, theta_min, theta_max) hatL1 = -nm_ratio*sum(get_log_densities(batch, theta1)) hatL2 = -nm_ratio*sum(get_log_densities(batch, theta2)) if (is.infinite(hatL1) || is.infinite(hatL2)) { stop(paste("Log likelihoods too small to calculate! Parameters probably became too extreme. Last values were", toString(theta), ". Try tighter theta_min or theta_max values.")) } gt[i] = (hatL1 - hatL2)/(theta1[i]-theta2[i]) } theta = project(theta-at*gt, theta_min, theta_max) estimates[t+2,1:4] = theta estimates[t+2,5] = log(2) - logSumExp(hatL1, hatL2) if (!silent && ((t+1) %% plotEvery == 0)) { graphics::par(mfrow=c(2,3)) for (i in 1:5) { ylim = range(estimates[ceiling(t/10):(t+1),i]) graphics::plot(estimates[,i], type='l', xlim=c(1,N), ylim=ylim, xlab="FDSA iteration", ylab=cnames[i]) } } if (!silent) { prog_bar$tick() } } if (!silent) { par(ask=oldask) } return(estimates) }
species.from.file <- function(filename, species.col = "species"){ input.df <- read.csv(filename, header = TRUE) if(!species.col %in% colnames(input.df)){ stop(paste("Column", species.col, "not found in", filename)) } sp.names <- unique(input.df[,species.col]) if(length(sp.names) == 1){ this.species <- enmtools.species(species.name = as.character(sp.names[1]), presence.points = input.df[input.df[,species.col] == sp.names[1],]) this.species <- check.species(this.species) return(this.species) } else { species.list <- list() for(i in sp.names){ this.species <- enmtools.species(species.name = i, presence.points = input.df[input.df[,species.col] == i,]) this.species <- check.species(this.species) species.list[[i]] <- this.species } return(species.list) } }
if (require(effectsize) && require(testthat)) { test_that("plot methods", { skip_if_not_installed("see", "0.6.8") skip_if_not_installed("ggplot2") expect_error(plot(d <- cohens_d(mpg ~ am, data = mtcars)), NA) expect_s3_class(plot(d), "ggplot") expect_error(plot(eqi <- equivalence_test(d)), NA) expect_s3_class(plot(eqi), "ggplot") }) }
make_layer <- function(x, type=c("final_centers", "original_centers", "centers_translation", "final_graticule", "original_graticule")) { if (!inherits(x, "cartogramR")) stop(paste(deparse(substitute(x)), "must be a cartogramR object")) type <- match.arg(type) if (type=="final_centers") { y_geom <- st_sfc(sf::st_multipoint(x$final_centers)) st_crs(y_geom) <- st_crs(x$cartogram) return(y_geom) } if (type=="original_centers") { y_geom <- st_sfc(sf::st_multipoint(x$orig_centers)) st_crs(y_geom) <- st_crs(x$cartogram) return(y_geom) } if (type=="original_graticule") { if (!(x$details["method"] %in% c("gsm", "gn"))) stop("cartogram method should be either 'gsm' or 'gn'") bbox <- sf::st_bbox(x$initial_data) LL <- x$options$paramsint[1] pf <- x$options$paramsdouble[3] graticule <- .Call(carto_makeoriggraticule, pf, as.integer(LL), bbox) sf::st_crs(graticule) <- sf::st_crs(x$cartogram) return(graticule) } if (type=="final_graticule") { if (!(x$details["method"] %in% c("gsm", "gn"))) stop("cartogram method should be either 'gsm' or 'gn'") bbox <- sf::st_bbox(x$initial_data) if (x$options$options["gridexport"]==0) stop("cartogram does not include grid\n Rerun cartogramR with options=list(grid=TRUE)") LL <- x$options$paramsint[1] pf <- x$options$paramsdouble[3] graticule <- .Call(carto_makefinalgraticule, pf, as.integer(LL), bbox, x$gridx, x$gridy) sf::st_crs(graticule) <- sf::st_crs(x$cartogram) return(graticule) } if (type=="centers_translation") { coordLine <-lapply(1:nrow(x$orig_centers), function(n) { sf::st_linestring(rbind(x$orig_centers[n,],x$final_centers[n,]))}) movement <- sf::st_sfc(coordLine) sf::st_crs(movement) <- sf::st_crs(x$cartogram) return(movement) } }
residuals.mat <- function(object, k, weighted = FALSE, ...) { auto <- FALSE if(missing(k)) { auto <- TRUE if(weighted) k <- which.min(object$weighted$rmse) else k <- which.min(object$standard$rmse) } if(weighted) res <- object$weighted$resid[k, ] else res <- object$standard$resid[k, ] retval <- list(residuals = res, k = k, weighted = weighted, auto = auto) class(retval) <- "residuals.mat" return(retval) } print.residuals.mat <- function(x, digits = 3, ...) { k <- x$k cat("\n") writeLines(strwrap("Modern Analogue Technique Residuals", prefix = "\t")) cat("\n") cat(paste("No. of analogues (k) :", k, "\n")) cat(paste("User supplied k? :", !x$auto, "\n")) cat(paste("Weighted analysis? :", x$weighted, "\n\n")) print.default(x$residuals, digits = digits) invisible(x) }
`gowdis` <- function(x, w, asym.bin = NULL, ord = c("podani", "metric", "classic") ){ if (length(dx <- dim(x)) != 2 || !(is.data.frame(x) || is.numeric(x))) stop("x is not a dataframe or a numeric matrix\n") n <- dx[1] p <- dx[2] ord <- match.arg(ord) varnames <- dimnames(x)[[2]] if (!missing(w)){ if (length(w) != p | !is.numeric(w) ) stop("w needs to be a numeric vector of length = number of variables in x\n") if (all(w == 0) ) stop("Cannot have only 0's in 'w'\n") w <- w / sum(w) } else w <- rep(1, p) / sum(rep(1, p)) if (is.data.frame(x)) { type <- sapply(x, data.class) } else { type <- rep("numeric", p) names(type) <- colnames(x) } if (any(type == "character") ) for (i in 1:p) if (type[i] == "character") x[,i] <- as.factor(x[,i]) is.bin <- function(k) all(k[!is.na(k)] %in% c(0,1)) bin.var <- rep(NA,p); names(bin.var) <- varnames for (i in 1:p) bin.var[i] <- is.bin(x[,i]) if (any(type[bin.var] != "numeric")) stop("Binary variables should be of class 'numeric'\n") type[type %in% c("numeric", "integer")] <- 1 type[type == "ordered"] <- 2 type[type %in% c("factor", "character")] <- 3 type[bin.var] <- 4 if (!is.null(asym.bin) ){ if (!all(bin.var[asym.bin])) stop("Asymetric binary variables must only contain 0 or 1\n") else type[asym.bin] <- 5 } type <- as.numeric(type) x <- data.matrix(x) if (any(type == 2) ) { if (ord != "classic") for (i in 1:p) if (type[i] == 2) x[,i] <- rank(x[,i], na.last = "keep") else for (i in 1:p) if (type[i] == 2) x[,i] <- as.numeric(x[,i]) } range.Data <- function(v){ r.Data <- range(v, na.rm = T) res <- r.Data[2]-r.Data[1] return(res) } range2<- apply(x, 2, range.Data) comp.Timax <- function(v){ Ti.max <- max(v, na.rm = T) no.na <- v[!is.na(v)] res <- length(no.na[no.na == Ti.max]) return(res) } Timax <- apply(x, 2, comp.Timax) comp.Timin <- function(v){ Ti.min <- min(v, na.rm = T) no.na <- v[!is.na(v)] res <- length(no.na[no.na == Ti.min]) return(res) } Timin <- apply(x, 2, comp.Timin) if (ord == "podani") pod <- 1 else pod <- 2 res <- .C("gowdis", as.double(x), as.double(w), as.integer(type), as.integer(n), as.integer(p), as.double(range2), as.integer(pod), as.double(Timax), as.double(Timin), res = double(n*(n-1)/2), NAOK = T, PACKAGE = "FD")$res type[type == 1] <- "C" type[type == 2] <- "O" type[type == 3] <- "N" type[type == 4] <- "B" type[type == 5] <- "A" if (any(is.na(res) ) ) attr(res, "NA.message") <- "NA's in the dissimilarity matrix!" attr(res, "Labels") <- dimnames(x)[[1]] attr(res, "Size") <- n attr(res, "Metric") <- "Gower" attr(res, "Types") <- type class(res) <- "dist" return(res) }
print.composite.desire.function <- function(x, ...) { message("Composite desirability: ") message("Inner function:") message(" ", attr(x, "composite.desc")) message("Desirability:") print(attr(x, "desire.function"), ...) } compositeDF <- function(expr, d, ...) { if ("composite.desire.function" %in% class(d)) stop("Cannot recursivly composition desirabilty function.") sexpr <- substitute(expr) if (is.call(sexpr)) { UseMethod("compositeDF", sexpr) } else { UseMethod("compositeDF", expr) } } compositeDF.call <- function(expr, d, ...) { expr <- substitute(expr) ev <- function(x, ...) { y <- eval(expr, envir=list(x=x)) d(y, ...) } class(ev) <- "composite.desire.function" attr(ev, "composite.desc") <- paste("Expression: ", deparse(expr)) attr(ev, "desire.function") <- d return(ev) } compositeDF.function <- function(expr, d, ...) { ev <- function(x, ...) d(expr(x), ...) class(ev) <- "composite.desire.function" attr(ev, "composite.desc") <- paste("Function: ", deparse(substitute(expr)), "(x)", sep="") attr(ev, "desire.function") <- d return(ev) } compositeDF.lm <- function(expr, d, ...) { sigma <- summary(expr)$sigma ev <- function(x, ...) { if (!is.data.frame(x)) { if (is.vector(x)) { names(x) <- pnames x <- as.data.frame(as.list(x)) } else if (is.matrix(x)) { colnames(x) <- pnames x <- as.data.frame(x) } else { stop("Cannot convert argument 'x' into a data.frame object.") } } y <- predict(expr, newdata=x) d(y, sd=sigma, ...) } pnames <- all.vars(formula(expr)[[3]]) attr(ev, "composite.desc") <- paste("Linear Model: ", deparse(expr$call)) class(ev) <- "composite.desire.function" attr(ev, "desire.function") <- d return(ev) }
set_class <- function(x, class = NULL) { if (is.null(class)) { return(x) } else if ("data.table" %in% class) { if (inherits(x, "data.table")) { return(x) } return(data.table::as.data.table(x)) } else if ("tibble" %in% class || "tbl_df" %in% class || "tbl" %in% class) { if (inherits(x, "tbl")) { return(x) } return(tibble::as_tibble(x)) } out <- structure(x, class = "data.frame") if (!length(rownames(out))) { rownames(out) <- as.character(seq_len(length(out[,1L,drop = TRUE]))) } return(out) }
context("racusum_beta_crit_sim") L0 <- 500 RQ <- 1 maxS <- 71 g0 <- -3.6798 g1 <- 0.0768 shape1 <- 1 shape2 <- 3 tol <- .3 test_that("Different input values for RA", { RAtest <- list(-1, 0, "0", NA) lapply(RAtest, function(x) { expect_error(do.call(x, racusum_beta_crit_sim, L0=L0, RQ=RQ, g0=g0, g1=g1, shape1=shape1, shape2=shape2, rs=maxS, RA=x))}) }) test_that("Different simulation algorithms, detecting deterioration", { skip_on_cran() skip_if(SKIP == TRUE, "skip this test now") m <- 1e3 expect_equal(racusum_beta_crit_sim(L0=L0, RA=2, RQ=RQ, g0=g0, g1=g1, shape1=shape1, shape2=shape2, rs=maxS, verbose=TRUE, m=m), 2.5091, tolerance=tol) expect_equal(racusum_beta_crit_sim(L0=L0, RA=2, RQ=RQ, g0=g0, g1=g1, shape1=shape1, shape2=shape2, rs=maxS, verbose=FALSE, m=m), 2.5091, tolerance=tol) })
grm.input <- function(file) { if (!file.exists(file)) { stop(paste("File ", file, " not found.")) } t <- read.table(file, header = FALSE) if (ncol(t) != 4) { stop("Table has to contain 4 columns") } ids <- NULL filebase <- gsub(".gz", "", file) idfile <- paste0(filebase, ".id") if (file.exists(idfile)) { ids <- unique(read.table(idfile)$V2) } return(vector2grm(t$V4, ids)) } vector2grm <- function(v, ids = NULL) { n <- (sqrt(1 + 8 * length(v)) - 1) / 2 A <- matrix(0, nrow = n, ncol = n) A[upper.tri(A, diag = TRUE)] <- v A <- A + t(A) diag(A) <- .5 * diag(A) return(A) }
gen.label = function(label, altlabel){ paste(ifelse(is.null(label), altlabel, label)) } gen.tflabel = function(condition, tlabel, flabel){ paste(ifelse(condition,tlabel,flabel)) } draw.error.bands = function(ex, ely, ehy, lty = 2){ lines(ex,ely,lty=lty) lines(ex,ehy,lty=lty) } draw.error.bars = function(ex, ely, ehy, hbar = TRUE, hbarscale = 0.3, lty = 2){ yy = double(3*length(ex)) jj = 1:length(ex)*3 yy[jj-2] = ely yy[jj-1] = ehy yy[jj] = NA xx = double(3*length(ex)) xx[jj-2] = ex xx[jj-1] = ex xx[jj] = NA lines(xx,yy,lty=lty) if (hbar){ golden = (1+sqrt(5))/2 hbardist = abs(max(ex) - min(ex))/length(ex)*hbarscale yg = abs(yy[jj-2]-yy[jj-1])/golden htest = (hbardist >= yg) xx[jj-2] = ex - ifelse(htest, yg/2, hbardist/2) xx[jj-1] = ex + ifelse(htest, yg/2, hbardist/2) ty = yy[jj-1] yy[jj-1] = yy[jj-2] lines(xx,yy) yy[jj-2] = ty yy[jj-1] = ty lines(xx,yy) } } draw.errors = function(ex, ely, ehy, plot.errors.style, plot.errors.bar, plot.errors.bar.num, lty){ if (plot.errors.style == "bar"){ ei = seq(1,length(ex),length.out = min(length(ex),plot.errors.bar.num)) draw.error.bars(ex = ex[ei], ely = ely[ei], ehy = ehy[ei], hbar = (plot.errors.bar == "I"), lty = lty) } else if (plot.errors.style == "band") { draw.error.bands(ex = ex, ely = ely, ehy = ehy, lty = lty) } } plotFactor <- function(f, y, ...){ plot(x = f, y = y, lty = "blank", ...) l.f = rep(f, each=3) l.f[3*(1:length(f))] = NA l.y = unlist(lapply(y, function (p) { c(0,p,NA) })) lines(x = l.f, y = l.y, lty = 2) points(x = f, y = y) } compute.bootstrap.errors = function(...,bws){ UseMethod("compute.bootstrap.errors",bws) } compute.bootstrap.errors.rbandwidth = function(xdat, ydat, exdat, gradients, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,],", "txdat = tsb[,1:(ncol(tsb)-1),drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices],", "tydat = tsb[,ncol(tsb)],") boofun = eval(parse(text=paste(strf, "npreg(", strtx, strty, "exdat = exdat, bws = bws,", "gradients = gradients)$", ifelse(gradients, "grad[,slice.index]", "mean"), "}", sep=""))) if (is.inid){ boot.out = boot(data = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index > 0 && (bws$xdati$iord | bws$xdati$iuno)[slice.index]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- bws$xdati$all.ulev[[slice.index]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- bws$xdati$all.lev[[slice.index]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.scbandwidth = function(xdat, ydat, zdat, exdat, ezdat, gradients, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ miss.z <- missing(zdat) boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) is.inid = plot.errors.boot.method=="inid" xi <- 1:ncol(xdat) yi <- ncol(xdat)+1 if (!miss.z) zi <- yi+1:ncol(zdat) strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,, drop = FALSE],", "txdat = tsb[,xi,drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices],", "tydat = tsb[,yi],") strtz <- ifelse(miss.z, '', ifelse(is.inid, 'tzdat = zdat[indices,, drop = FALSE],', 'tzdat = tsb[,zi, drop = FALSE],')) boofun = eval(parse(text=paste(strf, "npscoef(", strtx, strty, strtz, "exdat = exdat,", ifelse(miss.z,"", "ezdat = ezdat,"), "bws = bws, iterate = FALSE)$", "mean", "}", sep=""))) boot.out <- eval(parse(text = paste(ifelse(is.inid, 'boot(data = ', 'tsboot(tseries ='), 'data.frame(xdat,ydat', ifelse(miss.z,'', ',zdat'), '), statistic = boofun, R = plot.errors.boot.num', ifelse(is.inid,'','l = plot.errors.boot.blocklen, sim = plot.errors.boot.method'),')'))) all.bp <- list() if ((slice.index > 0) && (((slice.index <= ncol(xdat)) && (bws$xdati$iord | bws$xdati$iuno)[slice.index]) || ((slice.index > ncol(xdat)) && (bws$zdati$iord | bws$zdati$iuno)[slice.index-ncol(xdat)]))) { boot.frame <- as.data.frame(boot.out$t) if(slice.index <= ncol(xdat)) u.lev <- bws$xdati$all.ulev[[slice.index]] else u.lev <- bws$zdati$all.ulev[[slice.index-ncol(xdat)]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) if(slice.index <= ncol(xdat)) all.bp$names <- bws$xdati$all.lev[[slice.index]] else all.bp$names <- bws$zdati$all.lev[[slice.index-ncol(xdat)]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.plbandwidth = function(xdat, ydat, zdat, exdat, ezdat, gradients, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,],", "txdat = tsb[,1:ncol(xdat),drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices],", "tydat = tsb[,ncol(xdat)+1],") strtz = ifelse(is.inid, "tzdat = zdat[indices,],", "tzdat = tsb[,(ncol(xdat)+2):ncol(tsb), drop=FALSE],") boofun = eval(parse(text=paste(strf, "npplreg(", strtx, strty, strtz, "exdat = exdat, ezdat = ezdat, bws = bws)$mean}", sep=""))) if (is.inid){ boot.out = boot(data = data.frame(xdat,ydat,zdat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat,ydat,zdat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index <= bws$xndim){ tdati <- bws$xdati ti <- slice.index } else { tdati <- bws$zdati ti <- slice.index - bws$xndim } if (slice.index > 0 && (tdati$iord | tdati$iuno)[ti]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- tdati$all.ulev[[ti]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- tdati$all.lev[[ti]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.bandwidth = function(xdat, exdat, cdf, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strt = ifelse(is.inid, "tdat = xdat[indices,],", "tdat = tsb,") boofun = eval(parse(text=paste(strf, ifelse(cdf, "npudist(", "npudens("), strt, "edat = exdat, bws = bws)$", ifelse(cdf, "dist", "dens"), "}", sep=""))) if (is.inid) { boot.out = boot(data = data.frame(xdat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index > 0 && (bws$xdati$iord | bws$xdati$iuno)[slice.index]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- bws$xdati$all.ulev[[slice.index]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- bws$xdati$all.lev[[slice.index]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.dbandwidth <- function(xdat, exdat, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strt = ifelse(is.inid, "tdat = xdat[indices,],", "tdat = tsb,") boofun = eval(parse(text=paste(strf, "npudist(", strt, "edat = exdat, bws = bws)$dist}", sep=""))) if (is.inid) { boot.out = boot(data = data.frame(xdat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index > 0 && (bws$xdati$iord | bws$xdati$iuno)[slice.index]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- bws$xdati$all.ulev[[slice.index]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- bws$xdati$all.lev[[slice.index]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.conbandwidth = function(xdat, ydat, exdat, eydat, cdf, quantreg, tau, gradients, gradient.index, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ exdat = toFrame(exdat) boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) tboo = if(quantreg) "quant" else if (cdf) "dist" else "dens" is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,],", "txdat = tsb[,1:ncol(xdat),drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices,],", "tydat = tsb[,(ncol(xdat)+1):ncol(tsb), drop=FALSE],") boofun = eval(parse(text=paste(strf, switch(tboo, "quant" = "npqreg(", "dist" = "npcdist(", "dens" = "npcdens("), strtx, strty, "exdat = exdat,", ifelse(quantreg, "tau = tau", "eydat = eydat"), ", bws = bws, gradients = gradients)$", switch(tboo, "quant" = ifelse(gradients, "yqgrad[,gradient.index]", "quantile"), "dist" = ifelse(gradients, "congrad[,gradient.index]", "condist"), "dens" = ifelse(gradients, "congrad[,gradient.index]", "condens")), "}", sep=""))) if (is.inid){ boot.out = boot(data = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index <= bws$xndim){ tdati <- bws$xdati ti <- slice.index } else { tdati <- bws$ydati ti <- slice.index - bws$xndim } if (slice.index > 0 && (tdati$iord | tdati$iuno)[ti]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- tdati$all.ulev[[ti]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- tdati$all.lev[[ti]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.condbandwidth = function(xdat, ydat, exdat, eydat, cdf, quantreg, tau, gradients, gradient.index, slice.index, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ exdat = toFrame(exdat) boot.err = matrix(data = NA, nrow = dim(exdat)[1], ncol = 3) tboo = if(quantreg) "quant" else if (cdf) "dist" else "dens" is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,],", "txdat = tsb[,1:ncol(xdat),drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices,],", "tydat = tsb[,(ncol(xdat)+1):ncol(tsb), drop=FALSE],") boofun = eval(parse(text=paste(strf, switch(tboo, "quant" = "npqreg(", "dist" = "npcdist(", "dens" = "npcdens("), strtx, strty, "exdat = exdat,", ifelse(quantreg, "tau = tau", "eydat = eydat"), ", bws = bws, gradients = gradients)$", switch(tboo, "quant" = ifelse(gradients, "yqgrad[,gradient.index]", "quantile"), "dist" = ifelse(gradients, "congrad[,gradient.index]", "condist"), "dens" = ifelse(gradients, "congrad[,gradient.index]", "condens")), "}", sep=""))) if (is.inid){ boot.out = boot(data = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } all.bp <- list() if (slice.index <= bws$xndim){ tdati <- bws$xdati ti <- slice.index } else { tdati <- bws$ydati ti <- slice.index - bws$xndim } if (slice.index > 0 && (tdati$iord | tdati$iuno)[ti]){ boot.frame <- as.data.frame(boot.out$t) u.lev <- tdati$all.ulev[[ti]] stopifnot(length(u.lev)==ncol(boot.frame)) all.bp$stats <- matrix(data = NA, nrow = 5, ncol = length(u.lev)) all.bp$conf <- matrix(data = NA, nrow = 2, ncol = length(u.lev)) for (i in 1:length(u.lev)){ t.bp <- boxplot.stats(boot.frame[,i]) all.bp$stats[,i] <- t.bp$stats all.bp$conf[,i] <- t.bp$conf all.bp$out <- c(all.bp$out,t.bp$out) all.bp$group <- c(all.bp$group, rep.int(i,length(t.bp$out))) } all.bp$n <- rep.int(plot.errors.boot.num, length(u.lev)) all.bp$names <- tdati$all.lev[[ti]] rm(boot.frame) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) list(boot.err = boot.err, bxp = all.bp) } compute.bootstrap.errors.sibandwidth = function(xdat, ydat, gradients, plot.errors.boot.method, plot.errors.boot.blocklen, plot.errors.boot.num, plot.errors.center, plot.errors.type, plot.errors.quantiles, bws){ boot.err = matrix(data = NA, nrow = nrow(xdat), ncol = 3) is.inid = plot.errors.boot.method=="inid" strf = ifelse(is.inid, "function(data,indices){", "function(tsb){") strtx = ifelse(is.inid, "txdat = xdat[indices,],", "txdat = tsb[,1:(ncol(tsb)-1),drop=FALSE],") strty = ifelse(is.inid, "tydat = ydat[indices],", "tydat = tsb[,ncol(tsb)],") boofun = eval(parse(text=paste(strf, "npindex(", strtx, strty, "exdat = xdat, bws = bws,", "gradients = gradients)$", ifelse(gradients, "grad[,1]", "mean"), "}", sep=""))) if (is.inid){ boot.out = boot(data = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num) } else { boot.out = tsboot(tseries = data.frame(xdat,ydat), statistic = boofun, R = plot.errors.boot.num, l = plot.errors.boot.blocklen, sim = plot.errors.boot.method) } if (plot.errors.type == "standard") { boot.err[,1:2] = 2.0*sqrt(diag(cov(boot.out$t))) } else if (plot.errors.type == "quantiles") { boot.err[,1:2] = t(sapply(as.data.frame(boot.out$t), function (y) { quantile(y,probs = plot.errors.quantiles) })) boot.err[,1] = boot.out$t0 - boot.err[,1] boot.err[,2] = boot.err[,2] - boot.out$t0 } if (plot.errors.center == "bias-corrected") boot.err[,3] <- 2*boot.out$t0-colMeans(boot.out$t) boot.err } uocquantile <- function(x, prob) { if(any(prob < 0 | prob > 1)) stop("'prob' outside [0,1]") if(any(is.na(x) | is.nan(x))) stop("missing values and NaN's not allowed") if (is.ordered(x)){ tq = unclass(table(x)) tq = tq / sum(tq) tq[length(tq)] <- 1.0 bscape <- sort(unique(x)) tq <- sapply(1:length(tq), function(y){ sum(tq[1:y]) }) j <- sapply(prob, function(p){ which(tq >= p)[1] }) bscape[j] } else if (is.factor(x)) { tq = unclass(table(x)) j = which(tq == max(tq))[1] sort(unique(x))[j] } else { quantile(x, probs = prob) } } trim.quantiles <- function(dat, trim){ if (sign(trim) == sign(-1)){ trim <- abs(trim) tq <- quantile(dat, probs = c(0.0, 0.0+trim, 1.0-trim,1.0)) tq <- c(2.0*tq[1]-tq[2], 2.0*tq[4]-tq[3]) } else { tq <- quantile(dat, probs = c(0.0+trim, 1.0-trim)) } tq } npplot <- function(bws = stop("'bws' has not been set"), ..., random.seed = 42){ if(exists(".Random.seed", .GlobalEnv)) { save.seed <- get(".Random.seed", .GlobalEnv) exists.seed = TRUE } else { exists.seed = FALSE } set.seed(random.seed) on.exit(if(exists.seed) assign(".Random.seed", save.seed, .GlobalEnv)) UseMethod("npplot",bws) } npplot.rbandwidth <- function(bws, xdat, ydat, data = NULL, xq = 0.5, xtrim = 0.0, neval = 50, common.scale = TRUE, perspective = TRUE, gradients = FALSE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.num = 399, plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow miss.xy = c(missing(xdat),missing(ydat)) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) ydat <- model.response(tmf) xdat <- tmf[, attr(attr(tmf, "terms"),"term.labels"), drop = FALSE] } else { if(all(miss.xy) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat = eval(bws$call[["ydat"]], environment(bws$call)) } xdat = toFrame(xdat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows] } xq = double(bws$ndim)+xq xtrim = double(bws$ndim)+xtrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((bws$ncon + bws$nord == 2) & (bws$nuno == 0) & perspective & !gradients & !any(xor(bws$xdati$iord, bws$xdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (is.ordered(xdat[,2])){ x2.eval = bws$xdati$all.ulev[[2]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(xdat[,2], xtrim[2]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (is.ordered(xdat[,1])) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (is.ordered(xdat[,2])) x2.eval <- (bws$xdati$all.dlev[[2]])[as.integer(x2.eval)] tobj = npreg(txdat = xdat, tydat = ydat, exdat = x.eval, bws = bws) terr = matrix(data = tobj$merr, nrow = dim(x.eval)[1], ncol = 3) terr[,3] = NA treg = matrix(data = tobj$mean, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors(xdat = xdat, ydat = ydat, exdat = x.eval, gradients = FALSE, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = tobj$mean - 2.0*tobj$merr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = tobj$mean + 2.0*tobj$merr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(tobj$mean),max(tobj$mean)) } if (plot.behavior != "plot"){ r1 = npregression(bws = bws, eval = x.eval, mean = as.double(treg), merr = terr[,1:2], ntrain = dim(xdat)[1]) r1$bias = NA if (plot.errors.center == "bias-corrected") r1$bias = terr[,3] - treg if (plot.behavior == "data") return ( list(r1 = r1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, treg, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$xnames[1], "X1")), ylab = ifelse(!is.null(ylab),ylab,gen.label(bws$xnames[2], "X2")), zlab = ifelse(!is.null(zlab),zlab,gen.label(bws$ynames,"Conditional Mean")), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } if (plot.behavior == "plot-data") return ( list(r1 = r1) ) } else { if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(bws$ndim),cex=par()$cex) ev = xdat[1,,drop = FALSE] for (i in 1:bws$ndim) ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) maxneval = max(c(sapply(xdat,nlevels),neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$ndim)) for (i in 1:bws$ndim) exdat[,i] = ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = bws$ndim) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*bws$ndim) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = bws$ndim)) all.bxp = list() } plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.mean = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = all.bxp[[i]],", "f = allei[,i],"), "x = allei[,i],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,i],", "y = temp.mean,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.mean - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.mean + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = "xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$xnames[i], paste('X', i, sep = '')))," pylabE = "ylab = ifelse(!is.null(ylab),ylab,paste(ifelse(gradients, paste('Gradient Component ', i, ' of', sep=''), ''), gen.label(bws$ynames, 'Conditional Mean')))," prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = expression(ifelse(common.scale, "ex = as.numeric(na.omit(allei[,i])),", "ex = as.numeric(na.omit(ei)),")) eelyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,i] - data.err[,3*i-2]),", "ely = na.omit(data.err[,3*i] - data.err[,3*i-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.mean - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),"))) eehyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,i] + data.err[,3*i-1]),", "ehy = na.omit(data.err[,3*i] + data.err[,3*i-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.mean + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),"))) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" for (i in 1:bws$ndim){ temp.err[,] = NA temp.mean[] = NA temp.boot = list() xi.factor = is.factor(xdat[,i]) if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tr = npreg(txdat = xdat, tydat = ydat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], bws = bws, gradients = gradients) temp.mean[1:xi.neval] = if(gradients) tr$grad[,i] else tr$mean if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*(if(gradients) tr$gerr[,i] else tr$merr)) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], gradients = gradients, slice.index = i, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] = temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,i] = ei data.eval[,i] = temp.mean if (plot.errors){ all.bxp[i] = NA all.bxp[[i]] = temp.boot data.err[,c(3*i-2,3*i-1,3*i)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[i] = NA if (gradients){ plot.out[[i]] = npregression(bws = bws, eval = as.data.frame(subcol(exdat,ei,i)[1:xi.neval,]), mean = tr$mean, merr = tr$merr, grad = na.omit(temp.mean), gerr = na.omit(cbind(-temp.err[,1], temp.err[,2])), ntrain = dim(xdat)[1]) plot.out[[i]]$gbias = na.omit(temp.mean - temp.err[,3]) } else { plot.out[[i]] = npregression(bws = bws, eval = as.data.frame(subcol(exdat,ei,i)[1:xi.neval,]), mean = na.omit(temp.mean), merr = na.omit(cbind(-temp.err[,1], temp.err[,2])), ntrain = dim(xdat)[1]) plot.out[[i]]$bias = na.omit(temp.mean - temp.err[,3]) } plot.out[[i]]$bxp = temp.boot } } if (common.scale & (plot.behavior != "data")){ jj = 1:bws$ndim*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0 ) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0 ) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } for (i in 1:bws$ndim){ xi.factor = is.factor(xdat[,i]) eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(allei[,i]), na.omit(data.err[,3*i]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = if (gradients) paste("rg",1:bws$ndim,sep="") else paste("r",1:bws$ndim,sep="") return (plot.out) } } } npplot.scbandwidth <- function(bws, xdat, ydat, zdat = NULL, data = NULL, xq = 0.5, zq = 0.5, xtrim = 0.0, ztrim = 0.0, neval = 50, common.scale = TRUE, perspective = TRUE, gradients = FALSE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.num = 399, plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow if(!missing(gradients)) stop("gradients not supported with smooth coefficient models.") miss.xy = c(missing(xdat),missing(ydat)) miss.z = missing(zdat) & is.null(bws$zdati) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) ydat <- model.response(tmf) xdat <- tmf[, bws$chromoly[[2]], drop = FALSE] if (!miss.z) zdat <- tmf[, bws$chromoly[[3]], drop = FALSE] } else { if(all(miss.xy) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat <- eval(bws$call[["ydat"]], environment(bws$call)) if (!miss.z) zdat <- data.frame(eval(bws$call[["zdat"]], environment(bws$call))) } xdat = toFrame(xdat) if(!miss.z) zdat <- toFrame(zdat) goodrows = 1:dim(xdat)[1] rows.omit = eval(parse(text = paste("attr(na.omit(data.frame(xdat, ydat", ifelse(miss.z,'',',zdat'),')), "na.action")'))) attr(na.omit(data.frame(xdat,ydat,zdat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] if(!miss.z) zdat <- zdat[goodrows,,drop = FALSE] ydat = ydat[goodrows] } xq = double(ncol(xdat))+xq xtrim = double(ncol(xdat))+xtrim if (!miss.z){ zq = double(ncol(zdat))+zq ztrim = double(ncol(zdat))+ztrim } if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((sum(c(bws$xdati$icon, bws$xdati$iord, bws$zdati$icon, bws$zdati$iord))== 2) & (sum(c(bws$xdati$iuno, bws$zdati$iuno)) == 0) & perspective & !gradients & !any(xor(c(bws$xdati$iord, bws$zdati$iord), c(bws$xdati$inumord, bws$zdati$inumord)))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if(!miss.z){ tdat <- zdat[,1] ti <- 1 tdati <- bws$zdati ttrim <- ztrim x2.names <- bws$znames } else { tdat <- xdat[,2] ti <- 2 tdati <- bws$xdati ttrim <- xtrim x2.names <- bws$xnames } if (is.ordered(tdat)){ x2.eval = tdati$all.ulev[[ti]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(tdat, ttrim[ti]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (is.ordered(xdat[,1])) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (is.ordered(tdat)) x2.eval <- (tdati$all.dlev[[ti]])[as.integer(x2.eval)] tobj <- eval(parse(text = paste('npscoef(txdat = xdat, tydat = ydat,', ifelse(miss.z,'','tzdat = zdat,'), ifelse(miss.z,'exdat = x.eval,','exdat = x.eval[,1, drop = FALSE], ezdat = x.eval[,2, drop = FALSE],'), 'bws = bws, iterate = FALSE, errors = plot.errors)'))) terr = matrix(data = tobj$merr, nrow = dim(x.eval)[1], ncol = 3) terr[,3] = NA treg = matrix(data = tobj$mean, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) if (plot.errors.method == "bootstrap"){ terr <- eval(parse(text = paste( 'compute.bootstrap.errors(xdat = xdat, ydat = ydat,', ifelse(miss.z,'','zdat = zdat,'), ifelse(miss.z, 'exdat = x.eval,', 'exdat = x.eval[,1, drop = FALSE], ezdat = x.eval[,1, drop = FALSE],'), ' gradients = FALSE, slice.index = 0,', 'plot.errors.boot.method = plot.errors.boot.method,', 'plot.errors.boot.blocklen = plot.errors.boot.blocklen,', 'plot.errors.boot.num = plot.errors.boot.num,', 'plot.errors.center = plot.errors.center,', 'plot.errors.type = plot.errors.type,', 'plot.errors.quantiles = plot.errors.quantiles,', 'bws = bws)[["boot.err"]]'))) pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = tobj$mean - 2.0*tobj$merr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = tobj$mean + 2.0*tobj$merr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(tobj$mean),max(tobj$mean)) } if (plot.behavior != "plot"){ r1 <- eval(parse(text = paste("smoothcoefficient(bws = bws,", ifelse(miss.z, "eval = x.eval,", "eval = list(exdat = x.eval[,1, drop = FALSE], ezdat = x.eval[,2, drop = FALSE])"), "mean = as.double(treg),", "merr = terr[,1:2],", "ntrain = dim(xdat)[1])"))) r1$bias = NA if (plot.errors.center == "bias-corrected") r1$bias = terr[,3] - treg if (plot.behavior == "data") return ( list(r1 = r1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, treg, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$xnames[1], "X1")), ylab = ifelse(!is.null(ylab),ylab,gen.label(x2.names[1], "X2")), zlab = ifelse(!is.null(zlab),zlab,gen.label(bws$ynames,"Conditional Mean")), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } if (plot.behavior == "plot-data") return ( list(r1 = r1) ) } else { tot.dim <- (bws$xndim <- length(bws$xdati$icon)) + (bws$zndim <- length(bws$zdati$icon)) if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(tot.dim),cex=par()$cex) maxneval = max(c(sapply(xdat,nlevels), unlist(sapply(zdat,nlevels)), neval)) all.isFactor = c(sapply(xdat, is.factor), unlist(sapply(zdat, is.factor))) x.ev = xdat[1,,drop = FALSE] for (i in 1:bws$xndim) x.ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$xndim)) for (i in 1:bws$xndim) exdat[,i] = x.ev[1,i] if (!miss.z){ z.ev = zdat[1,,drop = FALSE] for (i in 1:bws$zndim) z.ev[1,i] = uocquantile(zdat[,i], prob=zq[i]) ezdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$zndim)) for (i in 1:bws$zndim) ezdat[,i] = z.ev[1,i] } if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = tot.dim) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*tot.dim) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = tot.dim)) all.bxp = list() } plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.mean = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "all.bxp[[plot.index]],", "f = allei[,plot.index],"), "x = allei[,plot.index],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,plot.index],", "y = temp.mean,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.mean - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.mean + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = expression(paste("xlab = gen.label(bws$", xOrZ, "names[i], paste('", toupper(xOrZ),"', i, sep = '')),",sep='')) pylabE = "ylab = paste(ifelse(gradients, paste('Gradient Component ', i, ' of', sep=''), ''), gen.label(bws$ynames, 'Conditional Mean'))," prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," txobjE <- parse(text = paste("npscoef(txdat = xdat, tydat = ydat,", ifelse(miss.z,"","tzdat = zdat,"), "exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", ifelse(miss.z,"","ezdat = ezdat[1:xi.neval,, drop = FALSE],"), "bws = bws, errors = plot.errors)")) plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = expression(ifelse(common.scale, "ex = as.numeric(na.omit(allei[,plot.index])),", "ex = as.numeric(na.omit(ei)),")) eelyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,plot.index] - data.err[,3*plot.index-2]),", "ely = na.omit(data.err[,3*plot.index] - data.err[,3*plot.index-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.mean - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),"))) eehyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,plot.index] + data.err[,3*plot.index-1]),", "ehy = na.omit(data.err[,3*plot.index] + data.err[,3*plot.index-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.mean + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),"))) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" plot.index = 0 xOrZ = "x" for (i in 1:bws$xndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.mean[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj <- eval(txobjE) temp.mean[1:xi.neval] = tobj$mean if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = 2.0*tobj$merr else if (plot.errors.method == "bootstrap"){ temp.boot <- eval(parse(text = paste("compute.bootstrap.errors(", "xdat = xdat, ydat = ydat,", ifelse(miss.z, "", "zdat = zdat,"), "exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", ifelse(miss.z,"","ezdat = ezdat[1:xi.neval,, drop = FALSE],"), "gradients = gradients,", "slice.index = plot.index,", "plot.errors.boot.method = plot.errors.boot.method,", "plot.errors.boot.blocklen = plot.errors.boot.blocklen,", "plot.errors.boot.num = plot.errors.boot.num,", "plot.errors.center = plot.errors.center,", "plot.errors.type = plot.errors.type,", "plot.errors.quantiles = plot.errors.quantiles,", "bws = bws)"))) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[, plot.index] = temp.mean if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[, c(3*plot.index-2,3*plot.index-1,3*plot.index)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[plot.index] = NA if (gradients){ } else { plot.out[[plot.index]] = eval(parse(text = paste("smoothcoefficient(bws = bws,", "eval = ", ifelse(miss.z, "subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", "list(exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], ezdat = ezdat[1:xi.neval,, drop = FALSE]),"), "mean = na.omit(temp.mean),", "ntrain = dim(xdat)[1],", "trainiseval = FALSE,", "xtra = c(0, 0, 0, 0, 0, 0))"))) plot.out[[plot.index]]$merr = NA plot.out[[plot.index]]$bias = NA if (plot.errors) plot.out[[plot.index]]$merr = temp.err[,1:2] if (plot.errors.center == "bias-corrected") plot.out[[plot.index]]$bias = temp.err[,3] - temp.mean plot.out[[plot.index]]$bxp = temp.boot } } } if (!miss.z){ xOrZ = "z" for (i in 1:bws$zndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.mean[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$zdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(zdat[,i], ztrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj <- npscoef(txdat = xdat, tydat = ydat, tzdat = zdat, exdat = exdat[1:xi.neval,, drop = FALSE], ezdat = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE], bws = bws) temp.mean[1:xi.neval] = tobj$mean if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = 2.0*tobj$merr else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, zdat = zdat, exdat = exdat[1:xi.neval,, drop = FALSE], ezdat = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE], gradients = gradients, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[, plot.index] = temp.mean if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[, c(3*plot.index-2,3*plot.index-1,3*plot.index)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[plot.index] = NA if (gradients){ } else { plot.out[[plot.index]] = smoothcoefficient(bws = bws, eval = list(exdat = exdat[1:xi.neval,, drop = FALSE], ezdat = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE]), mean = na.omit(temp.mean), ntrain = dim(zdat)[1], trainiseval = FALSE) plot.out[[plot.index]]$merr = NA plot.out[[plot.index]]$bias = NA if (plot.errors) plot.out[[plot.index]]$merr = temp.err[,1:2] if (plot.errors.center == "bias-corrected") plot.out[[plot.index]]$bias = temp.err[,3] - temp.mean plot.out[[plot.index]]$bxp = temp.boot } } } } if (common.scale & (plot.behavior != "data")){ jj = 1:(bws$xndim + bws$zndim)*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } xOrZ = "x" for (plot.index in 1:(bws$xndim + bws$zndim)){ i = ifelse(plot.index <= bws$xndim, plot.index, plot.index - bws$xndim) if (plot.index > bws$xndim) xOrZ <- "z" xi.factor = all.isFactor[plot.index] eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = if (gradients){ } else paste("sc",1:(bws$xndim+bws$zndim),sep="") return (plot.out) } } } npplot.plbandwidth <- function(bws, xdat, ydat, zdat, data = NULL, xq = 0.5, zq = 0.5, xtrim = 0.0, ztrim = 0.0, neval = 50, common.scale = TRUE, perspective = TRUE, gradients = FALSE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.boot.num = 399, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow if(!missing(gradients)) stop("gradients not supported with partially linear models. Coefficients may be extracted with coef()") miss.xyz = c(missing(xdat), missing(ydat), missing(zdat)) if (any(miss.xyz) && !all(miss.xyz)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xyz) && !is.null(bws$formula)){ tt <- terms(bws) m <- match(c("formula", "data", "subset", "na.action"), names(bws$call), nomatch = 0) tmf.xf <- tmf.x <- tmf <- bws$call[c(1,m)] tmf.x[[1]] <- as.name("model.matrix") tmf.xf[[1]] <- tmf[[1]] <- as.name("model.frame") tmf[["formula"]] <- tt umf <- tmf <- eval(tmf, envir = environment(tt)) bronze <- lapply(bws$chromoly, paste, collapse = " + ") tmf.x[["object"]] <- as.formula(paste(" ~ ", bronze[[2]]), env = environment(formula)) tmf.x <- eval(tmf.x,parent.frame()) tmf.xf[["formula"]] <- as.formula(paste(" ~ ", bronze[[2]]), env = environment(formula)) tmf.xf <- eval(tmf.xf,parent.frame()) ydat <- model.response(tmf) xdat <- as.data.frame(tmf.x[,-1, drop = FALSE]) cc <- attr(tmf.x,'assign')[-1] for(i in 1:length(cc)) xdat[,i] <- cast(xdat[,i], tmf.xf[,cc[i]], same.levels = FALSE) zdat <- tmf[, bws$chromoly[[3]], drop = FALSE] } else { if(all(miss.xyz) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat = eval(bws$call[["ydat"]], environment(bws$call)) zdat <- data.frame(eval(bws$call[["zdat"]], environment(bws$call))) } xdat = toFrame(xdat) zdat = toFrame(zdat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat,zdat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Training data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows] zdat = zdat[goodrows,,drop = FALSE] } nxcon = sum(bws$xdati$icon) nxuno = sum(bws$xdati$iuno) nxord = sum(bws$xdati$iord) nzcon = sum(bws$zdati$icon) nzuno = sum(bws$zdati$iuno) nzord = sum(bws$zdati$iord) xq = double(bws$xndim)+xq zq = double(bws$zndim)+zq xtrim = double(bws$xndim)+xtrim ztrim = double(bws$zndim)+ztrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { warning(paste("asymptotic errors are not supported with partially linear regression.\n", "Proceeding without calculating errors")) plot.errors.method = "none" } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((nxcon + nxord == 1) & (nzcon + nzord == 1) & (nxuno + nzuno == 0) & perspective & !gradients & !any(xor(bws$xdati$iord, bws$xdati$inumord)) & !any(xor(bws$zdati$iord, bws$zdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (is.ordered(zdat[,1])){ z1.eval = bws$zdati$all.ulev[[1]] z1.neval = length(z1.eval) } else { z1.neval = neval qi = trim.quantiles(zdat[,1], ztrim[1]) z1.eval = seq(qi[1], qi[2], length.out = z1.neval) } x.eval <- expand.grid(x1.eval, z1.eval) if (bws$xdati$iord[1]) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (bws$zdati$iord[1]) z1.eval <- (bws$zdati$all.dlev[[1]])[as.integer(z1.eval)] tobj = npplreg(txdat = xdat, tydat = ydat, tzdat = zdat, exdat = x.eval[,1], ezdat = x.eval[,2], bws = bws) terr = matrix(data = NA, nrow = nrow(x.eval), ncol = 3) treg = matrix(data = tobj$mean, nrow = x1.neval, ncol = z1.neval, byrow = FALSE) if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, zdat = zdat, exdat = x.eval[,1], ezdat = x.eval[,2], gradients = FALSE, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} -terr[,1], nrow = x1.neval, ncol = z1.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {tobj$mean} +terr[,2], nrow = x1.neval, ncol = z1.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(tobj$mean),max(tobj$mean)) } if (plot.behavior != "plot"){ r1 = plregression(bws = bws, xcoef = tobj$xcoef, xcoefvcov = vcov(tobj), xcoeferr = tobj$xcoeferr, evalx = x.eval[,1], evalz = x.eval[,2], mean = tobj$mean, ntrain = dim(xdat)[1], trainiseval = FALSE, xtra=c(tobj$RSQ,tobj$MSE,0,0,0,0)) r1$merr = NA r1$bias = NA if (plot.errors) r1$merr = terr[,1:2] if (plot.errors.center == "bias-corrected") r1$bias = terr[,3] - treg if (plot.behavior == "data") return ( list(r1 = r1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, z1.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, z1.eval, treg, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(names(xdat)[1], "X1")), ylab = ifelse(!is.null(ylab),ylab,gen.label(names(xdat)[2], "Z1")), zlab = ifelse(!is.null(zlab),zlab,gen.label(names(ydat),"Conditional Mean")), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, z1.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } if (plot.behavior == "plot-data") return ( list(r1 = r1) ) } else { if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(bws$xndim + bws$zndim),cex=par()$cex) x.ev = xdat[1,,drop = FALSE] z.ev = zdat[1,,drop = FALSE] for (i in 1:bws$xndim) x.ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) for (i in 1:bws$zndim) z.ev[1,i] = uocquantile(zdat[,i], prob=zq[i]) maxneval = max(c(sapply(xdat,nlevels), sapply(zdat,nlevels), neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$xndim)) ezdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$zndim)) for (i in 1:bws$xndim) exdat[,i] = x.ev[1,i] for (i in 1:bws$zndim) ezdat[,i] = z.ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = (bws$xndim + bws$zndim)) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*(bws$xndim + bws$zndim)) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = bws$xndim + bws$zndim)) all.bxp = list() } all.isFactor = c(sapply(xdat, is.factor), sapply(zdat, is.factor)) plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.mean = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "all.bxp[[plot.index]],", "f = allei[,plot.index],"), "x = allei[,plot.index],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,plot.index],", "y = temp.mean,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.mean - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.mean + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = expression(paste("xlab = gen.label(bws$", xOrZ, "names[i], paste('", toupper(xOrZ),"', i, sep = '')),",sep='')) pylabE = "ylab = paste(ifelse(gradients, paste('Gradient Component ', i, ' of', sep=''), ''), gen.label(bws$ynames, 'Conditional Mean'))," prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = expression(ifelse(common.scale, "ex = as.numeric(na.omit(allei[,plot.index])),", "ex = as.numeric(na.omit(ei)),")) eelyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,plot.index] - data.err[,3*plot.index-2]),", "ely = na.omit(data.err[,3*plot.index] - data.err[,3*plot.index-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.mean - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),"))) eehyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,plot.index] + data.err[,3*plot.index-1]),", "ehy = na.omit(data.err[,3*plot.index] + data.err[,3*plot.index-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.mean + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),"))) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" plot.index = 0 xOrZ = "x" for (i in 1:bws$xndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.mean[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj <- npplreg(txdat = xdat, tydat = ydat, tzdat = zdat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], ezdat = ezdat[1:xi.neval,, drop = FALSE], bws = bws) temp.mean[1:xi.neval] = tobj$mean if (plot.errors){ if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, zdat = zdat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], ezdat = ezdat[1:xi.neval,, drop = FALSE], gradients = gradients, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[, plot.index] = temp.mean if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[, c(3*plot.index-2,3*plot.index-1,3*plot.index)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[plot.index] = NA if (gradients){ } else { plot.out[[plot.index]] = plregression(bws = bws, xcoef = tobj$xcoef, xcoefvcov = vcov(tobj), xcoeferr = tobj$xcoeferr, evalx = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], evalz = ezdat[1:xi.neval,, drop = FALSE], mean = na.omit(temp.mean), ntrain = dim(xdat)[1], trainiseval = FALSE, xtra = c(tobj$RSQ, tobj$MSE, 0, 0, 0, 0)) plot.out[[plot.index]]$merr = NA plot.out[[plot.index]]$bias = NA if (plot.errors) plot.out[[plot.index]]$merr = temp.err[,1:2] if (plot.errors.center == "bias-corrected") plot.out[[plot.index]]$bias = temp.err[,3] - temp.mean plot.out[[plot.index]]$bxp = temp.boot } } } xOrZ = "z" for (i in 1:bws$zndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.mean[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$zdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(zdat[,i], ztrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj <- npplreg(txdat = xdat, tydat = ydat, tzdat = zdat, exdat = exdat[1:xi.neval,, drop = FALSE], ezdat = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE], bws = bws) temp.mean[1:xi.neval] = tobj$mean if (plot.errors){ if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, zdat = zdat, exdat = exdat[1:xi.neval,, drop = FALSE], ezdat = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE], gradients = gradients, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[, plot.index] = temp.mean if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[, c(3*plot.index-2,3*plot.index-1,3*plot.index)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[plot.index] = NA if (gradients){ } else { plot.out[[plot.index]] = plregression(bws = bws, xcoef = tobj$xcoef, xcoeferr = tobj$xcoeferr, xcoefvcov = vcov(tobj), evalx = exdat[1:xi.neval,, drop = FALSE], evalz = subcol(ezdat,ei,i)[1:xi.neval,, drop = FALSE], mean = na.omit(temp.mean), ntrain = dim(zdat)[1], trainiseval = FALSE, xtra = c(tobj$RSQ, tobj$MSE, 0, 0, 0, 0)) plot.out[[plot.index]]$merr = NA plot.out[[plot.index]]$bias = NA if (plot.errors) plot.out[[plot.index]]$merr = temp.err[,1:2] if (plot.errors.center == "bias-corrected") plot.out[[plot.index]]$bias = temp.err[,3] - temp.mean plot.out[[plot.index]]$bxp = temp.boot } } } if (common.scale & (plot.behavior != "data")){ jj = 1:(bws$xndim + bws$zndim)*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } xOrZ = "x" for (plot.index in 1:(bws$xndim + bws$zndim)){ i = ifelse(plot.index <= bws$xndim, plot.index, plot.index - bws$xndim) if (plot.index > bws$xndim) xOrZ <- "z" xi.factor = all.isFactor[plot.index] eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = if (gradients){ } else paste("plr",1:(bws$xndim+bws$zndim),sep="") return (plot.out) } } } npplot.bandwidth <- function(bws, xdat, data = NULL, xq = 0.5, xtrim = 0.0, neval = 50, common.scale = TRUE, perspective = TRUE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.boot.num = 399, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow miss.x <- missing(xdat) if(miss.x && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) xdat <- tmf[, attr(attr(tmf, "terms"),"term.labels"), drop = FALSE] } else { if(miss.x && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["dat"]], environment(bws$call))) } xdat = toFrame(xdat) xdat = na.omit(xdat) } xq = double(bws$ndim)+xq xtrim = double(bws$ndim)+xtrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((bws$ncon + bws$nord == 2) & (bws$nuno == 0) & perspective & !any(xor(bws$xdati$iord, bws$xdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (is.ordered(xdat[,2])){ x2.eval = bws$xdati$all.ulev[[2]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(xdat[,2], xtrim[2]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (is.ordered(xdat[,1])) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (is.ordered(xdat[,2])) x2.eval <- (bws$xdati$all.dlev[[2]])[as.integer(x2.eval)] tobj = npudens(tdat = xdat, edat = x.eval, bws = bws) tcomp = parse(text="tobj$dens") tdens = matrix(data = eval(tcomp), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) terr = matrix(data = tobj$derr, nrow = nrow(x.eval), ncol = 3) terr[,3] = NA if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors(xdat = xdat, exdat = x.eval, cdf = FALSE, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = eval(tcomp) - 2.0*tobj$derr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = eval(tcomp) + 2.0*tobj$derr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(eval(tcomp)),max(eval(tcomp))) } tret = parse(text=paste( "npdensity", "(bws = bws, eval = x.eval,", "dens", " = eval(tcomp), derr = terr[,1:2], ntrain = nrow(xdat))", sep="")) if (plot.behavior != "plot"){ d1 = eval(tret) d1$bias = NA if (plot.errors.center == "bias-corrected") d1$bias = terr[,3] - eval(tcomp) if (plot.behavior == "data") return ( list(d1 = d1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, tdens, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(names(xdat)[1], "X1")), ylab = ifelse(!is.null(ylab),ylab,gen.label(names(xdat)[2], "X2")), zlab = ifelse(!is.null(zlab),zlab,"Joint Density"), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } if (plot.behavior == "plot-data") return ( list(d1 = d1) ) } else { if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(bws$ndim),cex=par()$cex) ev = xdat[1,,drop = FALSE] for (i in 1:bws$ndim) ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) maxneval = max(c(sapply(xdat,nlevels),neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$ndim)) for (i in 1:bws$ndim) exdat[,i] = ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = bws$ndim) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*bws$ndim) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = bws$ndim)) all.bxp = list() } plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.dens = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = all.bxp[[i]],", "f = allei[,i],"), "x = allei[,i],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,i],", "y = temp.dens,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.dens - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.dens + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = "xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$xnames[i], paste('X', i, sep = '')))," pylabE = paste("ylab = ", "ifelse(!is.null(ylab),ylab,'Density')", ",") prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = ifelse(common.scale, "ex = as.numeric(na.omit(allei[,i])),", "ex = as.numeric(na.omit(ei)),") eelyE = ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,i] - data.err[,3*i-2]),", "ely = na.omit(data.err[,3*i] - data.err[,3*i-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.dens - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),")) eehyE = ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,i] + data.err[,3*i-1]),", "ehy = na.omit(data.err[,3*i] + data.err[,3*i-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.dens + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),")) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(!is.null(lty),lty,ifelse(xi.factor,1,2))" devalE = parse(text=paste("npudens", "(tdat = xdat, edat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], bws = bws)", sep="")) dcompE = parse(text="tobj$dens") doutE = parse(text=paste("npdensity", "(bws = bws, eval = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", "dens", "= na.omit(temp.dens), derr = na.omit(cbind(-temp.err[,1], temp.err[,2])), ntrain = bws$nobs)", sep="")) for (i in 1:bws$ndim){ temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = is.factor(xdat[,i]) if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(devalE) temp.dens[1:xi.neval] = eval(dcompE) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*tobj$derr) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], cdf = FALSE, slice.index = i, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] = temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,i] = ei data.eval[,i] = temp.dens if (plot.errors){ all.bxp[i] = NA all.bxp[[i]] = temp.boot data.err[,c(3*i-2,3*i-1,3*i)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[i] = NA plot.out[[i]] = eval(doutE) plot.out[[i]]$bias = na.omit(temp.dens - temp.err[,3]) plot.out[[i]]$bxp = temp.boot } } if (common.scale & (plot.behavior != "data")){ jj = 1:bws$ndim*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0 ) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0 ) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } for (i in 1:bws$ndim){ xi.factor = is.factor(xdat[,i]) eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = paste("d",1:bws$ndim,sep="") return (plot.out) } } } npplot.dbandwidth <- function(bws, xdat, data = NULL, xq = 0.5, xtrim = 0.0, neval = 50, common.scale = TRUE, perspective = TRUE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.boot.num = 399, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow miss.x <- missing(xdat) if(miss.x && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) xdat <- tmf[, attr(attr(tmf, "terms"),"term.labels"), drop = FALSE] } else { if(miss.x && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["dat"]], environment(bws$call))) } xdat = toFrame(xdat) xdat = na.omit(xdat) } xq = double(bws$ndim)+xq xtrim = double(bws$ndim)+xtrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((bws$ncon + bws$nord == 2) & (bws$nuno == 0) & perspective & !any(xor(bws$xdati$iord, bws$xdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (is.ordered(xdat[,2])){ x2.eval = bws$xdati$all.ulev[[2]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(xdat[,2], xtrim[2]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (is.ordered(xdat[,1])) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (is.ordered(xdat[,2])) x2.eval <- (bws$xdati$all.dlev[[2]])[as.integer(x2.eval)] tobj = npudist(tdat = xdat, edat = x.eval, bws = bws) tdens = matrix(data = tobj$dist, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) terr = matrix(data = tobj$derr, nrow = nrow(x.eval), ncol = 3) terr[,3] = NA if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors(xdat = xdat, exdat = x.eval, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {tobj$dist} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {tobj$dist} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = tobj$dist - 2.0*tobj$derr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = tobj$dist + 2.0*tobj$derr, nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(tobj$dist),max(tobj$dist)) } if (plot.behavior != "plot"){ d1 <- npdistribution(bws = bws, eval = x.eval, dist = tobj$dist, derr = terr[,1:2], ntrain = nrow(xdat)) d1$bias = NA if (plot.errors.center == "bias-corrected") d1$bias = terr[,3] - tobj$dist if (plot.behavior == "data") return ( list(d1 = d1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, tdens, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(names(xdat)[1], "X1")), ylab = ifelse(!is.null(ylab),ylab,gen.label(names(xdat)[2], "X2")), zlab = ifelse(!is.null(zlab),zlab,"Joint Distribution"), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } if (plot.behavior == "plot-data") return ( list(d1 = d1) ) } else { if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(bws$ndim),cex=par()$cex) ev = xdat[1,,drop = FALSE] for (i in 1:bws$ndim) ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) maxneval = max(c(sapply(xdat,nlevels),neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$ndim)) for (i in 1:bws$ndim) exdat[,i] = ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = bws$ndim) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*bws$ndim) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = bws$ndim)) all.bxp = list() } plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.dens = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = all.bxp[[i]],", "f = allei[,i],"), "x = allei[,i],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,i],", "y = temp.dens,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.dens - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.dens + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = "xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$xnames[i], paste('X', i, sep = '')))," pylabE = "ylab = ifelse(!is.null(ylab),ylab,'Distribution')," prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = ifelse(common.scale, "ex = as.numeric(na.omit(allei[,i])),", "ex = as.numeric(na.omit(ei)),") eelyE = ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,i] - data.err[,3*i-2]),", "ely = na.omit(data.err[,3*i] - data.err[,3*i-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.dens - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),")) eehyE = ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,i] + data.err[,3*i-1]),", "ehy = na.omit(data.err[,3*i] + data.err[,3*i-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.dens + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),")) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" devalE = parse(text="npudist(tdat = xdat, edat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], bws = bws)") dcompE = parse(text="tobj$dist") doutE = parse(text="npdistribution(bws = bws, eval = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], dist = na.omit(temp.dens), derr = na.omit(cbind(-temp.err[,1], temp.err[,2])), ntrain = bws$nobs)") for (i in 1:bws$ndim){ temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = is.factor(xdat[,i]) if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(devalE) temp.dens[1:xi.neval] = eval(dcompE) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*tobj$derr) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], slice.index = i, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] = temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,i] = ei data.eval[,i] = temp.dens if (plot.errors){ all.bxp[i] = NA all.bxp[[i]] = temp.boot data.err[,c(3*i-2,3*i-1,3*i)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot") { plot.out[i] = NA plot.out[[i]] = eval(doutE) plot.out[[i]]$bias = na.omit(temp.dens - temp.err[,3]) plot.out[[i]]$bxp = temp.boot } } if (common.scale & (plot.behavior != "data")){ jj = 1:bws$ndim*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0 ) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0 ) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } for (i in 1:bws$ndim){ xi.factor = is.factor(xdat[,i]) eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = paste("d",1:bws$ndim,sep="") return (plot.out) } } } npplot.conbandwidth <- function(bws, xdat, ydat, data = NULL, xq = 0.5, yq = 0.5, xtrim = 0.0, ytrim = 0.0, neval = 50, gradients = FALSE, common.scale = TRUE, perspective = TRUE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, tau = 0.5, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.boot.num = 399, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow cdf <- FALSE quantreg <- FALSE miss.xy = c(missing(xdat),missing(ydat)) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) ydat <- tmf[, bws$variableNames[["response"]], drop = FALSE] xdat <- tmf[, bws$variableNames[["terms"]], drop = FALSE] } else { if(all(miss.xy) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat <- data.frame(eval(bws$call[["ydat"]], environment(bws$call))) } xdat = toFrame(xdat) ydat = toFrame(ydat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows,,drop = FALSE] } if (quantreg & dim(ydat)[2] != 1) stop("'ydat' must have one column for quantile regression") xq = double(bws$xndim)+xq yq = double(bws$yndim)+yq xtrim = double(bws$xndim)+xtrim ytrim = double(bws$yndim)+ytrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } if (quantreg & gradients){ warning(paste("no asymptotic errors available for quantile regression gradients.", "\nOne must instead use bootstrapping.")) plot.errors.method = "none" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((bws$xncon + bws$xnord + bws$yncon + bws$ynord - quantreg == 2) & (bws$xnuno + bws$ynuno == 0) & perspective & !gradients & !any(xor(bws$xdati$iord, bws$xdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (quantreg){ tx2 <- xdat[,2] txi <- 2 txdati <- bws$xdati txtrim <- xtrim } else{ tx2 <- ydat[,1] txi <- 1 txdati <- bws$ydati txtrim <- ytrim } if (txdati$iord[txi]){ x2.eval = txdati$all.ulev[[txi]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(tx2, txtrim[txi]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (bws$xdati$iord[1]) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (txdati$iord[txi]) x2.eval <- (txdati$all.dlev[[txi]])[as.integer(x2.eval)] tboo = if(quantreg) "quant" else if (cdf) "dist" else "dens" tobj = eval(parse(text = paste( switch(tboo, "quant" = "npqreg", "dist" = "npcdist", "dens" = "npcdens"), "(txdat = xdat, tydat = ydat, exdat =", ifelse(quantreg, "x.eval, tau = tau", "x.eval[,1], eydat = x.eval[,2]"), ", bws = bws)", sep=""))) tcomp = parse(text=paste("tobj$", switch(tboo, "quant" = "quantile", "dist" = "condist", "dens" = "condens"), sep="")) tcerr = parse(text=paste(ifelse(quantreg, "tobj$quanterr", "tobj$conderr"))) tex = parse(text=paste(ifelse(quantreg, "x.eval", "x.eval[,1]"))) tey = parse(text=paste(ifelse(quantreg, "NA", "x.eval[,2]"))) tdens = matrix(data = eval(tcomp), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) terr = matrix(data = eval(tcerr), nrow = length(eval(tcomp)), ncol = 3) terr[,3] = NA if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors(xdat = xdat, ydat = ydat, exdat = eval(tex), eydat = eval(tey), cdf = cdf, quantreg = quantreg, tau = tau, gradients = FALSE, gradient.index = 0, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = eval(tcomp) - 2.0*eval(tcerr), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = eval(tcomp) + 2.0*eval(tcerr), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } if(is.null(zlim)) { zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(eval(tcomp)),max(eval(tcomp))) } tret = parse(text=paste( switch(tboo, "quant" = "qregression", "dist" = "condistribution", "dens" = "condensity"), "(bws = bws, xeval = eval(tex),", ifelse(quantreg, "tau = tau, quantile = eval(tcomp), quanterr = terr[,1:2]", paste("yeval = eval(tey),", ifelse(cdf, "condist = ", "condens = "), "eval(tcomp), conderr = terr[,1:2]")), ", ntrain = dim(xdat)[1])", sep="")) if (plot.behavior != "plot"){ cd1 = eval(tret) cd1$bias = NA if (plot.errors.center == "bias-corrected") cd1$bias = terr[,3] - eval(tcomp) if (plot.behavior == "data") return ( list(cd1 = cd1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, tdens, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(names(xdat)[1], "X")), ylab = ifelse(!is.null(ylab),ylab,gen.label(names(ydat)[1], "Y")), zlab = ifelse(!is.null(zlab),zlab,paste("Conditional", ifelse(cdf,"Distribution", "Density"))), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } } else { dsf = ifelse(gradients,bws$xndim,1) tot.dim = bws$xndim + bws$yndim - quantreg if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(dsf*tot.dim),cex=par()$cex) x.ev = xdat[1,,drop = FALSE] y.ev = ydat[1,,drop = FALSE] for (i in 1:bws$xndim) x.ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) for (i in 1:bws$yndim) y.ev[1,i] = uocquantile(ydat[,i], prob=yq[i]) maxneval = max(c(sapply(xdat,nlevels), sapply(ydat,nlevels), neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$xndim)) eydat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$yndim)) for (i in 1:bws$xndim) exdat[,i] = x.ev[1,i] for (i in 1:bws$yndim) eydat[,i] = y.ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = tot.dim*dsf) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*tot.dim*dsf) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = tot.dim)) all.bxp = list() } all.isFactor = c(sapply(xdat, is.factor), sapply(ydat, is.factor)) plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.dens = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "all.bxp[[plot.index]],", "f = allei[,plot.index],"), "x = allei[,plot.index],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,plot.index],", "y = temp.dens,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.dens - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.dens + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = expression(paste("xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$", xOrY, "names[i], paste('", toupper(xOrY),"', i, sep = ''))),",sep='')) tylabE = ifelse(quantreg, paste(tau, 'quantile'), paste('Conditional', ifelse(cdf,'Distribution', 'Density'))) pylabE = paste("ylab =", "ifelse(!is.null(ylab),ylab,paste(", ifelse(gradients,"'GC',j,'of',",''), "tylabE)),") prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = expression(ifelse(common.scale, "ex = as.numeric(na.omit(allei[,plot.index])),", "ex = as.numeric(na.omit(ei)),")) eelyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,plot.index] - data.err[,3*plot.index-2]),", "ely = na.omit(data.err[,3*plot.index] - data.err[,3*plot.index-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.dens - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),"))) eehyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,plot.index] + data.err[,3*plot.index-1]),", "ehy = na.omit(data.err[,3*plot.index] + data.err[,3*plot.index-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.dens + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),"))) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" plot.index = 0 xOrY = "x" for (i in 1:bws$xndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(parse(text=paste(ifelse(cdf, "npcdist", ifelse(quantreg, "npqreg", "npcdens")), "(txdat = xdat, tydat = ydat,", "exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", ifelse(quantreg, "tau = tau,", "eydat = eydat[1:xi.neval,, drop = FALSE],"), "gradients = gradients, bws = bws)",sep=""))) tevalexpr = parse(text=paste("tobj$",ifelse(gradients, ifelse(quantreg, "quantgrad[,j]","congrad[,j]"), ifelse(cdf, "condist", ifelse(quantreg, "quantile", "condens"))), sep="")) terrexpr = parse(text=paste("tobj$",ifelse(gradients, "congerr[,j]", ifelse(quantreg,"quanterr", "conderr")), sep="")) if (gradients & quantreg) terrexpr = parse(text="NA") if (plot.behavior != "plot"){ plot.out[plot.index] = NA plot.out[[plot.index]] = tobj } for (j in 1:dsf){ temp.boot = list() temp.dens[1:xi.neval] = eval(tevalexpr) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*eval(terrexpr)) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], eydat = eydat[1:xi.neval,, drop = FALSE], cdf = cdf, quantreg = quantreg, tau = tau, gradients = gradients, gradient.index = j, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[,(plot.index-1)*dsf+j] = temp.dens if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[,seq(3*((plot.index-1)*dsf+j)-2,length=3)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot" & plot.errors) { eval(parse(text=paste("plot.out[[plot.index]]$",ifelse(gradients, paste("gc",j,"err",sep=""), ifelse(quantreg, "quanterr", "conderr")), "= na.omit(cbind(-temp.err[,1], temp.err[,2]))", sep=""))) eval(parse(text=paste("plot.out[[plot.index]]$", ifelse(gradients, paste("gc",j,"bias",sep=""), "bias"), "= na.omit(temp.dens - temp.err[,3])", sep=""))) plot.out[[plot.index]]$bxp = temp.boot } } } if (!quantreg){ xOrY = "y" for (i in 1:bws$yndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$ydati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(ydat[,i], ytrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(parse(text=paste(ifelse(cdf, "npcdist", ifelse(quantreg, "npqreg", "npcdens")), "(txdat = xdat, tydat = ydat,", ifelse(quantreg, "tau = tau,", "exdat = exdat[1:xi.neval,, drop = FALSE],"), "eydat = subcol(eydat,ei,i)[1:xi.neval,, drop = FALSE],", "gradients = gradients, bws = bws)",sep=""))) tevalexpr = parse(text=paste("tobj$",ifelse(gradients, ifelse(quantreg, "quantgrad[,j]","congrad[,j]"), ifelse(cdf, "condist", ifelse(quantreg, "quantile", "condens"))), sep="")) terrexpr = parse(text=paste("tobj$",ifelse(gradients, "congerr[,j]", ifelse(quantreg,"quanterr", "conderr")), sep="")) if (gradients & quantreg) terrexpr = parse(text="NA") if (plot.behavior != "plot"){ plot.out[plot.index] = NA plot.out[[plot.index]] = tobj } for (j in 1:dsf){ temp.boot = list() temp.dens[1:xi.neval] = eval(tevalexpr) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*eval(terrexpr)) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, exdat = exdat[1:xi.neval,, drop = FALSE], eydat = subcol(eydat,ei,i)[1:xi.neval,, drop = FALSE], cdf = cdf, quantreg = quantreg, tau = tau, gradients = gradients, gradient.index = j, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[,(plot.index-1)*dsf+j] = temp.dens if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[,seq(3*((plot.index-1)*dsf+j)-2,length=3)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot" & plot.errors) { eval(parse(text=paste("plot.out[[plot.index]]$",ifelse(gradients, paste("gc",j,"err",sep=""), ifelse(quantreg, "quanterr", "conderr")), "= na.omit(cbind(-temp.err[,1], temp.err[,2]))", sep=""))) eval(parse(text=paste("plot.out[[plot.index]]$", ifelse(gradients, paste("gc",j,"bias",sep=""), "bias"), "= na.omit(temp.dens - temp.err[,3])", sep=""))) plot.out[[plot.index]]$bxp = temp.boot } } } } if (common.scale & (plot.behavior != "data")){ jj = 1:(dsf*tot.dim)*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } xOrY = "x" for (plot.index in 1:tot.dim){ i = ifelse(plot.index <= bws$xndim, plot.index, plot.index - bws$xndim) if (plot.index > bws$xndim) xOrY <- "y" xi.factor = all.isFactor[plot.index] for (j in 1:dsf){ eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = paste("cd", 1:tot.dim, sep="") return (plot.out) } } } npplot.condbandwidth <- function(bws, xdat, ydat, data = NULL, xq = 0.5, yq = 0.5, xtrim = 0.0, ytrim = 0.0, neval = 50, quantreg = FALSE, gradients = FALSE, common.scale = TRUE, perspective = TRUE, main = NULL, type = NULL, border = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, zlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, zlim = NULL, lty = NULL, lwd = NULL, theta = 0.0, phi = 10.0, tau = 0.5, view = c("rotate","fixed"), plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.boot.num = 399, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = min(neval,25), plot.bxp = FALSE, plot.bxp.out = TRUE, plot.par.mfrow = TRUE, ..., random.seed){ if(!is.null(options('plot.par.mfrow')$plot.par.mfrow)) plot.par.mfrow <- options('plot.par.mfrow')$plot.par.mfrow cdf <- TRUE miss.xy = c(missing(xdat),missing(ydat)) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) ydat <- tmf[, bws$variableNames[["response"]], drop = FALSE] xdat <- tmf[, bws$variableNames[["terms"]], drop = FALSE] } else { if(all(miss.xy) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat <- data.frame(eval(bws$call[["ydat"]], environment(bws$call))) } xdat = toFrame(xdat) ydat = toFrame(ydat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows,,drop = FALSE] } if (quantreg & dim(ydat)[2] != 1) stop("'ydat' must have one column for quantile regression") xq = double(bws$xndim)+xq yq = double(bws$yndim)+yq xtrim = double(bws$xndim)+xtrim ytrim = double(bws$yndim)+ytrim if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { if (plot.errors.type == "quantiles"){ warning("quantiles cannot be calculated with asymptotics, calculating standard errors") plot.errors.type = "standard" } if (plot.errors.center == "bias-corrected") { warning("no bias corrections can be calculated with asymptotics, centering on estimate") plot.errors.center = "estimate" } if (quantreg & gradients){ warning(paste("no asymptotic errors available for quantile regression gradients.", "\nOne must instead use bootstrapping.")) plot.errors.method = "none" } } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if ((bws$xncon + bws$xnord + bws$yncon + bws$ynord - quantreg == 2) & (bws$xnuno + bws$ynuno == 0) & perspective & !gradients & !any(xor(bws$xdati$iord, bws$xdati$inumord))){ view = match.arg(view) rotate = (view == "rotate") if (is.ordered(xdat[,1])){ x1.eval = bws$xdati$all.ulev[[1]] x1.neval = length(x1.eval) } else { x1.neval = neval qi = trim.quantiles(xdat[,1], xtrim[1]) x1.eval = seq(qi[1], qi[2], length.out = x1.neval) } if (quantreg){ tx2 <- xdat[,2] txi <- 2 txdati <- bws$xdati txtrim <- xtrim } else{ tx2 <- ydat[,1] txi <- 1 txdati <- bws$ydati txtrim <- ytrim } if (txdati$iord[txi]){ x2.eval = txdati$all.ulev[[txi]] x2.neval = length(x2.eval) } else { x2.neval = neval qi = trim.quantiles(tx2, txtrim[txi]) x2.eval = seq(qi[1], qi[2], length.out = x2.neval) } x.eval <- expand.grid(x1.eval, x2.eval) if (bws$xdati$iord[1]) x1.eval <- (bws$xdati$all.dlev[[1]])[as.integer(x1.eval)] if (txdati$iord[txi]) x2.eval <- (txdati$all.dlev[[txi]])[as.integer(x2.eval)] tboo = if(quantreg) "quant" else if (cdf) "dist" else "dens" tobj = eval(parse(text = paste( switch(tboo, "quant" = "npqreg", "dist" = "npcdist", "dens" = "npcdens"), "(txdat = xdat, tydat = ydat, exdat =", ifelse(quantreg, "x.eval, tau = tau", "x.eval[,1], eydat = x.eval[,2]"), ", bws = bws)", sep=""))) tcomp = parse(text=paste("tobj$", switch(tboo, "quant" = "quantile", "dist" = "condist", "dens" = "condens"), sep="")) tcerr = parse(text=paste(ifelse(quantreg, "tobj$quanterr", "tobj$conderr"))) tex = parse(text=paste(ifelse(quantreg, "x.eval", "x.eval[,1]"))) tey = parse(text=paste(ifelse(quantreg, "NA", "x.eval[,2]"))) tdens = matrix(data = eval(tcomp), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) terr = matrix(data = eval(tcerr), nrow = length(eval(tcomp)), ncol = 3) terr[,3] = NA if (plot.errors.method == "bootstrap"){ terr <- compute.bootstrap.errors(xdat = xdat, ydat = ydat, exdat = eval(tex), eydat = eval(tey), cdf = cdf, quantreg = quantreg, tau = tau, gradients = FALSE, gradient.index = 0, slice.index = 0, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws)[["boot.err"]] pc = (plot.errors.center == "bias-corrected") lerr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} -terr[,1], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = if(pc) {terr[,3]} else {eval(tcomp)} +terr[,2], nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } else if (plot.errors.method == "asymptotic") { lerr = matrix(data = eval(tcomp) - 2.0*eval(tcerr), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) herr = matrix(data = eval(tcomp) + 2.0*eval(tcerr), nrow = x1.neval, ncol = x2.neval, byrow = FALSE) } zlim = if (plot.errors) c(min(lerr),max(herr)) else c(min(eval(tcomp)),max(eval(tcomp))) tret = parse(text=paste( switch(tboo, "quant" = "qregression", "dist" = "condistribution", "dens" = "condensity"), "(bws = bws, xeval = eval(tex),", ifelse(quantreg, "tau = tau, quantile = eval(tcomp), quanterr = terr[,1:2]", paste("yeval = eval(tey),", ifelse(cdf, "condist = ", "condens = "), "eval(tcomp), conderr = terr[,1:2]")), ", ntrain = dim(xdat)[1])", sep="")) if (plot.behavior != "plot"){ cd1 = eval(tret) cd1$bias = NA if (plot.errors.center == "bias-corrected") cd1$bias = terr[,3] - eval(tcomp) if (plot.behavior == "data") return ( list(cd1 = cd1) ) } dtheta = 5.0 dphi = 10.0 persp.col = ifelse(plot.errors, FALSE, ifelse(!is.null(col),col,"lightblue")) for (i in 0:((360 %/% dtheta - 1)*rotate)*dtheta+theta){ if (plot.errors){ persp(x1.eval, x2.eval, lerr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) par(new = TRUE) } persp(x1.eval, x2.eval, tdens, zlim = zlim, col = persp.col, border = ifelse(!is.null(border),border,"black"), ticktype = "detailed", cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,gen.label(names(xdat)[1], "X")), ylab = ifelse(!is.null(ylab),ylab,gen.label(names(ydat)[1], "Y")), zlab = ifelse(!is.null(zlab),zlab,paste("Conditional", ifelse(cdf,"Distribution", "Density"))), theta = i, phi = phi, main = gen.tflabel(!is.null(main), main, paste("[theta= ", i,", phi= ", phi,"]", sep=""))) if (plot.errors){ par(new = TRUE) persp(x1.eval, x2.eval, herr, zlim = zlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), col = persp.col, border = ifelse(!is.null(border),border,"grey"), ticktype = "detailed", xlab = "", ylab = "", zlab = "", theta = i, phi = phi, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } Sys.sleep(0.5) } } else { dsf = ifelse(gradients,bws$xndim,1) tot.dim = bws$xndim + bws$yndim - quantreg if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=n2mfrow(dsf*tot.dim),cex=par()$cex) x.ev = xdat[1,,drop = FALSE] y.ev = ydat[1,,drop = FALSE] for (i in 1:bws$xndim) x.ev[1,i] = uocquantile(xdat[,i], prob=xq[i]) for (i in 1:bws$yndim) y.ev[1,i] = uocquantile(ydat[,i], prob=yq[i]) maxneval = max(c(sapply(xdat,nlevels), sapply(ydat,nlevels), neval)) exdat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$xndim)) eydat = as.data.frame(matrix(data = 0, nrow = maxneval, ncol = bws$yndim)) for (i in 1:bws$xndim) exdat[,i] = x.ev[1,i] for (i in 1:bws$yndim) eydat[,i] = y.ev[1,i] if (common.scale){ data.eval = matrix(data = NA, nrow = maxneval, ncol = tot.dim*dsf) data.err = matrix(data = NA, nrow = maxneval, ncol = 3*tot.dim*dsf) allei = as.data.frame(matrix(data = NA, nrow = maxneval, ncol = tot.dim)) all.bxp = list() } all.isFactor = c(sapply(xdat, is.factor), sapply(ydat, is.factor)) plot.out = list() temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.dens = replicate(maxneval, NA) plot.bootstrap = plot.errors.method == "bootstrap" pfunE = expression(ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp,"bxp","plotFactor"), "plot")) pxE = expression(ifelse(common.scale, ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "all.bxp[[plot.index]],", "f = allei[,plot.index],"), "x = allei[,plot.index],"), ifelse(xi.factor, ifelse(plot.bootstrap & plot.bxp, "z = temp.boot,", "f = ei,"), "x = ei,"))) pyE = expression(ifelse(xi.factor & plot.bootstrap & plot.bxp, "", ifelse(common.scale,"y = data.eval[,plot.index],", "y = temp.dens,"))) pylimE = ifelse(common.scale, "ylim = c(y.min,y.max),", ifelse(plot.errors, "ylim = c(min(na.omit(c(temp.dens - temp.err[,1], temp.err[,3] - temp.err[,1]))), max(na.omit(c(temp.dens + temp.err[,2], temp.err[,3] + temp.err[,2])))),", "")) pxlabE = expression(paste("xlab = ifelse(!is.null(xlab),xlab,gen.label(bws$", xOrY, "names[i], paste('", toupper(xOrY),"', i, sep = ''))),",sep='')) tylabE = ifelse(quantreg, paste(tau, 'quantile'), paste('Conditional', ifelse(cdf,'Distribution', 'Density'))) pylabE = paste("ylab =", "paste(", ifelse(gradients,"'GC',j,'of',",''), "tylabE),") prestE = expression(ifelse(xi.factor,"", "type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), lwd = ifelse(!is.null(lwd),lwd,par()$lwd), cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub),")) pmainE = "main = ifelse(!is.null(main),main,''), sub = ifelse(!is.null(sub),sub,'')," plotOnEstimate = (plot.errors.center == "estimate") efunE = "draw.errors" eexE = expression(ifelse(common.scale, "ex = as.numeric(na.omit(allei[,plot.index])),", "ex = as.numeric(na.omit(ei)),")) eelyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ely = na.omit(data.eval[,plot.index] - data.err[,3*plot.index-2]),", "ely = na.omit(data.err[,3*plot.index] - data.err[,3*plot.index-2]),"), ifelse(plotOnEstimate, "ely = na.omit(temp.dens - temp.err[,1]),", "ely = na.omit(temp.err[,3] - temp.err[,1]),"))) eehyE = expression(ifelse(common.scale, ifelse(plotOnEstimate, "ehy = na.omit(data.eval[,plot.index] + data.err[,3*plot.index-1]),", "ehy = na.omit(data.err[,3*plot.index] + data.err[,3*plot.index-1]),"), ifelse(plotOnEstimate, "ehy = na.omit(temp.dens + temp.err[,2]),", "ehy = na.omit(temp.err[,3] + temp.err[,2]),"))) erestE = "plot.errors.style = ifelse(xi.factor,'bar',plot.errors.style), plot.errors.bar = ifelse(xi.factor,'I',plot.errors.bar), plot.errors.bar.num = plot.errors.bar.num, lty = ifelse(xi.factor,1,2)" plot.index = 0 xOrY = "x" for (i in 1:bws$xndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$xdati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(xdat[,i], xtrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(parse(text=paste(ifelse(cdf, "npcdist", ifelse(quantreg, "npqreg", "npcdens")), "(txdat = xdat, tydat = ydat,", "exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE],", ifelse(quantreg, "tau = tau,", "eydat = eydat[1:xi.neval,, drop = FALSE],"), "gradients = gradients, bws = bws)",sep=""))) tevalexpr = parse(text=paste("tobj$",ifelse(gradients, ifelse(quantreg, "quantgrad[,j]","congrad[,j]"), ifelse(cdf, "condist", ifelse(quantreg, "quantile", "condens"))), sep="")) terrexpr = parse(text=paste("tobj$",ifelse(gradients, "congerr[,j]", ifelse(quantreg,"quanterr", "conderr")), sep="")) if (gradients & quantreg) terrexpr = parse(text="NA") if (plot.behavior != "plot"){ plot.out[plot.index] = NA plot.out[[plot.index]] = tobj } for (j in 1:dsf){ temp.boot = list() temp.dens[1:xi.neval] = eval(tevalexpr) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*eval(terrexpr)) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, exdat = subcol(exdat,ei,i)[1:xi.neval,, drop = FALSE], eydat = eydat[1:xi.neval,, drop = FALSE], cdf = cdf, quantreg = quantreg, tau = tau, gradients = gradients, gradient.index = j, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[,(plot.index-1)*dsf+j] = temp.dens if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[,seq(3*((plot.index-1)*dsf+j)-2,length=3)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot" & plot.errors) { eval(parse(text=paste("plot.out[[plot.index]]$",ifelse(gradients, paste("gc",j,"err",sep=""), ifelse(quantreg, "quanterr", "conderr")), "= na.omit(cbind(-temp.err[,1], temp.err[,2]))", sep=""))) eval(parse(text=paste("plot.out[[plot.index]]$", ifelse(gradients, paste("gc",j,"bias",sep=""), "bias"), "= na.omit(temp.dens - temp.err[,3])", sep=""))) plot.out[[plot.index]]$bxp = temp.boot } } } if (!quantreg){ xOrY = "y" for (i in 1:bws$yndim){ plot.index = plot.index + 1 temp.err[,] = NA temp.dens[] = NA temp.boot = list() xi.factor = all.isFactor[plot.index] if (xi.factor){ ei = bws$ydati$all.ulev[[i]] xi.neval = length(ei) } else { xi.neval = neval qi = trim.quantiles(ydat[,i], ytrim[i]) ei = seq(qi[1], qi[2], length.out = neval) } if (xi.neval < maxneval){ ei[(xi.neval+1):maxneval] = NA } tobj = eval(parse(text=paste(ifelse(cdf, "npcdist", ifelse(quantreg, "npqreg", "npcdens")), "(txdat = xdat, tydat = ydat,", ifelse(quantreg, "tau = tau,", "exdat = exdat[1:xi.neval,, drop = FALSE],"), "eydat = subcol(eydat,ei,i)[1:xi.neval,, drop = FALSE],", "gradients = gradients, bws = bws)",sep=""))) tevalexpr = parse(text=paste("tobj$",ifelse(gradients, ifelse(quantreg, "quantgrad[,j]","congrad[,j]"), ifelse(cdf, "condist", ifelse(quantreg, "quantile", "condens"))), sep="")) terrexpr = parse(text=paste("tobj$",ifelse(gradients, "congerr[,j]", ifelse(quantreg,"quanterr", "conderr")), sep="")) if (gradients & quantreg) terrexpr = parse(text="NA") if (plot.behavior != "plot"){ plot.out[plot.index] = NA plot.out[[plot.index]] = tobj } for (j in 1:dsf){ temp.boot = list() temp.dens[1:xi.neval] = eval(tevalexpr) if (plot.errors){ if (plot.errors.method == "asymptotic") temp.err[1:xi.neval,1:2] = replicate(2,2.0*eval(terrexpr)) else if (plot.errors.method == "bootstrap"){ temp.boot <- compute.bootstrap.errors( xdat = xdat, ydat = ydat, exdat = exdat[1:xi.neval,, drop = FALSE], eydat = subcol(eydat,ei,i)[1:xi.neval,, drop = FALSE], cdf = cdf, quantreg = quantreg, tau = tau, gradients = gradients, gradient.index = j, slice.index = plot.index, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) temp.err[1:xi.neval,] <- temp.boot[["boot.err"]] temp.boot <- temp.boot[["bxp"]] if (!plot.bxp.out){ temp.boot$out <- numeric() temp.boot$group <- integer() } } } if (common.scale){ allei[,plot.index] = ei data.eval[,(plot.index-1)*dsf+j] = temp.dens if (plot.errors){ all.bxp[plot.index] = NA all.bxp[[plot.index]] = temp.boot data.err[,seq(3*((plot.index-1)*dsf+j)-2,length=3)] = temp.err } } else if (plot.behavior != "data") { eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } if (plot.behavior != "plot" & plot.errors) { eval(parse(text=paste("plot.out[[plot.index]]$",ifelse(gradients, paste("gc",j,"err",sep=""), ifelse(quantreg, "quanterr", "conderr")), "= na.omit(cbind(-temp.err[,1], temp.err[,2]))", sep=""))) eval(parse(text=paste("plot.out[[plot.index]]$", ifelse(gradients, paste("gc",j,"bias",sep=""), "bias"), "= na.omit(temp.dens - temp.err[,3])", sep=""))) plot.out[[plot.index]]$bxp = temp.boot } } } } if (common.scale & (plot.behavior != "data")){ jj = 1:(dsf*tot.dim)*3 if (plot.errors.center == "estimate" | !plot.errors) { y.max = max(na.omit(as.double(data.eval)) + if (plot.errors) na.omit(as.double(data.err[,jj-1])) else 0) y.min = min(na.omit(as.double(data.eval)) - if (plot.errors) na.omit(as.double(data.err[,jj-2])) else 0) } else if (plot.errors.center == "bias-corrected") { y.max = max(na.omit(as.double(data.err[,jj] + data.err[,jj-1]))) y.min = min(na.omit(as.double(data.err[,jj] - data.err[,jj-2]))) } if(!is.null(ylim)){ y.min = ylim[1] y.max = ylim[2] } xOrY = "x" for (plot.index in 1:tot.dim){ i = ifelse(plot.index <= bws$xndim, plot.index, plot.index - bws$xndim) if (plot.index > bws$xndim) xOrY <- "y" xi.factor = all.isFactor[plot.index] for (j in 1:dsf){ eval(parse(text = paste(eval(pfunE), "(", eval(pxE), eval(pyE), eval(pylimE), eval(pxlabE), eval(pylabE), eval(prestE), eval(pmainE), ")"))) if (plot.errors && !(xi.factor & plot.bootstrap & plot.bxp)){ if (!xi.factor && !plotOnEstimate) lines(na.omit(ei), na.omit(temp.err[,3]), lty = 3) eval(parse(text = paste(eval(efunE), "(", eval(eexE), eval(eelyE), eval(eehyE), eval(erestE), ")"))) } } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = paste("cd", 1:tot.dim, sep="") return (plot.out) } } } npplot.sibandwidth <- function(bws, xdat, ydat, data = NULL, common.scale = TRUE, gradients = FALSE, main = NULL, type = NULL, cex.axis = NULL, cex.lab = NULL, cex.main = NULL, cex.sub = NULL, col = NULL, ylab = NULL, xlab = NULL, sub = NULL, ylim = NULL, xlim = NULL, lty = NULL, lwd = NULL, plot.behavior = c("plot","plot-data","data"), plot.errors.method = c("none","bootstrap","asymptotic"), plot.errors.boot.num = 399, plot.errors.boot.method = c("inid", "fixed", "geom"), plot.errors.boot.blocklen = NULL, plot.errors.center = c("estimate","bias-corrected"), plot.errors.type = c("standard","quantiles"), plot.errors.quantiles = c(0.025,0.975), plot.errors.style = c("band","bar"), plot.errors.bar = c("|","I"), plot.errors.bar.num = NULL, plot.par.mfrow = TRUE, ..., random.seed){ miss.xy = c(missing(xdat),missing(ydat)) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) && !is.null(bws$formula)){ 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 umf <- tmf <- eval(tmf, envir = environment(tt)) ydat <- model.response(tmf) xdat <- tmf[, attr(attr(tmf, "terms"),"term.labels"), drop = FALSE] } else { if(all(miss.xy) && !is.null(bws$call)){ xdat <- data.frame(eval(bws$call[["xdat"]], environment(bws$call))) ydat = eval(bws$call[["ydat"]], environment(bws$call)) } xdat = toFrame(xdat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows] } if (is.null(plot.errors.bar.num)) plot.errors.bar.num = min(length(ydat),25) if (missing(plot.errors.method) & any(!missing(plot.errors.boot.num), !missing(plot.errors.boot.method), !missing(plot.errors.boot.blocklen))){ warning(paste("plot.errors.method must be set to 'bootstrap' to use bootstrapping.", "\nProceeding without bootstrapping.")) } plot.behavior = match.arg(plot.behavior) plot.errors.method = match.arg(plot.errors.method) plot.errors.boot.method = match.arg(plot.errors.boot.method) plot.errors.center = match.arg(plot.errors.center) plot.errors.type = match.arg(plot.errors.type) plot.errors.style = match.arg(plot.errors.style) plot.errors.bar = match.arg(plot.errors.bar) common.scale = common.scale | (!is.null(ylim)) if (plot.errors.method == "asymptotic") { warning(paste("asymptotic errors are not supported with single index regression.\n", "Proceeding without calculating errors")) plot.errors.method = "none" } if (is.element(plot.errors.boot.method, c("fixed", "geom")) && is.null(plot.errors.boot.blocklen)) plot.errors.boot.blocklen = b.star(xdat,round=TRUE)[1,1] plot.errors = (plot.errors.method != "none") if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=if(gradients) n2mfrow(bws$ndim) else c(1,1),cex=par()$cex) plot.out = list() neval = maxneval = length(ydat) tobj = npindex(txdat = xdat, tydat = ydat, bws = bws, gradients = gradients) temp.err = matrix(data = NA, nrow = maxneval, ncol = 3) temp.mean = replicate(maxneval, NA) temp.mean[] = if(gradients) tobj$grad[,1] else tobj$mean if (plot.errors){ if (plot.errors.method == "bootstrap") temp.err[,] = compute.bootstrap.errors( xdat = xdat, ydat = ydat, gradients = gradients, plot.errors.boot.method = plot.errors.boot.method, plot.errors.boot.blocklen = plot.errors.boot.blocklen, plot.errors.boot.num = plot.errors.boot.num, plot.errors.center = plot.errors.center, plot.errors.type = plot.errors.type, plot.errors.quantiles = plot.errors.quantiles, bws = bws) } i.sort = sort(tobj$index, index.return=TRUE)$ix if (!gradients){ if(!is.null(ylim)){ ymin = ylim[1] ymax = ylim[2] } else { ymin <- eval(parse(text=paste("min(", ifelse(plot.errors,"na.omit(",""), "c(temp.mean", ifelse(plot.errors,"- temp.err[,1]",""), ", temp.err[,3]", ifelse(plot.errors,"- temp.err[,1]",""), "))", ifelse(plot.errors,")","")))) ymax <- eval(parse(text=paste("max(", ifelse(plot.errors,"na.omit(",""), "c(temp.mean", ifelse(plot.errors,"+ temp.err[,2]",""), ", temp.err[,3]", ifelse(plot.errors,"+ temp.err[,2]",""), "))", ifelse(plot.errors,")","")))) } if (plot.behavior != "data"){ if (plot.errors){ plot(tobj$index[i.sort], temp.mean[i.sort], ylim = ifelse(!is.null(ylim),ylim,c(ymin,ymax)), xlim = xlim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,"index"), ylab = ifelse(!is.null(ylab),ylab,gen.label(bws$ynames, 'Conditional Mean')), type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), main = main, sub = sub, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) if (plot.errors.center == "estimate") { draw.errors(ex = na.omit(tobj$index[i.sort]), ely = na.omit(temp.mean[i.sort] - temp.err[i.sort,1]), ehy = na.omit(temp.mean[i.sort] + temp.err[i.sort,2]), plot.errors.style = plot.errors.style, plot.errors.bar = plot.errors.bar, plot.errors.bar.num = plot.errors.bar.num, lty = 2) } else if (plot.errors.center == "bias-corrected") { lines(na.omit(tobj$index[i.sort]), na.omit(temp.err[i.sort,3]), lty = 3) draw.errors(ex = na.omit(tobj$index[i.sort]), ely = na.omit(temp.err[i.sort,3] - temp.err[i.sort,1]), ehy = na.omit(temp.err[i.sort,3] + temp.err[i.sort,2]), plot.errors.style = plot.errors.style, plot.errors.bar = plot.errors.bar, plot.errors.bar.num = plot.errors.bar.num, lty = 2) } } else { plot(tobj$index[i.sort], temp.mean[i.sort], cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,"Index"), ylab = ifelse(!is.null(ylab),ylab,gen.label(bws$ynames, 'Conditional Mean')), type = ifelse(!is.null(type),type,'l'), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), main = main, sub = sub, xlim = xlim, ylim = ylim, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) } } if (plot.behavior != "plot") { plot.out[1] = NA plot.out[[1]] = tobj } } else { bmax = max(bws$beta) bmin = min(bws$beta) if (plot.errors){ ymax = max(temp.mean + temp.err[,2]) ymin = min(temp.mean - temp.err[,1]) } else { ymax = max(temp.mean) ymin = min(temp.mean) } ylim = c(min(bmin*ymax,bmax*ymin),max(bmax*ymax,bmin*ymin)) if(!is.null(ylim)){ ymin = ylim[1] ymax = ylim[2] } if (plot.behavior != "plot"){ plot.out[1] = NA plot.out[[1]] = tobj plot.out[[1]]$index = tobj$index[i.sort] plot.out[[1]]$mean = tobj$mean[i.sort] plot.out[[1]]$grad = matrix(data=0,nrow = nrow(xdat), ncol = ncol(xdat)) plot.out[[1]]$glerr = matrix(data=0,nrow = nrow(xdat), ncol = ncol(xdat)) plot.out[[1]]$gherr = matrix(data=0,nrow = nrow(xdat), ncol = ncol(xdat)) } for (i in 1:ncol(xdat)){ if (plot.behavior != "data"){ if(!common.scale) ylim = c(min(temp.mean*bws$beta[i]), max(temp.mean*bws$beta[i])) plot(tobj$index[i.sort], temp.mean[i.sort]*bws$beta[i], ylim = ylim, cex.axis = ifelse(!is.null(cex.axis),cex.axis,par()$cex.axis), cex.lab = ifelse(!is.null(cex.lab),cex.lab,par()$cex.lab), cex.main = ifelse(!is.null(cex.main),cex.main,par()$cex.main), cex.sub = ifelse(!is.null(cex.sub),cex.sub,par()$cex.sub), xlab = ifelse(!is.null(xlab),xlab,"index"), ylab = paste("Gradient Component",i, "of", gen.label(bws$ynames, 'Conditional Mean')), lty = ifelse(!is.null(lty),lty,par()$lty), col = ifelse(!is.null(col),col,par()$col), type = ifelse(!is.null(type),type,'l'), main = main, sub = sub, lwd = ifelse(!is.null(lwd),lwd,par()$lwd)) if (plot.errors){ if (plot.errors.center == "estimate") { draw.errors(ex = na.omit(tobj$index[i.sort]), ely = na.omit(bws$beta[i]*(temp.mean[i.sort] - temp.err[i.sort,1])), ehy = na.omit(bws$beta[i]*(temp.mean[i.sort] + temp.err[i.sort,2])), plot.errors.style = plot.errors.style, plot.errors.bar = plot.errors.bar, plot.errors.bar.num = plot.errors.bar.num, lty = 2) } else if (plot.errors.center == "bias-corrected") { lines(na.omit(tobj$index[i.sort]), na.omit(temp.err[i.sort,3]), lty = 3) draw.errors(ex = na.omit(tobj$index[i.sort]), ely = na.omit(temp.err[i.sort,3] - temp.err[i.sort,1]), ehy = na.omit(temp.err[i.sort,3] + temp.err[i.sort,2]), plot.errors.style = plot.errors.style, plot.errors.bar = plot.errors.bar, plot.errors.bar.num = plot.errors.bar.num, lty = 2) } } } if (plot.behavior != "plot"){ plot.out[[1]]$grad[,i] = bws$beta[i]*temp.mean[i.sort] plot.out[[1]]$glerr[,i] = bws$beta[i]*temp.err[i.sort,ifelse(bws$beta >= 0.0,1,2)] plot.out[[1]]$gherr[,i] = bws$beta[i]*temp.err[i.sort,ifelse(bws$beta < 0.0,1,2)] plot.out[[1]]$gbias[,i] = bws$beta[i]*temp.err[i.sort,3] } } } if (plot.behavior != "data" && plot.par.mfrow) par(mfrow=c(1,1),cex=par()$cex) if (plot.behavior != "plot"){ names(plot.out) = paste(ifelse(gradients, "si.grad", "si"),1:ncol(xdat),sep="") return (plot.out) } }
"LSWsim"<- function(spec){ if (any(spec$D < 0)) stop("All spectral elements must be non-negative") nlev <- nlevelsWT(spec) len <- 2^nlev for(i in (nlev-1):0) { v <- accessD(spec, level=i) v <- sqrt(v)*2^(nlev-i)*rnorm(len) spec <- putD(spec, level=i, v=v) } AvBasis(convert(spec)) } "cns"<- function(n, filter.number=1, family="DaubExPhase"){ if (is.na(IsPowerOfTwo(n))) stop("n must be a power of two") z <- rep(0, n) zwdS <- wd(z, filter.number=filter.number, family=family, type="station") zwdS } "checkmyews" <- function(spec, nsim=10){ ans <- cns(2^nlevelsWT(spec)) for(i in 1:nsim) { cat(".") LSWproc <- LSWsim(spec) ews <- ewspec(LSWproc, filter.number=1, family="DaubExPhase", WPsmooth=FALSE) ans$D <- ans$D + ews$S$D ans$C <- ans$C + ews$S$C } ans$D <- ans$D/nsim ans$C <- ans$C/nsim ans }
plot(ml.binom2, hline = TRUE) %>% gf_lims(y = c(-45, -35)) %>% gf_labs(x = "log odds")
'_PACKAGE' localDensity <- function(distance, dc, gaussian = FALSE) { if (gaussian) { res <- gaussianLocalDensity(distance, attr(distance, "Size"), dc) } else { res <- nonGaussianLocalDensity(distance, attr(distance, "Size"), dc) } if (is.null(attr(distance, 'Labels'))) { names(res) <- NULL } else { names(res) <- attr(distance, 'Labels') } res } distanceToPeak <- function(distance, rho) { res <- distanceToPeakCpp(distance, rho); names(res) <- names(rho) res } estimateDc <- function(distance, neighborRateLow = 0.01, neighborRateHigh = 0.02) { size <- attr(distance, 'Size') if (size > 448) { distance <- distance[sample.int(length(distance), 100128)] size <- 448 } low <- min(distance) high <- max(distance) dc <- 0 while (TRUE) { dc <- (low + high) / 2 neighborRate <- (((sum(distance < dc) * 2 + (if (0 <= dc) size)) / size - 1)) / size if (neighborRate >= neighborRateLow && neighborRate <= neighborRateHigh) break if (neighborRate < neighborRateLow) { low <- dc } else { high <- dc } } cat('Distance cutoff calculated to', dc, '\n') dc } densityClust <- function(distance, dc, gaussian=FALSE, verbose = FALSE, ...) { if (is.data.frame(distance) || is.matrix(distance)) { dp_knn_args <- list(mat = distance, verbose = verbose, ...) res <- do.call(densityClust.knn, dp_knn_args) } else { if (missing(dc)) { if (verbose) message('Calculating the distance cutoff') dc <- estimateDc(distance) } if (verbose) message('Calculating the local density for each sample based on distance cutoff') rho <- localDensity(distance, dc, gaussian = gaussian) if (verbose) message('Calculating the minimal distance of a sample to another sample with higher density') delta <- distanceToPeak(distance, rho) if (verbose) message('Returning result...') res <- list( rho = rho, delta = delta, distance = distance, dc = dc, threshold = c(rho = NA, delta = NA), peaks = NA, clusters = NA, halo = NA, knn_graph = NA, nearest_higher_density_neighbor = NA, nn.index = NA, nn.dist = NA ) class(res) <- 'densityCluster' } res } plot.densityCluster <- function(x, ...) { plot(x$rho, x$delta, main = 'Decision graph', xlab = expression(rho), ylab = expression(delta)) if (!is.na(x$peaks[1])) { points(x$rho[x$peaks], x$delta[x$peaks], col = 2:(1 + length(x$peaks)), pch = 19) } } plotMDS <- function(x, ...) { UseMethod('plotMDS') } plotMDS.densityCluster <- function(x, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { mds <- cmdscale(dist(x$distance)) } else { mds <- cmdscale(x$distance) } plot(mds[,1], mds[,2], xlab = '', ylab = '', main = 'MDS plot of observations') if (!is.na(x$peaks[1])) { for (i in 1:length(x$peaks)) { ind <- which(x$clusters == i) points(mds[ind, 1], mds[ind, 2], col = i + 1, pch = ifelse(x$halo[ind], 1, 19)) } legend('topright', legend = c('core', 'halo'), pch = c(19, 1), horiz = TRUE) } } plotTSNE <- function(x, ...) { UseMethod('plotTSNE') } plotTSNE.densityCluster <- function(x, max_components = 2, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { data <- as.matrix(dist(x$distance)) } else { data <- as.matrix(x$distance) } dup_id <- which(duplicated(data)) if (length(dup_id) > 0) { data[dup_id, ] <- data[dup_id, ] + rnorm(length(dup_id) * ncol(data), sd = 1e-10) } tsne_res <- Rtsne::Rtsne(as.matrix(data), dims = max_components, pca = T) tsne_data <- tsne_res$Y[, 1:max_components] plot(tsne_data[,1], tsne_data[,2], xlab = '', ylab = '', main = 'tSNE plot of observations') if (!is.na(x$peaks[1])) { for (i in 1:length(x$peaks)) { ind <- which(x$clusters == i) points(tsne_data[ind, 1], tsne_data[ind, 2], col = i + 1, pch = ifelse(x$halo[ind], 1, 19)) } legend('topright', legend = c('core', 'halo'), pch = c(19, 1), horiz = TRUE) } } print.densityCluster <- function(x, ...) { if (is.na(x$peaks[1])) { cat('A densityCluster object with no clusters defined\n\n') cat('Number of observations:', length(x$rho), '\n') } else { cat('A densityCluster object with', length(x$peaks), 'clusters defined\n\n') cat('Number of observations:', length(x$rho), '\n') cat('Observations in core: ', sum(!x$halo), '\n\n') cat('Parameters:\n') cat('dc (distance cutoff) rho threshold delta threshold\n') cat(formatC(x$dc, width = -22), formatC(x$threshold[1], width = -22), x$threshold[2]) } } findClusters <- function(x, ...) { UseMethod("findClusters") } findClusters.densityCluster <- function(x, rho, delta, plot = FALSE, peaks = NULL, verbose = FALSE, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { peak_ind <- which(x$rho > rho & x$delta > delta) x$peaks <- peak_ind runOrder <- order(x$rho, decreasing = TRUE) cluster <- rep(NA, length(x$rho)) for (i in x$peaks) { cluster[i] <- match(i, x$peaks) } for (ind in setdiff(runOrder, x$peaks)) { target_lower_density_samples <- which(x$nearest_higher_density_neighbor == ind) cluster[ind] <- cluster[x$nearest_higher_density_neighbor[ind]] } potential_duplicates <- which(is.na(cluster)) for (ind in potential_duplicates) { res <- as.integer(names(which.max(table(cluster[x$nn.index[ind, ]])))) if (length(res) > 0) { cluster[ind] <- res } else { message('try to increase the number of kNN (through argument k) at step of densityClust.') cluster[ind] <- NA } } x$clusters <- factor(cluster) border <- rep(0, length(x$peaks)) if (verbose) message('Identifying core and halo for each cluster') for (i in 1:length(x$peaks)) { if (verbose) message('the current index of the peak is ', i) connect_samples_ind <- intersect(unique(x$nn.index[cluster == i, ]), which(cluster != i)) averageRho <- outer(x$rho[cluster == i], x$rho[connect_samples_ind], '+') / 2 if (any(connect_samples_ind)) border[i] <- max(averageRho[connect_samples_ind]) } x$halo <- x$rho < border[cluster] x$threshold['rho'] <- rho x$threshold['delta'] <- delta } else { if (!is.null(peaks)) { if (verbose) message('peaks are provided, clustering will be performed based on them') x$peaks <- peaks } else { if (missing(rho) || missing(delta)) { x$peaks <- NA plot(x) cat('Click on plot to select thresholds\n') threshold <- locator(1) if (missing(rho)) rho <- threshold$x if (missing(delta)) delta <- threshold$y plot = TRUE } x$peaks <- which(x$rho > rho & x$delta > delta) x$threshold['rho'] <- rho x$threshold['delta'] <- delta } if (plot) { plot(x) } runOrder <- order(x$rho, decreasing = TRUE) cluster <- rep(NA, length(x$rho)) if (verbose) message('Assigning each sample to a cluster based on its nearest density peak') for (i in runOrder) { if ((i %% round(length(runOrder) / 25)) == 0) { if (verbose) message(paste('the runOrder index is', i)) } if (i %in% x$peaks) { cluster[i] <- match(i, x$peaks) } else { higherDensity <- which(x$rho > x$rho[i]) cluster[i] <- cluster[higherDensity[which.min(findDistValueByRowColInd(x$distance, attr(x$distance, 'Size'), i, higherDensity))]] } } x$clusters <- cluster border <- rep(0, length(x$peaks)) if (verbose) message('Identifying core and halo for each cluster') for (i in 1:length(x$peaks)) { if (verbose) message('the current index of the peak is ', i) averageRho <- outer(x$rho[cluster == i], x$rho[cluster != i], '+')/2 index <- findDistValueByRowColInd(x$distance, attr(x$distance, 'Size'), which(cluster == i), which(cluster != i)) <= x$dc if (any(index)) border[i] <- max(averageRho[index]) } x$halo <- x$rho < border[cluster] } x$halo <- x$rho < border[cluster] gamma <- x$rho * x$delta pk.ordr <- order(gamma[x$peaks], decreasing = TRUE) x$peaks <- x$peaks[pk.ordr] x$clusters <- match(x$clusters, pk.ordr) x } clusters <- function(x, ...) { UseMethod("clusters") } clusters.densityCluster <- function(x, as.list = FALSE, halo.rm = TRUE, ...) { if (!clustered(x)) stop('x must be clustered prior to cluster extraction') res <- x$clusters if (halo.rm) { res[x$halo] <- NA } if (as.list) { res <- split(1:length(res), res) } res } clustered <- function(x) { UseMethod("clustered") } clustered.densityCluster <- function(x) { !any(is.na(x$peaks[1]), is.na(x$clusters[1]), is.na(x$halo[1])) } labels.densityCluster <- function(object, ...) { labels(object$distance) } densityClust.knn <- function(mat, k = NULL, verbose = F, ...) { if (is.null(k)) { k <- round(sqrt(nrow(mat)) / 2) k <- max(10, k) } if (verbose) message('Finding kNN using FNN with ', k, ' neighbors') dx <- get.knn(mat, k = k, ...) nn.index <- dx$nn.index nn.dist <- dx$nn.dist N <- nrow(nn.index) knn_graph <- NULL if (verbose) message('Calculating the local density for each sample based on kNNs ...') rho <- apply(nn.dist, 1, function(x) { exp(-mean(x)) }) if (verbose) message('Calculating the minimal distance of a sample to another sample with higher density ...') rho_order <- order(rho) delta <- vector(mode = 'integer', length = N) nearest_higher_density_neighbor <- vector(mode = 'integer', length = N) delta_neighbor_tmp <- smallest_dist_rho_order_coords(rho[rho_order], as.matrix(mat[rho_order, ])) delta[rho_order] <- delta_neighbor_tmp$smallest_dist nearest_higher_density_neighbor[rho_order] <- rho_order[delta_neighbor_tmp$nearest_higher_density_sample + 1] if (verbose) message('Returning result...') res <- list( rho = rho, delta = delta, distance = mat, dc = NULL, threshold = c(rho = NA, delta = NA), peaks = NA, clusters = NA, halo = NA, knn_graph = knn_graph, nearest_higher_density_neighbor = nearest_higher_density_neighbor, nn.index = nn.index, nn.dist = nn.dist ) class(res) <- 'densityCluster' res }
context("plotmap") test_that("test basic error checking",{ object<-c("this","that","the other") expect_error(plotmap(object),"Error in plotmap: inclust must be a clust object") N<-5 Tmax<-100 rho<-0.5 sig<-matrix(rho,N,N) diag(sig)<-1 d<-t(cbind(copy_rmvnorm(Tmax,mean=rep(0,N),sigma=sig), copy_rmvnorm(Tmax,mean=rep(0,N),sigma=sig))) d<-cleandat(d,1:Tmax,1)$cdat coords<-data.frame(X=runif(N*2,1,10),Y=runif(N*2,1,10)) cl1<-clust(dat=d,times=1:Tmax,coords=coords,method="pearson") cl1$clusters[[2]]<-1:(N*2) expect_error(plotmap(cl1),"Error in plotmap: more than 9 modules, plotmap cannot proceed") }) test_that("tests on clust objects",{ set.seed(101) N<-20 Tmax<-500 tim<-1:Tmax ts1<-sin(2*pi*tim/5) ts1s<-sin(2*pi*tim/5+pi/2) ts2<-sin(2*pi*tim/12) ts2s<-sin(2*pi*tim/12+pi/2) gp1A<-1:5 gp1B<-6:10 gp2A<-11:15 gp2B<-16:20 d<-matrix(NA,Tmax,N) d[,c(gp1A,gp1B)]<-ts1 d[,c(gp2A,gp2B)]<-ts1s d[,c(gp1A,gp2A)]<-d[,c(gp1A,gp2A)]+matrix(ts2,Tmax,N/2) d[,c(gp1B,gp2B)]<-d[,c(gp1B,gp2B)]+matrix(ts2s,Tmax,N/2) d<-d+matrix(rnorm(Tmax*N,0,2),Tmax,N) d<-t(d) d<-cleandat(d,1:Tmax,1)$cdat coords<-data.frame(X=c(rep(1,10),rep(2,10)),Y=rep(c(1:5,7:11),times=2)) cl1<-clust(dat=d,times=1:Tmax,coords=coords,method="ReXWT",tsrange=c(4,6)) Test_plotmap_1<-function(){plotmap(cl1)} expect_doppelganger(title="Test-plotmap-1",fig=Test_plotmap_1) Test_plotmap_2<-function(){plotmap(cl1, spltlvl=1)} expect_doppelganger(title="Test-plotmap-2",fig=Test_plotmap_2) Test_plotmap_3<-function(){plotmap(cl1, nodesize=c(1,2))} expect_doppelganger(title="Test-plotmap-3",fig=Test_plotmap_3) Test_plotmap_4<-function(){plotmap(cl1, nodesize=c(2,2))} expect_doppelganger(title="Test-plotmap-4",fig=Test_plotmap_4) })
context("Test for tdc output") test_that("Adjamatrices: centrality_evolution=FALSE when running tdc", { expect_is(tdc(As, "M", normalize = T, centrality_evolution = F), "numeric") expect_length(tdc(As, "M", normalize = T, centrality_evolution = F), numberNodes) expect_true(all(tdc(As, "M", normalize = T, centrality_evolution = F)<=1)) }) test_that("Adjamatrices: centrality_evolution=TRUE when running tdc", { expect_is(tdc(As, "M", normalize = T, centrality_evolution = T), "list") expect_length(tdc(As, "M", normalize = T, centrality_evolution = T), 2) expect_is(tdc(As, "M", normalize = T, centrality_evolution = T)[[2]], "matrix") }) test_that("Adjalists: centrality_evolution=FALSE when running tdc", { expect_is(tdc(Es, "L", normalize = T, centrality_evolution = F), "numeric") expect_length(tdc(Es, "L", normalize = T, centrality_evolution = F), numberNodes) expect_true(all(tdc(Es, "L", normalize = T, centrality_evolution = F)<=1)) }) test_that("Adjalists: centrality_evolution=TRUE when running tdc", { expect_is(tdc(Es, "L", normalize = T, centrality_evolution = T), "list") expect_length(tdc(Es, "L", normalize = T, centrality_evolution = T), 2) expect_is(tdc(Es, "L", normalize = T, centrality_evolution = T)[[2]], "matrix") }) test_that("Adjalists compared to Adjamatrices", { expect_equal(tdc(Es, "L", normalize = T, centrality_evolution = T), tdc(As, "M", normalize = T, centrality_evolution = T)) })
commarobust <- function(model, se_type = NULL, clusters = NULL, ci = TRUE, alpha = 0.05) { if (class(model)[1] != "lm") { stop("`model` must be an lm object") } coefs <- as.matrix(coef(model)) est_exists <- !is.na(coefs) covs_used <- which(est_exists) coefs <- coefs[covs_used, , drop = FALSE] Qr <- qr(model) p1 <- seq_len(model$rank) XtX_inv <- chol2inv(Qr$qr[p1, p1, drop = FALSE]) clustered <- !is.null(clusters) se_type <- check_se_type(se_type = se_type, clustered = clustered) X <- model.matrix.default(model) contrasts <- attr(X, "contrasts") N <- nrow(X) data <- list( y = as.matrix(model.response(model$model)), X = X, weights = weights(model) ) weighted <- is.numeric(data[["weights"]]) if (clustered) { if (is.matrix(clusters) && ncol(clusters) > 1) { stop("`clusters` must be a single vector or column denoting the clusters.") } if (length(clusters) != N) { stop("`clusters` must be the same length as the model data.") } data[["cluster"]] <- as.factor(clusters) } data <- prep_data( data = data, se_type = se_type, clustered = clustered, weighted = weighted, fes = FALSE, iv_stage = list(0) ) ei <- as.matrix(resid(model)) if (clustered) { ei <- ei[data[["cl_ord"]], , drop = FALSE] } if (any(!est_exists)) { data <- drop_collinear(data, covs_used, weighted, FALSE) } if (weighted) { ei <- data[["weights"]] * ei XtX_inv <- data[["weight_mean"]] * XtX_inv if (se_type == "CR2") { eiunweighted <- as.matrix(data[["yunweighted"]] - data[["Xunweighted"]] %*% coefs) data[["X"]] <- data[["weights"]] * data[["X"]] } } vcov_fit <- lm_variance( X = data[["X"]], Xunweighted = data[["Xunweighted"]], XtX_inv = XtX_inv, ei = if (se_type == "CR2" && weighted) eiunweighted else ei, weight_mean = data[["weight_mean"]], cluster = data[["cluster"]], J = data[["J"]], ci = ci, se_type = se_type, which_covs = rep(TRUE, model$rank), fe_rank = 0 ) return_list <- list( coefficients = as.matrix(coef(model)), std.error = NA, df = NA, term = names(coef(model)), outcome = as.character(rlang::f_lhs(formula(model))), alpha = alpha, se_type = se_type, df.residual = df.residual(model), weighted = weighted, fes = FALSE, clustered = clustered, nobs = nobs(model), rank = model$rank, k = ncol(X), fitted.values = fitted.values(model), contrasts = contrasts, terms = model$terms, xlevels = model$xlevels, weights = weights(model) ) return_list[["std.error"]][est_exists] <- sqrt(diag(vcov_fit$Vcov_hat)) return_list[["df"]][est_exists] <- ifelse(vcov_fit$dof == -99, NA, vcov_fit$dof) if (clustered) { return_list[["nclusters"]] <- data[["J"]] } return_list[["res_var"]] <- get_resvar( data = data, ei = ei, df.residual = return_list[["df.residual"]], vcov_fit = vcov_fit, weighted = weighted ) return_list <- add_cis_pvals(return_list, alpha, ci && se_type != "none") tss_r2s <- get_r2s( y = data[["y"]], return_list = return_list, yunweighted = data[["yunweighted"]], has_int = attr(model$terms, "intercept"), weights = data[["weights"]], weight_mean = data[["weight_mean"]] ) if (clustered) { dendf <- data[["J"]] - 1 } else { dendf <- return_list[["df.residual"]] } f <- get_fstat( tss_r2s = tss_r2s, return_list = return_list, iv_ei = NULL, nomdf = model$rank - attr(model$terms, "intercept"), dendf = dendf, vcov_fit = vcov_fit, has_int = attr(model$terms, "intercept"), iv_stage = list(0) ) return_list <- c(return_list, tss_r2s) return_list[["fstatistic"]] <- f return_list[["vcov"]] <- vcov_fit$Vcov_hat dimnames(return_list[["vcov"]]) <- list( return_list$term[est_exists], return_list$term[est_exists] ) return_list <- lm_return(return_list, model_data = NULL, formula = NULL) attr(return_list, "class") <- "lm_robust" return(return_list) } starprep <- function(..., stat = c("std.error", "statistic", "p.value", "ci", "df"), se_type = NULL, clusters = NULL, alpha = 0.05) { if (inherits(..1, "list")) { if (...length() > 1) { stop("`...` must be one list of model fits or several comma separated model fits") } fits <- ..1 } else { fits <- list(...) } is_list_of_lm <- vapply(fits, inherits, what = c("lm","lm_robust"), TRUE) if (any(!is_list_of_lm)) { stop("`...` must contain only `lm` or `lm_robust` objects.") } fitlist <- lapply( fits, function(x) { if (inherits(x, "lm")) commarobust(x, se_type = se_type, clusters = clusters, alpha = alpha) else x } ) stat <- match.arg(stat) if (stat == "ci") { out <- lapply(fitlist, function(x) cbind(x[["conf.low"]], x[["conf.high"]])) } else { out <- lapply(fitlist, `[[`, stat) } return(out) }
library(testthat) escapeString <- function(s) { t <- gsub("(\\\\)", "\\\\\\\\", s) t <- gsub("(\n)", "\\\\n", t) t <- gsub("(\r)", "\\\\r", t) t <- gsub("(\")", "\\\\\"", t) return(t) } prepStr <- function(s) { t <- escapeString(s) u <- eval(parse(text=paste0("\"", t, "\""))) if(s!=u) stop("Unable to escape string!") t <- paste0("\thtml <- \"", t, "\"") utils::writeClipboard(t) return(invisible()) } evaluationMode <- "sequential" processingLibrary <- "dplyr" description <- "test: sequential dplyr" countFunction <- "n()" isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) testScenarios <- function(description="test", releaseEvaluationMode="batch", releaseProcessingLibrary="dplyr", runAllForReleaseVersion=FALSE) { isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) if(isDevelopmentVersion||runAllForReleaseVersion) { evaluationModes <- c("sequential", "batch") processingLibraries <- c("dplyr", "data.table") } else { evaluationModes <- releaseEvaluationMode processingLibraries <- releaseProcessingLibrary } testCount <- length(evaluationModes)*length(processingLibraries) c1 <- character(testCount) c2 <- character(testCount) c3 <- character(testCount) c4 <- character(testCount) testCount <- 0 for(evaluationMode in evaluationModes) for(processingLibrary in processingLibraries) { testCount <- testCount + 1 c1[testCount] <- evaluationMode c2[testCount] <- processingLibrary c3[testCount] <- paste0(description, ": ", evaluationMode, " ", processingLibrary) c4[testCount] <- ifelse(processingLibrary=="data.table", ".N", "n()") } df <- data.frame(evaluationMode=c1, processingLibrary=c2, description=c3, countFunction=c4, stringsAsFactors=FALSE) return(df) } context("BASIC LAYOUT TESTS") scenarios <- testScenarios("basic layout tests: empty pivot") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$evaluatePivot() str <- " " html <- "<table class=\"Table\">\n <tr>\n <td class=\"Cell\" style=\"text-align: center; padding: 6px\">(no data)</td>\n </tr>\n</table>" expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: empty pivot plus data") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$evaluatePivot() str <- " " html <- "<table class=\"Table\">\n <tr>\n <td class=\"Cell\" style=\"text-align: center; padding: 6px\">(no data)</td>\n </tr>\n</table>" expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: just a total") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() str <- " TotalTrains \n 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"0\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 83710) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: two measures") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$evaluatePivot() str <- " TotalTrains MaxSchedSpeed \n 83710 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"0\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 83835) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows only") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE)) pt$addData(bhmtrains) pt$addRowDataGroups("TOC") pt$evaluatePivot() str <- "Arriva Trains Wales \nCrossCountry \nLondon Midland \nVirgin Trains \nTotal " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <th class=\"ColumnHeader\">&nbsp;</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows plus total") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() str <- " TotalTrains \nArriva Trains Wales 3909 \nCrossCountry 22928 \nLondon Midland 48279 \nVirgin Trains 8594 \nTotal 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167420) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows plus two measures") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$evaluatePivot() str <- " TotalTrains MaxSchedSpeed \nArriva Trains Wales 3909 90 \nCrossCountry 22928 125 \nLondon Midland 48279 110 \nVirgin Trains 8594 125 \nTotal 83710 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">90</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">110</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167995) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: columns only") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TOC") pt$evaluatePivot() str <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total \n " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"0\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"1\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"1\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: columns plus total") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() str <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total \n 3909 22928 48279 8594 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"0\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"1\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"1\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167420) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: columns plus two totals") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$evaluatePivot() str <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total \n TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed \n 3909 90 22928 125 48279 110 8594 125 83710 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"0\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"2\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"2\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167995) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows and columns only") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$evaluatePivot() str <- " Express Passenger Ordinary Passenger Total \nArriva Trains Wales \nCrossCountry \nLondon Midland \nVirgin Trains \nTotal " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows, columns and calculation") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() str <- " Express Passenger Ordinary Passenger Total \nArriva Trains Wales 3079 830 3909 \nCrossCountry 22865 63 22928 \nLondon Midland 14487 33792 48279 \nVirgin Trains 8594 8594 \nTotal 49025 34685 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 334840) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows, columns and two calculations") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$evaluatePivot() str <- " Express Passenger Ordinary Passenger Total \n TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed TotalTrains MaxSchedSpeed \nArriva Trains Wales 3079 90 830 90 3909 90 \nCrossCountry 22865 125 63 100 22928 125 \nLondon Midland 14487 110 33792 100 48279 110 \nVirgin Trains 8594 125 8594 125 \nTotal 49025 125 34685 100 83710 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n <th class=\"ColumnHeader\" colspan=\"1\">TotalTrains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">MaxSchedSpeed</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">90</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">110</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 336380) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: columns plus total on row") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$addRowCalculationGroups() pt$evaluatePivot() str <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total \nTotalTrains 3909 22928 48279 8594 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"1\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"1\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167420) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: columns plus two totals on rows") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$addRowCalculationGroups() pt$evaluatePivot() str <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total \nTotalTrains 3909 22928 48279 8594 83710 \nMaxSchedSpeed 90 125 110 125 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"1\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"1\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">83710</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 167995) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows, columns and calculation on rows") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$addRowCalculationGroups() pt$evaluatePivot() str <- " Express Passenger Ordinary Passenger Total \nArriva Trains Wales 3079 830 3909 \nCrossCountry 22865 63 22928 \nLondon Midland 14487 33792 48279 \nVirgin Trains 8594 8594 \nTotal 49025 34685 83710 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 334840) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: rows, columns and two calculations on rows") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaxSchedSpeed", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$addRowCalculationGroups() pt$evaluatePivot() str <- " Express Passenger Ordinary Passenger Total \nArriva Trains Wales TotalTrains 3079 830 3909 \n MaxSchedSpeed 90 90 90 \nCrossCountry TotalTrains 22865 63 22928 \n MaxSchedSpeed 125 100 125 \nLondon Midland TotalTrains 14487 33792 48279 \n MaxSchedSpeed 110 100 110 \nVirgin Trains TotalTrains 8594 8594 \n MaxSchedSpeed 125 125 \nTotal TotalTrains 49025 34685 83710 \n MaxSchedSpeed 125 100 125 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"2\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">Arriva Trains Wales</th>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">CrossCountry</th>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">London Midland</th>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">110</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">Virgin Trains</th>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">Total</th>\n <th class=\"RowHeader\" rowspan=\"1\">TotalTrains</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">MaxSchedSpeed</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 336380) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("basic layout tests: more than 10 calculation columns") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) d <- data.frame(a=c("a","b","c"),b=c("a","b","c"), X1Qty=c(1, 2, 3), X2Qty=c(1, 2, 3), X3Qty=c(1, 2, 3), X4Qty=c(1, 2, 3), X5Qty=c(1, 2, 3), X6Qty=c(1, 2, 3), X7Qty=c(1, 2, 3), X8Qty=c(1, 2, 3), X9Qty=c(1, 2, 3), X10Qty=c(1, 2, 3), X11Qty=c(1, 2, 3), X12Qty=c(1, 2, 3)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode) pt$addData(d) pt$addRowDataGroups("a") pt$addColumnDataGroups("b") pt$defineCalculation(calculationName="Jan Sales Qty", summariseExpression="sum(X1Qty)") pt$defineCalculation(calculationName="Feb Sales Qty", summariseExpression="sum(X2Qty)") pt$defineCalculation(calculationName="Mar Sales Qty", summariseExpression="sum(X3Qty)") pt$defineCalculation(calculationName="Apr Sales Qty", summariseExpression="sum(X4Qty)") pt$defineCalculation(calculationName="May Sales Qty", summariseExpression="sum(X5Qty)") pt$defineCalculation(calculationName="Jun Sales Qty", summariseExpression="sum(X6Qty)") pt$defineCalculation(calculationName="Jul Sales Qty", summariseExpression="sum(X7Qty)") pt$defineCalculation(calculationName="Aug Sales Qty", summariseExpression="sum(X8Qty)") pt$defineCalculation(calculationName="Sep Sales Qty", summariseExpression="sum(X9Qty)") pt$defineCalculation(calculationName="Oct Sales Qty", summariseExpression="sum(X10Qty)") pt$defineCalculation(calculationName="Nov Sales Qty", summariseExpression="sum(X11Qty)") pt$defineCalculation(calculationName="Dec Sales Qty", summariseExpression="sum(X12Qty)") pt$evaluatePivot() str <- " a b c Total \n Jan Sales Qty Feb Sales Qty Mar Sales Qty Apr Sales Qty May Sales Qty Jun Sales Qty Jul Sales Qty Aug Sales Qty Sep Sales Qty Oct Sales Qty Nov Sales Qty Dec Sales Qty Jan Sales Qty Feb Sales Qty Mar Sales Qty Apr Sales Qty May Sales Qty Jun Sales Qty Jul Sales Qty Aug Sales Qty Sep Sales Qty Oct Sales Qty Nov Sales Qty Dec Sales Qty Jan Sales Qty Feb Sales Qty Mar Sales Qty Apr Sales Qty May Sales Qty Jun Sales Qty Jul Sales Qty Aug Sales Qty Sep Sales Qty Oct Sales Qty Nov Sales Qty Dec Sales Qty Jan Sales Qty Feb Sales Qty Mar Sales Qty Apr Sales Qty May Sales Qty Jun Sales Qty Jul Sales Qty Aug Sales Qty Sep Sales Qty Oct Sales Qty Nov Sales Qty Dec Sales Qty \na 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \nb 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 \nc 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 \nTotal 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 6 6 6 6 6 6 6 6 6 6 6 6 " html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"12\">a</th>\n <th class=\"ColumnHeader\" colspan=\"12\">b</th>\n <th class=\"ColumnHeader\" colspan=\"12\">c</th>\n <th class=\"ColumnHeader\" colspan=\"12\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\">Jan Sales Qty</th>\n <th class=\"ColumnHeader\">Feb Sales Qty</th>\n <th class=\"ColumnHeader\">Mar Sales Qty</th>\n <th class=\"ColumnHeader\">Apr Sales Qty</th>\n <th class=\"ColumnHeader\">May Sales Qty</th>\n <th class=\"ColumnHeader\">Jun Sales Qty</th>\n <th class=\"ColumnHeader\">Jul Sales Qty</th>\n <th class=\"ColumnHeader\">Aug Sales Qty</th>\n <th class=\"ColumnHeader\">Sep Sales Qty</th>\n <th class=\"ColumnHeader\">Oct Sales Qty</th>\n <th class=\"ColumnHeader\">Nov Sales Qty</th>\n <th class=\"ColumnHeader\">Dec Sales Qty</th>\n <th class=\"ColumnHeader\">Jan Sales Qty</th>\n <th class=\"ColumnHeader\">Feb Sales Qty</th>\n <th class=\"ColumnHeader\">Mar Sales Qty</th>\n <th class=\"ColumnHeader\">Apr Sales Qty</th>\n <th class=\"ColumnHeader\">May Sales Qty</th>\n <th class=\"ColumnHeader\">Jun Sales Qty</th>\n <th class=\"ColumnHeader\">Jul Sales Qty</th>\n <th class=\"ColumnHeader\">Aug Sales Qty</th>\n <th class=\"ColumnHeader\">Sep Sales Qty</th>\n <th class=\"ColumnHeader\">Oct Sales Qty</th>\n <th class=\"ColumnHeader\">Nov Sales Qty</th>\n <th class=\"ColumnHeader\">Dec Sales Qty</th>\n <th class=\"ColumnHeader\">Jan Sales Qty</th>\n <th class=\"ColumnHeader\">Feb Sales Qty</th>\n <th class=\"ColumnHeader\">Mar Sales Qty</th>\n <th class=\"ColumnHeader\">Apr Sales Qty</th>\n <th class=\"ColumnHeader\">May Sales Qty</th>\n <th class=\"ColumnHeader\">Jun Sales Qty</th>\n <th class=\"ColumnHeader\">Jul Sales Qty</th>\n <th class=\"ColumnHeader\">Aug Sales Qty</th>\n <th class=\"ColumnHeader\">Sep Sales Qty</th>\n <th class=\"ColumnHeader\">Oct Sales Qty</th>\n <th class=\"ColumnHeader\">Nov Sales Qty</th>\n <th class=\"ColumnHeader\">Dec Sales Qty</th>\n <th class=\"ColumnHeader\">Jan Sales Qty</th>\n <th class=\"ColumnHeader\">Feb Sales Qty</th>\n <th class=\"ColumnHeader\">Mar Sales Qty</th>\n <th class=\"ColumnHeader\">Apr Sales Qty</th>\n <th class=\"ColumnHeader\">May Sales Qty</th>\n <th class=\"ColumnHeader\">Jun Sales Qty</th>\n <th class=\"ColumnHeader\">Jul Sales Qty</th>\n <th class=\"ColumnHeader\">Aug Sales Qty</th>\n <th class=\"ColumnHeader\">Sep Sales Qty</th>\n <th class=\"ColumnHeader\">Oct Sales Qty</th>\n <th class=\"ColumnHeader\">Nov Sales Qty</th>\n <th class=\"ColumnHeader\">Dec Sales Qty</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">a</th>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">b</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">c</th>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">1</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">2</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">3</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n <td class=\"Total\">6</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 288) expect_identical(pt$print(asCharacter=TRUE), str) expect_identical(as.character(pt$getHtml()), html) }) }
library("matrixStats") rowMedians_R <- function(x, na.rm = FALSE, ..., useNames = NA) { res <- apply(x, MARGIN = 1L, FUN = median, na.rm = na.rm) if (is.na(useNames) || !useNames) names(res) <- NULL res } colMedians_R <- function(x, na.rm = FALSE, ..., useNames = NA) { res <- apply(x, MARGIN = 2L, FUN = median, na.rm = na.rm) if (is.na(useNames) || !useNames) names(res) <- NULL res } source("utils/validateIndicesFramework.R") x <- matrix(runif(6 * 6, min = -3, max = 3), nrow = 6, ncol = 6) storage.mode(x) <- "integer" dimnames <- list(letters[1:6], LETTERS[1:6]) for (setDimnames in c(TRUE, FALSE)) { if (setDimnames) dimnames(x) <- dimnames else dimnames(x) <- NULL for (rows in index_cases) { for (cols in index_cases) { for (na.rm in c(TRUE, FALSE)) { for (useNames in c(NA, TRUE, FALSE)) { validateIndicesTestMatrix(x, rows, cols, ftest = rowMedians, fsure = rowMedians_R, na.rm = na.rm, useNames = useNames) validateIndicesTestMatrix(x, rows, cols, fcoltest = colMedians, fsure = rowMedians_R, na.rm = na.rm, useNames = useNames) } } } } }
context("or_glm") library("mgcv") library("MASS") test_that("correct level count of indicator variable for glm", { data("data_glm") fit_glm <- glm(admit ~ rank, data = data_glm, family = "binomial") out <- or_glm(data = data_glm, model = fit_glm) expect_length(out$predictor, length(levels(data_glm$rank)) - 1) }) test_that("or_glm works with glmmPQL", { data(bacteria) fit_glmmpql <- glmmPQL(y ~ trt + week, random = ~ 1 | ID, family = binomial, data = bacteria, verbose = FALSE ) out <- or_glm(data = bacteria, model = fit_glmmpql, incr = list(week = 5)) expect_length(out, 5) })
getSeries <- function(series, start = NULL, end = format(Sys.Date(), "%Y-%m"), return.class = "data.frame", verbose = TRUE, dest.dir = NULL) { on.exit(return(invisible(NULL))) real.time <- grepl("^BBKRT", series) if (real.time) { site <- paste0("https://www.bundesbank.de/statistic-rmi/", "StatisticDownload?tsId=", series, "&rtd_csvFormat=en", "&rtd_fileFormat=csv", "&mode=rtd") } else { if (!is.null(start)) { if (nchar(as.character(start)) == 4L) start <- paste0(as.character(start), "-01") if (nchar(start) != 7L) { warning("'start' not in format YYYY-MM") tmp <- as.Date(as.character(start)) if (!is.na(tmp)) start <- strftime(tmp, "%Y-%m") else stop("'start' not in required format") } } if (nchar(end) != 7L) { if (nchar(as.character(end)) == 4L) end <- paste0(as.character(end), "-12") warning("'end' not in format YYYY-MM") tmp <- as.Date(as.character(end)) if (!is.na(tmp)) end <- strftime(tmp, "%Y-%m") else stop("'end' not in required format") } sstart <- ifelse(is.null(start), "", paste("&its_from=", start, sep = "")) sto <- paste("&its_to=", end, sep = "") site <- paste("http://www.bundesbank.de/cae/servlet/CsvDownload?", "tsId=", series, "&mode=its&its_csvFormat=en", "&its_currency=default&its_dateFormat=dateOfDay&", sstart, "&", sto, sep = "") } if (!is.null(dest.dir)) { filename <- paste0(format(Sys.Date(), "%Y%m%d"), "__", series, "__", start, "__", end, ".csv") filename <- file.path(dest.dir, filename) if (!file.exists(filename)) { if (verbose) message("Downloading data from Bundesbank ... ", appendLF = FALSE) download.file(site, filename, quiet = TRUE) } else if (verbose) message("Using cache ... ", appendLF = FALSE) dats <- try(readLines(filename), silent = TRUE) em <- geterrmessage() } else { if (verbose) message("Downloading data from Bundesbank ... ", appendLF = FALSE) con <- url(site) dats <- try(readLines(con), silent = TRUE) close(con) em <- geterrmessage() } if (inherits(dats, "try-error")) { if (verbose) { message("failed") message(em) } return(invisible(NULL)) } else { if (verbose) message("done") } if (real.time) { txt.head <- dats[1:5] txt.csv <- dats[-c(1:5)] tb <- read.table(text = txt.csv, header = FALSE, sep = ",", stringsAsFactors = FALSE) row.names(tb) <- tb[[1L]] tb <- tb[, -1L] h.split <- strsplit(txt.head, " *, *") colnames(tb) <- h.split[[1]][-1L] attr(tb, "date") <- as.Date(h.split[[1]][-1L]) attr(tb, "unit") <- h.split[[2]][-1L] attr(tb, "unit multiplier") <- h.split[[3]][-1L] attr(tb, "Baseyear") <- h.split[[4]][-1L] attr(tb, "Record meth") <- h.split[[5]][-1L] result <- tb } else { dats <- read.csv(text = dats, stringsAsFactors = FALSE, as.is = TRUE) if (dats[NROW(dats), 1L] == "") { doc <- dats[NROW(dats), 2L] dats <- dats[-NROW(dats), ] } else doc <- NULL doc0 <- dats[2:4, ] doc0 <- paste(doc0[, 1L], doc0[, 2L], sep = ": ") doc0 <- c(dats[1L, 2L], doc0) doc <- c(doc0, doc) dats <- dats[-(1:4), ] dates <- as.Date(dats[, 1L]) values <- dats[, 2L] NAs <- is.na(dates) dates <- dates[!NAs] values <- values[!NAs] missing <- values == "." dates <- dates[!missing] values <- as.numeric(values[!missing]) if (!is.null(return.class)) { if (return.class == "zoo") if (requireNamespace("zoo")) result <- zoo::zoo(values, dates) else stop("package ", sQuote("zoo"), " not available") else if (return.class == "data.frame") result <- data.frame(dates = dates, values = values) else if (return.class == "list") result <- list(dates = dates, values = values) } else result <- list(dates = dates, values = values) attr(result, "info") <- doc } on.exit() result }
MeasureSurvSchmid = R6::R6Class("MeasureSurvSchmid", inherit = MeasureSurv, public = list( initialize = function() { ps = ps( integrated = p_lgl(default = TRUE), times = p_uty(), t_max = p_dbl(0), p_max = p_dbl(0, 1), method = p_int(1L, 2L, default = 2L), se = p_lgl(default = FALSE), proper = p_lgl(default = FALSE), eps = p_dbl(0, 1, default = 1e-3) ) ps$values = list( integrated = TRUE, method = 2L, se = FALSE, proper = FALSE, eps = 1e-3 ) super$initialize( param_set = ps, id = "surv.schmid", range = c(0, Inf), minimize = TRUE, packages = "distr6", predict_type = "distr", man = "mlr3proba::mlr_measures_surv.schmid", ) } ), private = list( .score = function(prediction, task, train_set, ...) { ps = self$param_set$values nok = sum(!is.null(ps$times), !is.null(ps$t_max), !is.null(ps$p_max)) > 1 if (nok) { stop("Only one of `times`, `t_max`, and `p_max` should be provided") } if (!ps$integrated) { msg = "If `integrated=FALSE` then `times` should be a scalar numeric." assert_numeric(ps$times, len = 1, .var.name = msg) } else { if (!is.null(ps$times) && length(ps$times) == 1) { ps$integrated = FALSE } } x = as.integer(!is.null(task)) + as.integer(!is.null(train_set)) if (x == 1) { stop("Either 'task' and 'train_set' should be passed to measure or neither.") } else if (x) { train = task$truth(train_set) } else { train = NULL } score = weighted_survival_score("schmid", truth = prediction$truth, distribution = prediction$distr, times = ps$times, t_max = ps$t_max, p_max = ps$p_max, proper = ps$proper, train = train, eps = ps$eps) if (ps$se) { integrated_se(score, ps$integrated) } else { integrated_score(score, ps$integrated, ps$method) } } ) )
wfunk <- function(beta = NULL, lambda, p, X = NULL, Y, offset = rep(0, length(Y)), ord = 2, pfixed = FALSE){ if (ord < 0) return(NULL) nn <- NROW(Y) if (NCOL(Y) == 2) Y <- cbind(rep(0, nn), Y) if (is.null(X)){ if (pfixed){ bdim <- 1 b <- -log(lambda) }else{ bdim <- 2 b <- c(-log(lambda), log(p)) } mb <- 0 fit <- .Fortran("wfuncnull", as.integer(ord), as.integer(pfixed), as.double(p), as.integer(bdim), as.double(b), as.integer(nn), as.double(Y[, 1]), as.double(Y[, 2]), as.integer(Y[, 3]), f = double(1), fp = double(bdim), fpp = double(bdim * bdim), ok = integer(1), PACKAGE = "eha" ) }else{ mb <- NCOL(X) if (length(beta) != mb) stop("beta mis-specified!") if (pfixed){ bdim <- mb + 1 b <- c(beta, -log(lambda)) }else{ bdim <- mb + 2 b <- c(beta, -log(lambda), log(p)) } cat("wfunc\n") fit <- .Fortran("wfunc", as.integer(ord), as.integer(pfixed), as.double(p), as.integer(bdim), as.integer(mb), as.double(b), as.integer(nn), as.double(t(X)), as.double(Y[, 1]), as.double(Y[, 2]), as.integer(Y[, 3]), as.double(offset), f = double(1), fp = double(bdim), fpp = double(bdim * bdim), ok = integer(1), PACKAGE = "eha" ) } ret <- list(f = -fit$f) if (ord >= 1){ xx <- rep(1, bdim) xx[mb + 1] <- -1 ret$fp <- -xx * fit$fp if (ord >= 2){ xx <- diag(xx) ret$fpp <- xx %*% matrix(fit$fpp, ncol = bdim) %*% t(xx) } } ret }
ghap.blockgen<-function( phase, windowsize=10, slide=5, unit="marker", nsnp=2 ){ if(class(phase) != "GHap.phase"){ stop("Argument phase must be a GHap.phase object.") } if(unit %in% c("marker","kbp","ibd") == FALSE){ stop("Unit must be specified as 'marker' or 'kbp'") } BLOCK <- rep(NA,times=phase$nmarkers.in) CHR <- rep(NA,times=phase$nmarkers.in) BP1 <- rep(NA,times=phase$nmarkers.in) BP2 <- rep(NA,times=phase$nmarkers.in) SIZE <- rep(NA,times=phase$nmarkers.in) NSNP <- rep(NA,times=phase$nmarkers.in) if(unit == "kbp"){ windowsize <- windowsize*1e+3 slide <- slide*1e+3 offset <- 0 for(k in unique(phase$chr)){ cmkr <- which(phase$marker.in & phase$chr == k) nmkr <- length(cmkr) bp <- phase$bp[cmkr] minbp <- bp[1] maxbp <- bp[nmkr] id1<-seq(1,maxbp,by=slide) id2<-id1+(windowsize-1) id1<-id1[id2 <= maxbp] id2<-id2[id2 <= maxbp] for(i in 1:length(id1)){ slice <- cmkr[which(bp >= id1[i] & bp <= id2[i])] CHR[i+offset] <- phase$chr[slice[1]] BP1[i+offset] <- id1[i] BP2[i+offset] <- id2[i] NSNP[i+offset] <- length(slice) BLOCK[i+offset] <- paste("CHR",CHR[i+offset],"_B",i,sep="") } offset <- offset + length(id1) } }else if(unit == "marker"){ offset <- 0 for(k in unique(phase$chr)){ cmkr <- which(phase$marker.in & phase$chr == k) nmkr <- length(cmkr) id1<-seq(1,nmkr,by=slide) id2<-id1+(windowsize-1) id1<-id1[id2 <= nmkr] id2<-id2[id2 <= nmkr] for(i in 1:length(id1)){ slice <- cmkr[id1[i]:id2[i]] CHR[i+offset] <- phase$chr[slice[1]] BP1[i+offset] <- phase$bp[slice[1]] BP2[i+offset] <- phase$bp[slice[length(slice)]] NSNP[i+offset] <- length(slice) BLOCK[i+offset] <- paste("CHR",CHR[i+offset],"_B",i,sep="") } offset <- offset + length(id1) } } results <- data.frame(BLOCK,CHR,BP1,BP2,NSNP,stringsAsFactors = FALSE) results <- unique(results) results$SIZE <- 1 + results$BP2 - results$BP1 results$SIZE[results$NSNP == 1] <- 1 results <- results[order(nchar(results$CHR),results$CHR,results$BP1,results$BP2),] results <- results[results$NSNP >= nsnp,] if(nrow(results) == 0){ stop("No blocks could be generated with the specified options. Try setting the nsnp argument to a smaller value.") } results <- na.exclude(results) results <- results[,c("BLOCK","CHR","BP1","BP2","SIZE","NSNP")] return(results) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(ggparliament) library(dplyr) library(ggplot2) require(tidyr) require(magrittr) require(purrr) source("../R/parliament_data.R") source("../R/geom_parliament_seats.R") source("../R/geom_highlight_government.R") source("../R/helper_funcs.R") source("../R/draw_majoritythreshold.R") source("../R/draw_partylabels.R") source("../R/draw_majoritythreshold.R") source("../R/draw_totalseats.R") source("../R/theme_ggparliament.R") load("../R/sysdata.rda") usa <- election_data %>% filter(country == "USA" & house == "Representatives") %>% split(.$year) %>% map(~parliament_data(election_data = ., party_seats = .$seats, parl_rows = 8, type = "semicircle")) %>% bind_rows() us <- ggplot(usa, aes(x, y, colour = party_short)) + geom_parliament_seats() + geom_highlight_government(government == 1) + labs(colour = NULL, title = "American Congress", subtitle = "The party that has control of US Congress is encircled in black.") + theme_ggparliament() + scale_colour_manual(values = usa$colour, limits = usa$party_short) + theme(legend.position = 'bottom') + facet_grid(~year, scales = 'free') us australia <- election_data %>% filter(country == "Australia" & year == "2016") %>% split(.$house) %>% map(~parliament_data(election_data = ., party_seats = .$seats, parl_rows = 4, type = "horseshoe")) %>% bind_rows() au <- ggplot(australia, aes(x, y, colour=party_short, type = "horseshoe")) + geom_parliament_seats() + geom_highlight_government(government == 1) + labs(colour = NULL, title = "Australian Parliament", subtitle = "Government encircled in black.") + scale_colour_manual(values = australia$colour, limits = australia$party_short) + theme_ggparliament() + theme(legend.position = 'bottom') + facet_grid(~house, scales = 'free') au uk<- election_data %>% filter(country == "UK") %>% split(.$year) %>% map(~parliament_data(election_data = ., party_seats = .$seats, group = .$government, type = "opposing_benches")) %>% bind_rows() ggplot(data = uk, aes(x = x, y = y, color = party_long)) + geom_parliament_seats(size = 1.5) + coord_flip() + facet_wrap(~year, ncol = 2) + scale_color_manual(values = uk$colour, limits = uk$party_long) + theme_ggparliament()
getnorm <- function(x, y, type="pooled"){ type <- match.arg(type, c("pooled","naive")) if(type=="pooled"){getnorm.pool(x,y)}else{ getnorm.naive(x,y) } }
NULL michael <- function(...){ get_quote(character = "Michael", ...) } jim <- function(...){ get_quote(character = "Jim", ...) } dwight <- function(...){ get_quote(character = "Dwight", ...) } pam <- function(...){ get_quote(character = "Pam", ...) } andy <- function(...){ get_quote(character = "Andy", ...) } kevin <- function(...){ get_quote(character = "Kevin", ...) } angela <- function(...){ get_quote(character = "Angela", ...) } erin <- function(...){ get_quote(character = "Erin", ...) } oscar <- function(...){ get_quote(character = "Oscar", ...) } ryan <- function(...){ get_quote(character = "Ryan", ...) } darryl <- function(...){ get_quote(character = "Darryl", ...) } phyllis <- function(...){ get_quote(character = "Phyllis", ...) } toby <- function(...){ get_quote(character = "Toby", ...) } kelly <- function(...){ get_quote(character = "Kelly", ...) } stanley <- function(...){ get_quote(character = "Stanley", ...) } meredith <- function(...){ get_quote(character = "Meredith", ...) } creed <- function(...){ get_quote(character = "Creed", ...) }
lsEspaGetOrderImages<-function(username=NULL,password=NULL,c.handle=NULL,order.list=NULL,verbose=TRUE){ if(is.null(c.handle)){ if(is.null(username)|is.null(username)){ stop("c.handle or username and password are null.") }else{ stopifnot(class(username)=="character") stopifnot(class(password)=="character") c.handle<-lsEspaCreateConnection(username,password) } } if(is.null(order.list)) order.list<-lsEspaGetOrders(c.handle=c.handle) img.list<-list() for(ol in order.list){ r <- curl_fetch_memory(paste0(getRGISToolsOpt("LS.ESPA.API"),getRGISToolsOpt("LS.ESPA.API.v"),"/order/",ol), c.handle) json_data<-fromJSON(rawToChar(r$content)) if(json_data$note==getRGISToolsOpt("LS.ESPA.Request")){ all.response<-unlist(json_data,recursive=TRUE) img.list[[ol]]<-list(OrderedImages=unname(all.response[grepl("inputs",names(all.response))]), Status=json_data$status) }else{ if(verbose)message(paste0(ol," is not an RGISTools request, not adding for downloading...")) } } return(img.list) }
las <- random_10_points test_that("header bbox is updated", { Zm <- las[["Max Z"]] las@header@PHB[["Max Z"]] <- 5 las <- las_update(las) expect_equal(las[["Max Z"]], Zm) })
"wbcel235"
predictlink.Jointlcmm <- function(x,ndraws=2000,Yvalues,...) { if(missing(x)) stop("The model should be specified.") if(!(inherits(x,"Jointlcmm"))) stop("To use only with \"Jointlcmm\" objects") if(x$linktype==-1) stop("The model does not define any link function.") if(x$conv!=1 & ndraws!=0) stop("No confidence intervals can be produced since the program did not converge properly") if(x$conv %in% c(1,2,3)) { if(missing(Yvalues)) { new.transf <- FALSE Yvalues <- x$estimlink[,1] } else { new.transf <- TRUE Yvalues <- na.omit(Yvalues) if(any(Yvalues<x$estimlink[1,1]) | any(Yvalues>x$estimlink[nrow(x$estimlink),1])) stop("The values specified in \"Yvalues\" are not in the range of the outcome") Yvalues <- sort(Yvalues) } npm <- length(x$best) best <- x$best if(x$idiag==0 & x$N[5]>0) best[sum(x$N[1:4])+1:x$N[5]] <- x$cholesky if(x$idiag==1 & x$N[5]>0) best[sum(x$N[1:4])+1:x$N[5]] <- sqrt(best[sum(x$N[1:4])+1:x$N[5]]) if(x$linktype==0) ntrtot <- 2 if(x$linktype==1) ntrtot <- 4 if(x$linktype==2) ntrtot <- length(x$linknodes)+2 imoins <- sum(x$N[1:7]) zitr <- x$linknodes maxnbzitr <- ifelse(x$linktype==2,length(x$linknodes),2) epsY <- x$epsY minY <- x$estimlink[1,1] maxY <- x$estimlink[nrow(x$estimlink),1] ny <- 1 nsim <- length(Yvalues) if(x$linktype==3) { ide <- x$ide dimide <- length(ide) } else { ide <- rep(0,1) dimide <- 1 } ndraws <- as.integer(ndraws) posfix <- eval(x$call$posfix) if(ndraws>0) { Mat <- matrix(0,ncol=npm,nrow=npm) Mat[upper.tri(Mat,diag=TRUE)]<- x$V if(length(posfix)) { Mat2 <- Mat[-posfix,-posfix] Chol2 <- chol(Mat2) Chol <- matrix(0,npm,npm) Chol[setdiff(1:npm,posfix),setdiff(1:npm,posfix)] <- Chol2 Chol <- t(Chol) } else { Chol <- chol(Mat) Chol <- t(Chol) } } if(isTRUE(new.transf) & ndraws==0) { resFortran <- rep(0,nsim) out0 <- .Fortran(C_calculustransfo, as.double(best), as.integer(npm), as.integer(ny), as.integer(x$linktype), as.integer(ntrtot), as.integer(imoins), as.double(zitr), as.integer(maxnbzitr), as.double(Yvalues), as.integer(nsim), as.double(minY), as.double(maxY), as.double(epsY), as.integer(ide), as.integer(dimide), transfo=as.double(resFortran)) transfY <- out0$transfo } else { transfY <- x$estimlink[,2] } if(ndraws>0) { if(x$conv==1) { Hydraws <- NULL for (j in 1:ndraws) { bdraw <- rnorm(npm) bdraw <- best + Chol %*% bdraw resFortran <- rep(0,nsim) out <- .Fortran(C_calculustransfo, as.double(bdraw), as.integer(npm), as.integer(ny), as.integer(x$linktype), as.integer(ntrtot), as.integer(imoins), as.double(zitr), as.integer(maxnbzitr), as.double(Yvalues), as.integer(nsim), as.double(minY), as.double(maxY), as.double(epsY), as.integer(ide), as.integer(dimide), transfo=as.double(resFortran)) Hydraws <- cbind(Hydraws,out$transfo) } f <- function(x) { quantile(x[!is.na(x)],probs=c(0.5,0.025,0.975)) } Hydistr <- apply(Hydraws,1,FUN=f) borne_inf <- as.vector(Hydistr[2,]) borne_sup <- as.vector(Hydistr[3,]) mediane <- as.vector(Hydistr[1,]) res <- data.frame(Yvalues=Yvalues,transfY_50=mediane,transfY_2.5=borne_inf,transfY_97.5=borne_sup) } if(x$conv==2 | x$conv==3) { borne_inf <- rep(NA,length(Yvalues)) borne_sup <- rep(NA,length(Yvalues)) mediane <- rep(NA,length(Yvalues)) res <- data.frame(Yvalues=Yvalues,transfY_50=mediane,transfY_2.5=borne_inf,transfY_97.5=borne_sup) } } else { res <- data.frame(Yvalues=Yvalues,transY=transfY) } } else { cat("Output can not be produced since the program stopped abnormally.") res <- NA } res.list <- NULL res.list$pred <- res res.list$object <- x class(res.list) <- "predictlink" return(res.list) }
expected <- eval(parse(text="NULL")); test(id=0, code={ argv <- eval(parse(text="list(list(structure(list(srcfile = c(\"/home/lzhao/tmp/RtmpTzriDZ/R.INSTALL30d4108a07be/mgcv/R/gam.fit3.r\", \"/home/lzhao/tmp/RtmpTzriDZ/R.INSTALL30d4108a07be/mgcv/R/gam.fit3.r\"), frow = c(1287L, 1289L), lrow = c(1287L, 1289L)), .Names = c(\"srcfile\", \"frow\", \"lrow\"), row.names = 1:2, class = \"data.frame\"), structure(list(srcfile = \"/home/lzhao/tmp/RtmpTzriDZ/R.INSTALL30d4108a07be/mgcv/R/gam.fit3.r\", frow = 1289L, lrow = 1289L), .Names = c(\"srcfile\", \"frow\", \"lrow\"), row.names = c(NA, -1L), class = \"data.frame\")))")); do.call(`names`, argv); }, o=expected);