code
stringlengths
1
13.8M
chart.RiskReward <- function(object, ...){ UseMethod("chart.RiskReward") }
.discretize.qq.gam <- function(P, discrete, ngr, CI, showReps){ n <- length(P$Dq) rep <- ncol(P$dm) if(discrete && ngr >= n){ discrete <- FALSE } if( CI && is.null(P$conf) ){ message("CI==TRUE but intervals have not been already computed by qq.gamViz. Setting CI to FALSE.") CI <- FALSE } if( discrete ){ DqFull <- P$Dq tmp <- bin1D(x = P$Dq, y = P$D, ngr = ngr) P$D <- tmp$ym P$Dq <- tmp$xm if( showReps && !is.null(P$dm) ){ tmp <- lapply(1:ncol(P$dm), function(ii) bin1D(DqFull, P$dm[ , ii], ngr)) dmx <- do.call("c", lapply(tmp, function(inp) inp$xm)) dmy <- do.call("c", lapply(tmp, function(inp) inp$ym)) id <- lapply(1:rep, function(ii) rep(ii, length(tmp[[ii]]$xm))) id <- do.call("c", id) } if( CI && !is.null(P$conf) ){ P$conf <- rbind(approx(x=DqFull, y=P$conf[1, , drop=T], xout=P$Dq)$y, approx(x=DqFull, y=P$conf[2, , drop=T], xout=P$Dq)$y) } } else { if( showReps && !is.null(P$dm) ){ dmx <- rep(P$Dq, rep) dmy <- c( as.numeric(P$dm) ) id <- rep(1:rep, each=n) } } if( showReps && !is.null(P$dm) ){ P$dm <- data.frame("x"=dmx, "y"=dmy, "id"=id) } if( CI && !is.null(P$conf) ){ P$conf <- data.frame("x"= c(P$Dq, rev(P$Dq)), "y"= c(P$conf[1, , drop=T], rev(P$conf[2, , drop=T]))) } return( P ) }
.onLoad <- function(libname, pkgname){ options(rstudio.markdownToHTML = function(inputFile, outputFile){ if (readLines(inputFile)[1] == '---'){ slidify(inputFile, knit_deck = FALSE) } else { markdownToHTML(inputFile, outputFile) } }) }
makeStackedLearner = function(base.learners, super.learner = NULL, predict.type = NULL, method = "stack.nocv", use.feat = FALSE, resampling = NULL) { baseType = unique(extractSubList(base.learners, "type")) if (!is.null(resampling) & method != "stack.cv") { stop("No resampling needed for this method") } if (is.null(resampling)) { resampling = makeResampleDesc("CV", iters = 5L, stratify = ifelse(baseType == "classif", TRUE, FALSE)) } assertChoice(method, c("average", "stack.nocv", "stack.cv", "step.stack.nocv", "step.stack.cv")) assertClass(resampling, "ResampleDesc") pts = unique(extractSubList(base.learners, "predict.type")) if (length(pts) > 1L) { stop("Base learner must all have the same predict type!") } if (method == "average" & (!is.null(super.learner) | is.null(predict.type))) { stop("No super learner needed for this method or the 'predict.type' is not specified.") } if (method != "average" & is.null(super.learner)) { stop("You have to specify a super learner for this method.") } if (method != "average" & !is.null(predict.type)) { stop("Predict type has to be specified within the super learner.") } if (method == "average" & use.feat) { stop("The original features can not be used for this method") } if (!inherits(resampling, "CVDesc")) { stop("Currently only CV is allowed for resampling!") } lrn = makeBaseEnsemble( id = "stack", base.learners = base.learners, cl = "StackedLearner" ) if (!is.null(super.learner)) { super.learner = checkLearner(super.learner) lrn = setPredictType(lrn, predict.type = super.learner$predict.type) } else { lrn = setPredictType(lrn, predict.type = predict.type) } lrn$fix.factors.prediction = TRUE lrn$use.feat = use.feat lrn$method = method lrn$super.learner = super.learner lrn$resampling = resampling return(lrn) } trainLearner.StackedLearner = function(.learner, .task, .subset, ...) { bls = .learner$base.learners ids = names(bls) .task = subsetTask(.task, subset = .subset) probs = makeDataFrame(.task$task.desc$size, ncol = length(bls), col.types = "numeric", col.names = ids) switch(.learner$method, average = averageBaseLearners(.learner, .task, probs), stack.nocv = stackNoCV(.learner, .task, probs), stack.cv = stackCV(.learner, .task, probs), step.stack.nocv = stepStackNoCV(.learner, .task, probs), step.stack.cv = stepStackCV(.learner, .task, probs) ) } predictLearner.StackedLearner = function(.learner, .model, .newdata, ...) { use.feat = .model$learner$use.feat sm.pt = .model$learner$predict.type sm = .model$learner.model$super.model bms.pt = unique(extractSubList(.model$learner$base.learners, "predict.type")) levs = .model$task.desc$class.levels td = .model$task.desc type = ifelse(td$type == "regr", "regr", ifelse(length(td$class.levels) == 2L, "classif", "multiclassif")) probs = exportPredictions(model = .model, newdata = .newdata, full.matrix = ifelse(.learner$method == "average", TRUE, FALSE), method = .learner$method) if (.learner$method == "average") { if (bms.pt == "prob") { prob = Reduce("+", probs) / length(probs) if (sm.pt == "prob") { return(as.matrix(prob)) } else { return(factor(colnames(prob)[apply(as.matrix(prob), 1L, which.max)], td$class.levels)) } } else { probs = as.data.frame(probs) if (type == "classif" | type == "multiclassif") { if (sm.pt == "prob") { return(as.matrix(t(apply(probs, 1L, function(X) (table(factor(X, td$class.levels)) / length(X)))))) } else { return(factor(apply(probs, 1L, computeMode), td$class.levels)) } } if (type == "regr") { prob = Reduce("+", probs) / length(probs) return(prob) } } } else { probs = as.data.frame(probs) feat = .newdata[, !colnames(.newdata) %in% .model$task.desc$target, drop = FALSE] if (use.feat) { predData = cbind(probs, feat) } else { predData = probs } pred = predict(sm, newdata = predData)$data if (sm.pt == "prob") { predProb = as.matrix(subset(pred, select = -response)) colnames(predProb) = levs return(predProb) } else { return(pred$response) } } } setPredictType.StackedLearner = function(learner, predict.type) { lrn = setPredictType.Learner(learner, predict.type) lrn$predict.type = predict.type if ("super.learner" %in% names(lrn)) lrn$super.learner$predict.type = predict.type return(lrn) } exportPredictions = function(model, newdata, full.matrix = TRUE, method) { bms = model$learner.model$base.models probs = vector("list", length(bms)) if (grepl("step", method)) { for (i in seq_along(bms)) { pred = predict(bms[[i]], newdata = newdata) probs[[i]] = getResponse(pred, full.matrix = full.matrix) addCol = cbind(probs[[i]]) colnames(addCol) = bms[[i]]$learner$id newdata = cbind(newdata, addCol) } } else { for (i in seq_along(bms)) { pred = predict(bms[[i]], newdata = newdata) probs[[i]] = getResponse(pred, full.matrix = full.matrix) } } names(probs) = sapply(bms, function(X) X$learner$id) return(probs) } averageBaseLearners = function(learner, task, probs) { bls = learner$base.learners base.models = vector("list", length(bls)) for (i in seq_along(bls)) { bl = bls[[i]] model = train(bl, task) base.models[[i]] = model } list(base.models = base.models, super.model = NULL) } stackNoCV = function(learner, task, probs) { type = ifelse(task$task.desc$type == "regr", "regr", ifelse(length(task$task.desc$class.levels) == 2L, "classif", "multiclassif")) bls = learner$base.learners use.feat = learner$use.feat base.models = probs = vector("list", length(bls)) for (i in seq_along(bls)) { bl = bls[[i]] model = train(bl, task) base.models[[i]] = model pred = predict(model, task = task) probs[[i]] = getResponse(pred, full.matrix = FALSE) } names(probs) = names(bls) if (type == "regr" | type == "classif") { probs = as.data.frame(probs) } else { probs = as.data.frame(lapply(probs, function(X) X)) } probs[[task$task.desc$target]] = getTaskTargets(task) if (use.feat) { feat = getTaskData(task) feat = feat[, !colnames(feat) %in% task$task.desc$target, drop = FALSE] probs = cbind(probs, feat) super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } else { super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } super.model = train(learner$super.learner, super.task) list(base.models = base.models, super.model = super.model) } stackCV = function(learner, task, probs) { type = ifelse(task$task.desc$type == "regr", "regr", ifelse(length(task$task.desc$class.levels) == 2L, "classif", "multiclassif")) bls = learner$base.learners use.feat = learner$use.feat base.models = probs = vector("list", length(bls)) rin = makeResampleInstance(learner$resampling, task = task) for (i in seq_along(bls)) { bl = bls[[i]] r = resample(bl, task, rin, show.info = FALSE) probs[[i]] = getResponse(r$pred, full.matrix = FALSE) base.models[[i]] = train(bl, task) } names(probs) = names(bls) if (type == "regr" | type == "classif") { probs = as.data.frame(probs) } else { probs = as.data.frame(lapply(probs, function(X) X)) } tn = task$task.desc$target test.inds = unlist(rin$test.inds) probs[[tn]] = getTaskTargets(task)[test.inds] probs = probs[order(test.inds), , drop = FALSE] if (use.feat) { feat = getTaskData(task) feat = feat[, !colnames(feat) %in% tn, drop = FALSE] probs = cbind(probs, feat) super.task = makeSuperLearnerTask(learner, data = probs, target = tn) } else { super.task = makeSuperLearnerTask(learner, data = probs, target = tn) } super.model = train(learner$super.learner, super.task) list(base.models = base.models, super.model = super.model) } stepStackNoCV = function(learner, task, probs) { type = ifelse(task$task.desc$type == "regr", "regr", ifelse(length(task$task.desc$class.levels) == 2L, "classif", "multiclassif")) if (type == "multiclassif") stop("Currently, this method does not support multiclass tasks") bls = learner$base.learners use.feat = learner$use.feat base.models = probs = vector("list", length(bls)) for (i in seq_along(bls)) { bl = bls[[i]] model = train(bl, task) base.models[[i]] = model pred = predict(model, task = task) probs[[i]] = getResponse(pred, full.matrix = FALSE) if (is.null(ncol(probs[[i]]))) { addCol = cbind(probs[[i]]) colnames(addCol) = names(bls)[[i]] } else { addCol = probs[[i]] colnames(addCol) = paste(names(bls)[[i]], colnames(addCol), sep = ".") } task = addFeature(task, add = addCol) } names(probs) = names(bls) if (type == "regr" | type == "classif") { probs = as.data.frame(probs) } else { probs = as.data.frame(lapply(probs, function(X) X)) } probs[[task$task.desc$target]] = getTaskTargets(task) if (use.feat) { feat = getTaskData(task) super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } else { super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } super.model = train(learner$super.learner, super.task) list(base.models = base.models, super.model = super.model) } stepStackCV = function(learner, task, probs) { type = ifelse(task$task.desc$type == "regr", "regr", ifelse(length(task$task.desc$class.levels) == 2L, "classif", "multiclassif")) if (type == "multiclassif") stop("Currently, this method does not support multiclass tasks") bls = learner$base.learners use.feat = learner$use.feat base.models = probs = vector("list", length(bls)) rin = makeResampleInstance(learner$resampling, task = task) for (i in seq_along(bls)) { bl = bls[[i]] r = resample(bl, task, rin, show.info = FALSE) probs[[i]] = getResponse(r$pred, full.matrix = FALSE) base.models[[i]] = train(bl, task) if (is.null(ncol(probs[[i]]))) { addCol = cbind(probs[[i]][order(unlist(rin$test.inds))]) colnames(addCol) = names(bls)[[i]] } else { addCol = probs[[i]][order(unlist(rin$test.inds))] colnames(addCol) = paste(names(bls)[[i]], colnames(addCol), sep = ".") } task = addFeature(task, add = addCol) } names(probs) = names(bls) if (type == "regr" | type == "classif") { probs = as.data.frame(probs) } else { probs = as.data.frame(lapply(probs, function(X) X)) } tn = task$task.desc$target test.inds = unlist(rin$test.inds) probs[[tn]] = getTaskTargets(task)[test.inds] probs = probs[order(test.inds), , drop = FALSE] if (use.feat) { feat = getTaskData(task) super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } else { super.task = makeSuperLearnerTask(learner, data = probs, target = task$task.desc$target) } super.model = train(learner$super.learner, super.task) list(base.models = base.models, super.model = super.model) } addFeature = function(task, subset, features, add) { task = changeData(task, cbind(getTaskData(task, subset, features), add), getTaskCosts(task, subset)) if (!missing(subset)) { if (task$task.desc$has.blocking) { task$blocking = task$blocking[subset] } if (task$task.desc$has.weights) { task$weights = task$weights[subset] } } return(task) } getResponse = function(pred, full.matrix = TRUE) { if (pred$predict.type == "prob") { if (full.matrix) { predReturn = pred$data[, paste("prob", pred$task.desc$class.levels, sep = ".")] colnames(predReturn) = pred$task.desc$class.levels return(predReturn) } else { getPredictionProbabilities(pred) } } else { pred$data$response } } makeSuperLearnerTask = function(learner, data, target) { if (learner$super.learner$type == "classif") { makeClassifTask(data = data, target = target) } else { makeRegrTask(data = data, target = target) } }
frm_em_ic <- function(ll_new, N, ind0, model_results) { res <- list( deviance=-2*ll_new, N=N, loglike=ll_new ) NM <- attr( ind0, "NM") np_models <- rep(0,NM+1) for (mm in seq(1,NM+1)){ np_models[mm] <- length( model_results[[mm]]$coefficients) if ( ind0[[mm]]$model=="linreg"){ np_models[mm] <- np_models[mm] + 1 - ind0[[mm]]$is_sigma_fixed } } res$np <- sum( np_models ) res$np_models <- np_models return(res) }
"predictHPdRF" <- function (object, newdata, trace=FALSE) { if (!inherits(object, "randomForest")) stop("object not of class randomForest") if (object$type != "classification" && object$type != "regression") stop("only objects of type 'classification' and 'regression' are supported") if (is.null(object$forest)) stop("No forest component in the object") if (!is.darray(newdata) && !is.dframe(newdata)) stop("newdata should be of type darray or dframe") nparts <- npartitions(newdata) nSamples <- NROW(newdata) if(nSamples == 0) stop("No sample found in the newdata") if((object$type == "classification") || is.dframe(newdata)) { have.dframe = TRUE if(is.darray(newdata)) { output <- dframe(npartitions=npartitions(newdata), distribution_policy=newdata@distribution_policy) } else output <- clone(newdata,ncol = 1) } else { have.dframe = FALSE output <- clone(newdata,ncol = 1) } errorList <- dlist(nparts) foreach(i, 1:nparts, progress=trace, function(object=object, new=splits(newdata,i), out=splits(output,i), erri=splits(errorList,i), have.dframe=have.dframe, coln=colnames(newdata)){ library(randomForest) result <- tryCatch({ colnames(new) <- coln out <- predict(object,new) if(have.dframe) out <- data.frame(out) update(out) }, error = function(err) { erri <- list(err) update(erri) } ) }) anyError <- getpartition(errorList) if(length(anyError) > 0) stop(anyError[[1]]) output }
context("Primary Call") test_that("basic functionality", { expect_equal(mgsub("hey, ho", pattern = c("hey", "ho"), replacement = c("ho", "hey")), "ho, hey") expect_equal(mgsub("Production Workers, All Other", c("s$", "s([[:punct:] ])", ", ? All Other$"), c("", "\\1", "")), "Production Workers") }) test_that("non-named mgsub and named sub works", { expect_equal(mgsub("Dopazamine and dopaloramide are fake chemicals.", c("dopa", "fake"), c("meta", "real"), ignore.case = TRUE), "metazamine and metaloramide are real chemicals.") expect_equal(mgsub("Hey, ho", ignore.case = TRUE, c("hey"), c("tomorrow")), "tomorrow, ho") }) test_that("partially named mgsub inputs works", { expect_equal(mgsub("Dopazamine and dopaloramide are fake chemicals.", pattern = c("dopa", "fake"), c("meta", "real"), ignore.case = TRUE), "metazamine and metaloramide are real chemicals.") expect_equal(mgsub("Dopazamine and dopaloramide are fake chemicals.", c("meta", "real"), pattern = c("dopa", "fake"), ignore.case = TRUE), "metazamine and metaloramide are real chemicals.") }) test_that("multiple input strings are processed", { expect_equal(mgsub(c("string", "test"), c("t"), c("p")), c("spring", "pesp")) expect_equal(mgsub(c("Dopazamine is not the same as Dopachloride and is still fake.", "dopazamine is undergoing a review by the fake news arm of the Dopazamine government"), c("[Dd]opa(.*?mine)", "fake"), c("Meta\\1", "real")), c("Metazamine is not the same as Dopachloride and is still real.", "Metazamine is undergoing a review by the real news arm of the Metazamine government")) }) test_that("NAs are correctly handled", { expect_equal(mgsub(c("string", NA, "test"), c("t"), c("p")), c("spring", NA, "pesp")) }) test_that("recylce has to be a boolean", { expect_error(mgsub("hey, ho", c("hey"), c("ho", "hey"), recycle = "yes")) expect_error(mgsub("hey, ho", c("hey"), c("ho", "hey"), recycle = 1)) }) test_that("non-recycled non-equal length match and replace input fails", { expect_error(mgsub("hey, ho", c("hey", "ho"), c("yo"))) expect_error(mgsub("hey, ho", c("hey"), c("ho", "yo"))) }) test_that("recycled longer replace than match warns and truncates", { expect_warning(mgsub("hey, ho", c("hey"), c("ho", "hey"), recycle = TRUE)) }) test_that("recycled replacements works", { expect_equal(mgsub("hey, ho", c("hey", "ho"), "yo", recycle = TRUE), "yo, yo") }) test_that("works even with start/end symbols", { expect_equal(mgsub(c("hi there", "who said hi to me?", "who said hi"), c("^hi"), c("bye")), c("bye there", "who said hi to me?", "who said hi")) expect_equal(mgsub(c("hi there", "who said hi to me?", "who said hi"), c("hi$"), c("bye")), c("hi there", "who said hi to me?", "who said bye")) }) test_that("all NA fails quickly", { expect_equal(mgsub(rep(NA, 4), "A", "b"), rep(NA, 4)) expect_equal(mgsub(NA, "A", "b"), NA) }) context("Worker") test_that("Letter substitution works", { expect_equal(unlist(worker("ho ho hoot", c("h", "o"), c("o", "h"))), "oh oh ohht") expect_equal(unlist(worker("developer", c("e", "p"), c("p", "e"))), "dpvploepr") }) test_that("Non-equilength matches replace", { expect_equal(unlist(worker("hey, ho", c("hey", "ho"), c("ho", "hey"))), "ho, hey") expect_equal(unlist(worker("hi there, buddy boy!", c("there", "buddy"), c("where", "enemy"))), "hi where, enemy boy!") }) test_that("Substring matches are superceded by longer matches", { expect_equal(unlist(worker("they don't understand the value of what they seek.", c("the", "they"), c("a", "we"))), "we don't understand a value of what we seek.") }) test_that("Same length matches are safely converted", { expect_equal(unlist(worker("hey, how are you?", c("hey", "how", "are", "you"), c("how", "are", "you", "hey"))), "how, are you hey?") }) test_that("Regular expression matches work", { expect_equal(unlist(worker("Dopazamine (of dopazamines family) is not the same as Dopachloride and is still fake.", c("[Dd]opa", "fake"), c("Meta", "real"))), "Metazamine (of Metazamines family) is not the same as Metachloride and is still real.") }) test_that("Regular expression substitions work", { expect_equal(unlist(worker("Dopazamine is not the same as Dopachloride and is still fake.", c("[Dd]opa(.*?mine)", "fake"), c("Meta\\1", "real"))), "Metazamine is not the same as Dopachloride and is still real.") }) test_that("Options passed to sub family work", { expect_equal(unlist(worker("Dopazamine and dopaloramide are fake chemicals.", c("dopa", "fake"), c("meta", "real"), ignore.case = TRUE)), "metazamine and metaloramide are real chemicals.") expect_equal(unlist(worker("Where are the \\bspaces\\b - not the spaces I want?", c("\\bspaces\\b", "[Ww]here"), c("boxes", "There"), fixed = TRUE)), "Where are the boxes - not the spaces I want?") }) test_that("Priority is based on matched length", { expect_equal(worker("Dopazamine is a fake chemical", c("do.*ne", "dopazamin"), c("metazamine", "freakout"), ignore.case = TRUE), "metazamine is a fake chemical") }) test_that("all missing patterns works", { expect_equal(worker("hi there", c("why", "not", "go"), c("a", "b", "c")), "hi there") }) test_that("some missing patterns work", { expect_equal(worker("hi there", c("hi", "bye"), c("bye", "hi")), "bye there") }) test_that("two patterns, only overlap, fast exit", { expect_equal(worker("the the the", c("the", "th"), c("a", "b")), "a a a") })
horizontal_aes_lookup = c( ymin = "xmin", ymax = "xmax", yend = "xend", y = "x", yintercept = "xintercept", ymin_final = "xmin_final", ymax_final = "xmax_final", y_scales = "x_scales", SCALE_Y = "SCALE_X", lower = "xlower", middle = "xmiddle", upper = "xupper" ) vertical_aes_lookup = c( xmin = "ymin", xmax = "ymax", xend = "yend", x = "y", xintercept = "yintercept", xmin_final = "ymin_final", xmax_final = "ymax_final", x_scales = "y_scales", SCALE_X = "SCALE_Y", xlower = "lower", xmiddle = "middle", xupper = "upper" ) flip_aes_lookup = c(horizontal_aes_lookup, vertical_aes_lookup) flip_aes = function(x, lookup = flip_aes_lookup) { UseMethod("flip_aes") } flip_aes.character = function(x, lookup = flip_aes_lookup) { flipped = lookup[x] x[!is.na(flipped)] = flipped[!is.na(flipped)] x } flip_aes.data.frame = function(x, lookup = flip_aes_lookup) { names(x) = flip_aes(names(x), lookup = lookup) x } flip_aes.function = function(x, lookup = flip_aes_lookup) { name = force(deparse(substitute(x))) function(...) { .Deprecated(name, package = "tidybayes") flip_aes(x(...), lookup = lookup) } }
twdtwReduceTime = function(x, y, weight.fun = NULL, dist.method = "Euclidean", step.matrix = symmetric1, from = NULL, to = NULL, by = NULL, overlap = .5, fill = 255){ px <- x[,names(x)!="date",drop=FALSE] tx <- as.Date(x$date) aligs <- lapply(seq_along(y), function(l){ py <- y[[l]][,names(y[[l]])!="date",drop=FALSE] ty <- as.Date(y[[l]]$date) names(py) <- tolower(names(py)) names(px) <- tolower(names(px)) px <- px[,names(py),drop=FALSE] py <- py[,names(px),drop=FALSE] cm <- proxy::dist(py, px, method = dist.method) if(!is.null(weight.fun)){ doyy <- as.numeric(format(ty, "%j")) doyx <- as.numeric(format(tx, "%j")) w <- .g(proxy::dist(doyy, doyx, method = dist.method)) cm <- weight.fun(cm, w) } internals <- .computecost(cm = cm, step.matrix = step.matrix) a <- internals$startingMatrix[internals$N,1:internals$M] d <- internals$costMatrix[internals$N,1:internals$M] candidates <- data.frame(a, d) candidates <- candidates[candidates$d==ave(candidates$d, candidates$a, FUN=min),,drop=FALSE] candidates$b <- as.numeric(row.names(candidates)) I <- order(candidates$d) if(length(I)<1) return(NULL) res <- data.frame( Alig.N = I, from = tx[candidates$a[I]], to = tx[candidates$b[I]], distance = candidates$d[I], label = l ) return(res) }) aligs <- data.table::rbindlist(aligs) breaks <- seq(as.Date(from), as.Date(to), by = by) best_matches <- .bestmatches( x = list(aligs[order(aligs$from, aligs$from),,drop=FALSE]), m = length(y), n = length(breaks) - 1, levels = seq_along(y), breaks = breaks, overlap = overlap, fill = 99999)$IM out <- as.data.frame(best_matches[,c(1,3),drop=FALSE]) names(out) <- c("label", "Alig.N") out$from <- breaks[-length(breaks)] out$to <- breaks[-1] out <- merge(out, aligs[, c("label", "Alig.N", "distance"),drop=FALSE], by.x = c("label", "Alig.N"), by.y = c("label", "Alig.N"), all.x = TRUE) out <- out[order(out$from), names(out)!="Alig.N"] if(any(out$label==0)) out[out$label==0,]$label <- fill return(out) }
`anova.ccanull` <- function(object, ...) { table <- matrix(0, nrow = 2, ncol = 4) if (object$CA$rank == 0) { table[1,] <- c(object$CCA$qrank, object$CCA$tot.chi, NA, NA) table[2,] <- c(0,0,NA,NA) } else { table[1,] <- c(0,0,0,NA) table[2,] <- c(nrow(object$CA$u) - 1, object$CA$tot.chi, NA, NA) } rownames(table) <- c("Model", "Residual") if (inherits(object, c("capscale", "dbrda")) && object$adjust == 1) varname <- "SumOfSqs" else if (inherits(object, "rda")) varname <- "Variance" else varname <- "ChiSquare" colnames(table) <- c("Df", varname, "F", "Pr(>F)") table <- as.data.frame(table) if (object$CA$rank == 0) head <- "No residual component\n" else if (is.null(object$CCA) || object$CCA$rank == 0) head <- "No constrained component\n" else head <- c("!!!!! ERROR !!!!!\n") head <- c(head, paste("Model:", c(object$call))) if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) seed <- get(".Random.seed", envir = .GlobalEnv, inherits = FALSE) else seed <- NULL structure(table, heading = head, Random.seed = seed, class = c("anova.cca", "anova", "data.frame")) }
source("inst/fannie_mae_10pct/0_setup.r") library(disk.frame) library(keras) acqall_dev = disk.frame(file.path(outpath, "appl_mdl_data_sampled")) stream_shglm <- function(df) { i = 0 is = sample(nchunks(df), replace = F) function(reset = F) { if(reset) { print("you've reset") i <<- 0 } else { i <<- i + 1 if (i > nchunks(df)) { return(NULL) } print(glue::glue("{i}/{nchunks(df)}")) return(get_chunk(df, is[i])) } } } acqall_dev1 = acqall_dev %>% delayed(~{ .x[,oltv_band := cut(oltv, c(-Inf, 60,80, Inf))] .x[,scr_band := addNA(cut(cscore_b, c(-Inf, 700,716,725,742,748,766,794, Inf)), ifany=F)] .x }) if(F) { aa = acqall_dev1 %>% collect glm(default_next_12m ~ oltv_band + scr_band - 1, data=aa) } head(acqall_dev1) build_model <- function() { model <- keras_model_sequential() %>% layer_dense(units = 2, activation = 'softmax') model %>% compile( loss = "categorical_crossentropy", optimizer = 'sgd' ) model } model = build_model() ol = levels(get_chunk(acqall_dev1,1)[,oltv_band]) dl = levels(get_chunk(acqall_dev1,1)[,scr_band]) kk <- function() { j = 0 done = F ii = 0 while(!done) { j <- j + 1 si = sample(nchunks(acqall_dev1), nchunks(acqall_dev1)*0.3) osi = setdiff(1:nchunks(acqall_dev1), si) system.time(a <- map_dfr(si, ~{ ii <- ii + 1 i = .x if(ii %% 20 == 0) print(glue::glue("{j}:{ii} {Sys.time()}")) a = get_chunk(acqall_dev1, i) a1 = cbind( a[,keras::to_categorical(as.integer(oltv_band) - 1)] ) at = a[,default_next_12m*1] Y_train = keras::to_categorical(at) hist = model %>% fit( a1, Y_train, epochs = 1, validation_split = 0.2, verbose = 0 ) gw = get_weights(model) gwdt = as.data.table(gw[1]) setnames(gwdt, names(gwdt), c("non_default", "default")) gwdt$i =i gwdt$var = c( rep("oltv_band", length(ol)) ) gwdt$band = c(ol,dl ) gwdt })) some_chunks <- map(osi, ~{ i = .x a = get_chunk(acqall_dev1, i) a1 = cbind( a[,keras::to_categorical(as.integer(oltv_band) -1)] ) a1 }) %>% reduce(rbind) outcomes <- map(osi, ~{ i = .x a = get_chunk(acqall_dev, i, keep=c("default_next_12m")) a[,default_next_12m] }) %>% unlist auc = auc(outcomes, predict(model, some_chunks)[,2]) p = predict(model, diag( length(ol) ))[,2] a_b = log(p/(1-p)) scalar = 20/log(2) intercept = 20*log(536870912/15)/log(2) a = mean(a_b) b = a_b - a done <- length(unique(sign(diff(b)))) == 1 scrs = data.table(base_scr = round(a*scalar+intercept,0), scr = round(-b*scalar,0)) scrs$var = c( rep("oltv_band", length(ol)) ) scrs$band = c(ol , dl ) scrs = scrs[band != "bias"] scrs = scrs[,.(var, band, scr, base_scr)] print(glue::glue("AUC: {auc}")) print(scrs) } scrs } pt = proc.time() scrs = kk() timetaken(pt) View(scrs)
knitr::opts_chunk$set( comment = " collapse = TRUE ) options( rlang_trace_top_env = globalenv(), rlang_backtrace_on_error = "full" ) options( digits = 3, width = 68, str = strOptions(strict.width = "cut"), crayon.enabled = TRUE ) knitr::opts_chunk$set(width = 68) if (knitr::is_latex_output()) { options(crayon.enabled = FALSE) options(cli.unicode = TRUE) } registerS3method("wrap", "error", envir = asNamespace("knitr"), function(x, options) { msg <- conditionMessage(x) call <- conditionCall(x) if (is.null(call)) { msg <- paste0("Error: ", msg) } else { msg <- paste0("Error in ", deparse(call)[[1]], ": ", msg) } msg <- error_wrap(msg) knitr:::msg_wrap(msg, "error", options) } ) error_wrap <- function(x, width = getOption("width")) { lines <- strsplit(x, "\n", fixed = TRUE)[[1]] paste(strwrap(lines, width = width), collapse = "\n") } knitr::knit_hooks$set(chunk_envvar = function(before, options, envir) { envvar <- options$chunk_envvar if (before && !is.null(envvar)) { old_envvar <<- Sys.getenv(names(envvar), names = TRUE, unset = NA) do.call("Sys.setenv", as.list(envvar)) } else { do.call("Sys.setenv", as.list(old_envvar)) } }) check_quietly <- purrr::quietly(devtools::check) install_quietly <- purrr::quietly(devtools::install) shhh_check <- function(..., quiet = TRUE) { out <- check_quietly(..., quiet = quiet) out$result } pretty_install <- function(...) { withr::local_options(list(crayon.enabled = FALSE)) out <- install_quietly(...) output <- strsplit(out$output, split = "\n")[[1]] output <- grep("^(\\s*|[-|])$", output, value = TRUE, invert = TRUE) c(output, out$messages) }
summary.lba.ls <- function(object, digits=2L, ...){ cat('|-------------------------------------------|\n') cat('| COMPOSITION DATA MATRIX |\n') cat('|-------------------------------------------|\n') print(round(object[[1]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| EXPECTED BUDGET |\n') cat('|-------------------------------------------|\n') print(round(object[[2]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| RESIDUAL MATRIX |\n') cat('|-------------------------------------------|\n') print(round(object[[3]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| UNIDENTIFIED MIXING PARAMETERS |\n') cat('|-------------------------------------------|\n') print(round(object[[4]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| UNIDENTIFIED LATENT BUDGETS |\n') cat('|-------------------------------------------|\n') print(round(object[[5]], digits=digits)) cat('\n') if(object$what == 'outer'){ cat('|-------------------------------------------|\n') cat('| OUTER EXTREME MIXING PARAMETERS |\n') cat('|-------------------------------------------|\n') print(round(object[[6]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| OUTER EXTREME LATENT BUDGETS |\n') cat('|-------------------------------------------|\n') print(round(object[[7]], digits=digits)) cat('\n') } else { cat('|-------------------------------------------|\n') cat('| INNER EXTREME MIXING PARAMETERS |\n') cat('|-------------------------------------------|\n') print(round(object[[6]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| INNER EXTREME LATENT BUDGETS |\n') cat('|-------------------------------------------|\n') print(round(object[[7]], digits=digits)) cat('\n') } cat('|-------------------------------------------|\n') cat('| RESCALED LATENT BUDGET |\n') cat('|-------------------------------------------|\n') print(round(object[[8]], digits=digits)) cat('\n') cat('|-------------------------------------------|\n') cat('| BUDGET PROPORTIONS |\n') cat('|-------------------------------------------|\n') print(round(object[[9]], digits=digits)) cat('\n') func <- formatC(round(object[[10]], digits=digits), format='f', digits=digits) cat('|-------------------------------------------|\n') cat('| VALUE OF THE LS FUNCTION:', func, paste(rep(' ',(45-(29+3+nchar(func)))),collapse=''), '|\n') cat('| NUMBER OF UNIDENTIFIED ITERACTIONS:',round(object[[11]],digits=digits), paste(rep(' ',(45-(41+nchar(object[[11]])))),collapse=''),'|\n') if(ncol(object[[6]])> 2){ cat('| NUMBER OF IDENTIFIED ITERACTIONS:',round(object[[12]],digits=digits), paste(rep(' ',(45-(38+nchar(object[[12]])))),collapse=''),'|\n') } cat('|-------------------------------------------|\n') }
classify_noise = function(las, algorithm) { UseMethod("classify_noise", las) } classify_noise.LAS = function(las, algorithm) { assert_is_algorithm(algorithm) assert_is_algorithm_out(algorithm) lidR.context <- "classify_noise" idx <- algorithm(las) if ("Classification" %in% names(las@data)) { nnoise <- fast_countequal(las@data[["Classification"]], LASNOISE) if (nnoise > 0) { message(glue::glue("Original dataset already contains {nnoise} noise points. These points were reclassified as 'unclassified' before performing a new noise classification.")) new_classes <- las@data[["Classification"]] new_classes[new_classes == LASNOISE] <- LASUNCLASSIFIED } else { new_classes <- las@data[["Classification"]] } } else new_classes <- rep(LASUNCLASSIFIED, npoints(las)) new_classes[idx] <- LASNOISE las@data[["Classification"]] <- new_classes return(las) } classify_noise.LAScluster = function(las, algorithm) { buffer <- NULL x <- readLAS(las) if (is.empty(x)) return(NULL) x <- classify_noise(x, algorithm) x <- filter_poi(x, buffer == LIDRNOBUFFER) return(x) } classify_noise.LAScatalog = function(las, algorithm) { opt_select(las) <- "*" options <- list(need_buffer = TRUE, drop_null = TRUE, need_output_file = TRUE, automerge = TRUE) output <- catalog_apply(las, classify_noise, algorithm = algorithm, .options = options) return(output) }
e2e_extract_start <- function(model, results,csv.output=TRUE) { oo <- options() on.exit(options(oo)) pkg.env$csv.output <- csv.output setup <- elt(model, "setup") read.only <- elt(setup, "read.only") model.path <- elt(setup, "model.path") resultsdir <- elt(model, "setup", "resultsdir") model.ident <- elt(model, "setup", "model.ident") output<-results$output endstate <- data.frame(rep(0,77)) for(jj in 2:78) { endstate[jj-1, 1] <- output[nrow(output), jj] } rownames(endstate)<-names(output[,2:78]) if (read.only & csv.output==TRUE) { message("Warning: cannot write model end-state back to the model input folders - model is read-only") message("Warning: to fix this, make a copy of the model using e2e_copy() into your own workspace.") message("Warning: writing the model end-state file to the current results folder instead.") } if (read.only) { filename = csvname(resultsdir, "initial_values", model.ident) } else { parameterpath <- makepath(model.path, PARAMETERS_DIR) filename = csvname(parameterpath, "initial_values", model.ident) } writecsv(endstate, filename, header=FALSE) names(endstate)<-"" return(endstate) }
qprior <- function(p, prior_par = list(mu_psi = 0, sigma_psi = 1, mu_beta = 0, sigma_beta = 1), what = "logor", hypothesis = "H1") { if (any(p < 0) || any(p > 1)) { stop('p needs to be between 0 and one', call. = FALSE) } if ( ! is.list(prior_par) || ! all(c("mu_psi", "sigma_psi", "mu_beta", "sigma_beta") %in% names(prior_par))) { stop('prior_par needs to be a named list with elements "mu_psi", "sigma_psi", "mu_beta", and "sigma_beta', call. = FALSE) } if (prior_par$sigma_psi <= 0 || prior_par$sigma_beta <= 0) { stop('sigma_psi and sigma_beta need to be larger than 0', call. = FALSE) } if ( ! (what %in% c("logor", "or", "rrisk", "arisk"))) { stop('what needs to be either "logor", "or", "rrisk", or "arisk"', call. = FALSE) } if ( ! (hypothesis %in% c("H1", "H+", "H-"))) { stop('hypothesis needs to be either "H1", "H+", or "H-"', call. = FALSE) } if (what == "logor") { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) start_value <- switch(hypothesis, "H1" = 0, "H+" = .5, "H-" = -.5) } else if (what == "or") { bounds <- switch(hypothesis, "H1" = c(0, Inf), "H+" = c(exp(0), Inf), "H-" = c(0, exp(0))) start_value <- switch(hypothesis, "H1" = 1, "H+" = 1.5, "H-" = .5) } else if (what == "rrisk") { bounds <- switch(hypothesis, "H1" = c(0, Inf), "H+" = c(1, Inf), "H-" = c(0, 1)) start_value <- switch(hypothesis, "H1" = 1, "H+" = 1.5, "H-" = .5) } else if (what == "arisk") { bounds <- switch(hypothesis, "H1" = c(-1, 1), "H+" = c(0, 1), "H-" = c(-1, 0)) start_value <- switch(hypothesis, "H1" = 0, "H+" = .5, "H-" = -.5) } if (what == "logor") { out <- qtruncnorm(p, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) } else { out <- vapply(p, FUN = function(x, start_value, bounds, prior_par, what, hypothesis) { nlminb(start = start_value, objective = function(q, p, prior_par, what, hypothesis) { (pprior(q, prior_par = prior_par, what = what, hypothesis = hypothesis) - p)^2 }, lower = bounds[1], upper = bounds[2], p = x, prior_par = prior_par, what = what, hypothesis = hypothesis)$par }, FUN.VALUE = 0, start_value = start_value, bounds = bounds, prior_par = prior_par, what = what, hypothesis = hypothesis) } return(out) }
t.test.cluster <- function(y, cluster, group, conf.int=.95) { group <- as.factor(group) cluster <- as.factor(cluster) s <- !(is.na(y)|is.na(cluster)|is.na(group)) y <- y[s]; cluster <- cluster[s]; group <- group[s] n <- length(y) if(n<2) stop("n<2") gr <- levels(group) if(length(gr)!=2) stop("must have exactly two treatment groups") n <- table(group) nc <- tapply(cluster, group, function(x)length(unique(x))) bar <- tapply(y, group, mean) u <- unclass(group) y1 <- y[u==1]; y2 <- y[u==2] c1 <- factor(cluster[u==1]); c2 <- factor(cluster[u==2]) b1 <- tapply(y1, c1, mean); b2 <- tapply(y2, c2, mean) m1 <- table(c1); m2 <- table(c2) if(any(names(m1)!=names(b1))) stop("logic error 1") if(any(names(m2)!=names(b2))) stop("logic error 2") if(any(m2 < 2)) stop(paste('The following clusters contain only one observation:', paste(names(m2[m2 < 2]), collapse=' '))) M1 <- mean(y1); M2 <- mean(y2) ssc1 <- sum(m1*((b1-M1)^2)); ssc2 <- sum(m2*((b2-M2)^2)) if(nc[1]!=length(m1)) stop("logic error 3") if(nc[2]!=length(m2)) stop("logic error 4") df.msc <- sum(nc)-2 msc <- (ssc1+ssc2)/df.msc v1 <- tapply(y1,c1,var); v2 <- tapply(y2,c2,var) ssw1 <- sum((m1-1)*v1); ssw2 <- sum((m2-1)*v2) df.mse <- sum(n)-sum(nc) mse <- (ssw1+ssw2)/df.mse na <- (sum(n)-(sum(m1^2)/n[1]+sum(m2^2)/n[2]))/(sum(nc)-1) rho <- (msc-mse)/(msc+(na-1)*mse) r <- max(rho, 0) C1 <- sum(m1*(1+(m1-1)*r))/n[1] C2 <- sum(m2*(1+(m2-1)*r))/n[2] v <- mse*(C1/n[1]+C2/n[2]) v.unadj <- mse*(1/n[1]+1/n[2]) de <- v/v.unadj dif <- diff(bar) se <- sqrt(v) zcrit <- qnorm((1+conf.int)/2) cl <- c(dif-zcrit*se, dif+zcrit*se) z <- dif/se P <- 2*pnorm(-abs(z)) stats <- matrix(NA, nrow=20, ncol=2, dimnames=list(c("N","Clusters","Mean", "SS among clusters within groups", "SS within clusters within groups", "MS among clusters within groups","d.f.", "MS within clusters within groups","d.f.", "Na","Intracluster correlation", "Variance Correction Factor","Variance of effect", "Variance without cluster adjustment","Design Effect", "Effect (Difference in Means)", "S.E. of Effect",paste(format(conf.int),"Confidence limits"), "Z Statistic","2-sided P Value"), gr)) stats[1,] <- n stats[2,] <- nc stats[3,] <- bar stats[4,] <- c(ssc1, ssc2) stats[5,] <- c(ssw1, ssw2) stats[6,1] <- msc stats[7,1] <- df.msc stats[8,1] <- mse stats[9,1] <- df.mse stats[10,1] <- na stats[11,1] <- rho stats[12,] <- c(C1, C2) stats[13,1] <- v stats[14,1] <- v.unadj stats[15,1] <- de stats[16,1] <- dif stats[17,1] <- se stats[18,] <- cl stats[19,1] <- z stats[20,1] <- P attr(stats,'class') <- "t.test.cluster" stats } print.t.test.cluster <- function(x, digits, ...) { if(!missing(digits)) { oldopt <- options('digits') options(digits=digits) on.exit(options(oldopt)) } cstats <- t(apply(x,1,format)) attr(cstats,'class') <- NULL cstats[is.na(x)] <- "" invisible(print(cstats, quote=FALSE)) }
context("Wind maps") test_that("idw360", { library(sp) df <- structure(list(date = structure(c(17472, 17472, 17472, 17472, 17472), class = "Date"), hour = c(15, 15, 15, 15, 15), station_code = c("ACO", "AJM", "AJU", "BJU", "CHO"), value = c(36, 6, 7, 319, 214), lat = c(19.635501, 19.272161, 19.154286, 19.370464, 19.266948), lon = c(-98.912003, -99.207744, -99.162611, -99.159596, -98.886088)), .Names = c("date", "hour", "station_code", "value", "lat", "lon"), row.names = c(NA, -5L), class = c("data.frame")) station_loc <- df[, c("lat", "lon", "value")] coordinates(station_loc) <- ~lon + lat crs_string <- "+proj=longlat +ellps=WGS84 +no_defs +towgs84=0,0,0" proj4string(station_loc) <- sp::CRS(crs_string) pixels <- 10 mxc_grid <- expand.grid(x = seq( (min(coordinates(station_loc)[, 1]) - .1), (max(coordinates(station_loc)[, 1]) + .1), length.out = pixels), y = seq( (min(coordinates(station_loc)[, 2]) - .1), (max(coordinates(station_loc)[, 2]) + .1), length.out = pixels)) mxc_grid_pts <- SpatialPixels(SpatialPoints( (mxc_grid))) mxc_grid_pts <- as(mxc_grid_pts, "SpatialGrid") proj4string(mxc_grid_pts) <- CRS(crs_string) idw <- idw360(station_loc$value, station_loc, mxc_grid_pts) expect_type(idw$pred, "double") expect_equal(length(idw$pred), 10 * 10) expect_true(all(idw$pred <= 360)) expect_true(all(idw$pred >= 0)) locations <- data.frame(lon = c(1, 2), lat = c(1, 2)) coordinates(locations) <- ~lon + lat values <- c(55, 355) grid <- data.frame(lon = c(1, 2, 1, 2), lat = c(1, 2, 2, 1)) coordinates(grid) <- ~lon + lat idw <- idw360(values, locations, grid) expect_equal(idw, data.frame(pred = c(55, 355, 25, 25))) })
esomTrain <- function(Data, Lines=50, Columns=82, Epochs=24, Toroid=TRUE, NeighbourhoodFunction="gauss", StartLearningRate=0.5, EndLearningRate=0.1, StartRadius=24, EndRadius=1, NeighbourhoodCooling="linear", LearningRateCooling="linear", ShinyProgress = NULL, ShiftToHighestDensity = TRUE, InitMethod="uni_min_max", Key = NULL, UmatrixForEsom=T){ distance = "euclidC" grid <- esomInit(Data,Lines,Columns, InitMethod) x <- esomTrainOnline(grid, Data, StartRadius, EndRadius, Columns,Lines, StartLearningRate, EndLearningRate, NeighbourhoodFunction, Toroid, Epochs, NeighbourhoodCooling, LearningRateCooling, ShinyProgress = ShinyProgress) if(!is.null(ShinyProgress)) ShinyProgress$set(message = "Generating Umatrix", value = 0) Weights = x if(ShiftToHighestDensity & Toroid){ print("shift to point of highest density") Radius = mean(dist(Data)) pmatrix = pmatrixForEsom(Data, Weights=Weights, Lines=Lines, Columns=Columns, Radius = Radius) pos <- which(pmatrix == max(pmatrix), arr.ind=T)[1,] Weights = shiftedNeurons(Weights, Lines, Columns, -pos[1], -pos[2]) x <- Weights } projection <- bestmatchesC(x, Data, Columns) if(!is.null(Key)) projection = cbind(Key, projection) else{ warning("No Keys given. 1:nrow(Data) will be used as keys for Bestmatches.") projection = cbind(1:nrow(projection), projection) } Umatrix = NULL if(UmatrixForEsom) Umatrix = umatrixForEsom(x, Lines, Columns, Toroid) list(BestMatches = projection, Weights = x, Lines = Lines, Columns = Columns, Toroid = Toroid, Umatrix = Umatrix) }
PEMM_fun <- function(X, phi, lambda=NULL, K=NULL, pos=NULL, tol=0.001, maxIter=100){ get.llik <- function(X, mu, S, phi, phi0){ if (length(which(X<0))==0) pos<- TRUE else pos<- FALSE llik <- 0 for (j in 1:nrow(X)){ Xi <- X[j,] idxi <- which(!is.na(Xi)) Xi <- Xi[idxi] Si <- as.matrix(S[idxi,idxi]) Sii <- my.solve(Si) oo <- - log(det(Si)) -(Xi-mu[idxi])%*%Sii%*%(Xi-mu[idxi]) oo <- 0.5*oo nmis <- length(X[j,])-length(idxi) if (phi==0){ vv <- 0 } else { if (pos){ vv1=sum(log(1-exp(-phi0-phi*Xi))) vv2 <- -phi0*nmis if (nmis==0){ vv3 <- 0 } else { Smi <- as.matrix(S[-idxi,-idxi]) mu.mis <- mu[-idxi]+matrix(S[-idxi,idxi],nrow=nmis)%*%Sii%*%(Xi-mu[idxi]) S.mis <- Smi - matrix(S[-idxi,idxi],nrow=nmis)%*%Sii%*%matrix(S[idxi,-idxi],ncol=nmis) vv3<- -sum(mu.mis)*phi+0.5*sum(S.mis)*phi^2 } vv <- vv1+vv2+vv3 } else { vv1=sum(log(1-exp(-phi0-phi*Xi^2))) vv2 <- -phi0*nmis if (nmis==0){ vv3 <- 0 } else { Smi <- as.matrix(S[-idxi,-idxi]) mu.mis <- mu[-idxi]+matrix(S[-idxi,idxi],nrow=nmis)%*%Sii%*%(Xi-mu[idxi]) S.mis <- Smi - matrix(S[-idxi,idxi],nrow=nmis)%*%Sii%*%matrix(S[idxi,-idxi],ncol=nmis) Smis.inv <- my.solve(S.mis) Smii <- Smis.inv diag(Smis.inv) <- diag(Smis.inv)+2*phi A <- my.solve(Smis.inv) vv3<- 0.5*(log(det(A)) -log(det(S.mis)) + matrix(mu.mis,nrow=1)%*%(Smii%*%A%*%Smii-Smii)%*%matrix(mu.mis,ncol=1) ) } vv <- vv1+vv2+vv3 } } llik <- llik+ oo+vv } pllik <- llik return(llik) } my.solve <- function(X){ if (!is.matrix(X)) X <- matrix(X, nrow=sqrt(length(X))) ss <- svd(X) Xinv <- ss$u%*%diag(1/ss$d, nrow=nrow(X), ncol=nrow(X))%*%t(ss$v) return(Xinv) } gets1 <- function(sigma, phi){ p <- nrow(sigma) s1 <- my.solve(sigma)+diag(2*phi, p, p) return(s1) } get.bg <- function(sigma, mu, phi){ p <- length(mu) s1 <- gets1(sigma, phi) s1inv <- my.solve(s1) ccen <- my.solve(sigma) A <- s1inv%*%ccen beta <- A%*%mu gamma <- s1inv return(list(beta=beta, gamma=gamma)) } find.lambda <- function(Sigma,N,p,K, delta=delta){ ffL <- function(lambda, Sigma, N, p, K){ Sigma.new <- N/(N+K)*Sigma*(N-1)/N + lambda/(N+K)*diag(1, p, p) return(abs(min(as.double(eigen(N*Sigma.new)$value)))) } Sigma2 = Sigma while (!is.double(eigen(N*Sigma2)$value)){ delta = delta+1 Sigma2 = N/(N+K)*Sigma*(N-1)/N + delta/(N+K)*diag(1, p, p) } Sigma=Sigma2 oo <- -min(as.double(eigen(N*Sigma)$value)) if (oo>0){ lambda <- optimize(ffL, lower=0,upper=oo, Sigma=Sigma, N=N, p=p, K=K)$minimum+delta } else { lambda <- delta } return(lambda) } if (is.null(pos)){ if (length(which(X<0))==0) pos<- TRUE else pos<- FALSE } if (phi==0) { phi0 <- -log(mean(is.na(X))) } else { phi0 <- 0 } p <- ncol(X) N <- nrow(X) if (is.null(K)){ K=5 } X.hat <- X mu.new <- matrix(colMeans(X,na.rm=T),ncol=1) Sigma.new <- cov(X, use="pairwise.complete") Sigma.new[is.na(Sigma.new)] <- 0 diff <- 999 iter <- 0 if (is.null(lambda)) { delta=5 Lambda <- find.lambda(Sigma.new,N=N,p=p,K=K, delta=delta) } else { Lambda <- lambda } Sigma.new <- N/(N+K)*Sigma.new*(N-1)/N + Lambda/(N+K)*diag(1, p, p) illik <- 999 while(iter<maxIter & diff>tol){ iter <- iter+1 mu <- mu.new Sigma <- Sigma.new cov.add <- matrix(0, p, p) for (i in 1:nrow(X)){ ii <- which(is.na(X[i,])) if (length(ii)>=1){ Soo <- as.matrix(Sigma[-ii,-ii]) pi <- nrow(Soo) mu.mis <- mu[ii]+Sigma[ii,-ii]%*%my.solve(Soo)%*%(X[i,-ii]-mu[-ii]) mu.mis <- matrix(mu.mis,ncol=1) cov.mis <- Sigma[ii,ii] - Sigma[ii,-ii]%*%my.solve(Soo)%*%Sigma[-ii, ii] if (phi!=0 & pos==TRUE){ X.hat[i,ii]<- mu.mis - phi*cov.mis%*%matrix(1,nrow=length(mu.mis),ncol=1) cov.ii <- cov.mis } else if (phi!=0 & pos==FALSE){ oo <- get.bg(cov.mis, mu.mis, phi) X.hat[i,ii] <- oo$beta cov.ii <- oo$gamma } else if (phi==0) { X.hat[i,ii] <- mu.mis cov.ii <- cov.mis } cov.add[ii,ii] <- cov.add[ii,ii] + cov.ii } } mu.new <- colMeans(X.hat) Sig <- cov(X.hat)*(N-1)/N+cov.add/N if (is.null(lambda)) { Lambda <- find.lambda(Sig,N=N,p=p,K=K,delta=delta) } else { Lambda <- lambda } Sigma.new <- N/(N+K)*(Sig) + Lambda/(N+K)*diag(1, p, p) illik <- c(illik, get.llik(X, mu.new, Sigma.new,phi=phi,phi0=phi0) - sum(diag(Lambda*my.solve(Sigma.new))) -K*log(det(Sigma.new)) ) diff <- abs(illik[iter+1]-illik[iter])/abs(illik[iter]) if (is.na(diff)) { diff <- 0 warning("The algorithm does not converge!") } } if (iter==maxIter) warning("The algorithm does not converge!") return(list(mu=mu, Sigma=Sigma, Xhat=X.hat)) }
cramer.folder <- function(xf) { x = as.data.frame(xf, stringsAsFactors = TRUE) group = x[, "group"] x = x[, -ncol(x)] return(by(x, INDICES=group, FUN=cramer.data.frame, check = FALSE)) } tschuprow.folder <- function(xf) { x = as.data.frame(xf, stringsAsFactors = TRUE) group = x[, "group"] x = x[, -ncol(x)] return(by(x, INDICES=group, FUN=cramer.data.frame, check = FALSE)) } pearson.folder <- function(xf) { x = as.data.frame(xf, stringsAsFactors = TRUE) group = x[, "group"] x = x[, -ncol(x)] return(by(x, INDICES=group, FUN=pearson.data.frame, check = FALSE)) } phi.folder <- function(xf) { x = as.data.frame(xf, stringsAsFactors = TRUE) group = x[, "group"] x = x[, -ncol(x)] return(by(x, INDICES=group, FUN=pearson.data.frame, check = FALSE)) }
structure(list(url = "https://api.twitter.com/2/tweets?tweet.fields=attachments%2Cauthor_id%2Cconversation_id%2Ccreated_at%2Centities%2Cgeo%2Cid%2Cin_reply_to_user_id%2Clang%2Cpublic_metrics%2Cpossibly_sensitive%2Creferenced_tweets%2Csource%2Ctext%2Cwithheld&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Cpublic_metrics%2Curl%2Cusername%2Cverified%2Cwithheld&expansions=author_id%2Centities.mentions.username%2Cgeo.place_id%2Cin_reply_to_user_id%2Creferenced_tweets.id%2Creferenced_tweets.id.author_id&place.fields=contained_within%2Ccountry%2Ccountry_code%2Cfull_name%2Cgeo%2Cid%2Cname%2Cplace_type&ids=1266813392293150721%2C1266813064185352193%2C1266812742440280064%2C1266812628816535553%2C1266811890258325505%2C1266811649949937670%2C1266811517787348993%2C1266811399071768579%2C1266810962985848833", status_code = 200L, headers = structure(list(date = "Tue, 21 Dec 2021 13:36:57 UTC", server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "7827", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "300", `x-rate-limit-reset` = "1640094716", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "298", `strict-transport-security` = "max-age=631138519", `x-response-time` = "356", `x-connection-hash` = "b914cde170481ca75c4b9b9291d6d4593fbb9c37fd3a37f09fefae48ca90f4e7"), class = c("insensitive", "list")), all_headers = list(list(status = 200L, version = "HTTP/2", headers = structure(list(date = "Tue, 21 Dec 2021 13:36:57 UTC", server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "7827", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "300", `x-rate-limit-reset` = "1640094716", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "298", `strict-transport-security` = "max-age=631138519", `x-response-time` = "356", `x-connection-hash` = "b914cde170481ca75c4b9b9291d6d4593fbb9c37fd3a37f09fefae48ca90f4e7"), class = c("insensitive", "list")))), cookies = structure(list(domain = c(".twitter.com", ".twitter.com", ".twitter.com", ".twitter.com"), flag = c(TRUE, TRUE, TRUE, TRUE), path = c("/", "/", "/", "/"), secure = c(TRUE, TRUE, TRUE, TRUE), expiration = structure(c(1702744284, 1702744284, 1702744284, 1702744284), class = c("POSIXct", "POSIXt")), name = c("guest_id_marketing", "guest_id_ads", "personalization_id", "guest_id"), value = c("REDACTED", "REDACTED", "REDACTED", "REDACTED")), row.names = c(NA, -4L), class = "data.frame"), content = charToRaw("{\"data\":[{\"id\":\"1266813392293150721\",\"referenced_tweets\":[{\"type\":\"retweeted\",\"id\":\"1266627581002072064\"}],\"entities\":{\"hashtags\":[{\"start\":40,\"end\":57,\"tag\":\"fridaysforfuture\"},{\"start\":58,\"end\":69,\"tag\":\"markuslanz\"},{\"start\":127,\"end\":139,\"tag\":\"Mattscheibe\"}],\"mentions\":[{\"start\":3,\"end\":12,\"username\":\"twitkalk\",\"id\":\"395595454\"},{\"start\":70,\"end\":86,\"username\":\"DavidHasselhoff\",\"id\":\"20014300\"},{\"start\":92,\"end\":102,\"username\":\"c_lindner\",\"id\":\"122104353\"}]},\"conversation_id\":\"1266813392293150721\",\"public_metrics\":{\"retweet_count\":8,\"reply_count\":0,\"like_count\":0,\"quote_count\":0},\"created_at\":\"2020-05-30T19:27:03.000Z\",\"source\":\"Twitter for Android\",\"text\":\"RT @twitkalk: Don't hassel the Hoff! \\uD83E\\uDD2C\\n date = structure(1640093817, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 3.1e-05, connect = 3.2e-05, pretransfer = 0.000122, starttransfer = 0.37172, total = 0.372436)), class = "response")
sim.bdtypes.stt.taxa <- function(n, lambdavector,deathvector,sampprobvector,init=-1,EI=FALSE,eliminate=0){ muvector<-deathvector*(1-sampprobvector) psivector<-deathvector*sampprobvector extincttree = 1 if ((init == -1) && (length(deathvector)==2)){ init<-2 lamb<-lambdavector[1,1]-lambdavector[2,2]-deathvector[1]+deathvector[2] c<- sqrt(lamb^2 + 4*lambdavector[1,2]*lambdavector[2,1]) f1 <- (c + lamb)/(c+lamb+2*lambdavector[1,2]) r<-runif(1,0,1) if (r<f1){init <-1} } if ((init==-1) && (length(deathvector)!=2)) {init<-sample(1:length(deathvector),1)} if (EI==TRUE){init<-1} while(extincttree==1){ edge <- c(-1,-2) leaves <- c(-2) types <- c(init) sampled <- vector() typessampled<-vector() timecreation <-c(0,0) extinct <- vector() time <-0 maxspecies <- -2 edge.length <- c(0) extincttree = 0 stop = 0 while (stop == 0 ){ if (length(leaves) == 0){ phy2=0 extincttree=1 print("extinct tree") stop = 1 } else { sumrates<-vector() for (i in 1:length(lambdavector[,1])){ sumrates<-c(sumrates,(length(which(types==i))*(sum(lambdavector[i,])+muvector[i]+psivector[i]))) } timestep <- rexp(1,sum(sumrates)) time = time+timestep r<-runif(1,0,sum(sumrates)) chosentype<-min(which(cumsum(sumrates)>r)) species <- sample(leaves[which(types==chosentype)],1) lambda<-sum(lambdavector[chosentype,]) gamma <- 0 if (EI==TRUE){ if (chosentype == 1) {gamma<-lambda lambda <-0 }} mu<-muvector[chosentype] psi<-psivector[chosentype] del <- which(leaves == species) specevent <- runif(1,0,1) edgespecevent <- which(edge == species) - length(edge.length) if ((lambda/(lambda+gamma+mu+psi)) > specevent) { edge.length[edgespecevent] <- time-timecreation[- species] edge <- rbind(edge,c(species,maxspecies-1)) edge <- rbind(edge,c(species,maxspecies-2)) edge.length <- c(edge.length,0,0) r<-runif(1,0,lambda) newtype<-min(which(cumsum(lambdavector[chosentype,])>r)) leaves <- c(leaves,maxspecies-1,maxspecies-2) types<- c(types, chosentype, newtype) maxspecies <- maxspecies-2 leaves <- leaves[- del] types <- types[- del] timecreation <- c(timecreation,time,time)} else if (((lambda+gamma)/(lambda+gamma+mu+psi)) > specevent) { types[del] <- 2 } else if (((lambda+gamma+psi)/(lambda+gamma+mu+psi)) > specevent) { sampled<-c(sampled,leaves[del]) if (EI == TRUE && length(typessampled)<eliminate){ typessampled<-c(typessampled,1) } else {typessampled<-c(typessampled,chosentype)} leaves <- leaves[- del] types <- types[- del] edge.length[edgespecevent] <- time-timecreation[- species] if (length(sampled) == n){ stop = 1 } } else { extinct <- c(extinct,leaves[del]) leaves <- leaves[- del] types <- types[- del] edge.length[edgespecevent] <- time-timecreation[- species] } } }} while (length(leaves)>0) { del<-1 extinct <- c(extinct,leaves[del]) k = which( edge == leaves[del] ) - length(edge.length) edge.length[k] <- time-timecreation[- leaves[del]] leaves <- leaves[- del] } for (j in 1:length(extinct)){ del<-which (edge==extinct[j]) - length(edge.length) surpress<-edge[del,1] edge.length<-edge.length[- del] edge<-edge[- del,] del2<-which (edge[,1]==surpress) modify <-which (edge[,2]==surpress) edge[modify,2]<-edge[del2,2] edge.length[modify]<-edge.length[modify]+edge.length[del2] edge.length<-edge.length[- del2] edge<-edge[- del2,] } leaf=1 interior=length(sampled)+1 edgetemp<-edge typessampledNew<-vector() temp<-unique(c(edge)) temp<-sort(temp,decreasing=TRUE) for (j in temp){ if (sum(match(sampled,j,0))==0 || j==-1) { posvalue <- interior interior <- interior +1 } else { typessampledNew<-c(typessampledNew,typessampled[which(sampled==j)]) posvalue <- leaf leaf <- leaf +1 } replacel <- which(edge == j) if (length(replacel)>0) { for (k in 1:length(replacel)) { if ((replacel[k]-1) < length(edge.length)) { edge[replacel[k],1] <- posvalue } else { edge[(replacel[k]-length(edge.length)),2] <- posvalue } } } } phy <- list(edge = edge) phy$tip.label <- paste("t", sample(length(sampled)), sep = "") phy$edge.length <- edge.length phy$Nnode <- length(sampled) phy$states<-typessampledNew class(phy) <- "phylo" br<-sort(getx(phy,sersampling=1),decreasing=TRUE) phy$root.edge<-br[1]-br[2] phy<-collapse.singles(phy) phy2 <- phy phy2 }
spacetime_bisquare = function(dom, knots, w_s, w_t) { prep = prepare_bisquare(dom, knots, type = "point") out = compute_basis_spt(prep$X, prep$knot_mat, w_s, w_t) sparseMatrix(i = out$ind_row + 1, j = out$ind_col + 1, x = out$values, dims = out$dim) }
quality_control<-function(data, int.window=2, perc.miss=20, ps.method="percentage", result = "plot", th.day=100, perc = 95, def.season = "natural", reduction = FALSE, red.level = 0.90, derivative = 5, man = 11, th.ma = 5, n.clinical = 5, window.clinical = 7, window.grains = 5, th.pollen = 10, th.sum = 100, type = "none", int.method = "lineal", ...){ data<-data.frame(data) if (class(data) != "data.frame"& !is.null(data)){ stop ("Please include a data.frame: first column with date, and the rest with pollen types")} if(class(data[,1])[1]!="Date" & !is.POSIXt(data[,1])) {stop("Please the first column of your data must be the date in 'Date' format")} data[,1]<-as.Date(data[,1]) if(class(int.window)!="numeric" | int.window %% 1 != 0){stop("int.window: Please, insert only an entire number bigger than 1")} if(int.window<1){stop("int.window: Please, insert only an entire number bigger or equal to 1")} if(class(perc.miss)!="numeric"){stop("perc.miss: Please, insert only a number between 0 and 100")} if(perc.miss<0 | perc.miss > 100){stop("perc.miss: Please, insert only a number between 0 and 100")} if(result!="plot" & result!="table"){stop("result: Please, insert only 'plot' or 'table'.")} Pollen<-calculate_ps(data=data, method=ps.method, th.day=th.day, perc=perc, def.season=def.season, reduction=reduction, red.level=red.level, derivative=derivative, man=man, th.ma=th.ma, n.clinical=n.clinical, window.clinical=window.clinical, window.grains=window.grains, th.pollen=th.pollen, th.sum=th.sum, type=type, interpolation=TRUE, int.method=int.method, plot=FALSE, maxdays = 300 ) Interpolated<-interpollen(data=data, method=int.method, maxdays = 300, plot=FALSE, result="long") Qualitycontrol<-data.frame() Dataframe<-Pollen[,c(1,2)] Dataframe$Complete<-TRUE Dataframe$Start<-TRUE Dataframe$Peak<-TRUE Dataframe$End<-TRUE Dataframe$Comp.MPS<-TRUE nrow<-nrow(Dataframe) for(a in 1:nrow){ if(any(is.na(Pollen[a,]))){ Dataframe[a,-c(1,2)]<-FALSE }else{ Interpolated$Type<-as.character(Interpolated$Type) Interwindow<-Interpolated[which(Interpolated$Type==as.character(Pollen[a,1]) & Interpolated$Date>=(Pollen[a,3]-int.window) & Interpolated$Date<=(Pollen[a,3]+int.window) ),] if(sum(Interwindow[,4],na.rm = T)!=0){ Dataframe[a,4]<-FALSE } Interwindow2<-Interpolated[which(Interpolated$Type==as.character(Pollen[a,1]) & Interpolated$Date>=(Pollen[a,11]-int.window) & Interpolated$Date<=(Pollen[a,11]+int.window) ),] if(sum(Interwindow2[,4],na.rm = T)!=0){ Dataframe[a,5]<-FALSE } Interwindow3<-Interpolated[which(Interpolated$Type==as.character(Pollen[a,1]) & Interpolated$Date>=(Pollen[a,5]-int.window) & Interpolated$Date<=(Pollen[a,5]+int.window) ),] if(sum(Interwindow3[,4],na.rm = T)!=0){ Dataframe[a,6]<-FALSE } MPS<-Interpolated[which(Interpolated$Type==as.character(Pollen[a,1]) & Interpolated$Date>=Pollen[a,3] & Interpolated$Date<=Pollen[a,5]),] Day.dif<-as.numeric(Pollen[a,5]-Pollen[a,3]) if(sum(MPS[,4],na.rm=T)>round(Day.dif*(perc.miss/100))){ Dataframe[a,7]<-FALSE } } } Dataframe$Risk<-apply(Dataframe[,-c(1,2)], 1, function(x) length(x[x==FALSE]) ) graph<-ggplot(Dataframe, aes(seasons, type))+ geom_tile(aes(fill=Risk), colour="grey")+ scale_fill_gradient(low="white", high=" scale_x_discrete(limits = unique(Dataframe$seasons))+ theme_classic()+ labs(title="Quality Control")+ theme(plot.title = element_text(hjust=0.5), title = element_text(size = 16, face="bold"),axis.title=element_blank(), axis.text = element_text(size = 12, face="bold", colour= "black"), axis.text.y = element_text(face="bold.italic"), legend.title = element_text(size = 14), legend.text = element_text(size = 12)) if(result=="plot"){ return(graph) } if(result=="table"){ return(Dataframe) } }
SILOThiessenShp<- function(SILOdata,path,shpname){ SiteTable <- SILOSiteSummary(SILOdata) SILOLocs <- sf::st_as_sf(SiteTable, coords = c("Longitude","Latitude")) . <- NULL TPoly <- SILOLocs %>% sf::st_geometry() %>% do.call(c, .) %>% sf::st_voronoi() %>% sf::st_collection_extract() SILOLocs$polys <- sf::st_intersects(SILOLocs, TPoly) %>% unlist %>% TPoly[.] TPoly_id <- sf::st_set_geometry(SILOLocs, "polys")["Station"] TPolyCRS <- sf::st_set_crs(TPoly_id, "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs") sf::st_write(TPolyCRS,dsn=path,layer=shpname,driver="ESRI Shapefile",delete_layer = TRUE) TPoly_annrain <- sf::st_set_geometry(SILOLocs, "polys")["AnnualRainfall"] return(TPoly_annrain) }
qtl2_to_cape <- function(cross, genoprobs = NULL, map = NULL, covar = NULL, verbose = TRUE){ phenotype_matrix = as.matrix(cross$pheno) if(is.null(map)){ map = cross$pmap } if(is.null(map)){ map <- cross$gmap } crosstype = cross$crosstype mpp_types <- c("do", "riself4", "riself8", "riself16", "magic19") is_mpp <- as.logical(length(which(mpp_types == crosstype))) if(is.null(genoprobs)){ geno <- cross$geno geno_ind <- rownames(geno[[1]]) if(is_mpp){ genoprobs<-probs_doqtl_to_qtl2(geno, map = map, pos_column = "pos") genoprobs<-genoprob_to_alleleprob(genoprobs) }else{ genoprobs <- calc_genoprob(cross, map = map) } }else{ geno_ind <- rownames(genoprobs[[1]]) } if(is.null(covar)){ if(!is.null(cross$covar)){ covar = as.matrix(cross$covar) num_covar <- matrix(NA, nrow = nrow(covar), ncol = ncol(covar)) dimnames(num_covar) <- dimnames(covar) covar_ind <- rownames(covar) for(i in 1:ncol(covar)){ as_num <- suppressWarnings(as.numeric(covar[,i])) if(all(is.na(as_num))){ if(verbose){cat("Converting", colnames(covar)[i], "to numeric.\n")} new_covar <- as.numeric(as.factor(covar[,i])) - 1 num_covar[,i] <- new_covar } } covar <- num_covar }else{ covar <- NULL covar_ind <- rownames(phenotype_matrix) } }else{ covar_ind <- rownames(covar) } chr_to_add <- setdiff(names(genoprobs), c("1", "X", "Y", "M")) if(verbose){cat("Converting genoprobs to array...\n")} n_dim_geno <- length(dim(genoprobs[[1]])) if(n_dim_geno == 2){ geno <- abind(genoprobs[[1]], 1-genoprobs[[1]], along = 3) for(i in chr_to_add){ a_geno <- abind(genoprobs[[i]], 1-genoprobs[[i]], along = 3) geno <- abind(geno, a_geno, along = 2) } geno <- aperm(geno, c(1,3,2)) }else{ geno <- abind(genoprobs[[1]], along = 3) for(i in chr_to_add){ geno <- abind(geno, genoprobs[[i]], along = 3) } } if(!is_mpp && dim(geno)[2] == 3){ to_biallelic <- function(marker_mat){ allele1 <- marker_mat[,1] het <- marker_mat[,2] allele2 <- marker_mat[,3] allele1 <- allele1 + het/2 allele2 <- allele2 + het/2 biallele_mat <- cbind(allele1, allele2) return(biallele_mat) } geno_temp <- apply(geno, 3, to_biallelic) geno <- array(geno_temp, dim = c(nrow(phenotype_matrix), 2, dim(geno)[3])) rownames(geno) <- geno_ind } colnames(geno) <- LETTERS[1:ncol(geno)] rownames(geno) <- geno_ind common_ind <- Reduce("intersect", list(rownames(phenotype_matrix), geno_ind, covar_ind)) common_pheno_locale <- match(common_ind, rownames(phenotype_matrix)) common_geno_locale <- match(common_ind, rownames(geno)) if(!is.null(covar)){ common_covar_locale <- match(common_ind, rownames(covar)) } pheno <- as.matrix(phenotype_matrix[common_pheno_locale,]) rownames(pheno) <- common_ind geno <- geno[common_geno_locale,,] chr_used <- setdiff(names(genoprobs), c("X", "Y", "M")) un_map <- unlist(map[chr_used]) marker_location <- as.numeric(un_map) split_marker <- strsplit(names(un_map), "\\.") chr <- as.numeric(sapply(split_marker, function(x) x[1])) marker_names <- sapply(split_marker, function(x) x[2]) dimnames(geno)[[3]] <- marker_names geno_names <- dimnames(geno) names(geno_names) <- c("mouse", "allele" ,"locus") data_obj <- list() data_obj$pheno <- pheno data_obj$geno_names <- geno_names data_obj$chromosome <- chr data_obj$marker_num <- 1:length(chr) data_obj$marker_location <- marker_location if(!is.null(covar)){ data_obj$pheno <- cbind(data_obj$pheno, covar[common_covar_locale,]) } result <- list("data_obj" = data_obj, "geno_obj" = geno) }
load_dia <- function(file, merge_id = "EMPI", sep = ":", id_length = "standard", perc = 0.6, na = TRUE, identical = TRUE, nThread = 4, mrn_type = FALSE) { DATA <- load_base(file = file, merge_id = merge_id, sep = sep, id_length = id_length, perc = perc, na = na, identical = identical, nThread = nThread, mrn_type = mrn_type, src = "dia") raw_id <- which(colnames(DATA) == "EMPI" | colnames(DATA) == "IncomingId")[1] data_raw <- DATA[, raw_id:dim(DATA)[2]] DATA <- DATA[, 1:(raw_id-1)] DATA$time_dia <- as.POSIXct(data_raw$Date, format = "%m/%d/%Y") DATA$dia_name <- pretty_text(data_raw$Diagnosis_Name, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_code <- pretty_text(data_raw$Code, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_code_type <- pretty_text(data_raw$Code_Type, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_flag <- pretty_text(data_raw$Diagnosis_Flag, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_provider <- pretty_text(data_raw$Provider, remove_after = FALSE, remove_white = FALSE) DATA$dia_clinic <- pretty_text(data_raw$Clinic, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_hosp <- pretty_text(data_raw$Hospital, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) DATA$dia_inpatient <- pretty_text(data_raw$Inpatient_Outpatient, remove_after = FALSE, remove_white = FALSE) DATA$dia_enc_num <- pretty_text(data_raw$Encounter_number, remove_after = FALSE, remove_punc = FALSE, remove_white = FALSE) if(dim(DATA)[1] != 1) {DATA <- remove_column(dt = DATA, na = na, identical = identical)} return(DATA) }
library(oompaBase) suppressWarnings( RNGversion("3.5.3") ) set.seed(372284) nPairs <- 3 nGenes <- 7 m <- matrix(rnorm(2*nPairs*nGenes), ncol=2*nPairs) v <- factor(rep(c("A","B"), each=nPairs)) pf <- rep(1:nPairs, 2) colnames(m) <- paste(as.character(v), pf, sep='') round(m, 2) mpt <- matrixPairedT(m, v, pf) realt <- sapply(1:nGenes, function(i) { x <- m[i, v=="A"] y <- m[i, v=="B"] t1 <- t.test(y, x, paired=TRUE) t1$statistic }) all(round(mpt-realt, 15) == 0) mtt <- matrixT(m, v) realt <- sapply(1:nGenes, function(i) { x <- m[i, v=="A"] y <- m[i, v=="B"] t1 <- t.test(x, y, paired=FALSE, var.equal=TRUE) t1$statistic }) all(round(mtt-realt, 15) == 0) mut <- matrixUnequalT(m,v) realt <- sapply(1:nGenes, function(i) { x <- m[i, v=="A"] y <- m[i, v=="B"] t1 <- t.test(x, y, paired=FALSE, var.equal=FALSE) t1$statistic }) all(round(mut$tt-realt, 15) == 0)
plot.reproData <- function(x, xlab, ylab = "Cumulated Number of offspring", main = NULL, concentration = NULL, style = "ggplot", pool.replicate = FALSE, addlegend = FALSE, remove.someLabels = FALSE, ...) { if (!is(x, "reproData")) stop("plot.reproData: object of class reproData expected") if (style == "generic" && remove.someLabels) warning("'remove.someLabels' argument is valid only in 'ggplot' style.", call. = FALSE) if (is.null(concentration) && addlegend) warning("'addlegend' argument is valid only when 'concentration' is not null.", call. = FALSE) if (pool.replicate) { x <- cbind(aggregate(cbind(Nreprocumul, Nsurv, Ninit) ~ time + conc, x, sum), replicate = 1) } if (is.null(concentration)) { reproDataPlotFull(x, xlab, ylab, style, remove.someLabels) } else { reproDataPlotFixedConc(x, xlab, ylab, main, concentration, style, addlegend, remove.someLabels) } } reproDataPlotFull <- function(data, xlab, ylab, style = "generic", remove.someLabels) { dataPlotFull(data, xlab, ylab, "Nreprocumul", style, remove.someLabels) } reproDataPlotFixedConc <- function(x, xlab, ylab, main, concentration, style = "generic", addlegend = FALSE, remove.someLabels = FALSE) { dataPlotFixedConc(x, xlab, ylab, main, "Nreprocumul", concentration, style, addlegend, remove.someLabels) }
util_warn_unordered <- function(x, varname) { if (missing(varname)) varname <- as.character(substitute(x)) if (sum(dim(x) != 1) > 1) { util_error( "util_warn_unordered only works on effectively one-dimensional input") } warn <- FALSE if (is.factor(x)) { if (!is.ordered(x)) { warn <- TRUE } } else if (!is.numeric(x)) { if (all(DATA_TYPES_OF_R_TYPE[class(x)] != DATA_TYPES$DATETIME)) { warn <- TRUE } } if (warn) { util_warning( c( "Don't know, how to compare values of %s (%s) -- comparisons", "may still be possbile, but they could be meaningless." ), dQuote(varname), paste0(sQuote(unique(c(class(x), typeof(x)))), collapse = ", "), applicability_problem = TRUE ) } invisible(NULL) }
rtrapezoid <- function(n, min = 0, mode1 = 1/3, mode2 = 2/3, max = 1, n1 = 2, n3 = 2, alpha = 1) { out <- qtrapezoid(p = runif(n), min = min, mode1 = mode1, mode2 = mode2, max = max, n1 = n1, n3 = n3, alpha = alpha) return(out) }
NULL setClassUnion("randomBlockSeq", members = c("rRtbdSeq", "rRpbrSeq")) setMethod("show", "randomBlockSeq", function(object) { cat("\nObject of class \"", class(object)[1],"\"\n\n", sep = "") cat("design =", getDesign(object), " \n") names <- slotNames(object) names <- names[!(names %in% c("M", "bc"))] for(name in names) { cat(name, "=", slot(object, name), "\n") } if (dim(object@M)[1] <= 3) { if (object@N <= 8) { sequences <- apply(getRandList(object), 1, function(x) paste(x, collapse = " ")) blockConst <- unlist(lapply(blocks(object), function(x) paste(x, collapse = " "))) } else { sequences <- apply(getRandList(object), 1, function(x) paste(c(x[1:8], "..."), collapse=" ")) blockConst <- unlist(lapply(blocks(object), function(x) { if (length(x) <= 5) { return(paste(x, collapse = " ")) } else { return(paste(c(x[1:5], "..."), collapse = " ")) } })) } print.data.frame <- function(m) { write.table(format(m, justify = "left"), row.names = F, col.names = T, quote = F) } cat("\n") print(data.frame("RandomizationSeqs" = paste(sequences, "\t"), BlockConst = blockConst)) } else { numberSeq <- dim(object@M)[1] object@M <- object@M[1:4, ] if (object@N <= 8) { sequences <- apply(getRandList(object)[1:3 , ], 1, function(x) paste(x, collapse = " ")) blockConst <- unlist(lapply(object@bc[1:3], function(x) paste(x, collapse = " "))) } else { sequences <- apply(getRandList(object)[1:3 , ], 1, function(x) paste(c(x[1:8], "..."), collapse = " ")) blockConst <- unlist(lapply(object@bc[1:3], function(x) { if (length(x) <= 5) { return(paste(x, collapse = " ")) } else { return(paste(c(x[1:5], "..."), collapse = " ")) } })) } sequences <- c(sequences, "...") blockConst <- c(blockConst, "...") cat("\nThe first 3 of", numberSeq, "sequences of M:\n") print.data.frame <- function(m) { write.table(format(m, justify = "left"), row.names = F, col.names = T, quote = F) } cat("\n") print(data.frame("RandomizationSeqs" = paste(sequences, "\t"), BlockConst = blockConst)) } })
context("create_pareto") data(words) table <- create_table(words$letter_count) plot <- create_pareto(table) test_that("plot has the proper structure", { expect_that(plot, is_a("gg")) expect_that(plot$labels$title, equals("Pareto Chart")) expect_that(plot$labels$subtitle, equals("")) expect_that(plot$labels$caption, equals("")) expect_that(plot$labels$x, equals("Groups")) expect_that(plot$labels$y, equals("Frequency")) }) test_that("plot uses correct data", { expect_that(table, equals(plot$data)) }) test_that("function returns an error", { expect_that(create_pareto(), throws_error()) })
knitr::opts_chunk$set( collapse = TRUE, comment = " out.width = "100%", tidy.opts = list(width.cutoff = 80), tidy = TRUE ) library(LoopRig) ovary_loops <- system.file("extdata/loops", "ovary_hg19.bedpe", package = "LoopRig", mustWork = TRUE) pancreas_loops <- system.file("extdata/loops", "pancreas_hg19.bedpe", package = "LoopRig", mustWork = TRUE) spleen_loops <- system.file("extdata/loops", "spleen_hg19.bedpe", package = "LoopRig", mustWork = TRUE) loops <- LoopsToRanges(ovary_loops, pancreas_loops, spleen_loops, custom_cols = 0, loop_names = c("ovary", "pancreas", "spleen")) head(loops, 1) class(loops) enhancers <- system.file("extdata/elements", "enhancers.bed", package = "LoopRig", mustWork = TRUE) promoters <- system.file("extdata/elements", "promoters.bed", package = "LoopRig", mustWork = TRUE) element_ranges <- ElementsToRanges(enhancers, promoters, element_names = c("enhancers", "promoters"), custom_cols = 1, custom_mcols = 4) head(element_ranges, 1) class(element_ranges) consensus_loops <- ConsensusLoops(loop_ranges = loops, stringency = 2, overlap_threshold = 1) head(consensus_loops, 1) length(loops) length(consensus_loops) class(consensus_loops) consensus_loops_dropped <- DropLoops(loop_ranges = consensus_loops, type = "loop_size", size = c(100000, 200000)) length(consensus_loops[[1]][[1]]) length(consensus_loops_dropped[[1]][[1]]) class(consensus_loops_dropped) linked_elements <- LinkedElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]]) linked_elements linked_elements_promoters <- LinkedElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]], range_out_y = TRUE) linked_elements_promoters class(linked_elements_promoters) stacked_elements <- StackedElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]]) stacked_elements stacked_elements_enhancers <- StackedElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]], range_out_x = TRUE) stacked_elements_enhancers class(stacked_elements_enhancers) scaffold_elements <- ScaffoldElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]]) scaffold_elements scaffold_elements_promoters <- ScaffoldElements(loop_ranges = consensus_loops, element_ranges_x = element_ranges[[1]], element_ranges_y = element_ranges[[2]], range_out_y = TRUE) scaffold_elements_promoters class(scaffold_elements_promoters)
kmeans.fd=function(fdataobj,ncl=2,metric=metric.lp ,dfunc=func.trim.FM,max.iter=100 ,par.metric=NULL,par.dfunc=list(trim=0.05) ,method="sample", cluster.size=5,draw=TRUE,...) { if (!is.fdata(fdataobj)) fdataobj=fdata(fdataobj) nas1<-is.na(fdataobj) if (any(nas1)) stop("fdataobj contain ",sum(nas1)," curves with some NA value \n") z<-fdataobj[["data"]] tt<-fdataobj[["argvals"]] rtt<-fdataobj[["rangeval"]] nr=nrow(z) nc=ncol(z) if (is.vector(ncl)) { len.ncl=length(ncl) if (len.ncl==1) { par.ini<- list() par.ini$fdataobj=fdataobj par.ini$method=method par.ini$ncl=ncl par.ini$metric=metric par.ini$draw=draw par.ini$max.comb = 1e6 par.ini$max.iter = max.iter if (!is.null(par.metric)) par.ini$par.metric<-par.metric par.ini$... <- par.metric out1=do.call(kmeans.center.ini,par.ini) lxm<-out1$lcenters out1$d=rbind(out1$z.dist,out1$z.dist[lxm,]) } else { ngroups <- length(ncl) lxm <- ncl xm <- z[lxm,] out1 <- list() out1$fdataobj <- fdataobj out1$ncl <- len.ncl if (is.null(par.metric)) par.metric <- list("p"=2,"w"=1) par.metric$fdata1 <- fdataobj mdist <- do.call(metric,par.metric) out1$z.dist <- mdist out1$d <- rbind(mdist,mdist[lxm,]) out1$centers <- fdataobj[ncl,] out1$lcenters <- ncl class(out1) <- "kmeans.fd" } } else if (is.fdata(ncl)) { lxm=NULL xm=ncl[["data"]] if (is.null(par.metric) ) par.metric=list("p"=2,"w"=1) par.metric$fdata1<-fdataobj mdist=do.call(metric,par.metric) par.metric2<-par.metric par.metric2$fdata2<-ncl mdist2=do.call(metric,par.metric2) out1 = list() out1$fdataobj<-fdataobj out1$centers = ncl out1$lcenters <- NULL ngroups=nrow(ncl) ncl = nrow(ncl) out1$d = rbind(mdist,t(mdist2)) class(out1) = "kmeans.fd" } ngroups=nrow(out1$centers[["data"]]) a=0;aa<-i<-1 same_centers=FALSE if (is.null(colnames(out1$d))) cnames<-colnames(out1$d)<-1:NCOL(out1$d) else cnames<-colnames(out1$d) while ((i<max.iter) && (!same_centers)) { iterar<-FALSE out3=kmeans.assig.groups(out1,draw=draw) names(out3$cluster) <- cnames tab <- table(out3$cluster) imin <- which.min(tab)[1] if (cluster.size > tab[imin] ) { warning(paste0(" One of the clusters only has ",tab[imin] , " curves and the minimum cluster size is ", cluster.size ,".\n The cluster is completed with the closest curves of the other clusters.")) iclust <- out3$cluster == imin dist.aux <- out1$d[imin,] icambios <- as.numeric(names(sort( out1$d[imin,])[1:cluster.size])) out1$d[imin,icambios]<- 0 out1$z.dist<-out1$d out3$cluster[icambios] <- imin out2<-out3 out1$cluster <- out3$cluster par.dfunc$fdataobj<-fdataobj[c(icambios)] out1$centers[imin]=do.call(dfunc,par.dfunc) iterar <-TRUE i=i+1 } out2=kmeans.centers.update(out1, group=out3$cluster , dfunc=dfunc, draw=draw , par.dfunc=par.dfunc ,...) if (!iterar){ same_centers <- out2$centers$data == out3$centers$data out1$centers <- out2$centers i=i+1 } } out<-list("cluster"=out2$cluster,"centers"=out2$centers) return(out) }
NULL clusters.key <- 'monocle3_clusters' partitions.key <- 'monocle3_partitions' as.cell_data_set <- function(x, ...) { CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github') UseMethod(generic = 'as.cell_data_set', object = x) } as.cell_data_set.Seurat <- function( x, assay = DefaultAssay(object = x), reductions = AssociatedDimReducs(object = x, assay = assay), default.reduction = DefaultDimReduc(object = x, assay = assay), graph = paste0(assay, '_snn'), group.by = NULL, ... ) { cds <- as( object = as.SingleCellExperiment(x = x, assay = assay), Class = 'cell_data_set' ) if (is.null(x = SummarizedExperiment::assays(x = cds)$counts)) { SummarizedExperiment::assays(x = cds)$counts <- SummarizedExperiment::assays(x = cds)[[1]] } if (!"Size_Factor" %in% colnames(x = SummarizedExperiment::colData(x = cds))) { size.factor <- paste0('nCount_', assay) if (size.factor %in% colnames(x = x[[]])) { SummarizedExperiment::colData(x = cds)$Size_Factor <- x[[size.factor, drop = TRUE]] } } SingleCellExperiment::reducedDims(x = cds)[SingleCellExperiment::reducedDimNames(x = cds)] <- NULL reductions <- intersect( x = reductions, y = AssociatedDimReducs(object = x, assay = assay) ) for (reduc in reductions) { SingleCellExperiment::reducedDims(x = cds)[[toupper(x = reduc)]] <- Embeddings(object = x[[reduc]]) loadings <- Loadings(object = x[[reduc]]) if (!IsMatrixEmpty(x = loadings)) { slot(object = cds, name = 'preprocess_aux')[['gene_loadings']] <- loadings } stdev <- Stdev(object = x[[reduc]]) if (length(x = stdev)) { slot(object = cds, name = 'preprocess_aux')[['prop_var_expl']] <- stdev } } if (!is.null(x = group.by)) { Idents(object = x) <- group.by } clusters.list <- if (is.null(x = group.by) && all(c(clusters.key, partitions.key) %in% colnames(x = x[[]]))) { message("Using existing Monocle 3 cluster membership and partitions") list( partitions = factor(x = x[[partitions.key, drop = TRUE]]), clusters = factor(x = x[[clusters.key, drop = TRUE]]) ) } else if (graph %in% names(x = x)) { g <- igraph::graph_from_adjacency_matrix( adjmatrix = x[[graph]], weighted = TRUE ) warning( "Monocle 3 trajectories require cluster partitions, which Seurat does not calculate. Please run 'cluster_cells' on your cell_data_set object", call. = FALSE, immediate. = TRUE ) partitions <- rep_len(x = 1, length.out = ncol(x = x)) list( cluster_result = list( g = g, relations = NULL, distMatrix = 'matrix', coord = NULL, edge_links = NULL, optim_res = list( membership = as.integer(x = Idents(object = x)), modularity = NA_real_ ) ), partitions = factor(x = partitions), clusters = Idents(object = x) ) } else { list() } if (length(x = clusters.list)) { slot(object = cds, name = 'clusters')[[toupper(x = default.reduction)]] <- clusters.list } return(cds) } as.Seurat.cell_data_set <- function( x, counts = 'counts', data = NULL, assay = 'RNA', project = 'cell_data_set', loadings = NULL, clusters = NULL, ... ) { CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github') object <- suppressWarnings(expr = as.Seurat( x = as(object = x, Class = 'SingleCellExperiment'), assay = assay, counts = counts, data = data, project = project )) lds.reduc <- ifelse( test = is.null(x = loadings), yes = grep( pattern = 'pca', x = SingleCellExperiment::reducedDimNames(x = x), ignore.case = TRUE, value = TRUE ), no = loadings ) if (length(x = lds.reduc) && !is.na(x = lds.reduc)) { loadings <- slot(object = x, name = 'preprocess_aux')[['gene_loadings']] if (!is.null(x = loadings)) { Loadings(object = object[[lds.reduc]], projected = FALSE) <- loadings } } if (length(x = slot(object = x, name = 'clusters'))) { clusters <- clusters %||% DefaultDimReduc(object = object) object[[clusters.key]] <- Idents(object = object) <- monocle3::clusters( x = x, reduction_method = clusters ) object[[partitions.key]] <- monocle3::partitions( x = x, reduction_method = clusters ) graph <- slot(object = x, name = 'clusters')[[clusters]]$cluster_result$g[] try( expr = { graph <- as.Graph(x = graph) DefaultAssay(object = graph) <- DefaultAssay(object = object) object[[paste0(DefaultAssay(object = graph), '_monocle3_graph')]] <- graph }, silent = TRUE ) try( expr = object[['monocle3_pseudotime']] <- monocle3::pseudotime( x = cds, reduction_method = clusters ), silent = TRUE ) } return(object) } LearnGraph <- function(object, reduction = DefaultDimReduc(object = object), ...) { CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github') if (reduction != 'UMAP') { if ('UMAP' %in% Reductions(object = object)) { '' } reduc <- object[[reduction]] suppressWarnings(expr = object[['UMAP']] <- reduc) } cds <- as.cell_data_set( x = object, assay = DefaultAssay(object = object[['UMAP']]), reductions = 'UMAP', default.reduction = 'UMAP' ) cds <- monocle3::learn_graph(cds = cds, ...) return(cds) }
LARSModel <- function( type = c("lasso", "lar", "forward.stagewise", "stepwise"), trace = FALSE, normalize = TRUE, intercept = TRUE, step = numeric(), use.Gram = TRUE ) { type <- match.arg(type) MLModel( name = "LARSModel", label = "Least Angle Regression", packages = "lars", response_types = "numeric", predictor_encoding = "model.matrix", params = new_params(environment()), gridinfo = new_gridinfo( param = "step", get_values = c( function(n, data, ...) seq_nvars(data, LARSModel, n) ) ), fit = function(formula, data, weights, step = NULL, ...) { x <- model.matrix(data, intercept = FALSE) y <- response(data) if (is.null(step)) { model_fit <- lars::lars(x, y, ...) model_fit$step <- length(model_fit$df) } else { model_fit <- lars::lars(x, y, max.steps = ceiling(step), ...) model_fit$step <- step } model_fit }, predict = function(object, newdata, ...) { newx <- model.matrix(newdata, intercept = FALSE) predict(object, newx = newx, s = object$step, type = "fit")$fit } ) } MLModelFunction(LARSModel) <- NULL
expected <- eval(parse(text="structure(c(0.00100000000111322, 0.0843333333343708, 0.167666666667856, 0.251000000001113, 0.334333333334371, 0.417666666667856, 0.501000000001113, 0.584333333334371, 0.667666666667856, 0.751000000001113, 0.834333333334371, 0.917666666667856, 0.00100000000111322, 0.0843333333343708, 0.167666666667856, 0.251000000001113, 0.334333333334371, 0.417666666667856, 0.501000000001113, 0.584333333334371, 0.667666666667856, 0.751000000001113, 0.834333333334371, 0.917666666667856, 0.00100000000111322), .Tsp = c(1976, 1978, 12), class = \"ts\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(1976.001, 1976.08433333333, 1976.16766666667, 1976.251, 1976.33433333333, 1976.41766666667, 1976.501, 1976.58433333333, 1976.66766666667, 1976.751, 1976.83433333333, 1976.91766666667, 1977.001, 1977.08433333333, 1977.16766666667, 1977.251, 1977.33433333333, 1977.41766666667, 1977.501, 1977.58433333333, 1977.66766666667, 1977.751, 1977.83433333333, 1977.91766666667, 1978.001), .Tsp = c(1976, 1978, 12), class = \"ts\"), 1)")); do.call(`%%`, argv); }, o=expected);
`calibrate.ordisurf` <- function(object, newdata, ...) { if (missing(newdata)) fit <- predict(object, type = "response", ...) else { if (is.vector(newdata) && length(newdata) == 2) newdata = data.frame(x1 = newdata[1], x2 = newdata[2]) else{ if (NCOL(newdata) < 2) stop("needs a matrix or a data frame with two columns") newdata <- data.frame(x1 = newdata[,1], x2 = newdata[,2]) } fit <- predict(object, newdata = newdata, type = "response", ...) } fit }
getwms <- function(x, provs, update_cache, cache_dir, verbose, res, transparent) { bbox <- as.double(sf::st_bbox(x)) dimx <- (bbox[3] - bbox[1]) dimy <- (bbox[4] - bbox[2]) maxdist <- max(dimx, dimy) center <- c(bbox[1] + dimx / 2, bbox[2] + dimy / 2) bboxsquare <- c( center[1] - maxdist / 2, center[2] - maxdist / 2, center[1] + maxdist / 2, center[2] + maxdist / 2 ) class(bboxsquare) <- "bbox" q <- provs[provs$field == "url_static", "value"] q <- gsub("{bbox}", paste0(bboxsquare, collapse = ","), q, fixed = TRUE) q <- gsub("512", as.character(res), q) src <- unique(provs$provider) ext <- "jpeg" if (length(grep("png", q)) > 0) { ext <- "png" } else if (length(grep("jpg", q)) > 0) { ext <- "jpg" } filename <- paste0( src, "_bbox3857_res", res, "_", paste0(bboxsquare, collapse = "_"), ".", ext ) filename <- file.path(cache_dir, filename) if (isFALSE(file.exists(filename)) | isTRUE(update_cache)) { if (verbose) { message("Downloading from \n", q, "\n to cache dir \n", cache_dir) } download.file( url = q, destfile = filename, mode = "wb", quiet = !verbose ) } else { if (verbose) { message("Requested tile already cached on \n", cache_dir) } } img <- png::readPNG(filename) * 255 if (dim(img)[3] == 4 && transparent) { nrow <- dim(img)[1] for (i in seq_len(nrow)) { row <- img[i, , ] alpha <- row[, 4] == 0 row[alpha, ] <- NA img[i, , ] <- row } } r_img <- suppressWarnings(terra::rast(img)) if (is.null(terra::RGB(r_img))) { terra::RGB(r_img) <- c(1, 2, 3) } terra::ext(r_img) <- terra::ext(bboxsquare[c(1, 3, 2, 4)]) terra::crs(r_img) <- "epsg:3857" return(r_img) } getwmts <- function(x, provs, update_cache, cache_dir, verbose, res, zoom, zoommin, type, transparent) { x <- sf::st_transform(x, 4326) bbx <- sf::st_bbox(x) if (is.null(zoom)) { gz <- slippymath::bbox_tile_query(bbx) zoom <- min(gz[gz$total_tiles %in% 4:10, "zoom"]) + zoommin if (verbose) { message("Auto zoom level: ", zoom) } } if ("minZoom" %in% provs$field) { minZoom <- as.numeric(provs[provs$field == "minZoom", "value"]) if (zoom < minZoom) { zoom <- max(zoom, minZoom) if (verbose) { message( "\nSwitching. Minimum zoom for this provider is ", zoom, "\n" ) } } } tile_grid <- slippymath::bbox_to_tile_grid(bbox = bbx, zoom = zoom) q <- provs[provs$field == "url_static", "value"] ext <- "jpeg" if (length(grep("png", q)) > 0) { ext <- "png" } else if (length(grep("jpg", q)) > 0) { ext <- "jpg" } if (verbose) { message("Caching tiles on ", cache_dir) } images <- apply( X = tile_grid$tiles, MARGIN = 1, FUN = dl_t, z = tile_grid$zoom, ext = ext, src = type, q = q, verbose = verbose, cache_dir = cache_dir, update_cache = update_cache ) rout <- compose_tile_grid(tile_grid, ext, images, transparent) return(rout) } compose_tile_grid <- function(tile_grid, ext, images, transparent) { bricks <- vector("list", nrow(tile_grid$tiles)) for (i in seq_along(bricks)) { bbox <- slippymath::tile_bbox( tile_grid$tiles$x[i], tile_grid$tiles$y[i], tile_grid$zoom ) img <- images[i] if (ext == "png") { img <- png::readPNG(img) * 255 if (dim(img)[3] == 4 && transparent) { nrow <- dim(img)[1] for (j in seq_len(nrow)) { row <- img[j, , ] alpha <- row[, 4] == 0 row[alpha, ] <- NA img[j, , ] <- row } } } r_img <- suppressWarnings(terra::rast(img)) r_img <- suppressWarnings(terra::rast(img)) if (is.null(terra::RGB(r_img))) { terra::RGB(r_img) <- c(1, 2, 3) } terra::ext(r_img) <- terra::ext(bbox[c( "xmin", "xmax", "ymin", "ymax" )]) bricks[[i]] <- r_img } if (length(bricks) == 1) { rout <- bricks[[1]] rout <- terra::merge(rout, rout) } else { rout <- do.call(terra::merge, bricks) } terra::RGB(rout) <- c(1, 2, 3) terra::crs(rout) <- "epsg:3857" return(rout) } dl_t <- function(x, z, ext, src, q, verbose, cache_dir, update_cache) { outfile <- paste0(cache_dir, "/", src, "_", z, "_", x[1], "_", x[2], ".", ext) if (!file.exists(outfile) | isTRUE(update_cache)) { q <- gsub( pattern = "{x}", replacement = x[1], x = q, fixed = TRUE ) q <- gsub( pattern = "{y}", replacement = x[2], x = q, fixed = TRUE ) q <- gsub( pattern = "{z}", replacement = z, x = q, fixed = TRUE ) if (verbose) { message("Downloading ", q, "\n") } download.file( url = q, destfile = outfile, quiet = TRUE, mode = "wb" ) } else if (verbose) { message("Tile cached on ", outfile) } return(outfile) }
"fun.auto.bimodal.ml"<- function (data, per.of.mix = 0.01, clustering.m = clara, init1.sel = "rprs", init2.sel = "rprs", init1=c(-1.5, 1.5), init2=c(-1.5, 1.5), leap1=3, leap2=3, fun1 = "runif.sobol", fun2 = "runif.sobol", no = 10000,max.it=5000,optim.further="Y") { data.mod <- fun.class.regime.bi(data, per.of.mix, clustering.m) data1 <- data.mod$data.a data2 <- data.mod$data.b prop <- length(data1)/(length(data1) + length(data2)) if (init1.sel == "rprs") { selc1 <- "rs" param1 <- "rs" first.fit <- fun.RPRS.ml(data = data1, rs.init = init1, leap = leap1, FUN = fun1, no = no) } if (init1.sel == "rmfmkl") { selc1 <- "fmkl" param1 <- "fmkl" first.fit <- fun.RMFMKL.ml(data = data1, fmkl.init = init1, leap = leap1, FUN = fun1, no = no) } if (init1.sel == "star") { selc1 <- "fmkl" param1 <- "fmkl" first.fit <- starship(data1)$lambda } if (init2.sel == "rprs") { selc2 <- "rs" param2 <- "rs" second.fit <- fun.RPRS.ml(data = data2, rs.init = init2, leap = leap2, FUN = fun2, no = no) } if (init2.sel == "rmfmkl") { selc2 <- "fmkl" param2 <- "fmkl" second.fit <- fun.RMFMKL.ml(data = data2, fmkl.init = init2, leap = leap2, FUN = fun2, no = no) } if (init2.sel == "star") { selc2 <- "fmkl" param2 <- "fmkl" second.fit <- starship(data2)$lambda } result <- optim(c(first.fit, second.fit, prop), optim.fun5, data = data, param1 = param1, param2 = param2, control = list(maxit = max.it)) result <- optim(c(result$par), optim.fun5, data = data, param1 = param1, param2 = param2, control = list(maxit = max.it)) if(optim.further=="Y"){ result<-optim(c(result$par), optim.fun.bi.final, data = data, param1 = param1, param2 = param2, control = list(maxit = max.it)) } return(result) }
`nseconds` <- function(x) { length(endpoints(x,on='seconds'))-1 } `nminutes` <- function(x) { length(endpoints(x,on='minutes'))-1 } `nhours` <- function(x) { length(endpoints(x,on='hours'))-1 } `ndays` <- function(x) { length(endpoints(x,on='days'))-1 } `nweeks` <- function(x) { length(endpoints(x,on='weeks'))-1 } `nmonths` <- function(x) { length(endpoints(x,on='months'))-1 } `nquarters` <- function(x) { length(endpoints(x,on='quarters'))-1 } `nyears` <- function(x) { length(endpoints(x,on='years'))-1 }
NULL confint.lm_mat <- function(object, parm, level = 0.95, ...){ confint.summary.lm_mat(object = summary(object), parm = parm, level = level) } confint.summary.lm_mat <- function(object, parm, level = 0.95, ...){ pnames <- rownames(object$coefficients) if(missing(parm)){ parm <- pnames }else if (is.numeric(parm)){ parm <- pnames[parm] } lower <- object$coefficients[parm,"Estimate"] - qt((1 - level) / 2, df = object$ftest["n"] - 2, lower.tail = F) * object$coefficients[parm,"Std. Error"] upper <- object$coefficients[parm,"Estimate"] + qt((1 - level) / 2, df = object$ftest["n"] - 2, lower.tail = F) * object$coefficients[parm,"Std. Error"] ci <- cbind(lower, upper) dimnames(ci) <- list(parm, paste(round2char(c((1 - level) / 2, 1 - (1 - level) / 2) * 100, digits = 1), "%")) ci }
summaryP <- function(formula, data=NULL, subset=NULL, na.action=na.retain, sort=TRUE, asna=c('unknown', 'unspecified'), ...) { formula <- Formula(formula) Y <- if(length(subset)) model.frame(formula, data=data, subset=subset, na.action=na.action) else model.frame(formula, data=data, na.action=na.action) X <- model.part(formula, data=Y, rhs=1) Y <- model.part(formula, data=Y, lhs=1) nY <- NCOL(Y) nX <- NCOL(X) namY <- names(Y) if(nX == 0) X <- data.frame(x=rep(1, NROW(Y))) else { i <- apply(is.na(X), 1, any) if(any(i)) { X <- X[! i,, drop=FALSE] Y <- Y[! i,, drop=FALSE] } } ux <- unique(X) Z <- NULL n <- nrow(X) Lev <- character(0) if(sort) { mfreq <- list() for(ny in namY) { y <- Y[[ny]] if(!inherits(y, 'ynbind') && !inherits(y, 'pBlock')) { if(length(asna) && (is.factor(y) || is.character(y))) y[y %in% asna] <- NA freq <- table(y) counts <- as.numeric(freq) names(counts) <- names(freq) mfreq[[ny]] <- - sort(- counts) } } } ylevels.to.exclude1 <- NULL for(ny in namY) { y <- Y[[ny]] la <- label(y) if(la == '') la <- ny tab <- table(y) tab <- structure(as.numeric(tab), names=names(tab)) if(length(tab) == 2) ylevels.to.exclude1 <- rbind(ylevels.to.exclude1, data.frame(var=la, val=names(tab)[which.max(tab)])) } for(i in 1 : nrow(ux)) { j <- rep(TRUE, n) if(nX > 0) for(k in 1 : nX) j <- j & (X[[k]] == ux[i, k]) for(k in 1 : nY) { y <- Y[[k]] y <- if(is.matrix(y)) y[j,, drop=FALSE] else y[j] if(inherits(y, 'ynbind') || inherits(y, 'pBlock')) { overlab <- attr(y, 'label') labs <- attr(y, 'labels') z <- NULL for(iy in 1 : ncol(y)) { tab <- table(y[, iy]) no <- as.numeric(sum(tab)) if(inherits(y, 'ynbind')) { d <- data.frame(var=overlab, val=labs[iy], freq=as.numeric(tab['TRUE']), denom=no) Lev <- c(Lev, as.character(labs[iy])) } else { d <- data.frame(var=overlab, val=names(tab), freq=as.numeric(tab), denom=no) Lev <- c(Lev, names(tab)) } z <- rbind(z, d) } } else { if(length(asna) && (is.factor(y) || is.character(y))) y[y %in% asna] <- NA tab <- table(y) ny <- namY[k] la <- label(y) if(la == '') la <- ny lev <- names(tab) no <- as.numeric(sum(tab)) if(sort) lev <- reorder(lev, (mfreq[[ny]])[lev]) Lev <- c(Lev, as.character(lev)) z <- data.frame(var = unname(la), val = lev, freq = as.numeric(tab), denom = no, stringsAsFactors=TRUE) } if(nX > 0) for(k in 1: nX) z[[names(ux)[k]]] <- if(is.character(ux[i,k])) factor(ux[i, k]) else ux[i,k] Z <- rbind(Z, z) } } Z$val <- factor(Z$val, levels=unique(Lev)) yl <- ylevels.to.exclude1 iex <- integer(0) if(length(yl)) { for(i in 1 : nrow(Z)) { exi <- FALSE for(j in 1 : nrow(yl)) if(as.character(Z$var[i]) == as.character(yl$var[j]) && as.character(Z$val[i]) == as.character(yl$val[j])) exi <- TRUE if(exi) iex <- c(iex, i) } } structure(Z, class=c('summaryP', 'data.frame'), formula=formula, nX=nX, nY=nY, rows.to.exclude1=iex) } plot.summaryP <- function(x, formula=NULL, groups=NULL, marginVal=NULL, marginLabel=marginVal, refgroup=NULL, exclude1=TRUE, xlim=c(-.05, 1.05), text.at=NULL, cex.values=0.5, key=list(columns=length(groupslevels), x=.75, y=-.04, cex=.9, col=trellis.par.get('superpose.symbol')$col, corner=c(0,1)), outerlabels=TRUE, autoarrange=TRUE, col=colorspace::rainbow_hcl, ...) { X <- x at <- attributes(x) Form <- at$formula nX <- at$nX nY <- at$nY groupslevels <- if(length(groups)) levels(x[[groups]]) condvar <- setdiff(names(X), c('val', 'freq', 'denom', groups)) numu <- function(x) if(is.factor(x)) length(levels(x)) else length(unique(x[! is.na(x)])) if(exclude1 && length(at$rows.to.exclude1)) X <- X[- at$rows.to.exclude1, , drop=FALSE] if(autoarrange && length(condvar) > 1) { nlev <- sapply(X[condvar], numu) condvar <- condvar[order(nlev)] } if(grType() == 'plotly') { condvar <- setdiff(condvar, 'var') if(length(condvar) > 1) stop('with options(grType="plotly") does not handle > 1 stratification variable') if(length(condvar) == 1 && length(marginVal)) { X$Big <- X[[condvar]] == marginVal if(marginLabel != marginVal) X[[condvar]] <- ifelse(X$Big, marginLabel, as.character(X[[condvar]])) } X$.gg. <- if(length(groups)) { if(length(condvar) == 1 && length(marginVal)) ifelse(X$Big, as.character(X[[groups]]), paste0(X[[groups]], ' stratified<br>by ', condvar[1])) else X[[groups]] } p <- with(X, dotchartpl(freq / denom, major = var, minor = val, group = if(length(groups)) .gg., mult = if(length(condvar) > 0) X[[condvar]], big = if(length(condvar) == 1 && length(marginVal)) Big, num = freq, denom = denom, refgroup = refgroup, xlim = xlim, col = col, nonbigtracename=if(length(condvar)) paste0('Stratified by\n', condvar[1]) else 'Stratified Estimates', ...) ) return(p) } form <- if(length(formula)) formula else as.formula( paste('val ~ freq', paste(condvar, collapse=' * '), sep=' | ')) pan <- function(x, y, subscripts, groups=NULL, ...) { y <- as.numeric(y) denom <- X$denom[subscripts] panel.dotplot(x/denom, y, subscripts=subscripts, groups=groups, ...) if(length(cex.values) && cex.values > 0) { col <- if(length(groups)) trellis.par.get('superpose.symbol')$col else trellis.par.get('dot.symbol')$col longest.string <- paste(max(x), max(denom), sep='/ ') length.longest <- unit(1, 'strwidth', longest.string) xpos <- unit(1, 'npc') - unit(1, 'mm') txt <- if(length(groups)) { groups <- groups[subscripts] tx <- '' ig <- 0 xpos <- xpos - length(levels(groups)) * length.longest for(g in levels(groups)) { ig <- ig + 1 i <- groups == g fr <- paste(x[i], denom[i], sep='/') xpos <- xpos + length.longest grid.text(fr, xpos, unit(y, 'native') - unit(1, 'mm'), just=c('right','top'), gp=gpar(cex=cex.values, col=col[ig])) } } else { fr <- paste(x, denom, sep='/') grid.text(fr, xpos, unit(y, 'native') - unit(1, 'mm'), gp=gpar(cex=cex.values, col=col[1]), just=c('right','top')) } } } scal <- list(y='free', rot=0) scal$x <- if(length(text.at)) { at <- pretty(xlim) list(limits=range(c(xlim, text.at)), at=at[at >= -0.0001 & at <= 1.0001]) } else list(limits=xlim) d <- if(!length(groups)) dotplot(form, data=X, scales=scal, panel=pan, xlab='Proportion', ...) else eval(parse(text= sprintf("dotplot(form, groups=%s, data=X, scales=scal, panel=pan, auto.key=key, xlab='Proportion', ...)", groups) )) if(length(dim(d)) == 2) d <- latticeExtra::useOuterStrips(d) if(condvar[length(condvar)] == 'var') { vars <- levels(X$var) nv <- length(vars) h <- integer(nv) for(i in 1 : nv) h[i] <- length(unique((X$val[X$var == vars[i]]))) d <- latticeExtra::resizePanels(d, h = h + 1) } d } ggplot.summaryP <- function(data, mapping, groups=NULL, exclude1=TRUE, xlim=c(0, 1), col=NULL, shape=NULL, size=function(n) n ^ (1/4), sizerange=NULL, abblen=5, autoarrange=TRUE, addlayer=NULL, ..., environment) { X <- data class(X) <- setdiff(class(X), 'summaryP') at <- attributes(X) Form <- at$formula nX <- at$nX nY <- at$nY groupslevels <- if(length(groups)) levels(X[[groups]]) condvar <- setdiff(names(X), c('val', 'freq', 'denom', groups)) numu <- function(x) if(is.factor(x)) length(levels(x)) else length(unique(x[! is.na(x)])) if(exclude1 && length(at$rows.to.exclude1)) X <- X[- at$rows.to.exclude1, , drop=FALSE] if(autoarrange && length(condvar) > 1) { nlev <- sapply(X[condvar], numu) condvar <- condvar[order(nlev)] } fnvar <- '' lvar <- levels(X$var) i <- 0 for(v in lvar) { maxlen <- nchar(v) if(maxlen > abblen) { nlev <- length(unique(X$val[X$var == v])) if(nlev == 1) { i <- i + 1 w <- paste('(', i, ')', sep='') if(i > 1) fnvar <- paste(fnvar, '; ', sep='') fnvar <- paste(fnvar, w, ' ', v, sep='') levels(X$var)[levels(X$var) == v] <- w } } } spl <- function(x) { u <- levels(x) n <- length(u) utrans <- character(n); names(utrans) <- u for(w in u) utrans[w] <- paste(strwrap(w, 10), collapse='\n') factor(x, u, utrans) } X$var <- spl(X$var) if(length(condvar) == 2) { othvar <- setdiff(condvar, 'var') X[[othvar]] <- spl(X[[othvar]]) } N <- X$denom rN <- range(N) ratioN <- rN[2] / rN[1] if(diff(rN) < 10 | (ratioN < 1.2)) size <- NULL X$hov <- paste0(round(X$freq / X$denom, 3), '&emsp;', markupSpecs$html$frac(X$freq, X$denom, size=90)) if(length(groups)) X$hov <- paste0(X[[groups]], '<br>', X$hov) k <- 'ggplot(X, aes(x=freq / denom, y=val, text=hov' if(length(groups)) k <- paste(k, sprintf(', color=%s, shape=%s', groups, groups)) k <- paste(k, '))') if(length(size)) { k <- paste(k, if(length(size)) 'geom_point(aes(size = N))' else 'geom_point()', sep=' + ') Ns <- X$denom if(! length(sizerange)) { fn <- if(is.function(size)) size else sqrt sizerange <- c(max(0.7, 2.7 / fn(ratioN)), 3.25) } if(is.function(size)) { X$N <- size(Ns) Ns0 <- Ns[Ns > 0] uN <- unique(sort(Ns0)) Nbreaks <- if(length(uN) < 8) uN else unique(round(quantile(Ns0, (0 : 6) / 6, type=1))) Nbreakst <- size(Nbreaks) k <- paste(k, 'scale_size_continuous(breaks=Nbreakst, labels=format(Nbreaks), range=sizerange)', sep=' + ') } else { k <- paste(k, 'scale_size_discrete(range = sizerange)', sep=' + ') X$N <- cut2(Ns, g=size) } } else k <- paste(k, 'geom_point()', sep=' + ') p <- eval(parse(text=k)) if(length(addlayer)) p <- p + addlayer if('var' %nin% condvar) stop('program logic error') if(length(condvar) == 1) p <- p + facet_grid(var ~ . , scales='free_y', space='free_y') else { p <- p + facet_grid(as.formula(sprintf('var ~ %s', othvar)), scales='free_y', space='free_y') } p <- p + xlim(xlim) + xlab('Proportion') + ylab('') if(length(col)) p <- p + scale_color_manual(values=col) if(length(shape)) p <- p + scale_shape_manual(values=shape) if(fnvar != '') attr(p, 'fnvar') <- fnvar p } latex.summaryP <- function(object, groups=NULL, exclude1=TRUE, file='', round=3, size=NULL, append=TRUE, ...) { class(object) <- 'data.frame' rte <- attr(object, 'rows.to.exclude1') if(exclude1 && length(rte)) object <- object[- rte, , drop=FALSE] if(! append) cat('', file=file) p <- ifelse(object$denom == 0, '', format(round(object$freq / object$denom, round))) object$y <- paste(p, ' {\\scriptsize$\\frac{', format(object$freq), '}{', format(object$denom), '}$}', sep='') object$freq <- object$denom <- NULL stratvar <- setdiff(names(object), c('var', 'val', 'y', groups)) svar <- if(! length(stratvar)) as.factor(rep('', nrow(object))) else { if(length(stratvar) == 1) object[[stratvar]] else do.call('interaction', list(object[stratvar], sep=' ')) } object$stratvar <- svar object <- object[, c('var', 'val', 'y', groups, 'stratvar')] nl <- 0 slev <- levels(svar) nslev <- length(slev) for(i in 1 : nslev) { if(nslev > 1) cat('\n\\vspace{1ex}\n\\begin{minipage}{\\linewidth}\n\\textbf{', slev[i], '}\n\\vspace{1ex}\n\n', sep='', file=file, append=TRUE) x <- object[svar == slev[i], colnames(object) != 'stratvar'] if(length(groups)) { ord <- function(v) { v <- as.character(v) un <- unique(v) vn <- 1 : length(un) names(vn) <- un vn[v] } varn <- ord(x$var) valn <- ord(x$val) r <- reshape(x, timevar=groups, direction='wide', idvar=c('var', 'val')) ir <- order(varn[as.character(r$var)], valn[as.character(r$val)]) r <- r[ir, ] lev <- levels(x[[groups]]) r <- r[c('var', 'val', paste('y', lev, sep='.'))] nl <- length(lev) w <- latex(r[colnames(r) != 'var'], table.env=FALSE, file=file, append=TRUE, rowlabel='', rowname=rep('', nrow(r)), rgroup=levels(r$var), n.rgroup=as.vector(table(r$var)), size=size, colheads=c(' ', lev), center='none') } else { w <- latex(x[colnames(x) != 'var'], table.env=FALSE, file=file, append=TRUE, rowlabel='', rowname=rep('', nrow(x)), rgroup=levels(x$var), n.rgroup=as.vector(table(x$var)), size=size, colheads=c(' ', ' '), center='none') } if(nslev > 1) cat('\\end{minipage}\n', file=file, append=TRUE) } attr(w, 'ngrouplevels') <- nl attr(w, 'nstrata') <- nslev w }
find_step <- function(design, step, verb) { if (is.numeric(step) && step <= length(design) && step > 0) return(step) if (is.character(step)) { design <- names(design) } w <- vapply(design, identical, FALSE, step) w <- which(w) if (length(w) == 0) { stop("Could not find step to ", verb, " in design") } w[1] } NULL insert_step <- function(design, new_step, before, after) { check_design_class_single(design) if (missing(before)) before <- NULL if (missing(after)) after <- NULL insert_step_(design, new_step, before, after, enexpr(new_step)) } insert_step_ <- function(design, new_step, before = NULL, after = NULL, new_step_expr) { check_design_class_single(design) if (is.null(after)) { if (is.null(before)) { stop("Must provide either before or after to add_step()") } after <- find_step(design, before, "insert before") - 1 } else { after <- find_step(design, after, "insert after") } new_step <- wrap_step(new_step, new_step_expr) i <- seq_along(design) <= after steps <- c(design[i], new_step, design[!i], recursive = FALSE) construct_design(steps) } delete_step <- function(design, step) { check_design_class_single(design) i <- find_step(design, step, "delete") construct_design(design[-i]) } replace_step <- function(design, step, new_step) { check_design_class_single(design) i <- find_step(design, step, "replace") new_step <- wrap_step(new_step, enexpr(new_step)) design[i] <- new_step names(design)[i] <- names(new_step) construct_design(design) }
aqs_qa_blanks_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaBlanks", cbdate = cbdate, cedate = cedate ) blanks <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) blanks %<>% aqs_removeheader return(blanks) } aqs_qa_collocated_assessments_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaCollocatedAssessments", cbdate = cbdate, cedate = cedate ) colocatedsummary <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) colocatedsummary %<>% aqs_removeheader return(colocatedsummary) } aqs_qa_flowrateverification_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaFlowRateVerifications", cbdate = cbdate, cedate = cedate ) frv <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) frv %<>% aqs_removeheader return(frv) } aqs_qa_flowrateaudit_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaFlowRateAudits", cbdate = cbdate, cedate = cedate ) fra <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) fra %<>% aqs_removeheader return(fra) } aqs_qa_one_point_qc_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaOnePointQcRawData", cbdate = cbdate, cedate = cedate ) opqcc <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) opqcc %<>% aqs_removeheader return(opqcc) } aqs_qa_pep_audit_by_pqao <- function(parameter, bdate, edate, pqao_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, pqao_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaPepAudits", cbdate = cbdate, cedate = cedate ) pepaudit <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) pepaudit %<>% aqs_removeheader return(pepaudit) } aqs_qa_annualpeferomanceeval_by_pqao <- function(parameter, bdate, edate, pqao_code, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, pqao_code, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "qaAnnualPerformanceEvaluations" ) qaape <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) qaape %<>% aqs_removeheader return(qaape) } aqs_qa_annualperformanceevaltransaction_by_pqao <- function(parameter, bdate, edate, pqao_code, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, pqao_code, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, pqao_code = pqao_code, service = "transactionsQaAnnualPerformanceEvaluations" ) tqaape <- purrr::pmap(.l = params, .f = aqs_services_by_pqao) if (!return_header) tqaape %<>% aqs_removeheader return(tqaape) }
suppressMessages(library(RcppRedis)) redis <- new(Redis) key <- "RcppRedis:test:myexists" redis$set(key, 10) n <- redis$exists(key) expect_equal(n, 1) n <- redis$exists("thisKeyIsNotSet-test") expect_equal(n, 0) n <- redis$exec(paste("del", key)) expect_equal(n, 1)
coef(f1.glm1) exp(coef(f1.glm1))
skip_on_cran() require(testthat) context("YAFS") options(width = 500) options(useFancyQuotes=FALSE) source("REF-9-YAFS.R") if(!exists("edsurveyHome")) { if (Sys.info()[['sysname']] == "Windows") { edsurveyHome <- "C:/EdSurveyData/" } else { edsurveyHome <- "~/EdSurveyData/" } } if (!dir.exists(edsurveyHome)) { dir.create(edsurveyHome) } test_that("PISA YAFS data reads in correctly", { expect_silent(pisa <<- readPISA(path = file.path(edsurveyHome, "PISA", "2012"), database = "INT", countries = "usa", verbose = FALSE)) expect_silent(pisa_yafs <<- readPISA_YAFS(datPath = file.path(edsurveyHome, "PISA YAFS", "2016", "PISA_YAFS2016_Data.dat"), spsPath = file.path(edsurveyHome, "PISA YAFS", "2016", "PISA_YAFS2016_SPSS.sps"), esdf_PISA2012_USA = pisa)) expect_is(pisa_yafs, "edsurvey.data.frame") expect_equal(dim(pisa_yafs), c(4978, 1964)) expect_equal(pisa_yafs$country, "USA") expect_equal(pisa_yafs$year, "2016") }) context("PISA YAFS edsurveyTable") test_that("PISA YAFS edsurveyTable",{ lit <- edsurveyTable(formula = lit ~ 1, data=pisa_yafs, omittedLevels=TRUE, jrrIMax = Inf) withr::with_options(list(digits=7), out <- capture.output(lit)) expect_equal(out, lit.ref) }) context("PISA YAFS achivementLevel one PV") test_that("PISA YAFS edsurveyTable one PV",{ achievementLevels_Lit <- achievementLevels(achievementVars=c("lit"), aggregateBy=NULL, data=pisa_yafs, weightVar = "w_yfstuwt", jrrIMax = Inf) withr::with_options(list(digits=7), out <- capture.output(achievementLevels_Lit)) expect_equal(out, achievement.ref) }) context("PISA YAFS achivementLevel two PVs") test_that("PISA YAFS edsurveyTable two PVs",{ achievementLevels_tableA10 <- achievementLevels(achievementVars=c("num", "math"), aggregateBy="math", data=pisa_yafs, returnVarEstInputs=TRUE, returnCumulative=FALSE, jrrIMax = Inf, cutpoints = list( c("Customized ESO 2 and 3" = 226.00, "Customized ESO 4 and above" = 326.00), c("Customized PISA 2 and 4" = 420.07, "Customized PISA 5 and above" = 544.68))) withr::with_options(list(digits=7), out <- capture.output(achievementLevels_tableA10)) expect_equal(out, achievement2.ref) }) context("PISA YAFS cor.sdf two PVs") test_that("PISA YAFS cor.sdf two PVs",{ cor_lit.read <- cor.sdf(x = "lit", y="read", data=pisa_yafs) withr::with_options(list(digits=7), out <- capture.output(cor_lit.read)) expect_equal(out, cor.ref) }) context("PISA YAFS logit") test_that("PISA YAFS logits",{ logit_b_q26a.bq_q2 <- logit.sdf(formula = I(b_q26a %in% "No") ~ bq_q2, data = pisa_yafs, jrrIMax = Inf) withr::with_options(list(digits=7), out <- capture.output(logit_b_q26a.bq_q2)) expect_equal(out, logit.ref) })
indifference <- function(..., ncurves = 1, xmax, ymax, type = "normal", x, pointcol = 1, curve_names = TRUE, names, linecol, labels, generic = TRUE, geom = "text", geomcol = 1, geomfill = "white", main = NULL, sub = NULL, xlab = NULL, ylab = NULL, bg.col = "white"){ m <- FALSE match.arg(type, choices = c("normal", "psubs", "pcom")) if(missing(...)){ ncurve <- ncurves if(missing(xmax)){ xmax <- 9 } if(missing(ymax)){ ymax <- 9 } if(type == "normal") { curve <- data.frame(Hmisc::bezier(c(0.9, xmax - 6, xmax), c(ymax, ymax - 6, 0.9))) m <- TRUE } if(type == "psubs") { curve <- data.frame(x = c(0.9, xmax), y = c(ymax, 0.9)) m <- TRUE } if(type == "pcom") { curve <- data.frame(x = c(rep(0.9, 10), seq(0.9, 9, length.out = 10)), y = c(seq(0.9, 9, length.out = 10), rep(0.9, 10))) m <- TRUE } } else{ curve <- list(...) class <- vector("character", length(curve)) for(i in 1:length(curve)) { class[i] <- class(curve[[i]]) } if(any(class != "data.frame")) { stop("You can only pass data frames to the '...' argument") } ncurve <- length(curve) if(ncurve == 1){ m <- TRUE } } if(missing(names)) { names <- sapply(1:ncurves, function(i) paste0("I[", i, "]")) } if(missing(linecol)){ if(missing(...)){ linecol <- 1 } if(!missing(...) & ncurve == 1){ linecol <- 1 } if(!missing(...) & ncurve > 1){ linecol <- rep(1, ncurve) } } else { if(!missing(...) & length(linecol) == 1){ linecol <- rep(linecol, ncurve) } else { } } if(missing(labels) & !missing(x)){ labels <- LETTERS[1:length(x)] } if(!missing(x)){ if(any(x < 0) | any(x > max(data.frame(curve)$y))) { warning("There are values on the 'x' argument lower than 0 or greater than the maximun value of the curve") x <- x[x <= max(data.frame(curve)$y)] } if(type == "pcom") { warning("Intersections not available for perfect complements. Please add the points manually") } else { intersections <- tibble() if(missing(...) | length(curve) == 1) { for(i in 1:length(x)) { intersections <- intersections %>% bind_rows(curve_intersect(data.frame(x = c(0, 10000), y = rep(x[i], 2)), data.frame(curve))) } } else { intersections <- vector("list", ncurve) for(i in 1:ncurve){ for(j in 1:length(x)) { intersections[[i]][[j]] <- bind_rows(curve_intersect(data.frame(x = 1:1000, y = rep(x[j], nrow(curve[[1]]))), curve[[i]])) } } intersections <- bind_rows(intersections) } } } p <- ggplot(mapping = aes(x = x, y = y)) if(missing(...) | m){ for(i in 0:(ncurves - 1)) { p <- p + geom_line(data = data.frame(curve) + i, color = linecol, size = 1, linetype = 1) } } else { for(i in 1:length(curve)) { p <- p + geom_line(data = data.frame(curve[[i]]), color = linecol[i], size = 1, linetype = 1) } } if(curve_names == TRUE) { if(ncurves == 1) { p <- p + annotate(geom = "text", x = max(as.data.frame(curve)$x) + 0.5, y = min(as.data.frame(curve)$y), label = "I", size = 4, color = geomcol) } else { j <- 0 for(i in 1:ncurves){ p <- p + annotate(geom = "text", x = max(as.data.frame(curve)$x) + j + 0.5, y = min(as.data.frame(curve)$y) + j, label = names[i], parse = TRUE, size = 4, color = geomcol) j <- j + 1 } } } if(!missing(x) & type != "pcom"){ p <- p + geom_segment(data = intersections, aes(x = x, y = 0, xend = x, yend = y), lty = "dotted") + geom_segment(data = intersections, aes(x = 0, y = y, xend = x, yend = y), lty = "dotted") + geom_point(data = intersections, size = 3, color = pointcol) if(geom == "label") { for(i in 1:length(x)){ p <- p + annotate(geom = "label", x = unlist(intersections[1][i, ]) + 0.25, y = unlist(intersections[2][i, ]) + 0.25, label = rev(labels)[i], size = 4, fill = "white", color = geomcol) } } if(geom == "text") { for(i in 1:length(x)){ p <- p + annotate(geom = "text", x = unlist(intersections[1][i, ]) + 0.25, y = unlist(intersections[2][i, ]) + 0.25, label = rev(labels)[i], size = 4, color = geomcol) } } if(generic == FALSE) { p <- p + scale_x_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + 1), breaks = intersections$x, labels = round(intersections$x, 2)) + scale_y_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + 1), breaks = intersections$y, labels = round(intersections$y, 2)) } else { if(ncurve == 1 | missing(...)){ p <- p + scale_x_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves), breaks = intersections$x, labels = sapply(length(x):1, function(i) as.expression(bquote(X[.(LETTERS[i])])))) + scale_y_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves), breaks = intersections$y, labels = sapply(length(x):1, function(i) as.expression(bquote(Y[.(LETTERS[i])])))) } else { labels <- sapply(length(intersections$x):1, function(i) as.expression(bquote(X[.(LETTERS[i])]))) p <- p + scale_x_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves), breaks = intersections$x, labels = labels) + scale_y_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves), breaks = x, labels = sapply(length(x):1, function(i) as.expression(bquote(Y[.(LETTERS[i])])))) } } } else { p <- p + scale_x_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves)) + scale_y_continuous(expand = c(0, 0), limits = c(0, max(unlist(curve)) + ncurves)) } p <- p + labs(x = xlab, y = ylab, title = main, subtitle = sub) p <- p + theme_classic() + theme(plot.title = element_text(size = rel(1.3)), axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0), angle = 0, vjust = 1), axis.title.x = element_text(margin = margin(t = 0, r = 25, b = 0, l = 0), angle = 0, hjust = 1), plot.background = element_rect(fill = bg.col), plot.margin = margin(0.5, 1, 0.5, 0.5, "cm")) if(!missing(x)){ return(list(p = p, intersections = intersections, curve = curve)) } else { return(list(p = p, curve = curve)) } }
source(system.file("doc/normalization.R", package="psd"), echo=TRUE)
JohnsonJohnson library(forecast) ?ets fit1 = ets(JohnsonJohnson) fit1 JohnsonJohnson head(JohnsonJohnson) tail(JohnsonJohnson) (f1= forecast(fit1,h=10)) ?forecast.ets plot(f1, main='Johnson Shares', ylab='Quartery Earnings', xlab='Time', flty = 3) par(mfrow=c(1,1)) f2 = auto.arima(JohnsonJohnson) summary(f2) tail(JohnsonJohnson) forecast(f2,h=5) library(tseries) plot(JohnsonJohnson) ndiffs(JohnsonJohnson) plot(diff(JohnsonJohnson)) plot(Nile) plot(diff(Nile)) ndiffs(Nile) djj = diff(JohnsonJohnson) plot(djj) dnile = diff(Nile) plot(dnile) adf.test(djj) Acf(dnile) ?arima Pacf(dnile) fit3 = arima(Nile, order=c(0,1,1)) fit3 (fit3b = arima(Nile, order=c(1,1,1))) qqnorm(fit3$residuals) qqline(fit3$residuals) Box.test(fit3$residuals, type='Ljung-Box') forecast(fit3,4) Nile library(forecast) fit4 = auto.arima(Nile) fit4 forecast(fit4,5) plot(forecast(fit4,5))
context("gainOffsetRescaleCpp") suppressPackageStartupMessages(library(raster)) r <- raster(vals = 1, ncol = 2, nrow = 2) r <- stack(r,r*2) r[[1]][1:4] <- c(NA, -100, 100, 0) gain <- c(.1,.2) offset <- c(.1,.4) clamp <- list(c(TRUE,FALSE), c(FALSE,TRUE), c(TRUE, TRUE), c(FALSE, FALSE)) expected <-list(c(NA, 0, 10.1, 0.1,rep(.8,4)), c(NA, -9.9, 1, 0.1, rep(.8,4)), c(NA, 0, 1, 0.1, rep(.8,4)), c(NA, -9.9, 10.1, 0.1,rep(.8,4))) test_that("NA, clamping, general",{ for(i in seq_along(clamp)){ out <- calc(r, function(x) gainOffsetRescale(x, gain, offset, clamp[[i]]), forcefun=T) expect_equal(as.vector(out[]), expected[[i]]) } })
plot_la <- function(x,y,z, use.locfdr=FALSE, cols=c("red","green","blue"),cex=0.5) { addTrans<-function(color,trans) { if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct") if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans)) if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color)) num2hex <- function(x) { hex <- unlist(strsplit("0123456789ABCDEF",split="")) return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep="")) } rgb <- rbind(col2rgb(color),trans) res <- paste(" return(res) } if(use.locfdr) { l<-locfdr(z, plot=0) grp<-rep(2, length(z)) grp[z<=max(z[z<median(z) & l$fdr<=0.5])]<-1 grp[z>=min(z[z>median(z) & l$fdr<=0.5])]<-3 }else{ cuts<-quantile(z, c(0.3333, 0.6666)) grp<-rep(2, length(z)) grp[z<cuts[1]]<-1 grp[z>cuts[2]]<-3 } plot(x,y, type="n") all.grp<-unique(grp) all.grp<-all.grp[order(all.grp)] r<-NULL r<-c(r,paste("LA score: ", signif(sum(x*y*z),3))) for(i in 1:length(all.grp)) { s<-which(grp == all.grp[i]) points(x[s],y[s],col=addTrans(cols[i],120), pch=19, cex=cex) r<-c(r, paste("group:", i,"(", signif(median(z[s]),2), ")", cols[i], ", corr=", round(cor(x[s],y[s]), 3))) } r }
ECSuit=function(value, crop="wheat"){ if(crop=="wheat"){suitclass=ifelse(value>6,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="maize"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="rice"){suitclass=ifelse(value>10,4,ifelse(value>6,3,ifelse(value>3,2,1)))} else if(crop=="sorghum"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="millet"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="barley"){suitclass=ifelse(value>20,4,ifelse(value>12,3,ifelse(value>6,2,1)))} else if(crop=="oat"){suitclass=ifelse(value>20,4,ifelse(value>12,3,ifelse(value>6,2,1)))} else if(crop=="groundnut"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="bean"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="pea"){suitclass=ifelse(value>2,4,ifelse(value>1,3,ifelse(value>0.5,2,1)))} else if(crop=="gram"){suitclass=ifelse(value>2,4,ifelse(value>1,3,ifelse(value>0.5,2,1)))} else if(crop=="soybean"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="lentil"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="poplar"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="grevillea"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="sesbania"){suitclass=ifelse(value>2,4,ifelse(value>1,3,ifelse(value>0.5,2,1)))} else if(crop=="gram"){suitclass=ifelse(value>2,4,ifelse(value>1,3,ifelse(value>0.5,2,1)))} else if(crop=="calliandra"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="leucaena"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="acacia"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="eucalyptus"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="teak"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="maple"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="ash"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="sesame"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="sunflower"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="oilpalm"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="castor"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="safflower"){suitclass=ifelse(value>12,4,ifelse(value>7.6,3,ifelse(value>6.2,2,1)))} else if(crop=="mustard"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="rapeseed"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="olive"){suitclass=ifelse(value>5,4,ifelse(value>3.8,3,ifelse(value>2.7,2,1)))} else if(crop=="cashew"){suitclass=ifelse(value>13,4,ifelse(value>10,3,ifelse(value>2,2,1)))} else if(crop=="coconut"){suitclass=ifelse(value>25,4,ifelse(value>15,3,ifelse(value>3,2,1)))} else if(crop=="almond"){suitclass=ifelse(value>6,4,ifelse(value>3,3,ifelse(value>1,2,1)))} else if(crop=="pistachio"){suitclass=ifelse(value>10,4,ifelse(value>5,3,ifelse(value>1,2,1)))} else if(crop=="cotton"){suitclass=ifelse(value>10,4,ifelse(value>5,3,ifelse(value>3,2,1)))} else if(crop=="sugarcane"){suitclass=ifelse(value>10,4,ifelse(value>5,3,ifelse(value>3,2,1)))} else if(crop=="tea"){suitclass=ifelse(value>2,4,ifelse(value>1.5,3,ifelse(value>1,2,1)))} else if(crop=="coffee"){suitclass=ifelse(value>2,4,ifelse(value>1.5,3,ifelse(value>1,2,1)))} else if(crop=="rubber"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="jute"){suitclass=ifelse(value>2,4,ifelse(value>1,3,ifelse(value>0.5,2,1)))} else if(crop=="saffron"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="pyrethrum"){suitclass=ifelse(value>8,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="tobacco"){suitclass=ifelse(value>2,4,ifelse(value>1.5,3,ifelse(value>1,2,1)))} else if(crop=="sweetpotato"){suitclass=ifelse(value>6,4,ifelse(value>3,3,ifelse(value>1,2,1)))} else if(crop=="cassava"){suitclass=ifelse(value>6,4,ifelse(value>3,3,ifelse(value>1,2,1)))} else if(crop=="potato"){suitclass=ifelse(value>6,4,ifelse(value>3,3,ifelse(value>1,2,1)))} else if(crop=="carrot"){suitclass=ifelse(value>7,4,ifelse(value>4.5,3,ifelse(value>1,2,1)))} else if(crop=="turnip"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="radish"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="mango"){suitclass=ifelse(value>3,4,ifelse(value>2,3,ifelse(value>0.5,2,1)))} else if(crop=="grape"){suitclass=ifelse(value>3,4,ifelse(value>1.5,3,ifelse(value>0.5,2,1)))} else if(crop=="citrus"){suitclass=ifelse(value>3,4,ifelse(value>1.5,3,ifelse(value>0.5,2,1)))} else if(crop=="pomegranate"){suitclass=ifelse(value>9,4,ifelse(value>3,3,ifelse(value>0.5,2,1)))} else if(crop=="banana"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="watermelon"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="melon"){suitclass=ifelse(value>8,4,ifelse(value>6,3,ifelse(value>4,2,1)))} else if(crop=="pineaple"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="pawpaw"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="avocado"){suitclass=ifelse(value>5,4,ifelse(value>4,3,ifelse(value>2,2,1)))} else if(crop=="cabbage"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="tomato"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="vegetable"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="broccoli"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="cauliflower"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="okra"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="chilli"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="pepper"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="ginger"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="tumeric"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="vanilla"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="lemongrass"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="cardamom"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="onion"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="alfalfa"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="rose"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="jasmine"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="yam"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="pumpkin"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="butternut"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} else if(crop=="squash"){suitclass=ifelse(value>4,4,ifelse(value>2,3,ifelse(value>1,2,1)))} return(suitclass) }
getProb<-function(ts){ N=length(ts) prob1<-mean(ts) freq11<-sum((ts[-1]+ts[-N])==2) freq1<-sum(ts[-N]==1) prob11<-freq11/freq1 prob10<-sum(ts[-1]==1&ts[-N]==0)/sum(ts[-N]==0) return(list(prob1,prob11,prob10)) }
context("PipeOpBoxCox") test_that("PipeOpBoxCox - general functionality", { task = mlr_tasks$get("iris") op = PipeOpBoxCox$new() expect_pipeop(op) expect_datapreproc_pipeop_class(PipeOpBoxCox, task = task) result = train_pipeop(op, inputs = list(task)) expect_task(result[[1]]) result = predict_pipeop(op, inputs = list(task)) expect_task(result[[1]]) }) test_that("PipeOpBoxCox - receive expected result", { task = mlr_tasks$get("iris") op = PipeOpBoxCox$new(param_vals = list(standardize = FALSE)) result = train_pipeop(op, inputs = list(task)) result.pred = predict_pipeop(op, inputs = list(task)) lambda = op$state$bc$Petal.Length$lambda lambda.id = lambda != 0 x = task$data()[[2]] x.trans = if (lambda.id) ((x^lambda) - 1)/lambda else log(x) expect_equal(x.trans, result[[1]]$data()[[2]]) expect_equal(x.trans, result.pred[[1]]$data()[[2]]) op = PipeOpBoxCox$new(param_vals = list(upper = 0.5, lower = 0)) result = train_pipeop(op, inputs = list(task)) lambda.new = unlist(lapply(op$state$bc[1:4], function(x) x$lambda)) expect_true(all(lambda.new <= 0.5 & lambda.new >= 0)) })
handle_triggers <- function(target, meta, config) { class(target) <- handle_triggers_class(target, config) handle_triggers_impl(target, meta, config) } handle_triggers_class <- function(target, config) { if (is_subtarget(target, config)) { return("subtarget") } if (is_registered_dynamic(target, config)) { return("dynamic_registered") } if (is_dynamic(target, config)) { return("dynamic_unregistered") } "static" } handle_triggers_impl <- function(target, meta, config) { UseMethod("handle_triggers_impl") } handle_triggers_impl.subtarget <- function(target, meta, config) { FALSE } handle_triggers_impl.dynamic_registered <- function(target, meta, config) { FALSE } handle_triggers_impl.dynamic_unregistered <- function(target, meta, config) { target <- unclass(target) static_ok <- !any_static_triggers(target, meta, config) || recover_target(target, meta, config) dynamic_ok <- !check_trigger_dynamic(target, meta, config) register_subtargets(target, static_ok, dynamic_ok, config) TRUE } handle_triggers_impl.static <- function(target, meta, config) { target <- unclass(target) any_triggers <- any_static_triggers(target, meta, config) || any_subtargetlike_triggers(target, meta, config) !any_triggers || recover_target(target, meta, config) } recover_target <- function(target, meta, config) { if (!config$settings$recover) { return(FALSE) } key <- recovery_key_impl(target = target, meta = meta, config = config) if (!config$cache$exists(key, namespace = "recover")) { return(FALSE) } meta_hash <- config$cache$get_hash( key, namespace = "recover" ) recovery_meta <- config$cache$driver$get_object(meta_hash) value_hash <- recovery_meta$hash exists_data <- config$cache$exists_object(meta_hash) && config$cache$exists_object(value_hash) if (!exists_data) { return(FALSE) } meta_old <- drake_meta_old(target, config) on.exit(config$meta_old[[target]] <- meta_old) config$meta_old[[target]] <- recovery_meta meta <- subsume_old_meta(target, meta, config) if (any_subtargetlike_triggers(target, meta, config)) { return(FALSE) } if (!is_dynamic(target, config)) { config$logger$target(target, "recover") } config$logger$disk( "recovered target originally stored on", recovery_meta$date, target = target ) config$cache$driver$set_hash( key = target, namespace = "meta", hash = meta_hash ) config$cache$driver$set_hash( key = target, namespace = config$cache$default_namespace, hash = value_hash ) set_progress( target = target, value = "done", config = config ) TRUE } recover_subtarget <- function(subtarget, parent, config) { meta <- drake_meta_(subtarget, config) class(subtarget) <- "subtarget" recover_target(subtarget, meta, config) } recovery_key <- function(target, meta, config) { if (is_subtarget(target, config)) { class(target) <- "subtarget" } recovery_key_impl(target, meta, config) } recovery_key_impl <- function(target, meta, config) { UseMethod("recovery_key_impl") } recovery_key_impl.subtarget <- function(target, meta, config) { parent <- subtarget_parent(target, config) parent_meta <- drake_meta_(parent, config) parent_key <- recovery_key(parent, parent_meta, config) x <- c(unclass(target), parent_key) x <- paste(x, collapse = "|") config$cache$digest(x, serialize = FALSE) } recovery_key_impl.default <- function(target, meta, config, ...) { change_hash <- ifelse( is.null(meta$trigger$value), NA_character_, config$cache$digest(meta$trigger$value) ) x <- c( meta$command, meta$dependency_hash, meta$input_file_hash, meta$output_file_hash, meta$trigger$mode, meta$format, as.character(meta$seed), safe_deparse(meta$trigger$condition, backtick = TRUE), change_hash ) x <- paste(x, collapse = "|") config$cache$digest(x, serialize = FALSE) } any_static_triggers <- function(target, meta, config) { if (check_triggers_stage1(target, meta, config)) { return(TRUE) } condition <- check_trigger_condition(target, meta, config) if (is_final_trigger(condition)) { return(condition) } if (condition) { return(TRUE) } if (check_triggers_stage2(target, meta, config)) { return(TRUE) } FALSE } any_subtargetlike_triggers <- function(target, meta, config) { if (check_trigger_format_file(target, meta, config)) { return(TRUE) } FALSE } any_subtarget_triggers <- function(target, subtargets, config) { any(check_subtarget_triggers(target, subtargets, config)) } check_triggers_stage1 <- function(target, meta, config) { if (check_trigger_imported(target, meta, config)) { return(TRUE) } if (check_trigger_missing(target, meta, config)) { return(TRUE) } FALSE } check_triggers_stage2 <- function(target, meta, config) { if (check_trigger_command(target, meta, config)) { return(TRUE) } if (check_trigger_depend(target, meta, config)) { return(TRUE) } if (check_trigger_file(target, meta, config)) { return(TRUE) } if (check_trigger_seed(target, meta, config)) { return(TRUE) } if (check_trigger_format(target, meta, config)) { return(TRUE) } if (check_trigger_change(target, meta, config)) { return(TRUE) } FALSE } check_trigger_imported <- function(target, meta, config) { if (meta$imported) { return(TRUE) } FALSE } check_trigger_missing <- function(target, meta, config) { if (meta$missing) { config$logger$disk("trigger missing", target = target) return(TRUE) } FALSE } check_trigger_condition <- function(target, meta, config) { condition <- trigger_condition(target = target, meta = meta, config = config) stopifnot(is.logical(condition)) if (condition) { config$logger$disk("trigger condition", target = target) } return(condition) } check_trigger_command <- function(target, meta, config) { if (identical(meta$trigger$command, TRUE)) { if (trigger_command(target, meta, config)) { config$logger$disk("trigger command", target = target) return(TRUE) } } FALSE } check_trigger_depend <- function(target, meta, config) { if (identical(meta$trigger$depend, TRUE)) { if (trigger_depend(target, meta, config)) { config$logger$disk("trigger depend", target = target) return(TRUE) } } FALSE } check_trigger_file <- function(target, meta, config) { if (identical(meta$trigger$file, TRUE)) { if (trigger_file(target, meta, config)) { config$logger$disk("trigger file", target = target) return(TRUE) } } FALSE } check_trigger_seed <- function(target, meta, config) { if (identical(meta$trigger$seed, TRUE)) { if (trigger_seed(target, meta, config)) { config$logger$disk("trigger seed", target = target) return(TRUE) } } FALSE } check_trigger_change <- function(target, meta, config) { if (!is.null(meta$trigger$change)) { if (trigger_change(target = target, meta = meta, config = config)) { config$logger$disk("trigger change", target = target) return(TRUE) } } config$logger$disk("skip", target = target) FALSE } check_trigger_format <- function(target, meta, config) { if (identical(meta$trigger$format, TRUE)) { if (trigger_format(target, meta, config)) { config$logger$disk("trigger format", target = target) return(TRUE) } } FALSE } check_trigger_dynamic <- function(target, meta, config) { if (identical(meta$trigger$depend, TRUE)) { if (trigger_dynamic(target, meta, config)) { config$logger$disk("trigger depend (dynamic)", target = target) return(TRUE) } } FALSE } check_trigger_format_file <- function(target, meta, config) { if (identical(meta$trigger$file, TRUE) && meta$format == "file") { if (trigger_format_file(target, meta, config)) { config$logger$disk("trigger file (format file)", target = target) return(TRUE) } } FALSE } check_subtarget_triggers <- function(target, subtargets, config) { out <- target_missing(subtargets, config) spec <- config$spec[[target]] format <- spec$format %||NA% "none" if (identical(spec$trigger$file, TRUE) && format == "file" && !all(out)) { i <- !out out[i] <- out[i] | check_trigger_subtarget_format_file( subtargets[i], target, config ) } out[is.na(out)] <- TRUE if (any(out)) { config$logger$disk("trigger subtarget (special)", target = target) } out } check_trigger_subtarget_format_file <- function( subtargets, parent, config ) { ht_set(config$ht_is_subtarget, subtargets) out <- lightly_parallelize( X = subtargets, FUN = check_trigger_subtarget_format_file_impl, jobs = config$settings$jobs_preprocess, parent = parent, config = config ) unlist(out) } check_trigger_subtarget_format_file_impl <- function( subtarget, parent, config ) { meta <- drake_meta_(subtarget, config) trigger_format_file(subtarget, meta, config) } trigger_command <- function(target, meta, config) { if (is.null(meta$command)) { return(FALSE) } meta_old <- drake_meta_old(target, config) command <- meta_elt(field = "command", meta = meta_old) !identical(command, meta$command) } trigger_depend <- function(target, meta, config) { if (is.null(meta$dependency_hash)) { return(FALSE) } meta_old <- drake_meta_old(target, config) dependency_hash <- meta_elt(field = "dependency_hash", meta = meta_old) !identical(dependency_hash, meta$dependency_hash) } trigger_file <- function(target, meta, config) { if (!length(target) || !length(config) || !length(meta)) { return(FALSE) } if (trigger_file_missing(target, meta, config)) { return(TRUE) } if (trigger_file_hash(target, meta, config)) { return(TRUE) } FALSE } trigger_file_missing <- function(target, meta, config) { file_out <- config$spec[[target]]$deps_build$file_out for (file in file_out) { if (!file.exists(config$cache$decode_path(file))) { return(TRUE) } } FALSE } trigger_file_hash <- function(target, meta, config) { for (hash_name in c("input_file_hash", "output_file_hash")) { meta_old <- drake_meta_old(target, config) old_file_hash <- meta_elt(field = hash_name, meta = meta_old) if (!identical(old_file_hash, meta[[hash_name]])) { return(TRUE) } } FALSE } trigger_seed <- function(target, meta, config) { meta_old <- drake_meta_old(target, config) seed <- meta_elt(field = "seed", meta = meta_old) !identical(as.integer(seed), as.integer(meta$seed)) } trigger_format <- function(target, meta, config) { meta_old <- drake_meta_old(target, config) format_new <- meta$format format_old <- meta_old$format if (is.null(format_new) || is.null(format_old)) { return(FALSE) } !identical(format_new, format_old) } trigger_condition <- function(target, meta, config) { if (!length(target) || !length(config) || !length(meta)) { return(FALSE) } if (is.language(meta$trigger$condition)) { try_load_deps( config$spec[[target]]$deps_condition$memory, config = config ) value <- eval(meta$trigger$condition, envir = config$envir_targets) } else { value <- meta$trigger$condition } value <- as.logical(value) if (length(value) != 1 || !is.logical(value)) { msg <- paste0( "The `condition` trigger must evaluate to a logical of length 1. ", "got `", value, "` for target ", target, "." ) config$logger$disk(paste("Error:", msg)) stop0(msg) } condition_decision(value = value, mode = meta$trigger$mode) } condition_decision <- function(value, mode) { if (identical(mode, "whitelist") && identical(value, TRUE)) { return(TRUE) } if (identical(mode, "blacklist") && identical(value, FALSE)) { return(as_final_trigger(FALSE)) } if (identical(mode, "condition")) { return(as_final_trigger(value)) } FALSE } as_final_trigger <- function(x) { structure(x, class = "final_trigger") } is_final_trigger <- function(x) { inherits(x, "final_trigger") } trigger_change <- function(target, meta, config) { if (!length(target) || !length(config) || !length(meta)) { return(FALSE) } if (!config$cache$exists(key = target, namespace = "change")) { return(TRUE) } old_value <- config$cache$get( key = target, namespace = "change", use_cache = FALSE ) !identical(old_value, meta$trigger$value) } trigger_dynamic <- function(target, meta, config) { meta_old <- drake_meta_old(target, config) old_hash <- meta_elt(field = "dynamic_dependency_hash", meta = meta_old) if (!identical(meta$dynamic_dependency_hash, old_hash)) { return(TRUE) } if (!identical(meta$max_expand, meta_old$max_expand)) { return(TRUE) } FALSE } trigger_format_file <- function(target, meta, config) { meta_old <- drake_meta_old(target, config) hash_new <- meta$format_file_hash hash_old <- meta_old$format_file_hash !identical(hash_new, hash_old) }
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, varName="html") { t <- escapeString(s) u <- eval(parse(text=paste0("\"", t, "\""))) if(s!=u) stop("Unable to escape string!") if(is.null(varName)) varName <- "html" t <- paste0("\t", varName, " <- \"", t, "\"") utils::writeClipboard(t) return(invisible()) } context("GET VALUES TESTS") test_that("retrieving cell value", { saleIds <- c(5334, 5336, 5338) items <- c("Apple", "Orange", "Banana") quantities <- c(5, 8, 6) prices <- c(0.34452354, 0.4732543, 1.3443243) library(basictabler) tbl <- BasicTable$new(compatibility=list(headerCellsAsTD=TRUE)) tbl$addData(data.frame(saleIds, items, quantities, prices, stringsAsFactors=FALSE), firstColumnAsRowHeaders=TRUE, explicitColumnHeaders=c("Sale ID", "Item", "Quantity", "Price"), columnFormats=list(NULL, NULL, NULL, "%.2f")) v1 <- tbl$cells$getValue(2, 4) v2 <- tbl$cells$getValue(2, 4, formattedValue=TRUE) rowValues <- tbl$cells$getRowValues(2, asList=TRUE) rowValues <- paste0(class(rowValues), ": ", paste(rowValues, collapse=", ")) columnValues <- tbl$cells$getColumnValues(3) columnValues <- paste0(class(columnValues), ": ", paste(columnValues, collapse=", ")) str <- "Sale ID Item Quantity Price \n 5334 Apple 5 0.34 \n 5336 Orange 8 0.47 \n 5338 Banana 6 1.34 " html <- "<table class=\"Table\">\n <tr>\n <td class=\"ColumnHeader\">Sale ID</td>\n <td class=\"ColumnHeader\">Item</td>\n <td class=\"ColumnHeader\">Quantity</td>\n <td class=\"ColumnHeader\">Price</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">5334</td>\n <td class=\"Cell\">Apple</td>\n <td class=\"Cell\">5</td>\n <td class=\"Cell\">0.34</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">5336</td>\n <td class=\"Cell\">Orange</td>\n <td class=\"Cell\">8</td>\n <td class=\"Cell\">0.47</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">5338</td>\n <td class=\"Cell\">Banana</td>\n <td class=\"Cell\">6</td>\n <td class=\"Cell\">1.34</td>\n </tr>\n</table>" expect_identical(tbl$print(asCharacter=TRUE), str) expect_identical(as.character(tbl$getHtml()), html) expect_equal(v1, 0.34452354) expect_identical(v2, "0.34") expect_identical(rowValues, "list: 5334, Apple, 5, 0.34452354") expect_identical(columnValues, "numeric: 5, 8, 6") })
NULL NULL fvbmstderr <- function(data,covarmat) { N <- dim(data)[1] D <- dim(data)[2] stderr <- sqrt(diag(covarmat))/sqrt(N) bvec <- stderr[c(1:D)] Mmat <- matrix(0,D,D) Mmat[lower.tri(Mmat)] <- stderr[-c(1:D)] Mmat <- Mmat + t(Mmat) return(list(bvec_se = bvec, Mmat_se = Mmat)) } fvbmHess <- function(data, model) { bvec <- model[[2]] Mmat <- model[[3]] N <- dim(data)[1] D <- length(bvec) HessComps <- list() HessComps[[1]] <- matrix(0,D+1,D+1) for (jj in 1:D) { HessComps[[jj]] <- matrix(0,D+1,D+1) for (ii in 1:N) { x_bar <- as.matrix(c(1,data[ii,]),D+1,1) HessComps[[jj]] <- HessComps[[jj]] - x_bar%*%t(x_bar)/ cosh(sum(Mmat[jj,]*data[ii,])+bvec[jj])^2 } } Index <- matrix(0,D,D) Index[lower.tri(Index)] <- 1:(D*(D-1)/2) Index <- Index + t(Index) BigHess <- matrix(0,D+D*(D-1)/2,D+D*(D-1)/2) for (jj in 1:D) { WHICH <- which(Index[lower.tri(Index)]%in%Index[jj,]) NonZero <- HessComps[[jj]][-c(jj+1),] NonZero <- NonZero[,-c(jj+1)] BigHess[c(jj,D+WHICH),c(jj,D+WHICH)] <- BigHess[c(jj,D+WHICH),c(jj,D+WHICH)] + NonZero } return(BigHess) } fvbmtests <- function(data,model,nullmodel) { Hess <- fvbmHess(data,model) covmat <- fvbmcov(data,model,fvbmHess) stderr <- fvbmstderr(data,covmat) zb <- (model$bvec-nullmodel$bvec)/stderr$bvec_se zM <- (model$Mmat-nullmodel$Mmat)/stderr$Mmat_se diag(zM)<-NA pvalb <- 2*pnorm(-abs(zb)) pvalM <- 2*pnorm(-abs(zM)) diag(pvalM)<-NA return(list(bvec_z = zb, bvec_p = pvalb, Mmat_z = zM, Mmat_p = pvalM)) } marginpfvbm <- function(bvec, Mmat) { n <- length(bvec) strings <- expand.grid(rep(list(0:1),n)) allprob <-allpfvbm(bvec,Mmat) margins <- array(NA,n) for (i in seq_len(n)){ margins[i] <- sum(allprob[which(strings[,i]==1)]) } return(margins) } NULL
aa2mass <- function(peptideSequence, mass=AA$Monoisotopic, letter1=AA$letter1){ return(.Call("aa2mass_main", peptideSequence, mass, letter1, PACKAGE = "protViz")$output) }
implied_ml_lvm <- function(model,all = FALSE){ if (model@cpp){ x <- formModelMatrices_cpp(model) } else { x <- formModelMatrices(model) } if (model@cpp){ x <- impliedcovstructures_cpp(x, "zeta_within", type = model@types$within_latent, all = all) x <- impliedcovstructures_cpp(x, "epsilon_within", type = model@types$within_residual, all = all) x <- impliedcovstructures_cpp(x, "zeta_between", type = model@types$between_latent, all = all) x <- impliedcovstructures_cpp(x, "epsilon_between", type = model@types$between_residual, all = all) } else { x <- impliedcovstructures(x, "zeta_within", type = model@types$within_latent, all = all) x <- impliedcovstructures(x, "epsilon_within", type = model@types$within_residual, all = all) x <- impliedcovstructures(x, "zeta_between", type = model@types$between_latent, all = all) x <- impliedcovstructures(x, "epsilon_between", type = model@types$between_residual, all = all) } nGroup <- length(x) design <- model@extramatrices$design nVar <- nrow(design) nMaxInCluster <- ncol(design) I_eta <- model@extramatrices$I_eta for (g in 1:nGroup){ BetaStar_within <- as.matrix(solve(Diagonal(nrow(x[[g]]$beta_within)) - x[[g]]$beta_within)) BetaStar_between <- as.matrix(solve(Diagonal(nrow(x[[g]]$beta_between)) - x[[g]]$beta_between)) Betasta_sigmaZeta_within <- BetaStar_within %*% x[[g]]$sigma_zeta_within Betasta_sigmaZeta_between <- BetaStar_between %*% x[[g]]$sigma_zeta_between impMu <- x[[g]]$nu + x[[g]]$lambda %*% BetaStar_between %*% x[[g]]$nu_eta fullMu <- as(do.call(rbind,lapply(seq_len(nMaxInCluster),function(t){ impMu[design[,t]==1,,drop=FALSE] })), "matrix") nLatent <- ncol(x[[g]]$lambda) sigma_eta_within <- Betasta_sigmaZeta_within %*% t(BetaStar_within) sigma_eta_between <- Betasta_sigmaZeta_between %*% t(BetaStar_between) fullSigma_within_latent <- as.matrix(Diagonal(nMaxInCluster) %x% sigma_eta_within) fullSigma_within <- (Diagonal(nMaxInCluster) %x% x[[g]]$lambda) %*% fullSigma_within_latent %*% (Diagonal(nMaxInCluster) %x% t(x[[g]]$lambda)) + (Diagonal(nMaxInCluster) %x% x[[g]]$sigma_epsilon_within) fullSigma_between <- matrix(1,nMaxInCluster,nMaxInCluster) %x% ( x[[g]]$lambda %*% sigma_eta_between %*% t(x[[g]]$lambda) + x[[g]]$sigma_epsilon_between ) fullSigma <- fullSigma_within + fullSigma_between x[[g]]$mu <- fullMu x[[g]]$sigma <- fullSigma[as.vector(design)==1,as.vector(design)==1] x[[g]]$sigma <- as.matrix(0.5*(x[[g]]$sigma + t(x[[g]]$sigma))) x[[g]]$kappa <- solve_symmetric(x[[g]]$sigma, logdet = TRUE) if (!all){ Lambda_BetaStar_within <- x[[g]]$lambda %*% BetaStar_within Lambda_BetaStar_between <- x[[g]]$lambda %*% BetaStar_between tBetakronBeta_within <- t(BetaStar_within) %x% BetaStar_within tBetakronBeta_between <- t(BetaStar_between) %x% BetaStar_between x[[g]]$BetaStar_within <- BetaStar_within x[[g]]$BetaStar_between <- BetaStar_between x[[g]]$Betasta_sigmaZeta_within <- Betasta_sigmaZeta_within x[[g]]$Betasta_sigmaZeta_between <- Betasta_sigmaZeta_between x[[g]]$Lambda_BetaStar_within <- Lambda_BetaStar_within x[[g]]$Lambda_BetaStar_between <- Lambda_BetaStar_between x[[g]]$tBetakronBeta_within <- tBetakronBeta_within x[[g]]$tBetakronBeta_between <- tBetakronBeta_between x[[g]]$sigma_eta_within <- sigma_eta_within x[[g]]$sigma_eta_between <- sigma_eta_between x[[g]]$lamWkronlamW <- x[[g]]$lambda %x% x[[g]]$lambda } else { x[[g]]$sigma_within <- x[[g]]$lambda %*% sigma_eta_within %*% t(x[[g]]$lambda) + x[[g]]$sigma_epsilon_within x[[g]]$sigma_between <- x[[g]]$lambda %*% sigma_eta_between %*% t(x[[g]]$lambda) + x[[g]]$sigma_epsilon_between x[[g]]$sigma_eta_within <- sigma_eta_within x[[g]]$sigma_eta_between <- sigma_eta_between x[[g]]$sigma_eta <- sigma_eta_within + sigma_eta_between x[[g]]$sigma_crosssection <- x[[g]]$sigma_within + x[[g]]$sigma_between } } x }
seqgen <- function(n, length, alphabet, p=NULL) { m <- matrix(nrow=n, ncol=length) for (i in 1:n) m[i,] <- sample(alphabet, length, replace=TRUE, p) colnames(m) <- paste("[",1:length,"]", sep="") rownames(m) <- 1:n return(m) }
cf_region = function(region){ get_stn_html = GET("https://cliflo.niwa.co.nz/pls/niwp/wstn.get_stn_html") region_xml = html_nodes(read_html(get_stn_html), "td.p_selected select.general option")[-1] region_names = html_text(region_xml) if (!missing(region)){ region_names_lower = tolower(region_names) region = tolower(region) region.choice = pmatch(region, region_names_lower) if (is.na(region.choice)){ warning("region not matched - ignoring", immediate. = TRUE) region.choice = menu(region_names, title = "Regions") if (region.choice) return(html_attr(region_xml[region.choice], "value")) } else { return(html_attr(region_xml[region.choice], "value")) } } else { region.choice = menu(region_names, title = "Regions") if (region.choice) return(html_attr(region_xml[region.choice], "value")) } } save_KML = function(df, file_name, file_path){ df$hoverstate = " df$hoverstate[df$open] = " df$name = as.character(df$name) doc = xml_new_root("kml", xmlns = "http://www.opengis.net/kml/2.2", "xmlns:gx" = "http://www.google.com/kml/ext/2.2", "xmlns:kml" = "http://www.opengis.net/kml/2.2", "xmlns:atom" = "http://w3.org/2005/Atom") %>% xml_add_child("Document") %>% xml_add_child("name", gsub("_", " ", strsplit(file_name, ".kml")[[1]])) %>% xml_add_sibling("open", 1) %>% xml_add_sibling("StyleMap", id = "hoverStateOpen") %>% xml_add_child("Pair") %>% xml_add_child("key", "normal") %>% xml_add_sibling("styleUrl", " xml_parent() %>% xml_add_sibling("Pair") %>% xml_add_child("key", "highlight") %>% xml_add_sibling("styleUrl", " xml_parent() %>% xml_parent() %>% xml_add_sibling("StyleMap", id = "hoverStateClosed") %>% xml_add_child("Pair") %>% xml_add_child("key", "normal") %>% xml_add_sibling("styleUrl", " xml_parent() %>% xml_add_sibling("Pair") %>% xml_add_child("key", "highlight") %>% xml_add_sibling("styleUrl", " xml_parent() %>% xml_parent() %>% xml_add_sibling("Style", id = "highlightStateOpen") %>% xml_add_child("IconStyle") %>% xml_add_child("scale", "1.3") %>% xml_add_sibling("Icon") %>% xml_add_child("href", "http://maps.google.com/mapfiles/kml/paddle/grn-circle.png") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("LabelStyle") %>% xml_add_child("scale", "1.3") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("Style", id = "highlightStateClosed") %>% xml_add_child("IconStyle") %>% xml_add_child("scale", "1.3") %>% xml_add_sibling("Icon") %>% xml_add_child("href", "http://maps.google.com/mapfiles/kml/paddle/red-circle.png") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("LabelStyle") %>% xml_add_child("scale", "1.3") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("Style", id = "normalStateOpen") %>% xml_add_child("IconStyle") %>% xml_add_child("scale", "0.9") %>% xml_add_sibling("Icon") %>% xml_add_child("href", "http://maps.google.com/mapfiles/kml/paddle/grn-circle.png") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("LabelStyle") %>% xml_add_child("scale", "0.7") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("Style", id = "normalStateClosed") %>% xml_add_child("IconStyle") %>% xml_add_child("scale", "0.9") %>% xml_add_sibling("Icon") %>% xml_add_child("href", "http://maps.google.com/mapfiles/kml/paddle/red-circle.png") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("LabelStyle") %>% xml_add_child("scale", "0.7") %>% xml_parent() %>% xml_parent() %>% xml_add_sibling("Folder") %>% xml_add_child("name", "Closed") for (i in which(!df$open)) { doc = doc %>% xml_add_sibling("Placemark") %>% xml_add_child("name", df$name[i]) %>% xml_add_sibling("description", paste0("Agent: ", df$agent[i], "\n", "Network: ", df$network[i], "\n", "Start date: ", df$start[i], "\n", "End date: ", df$end[i], "\n")) %>% xml_add_sibling("styleUrl", df$hoverstate[i]) %>% xml_add_sibling("Point") %>% xml_add_child("coordinates", paste(df$lon[i], df$lat[i], 0, sep = ",")) %>% xml_parent() %>% xml_parent() } doc = doc %>% xml_parent() %>% xml_add_sibling("Folder") %>% xml_add_child("name", "Open") for (i in which(df$open)) { doc = doc %>% xml_add_sibling("Placemark") %>% xml_add_child("name", df$name[i]) %>% xml_add_sibling("description", paste0("Agent: ", df$agent[i], "\n", "Network: ", df$network[i], "\n", "Start date: ", df$start[i], "\n", "End date: ", df$end[i], "\n")) %>% xml_add_sibling("styleUrl", df$hoverstate[i]) %>% xml_add_sibling("Point") %>% xml_add_child("coordinates", paste(df$lon[i], df$lat[i], 0, sep = ",")) %>% xml_parent() %>% xml_parent() } doc = doc %>% xml_root() if (file_name == "my_stations_"){ xml_file = tempfile(file_name, file_path, ".kml") write_xml(doc, file = xml_file) } else { if (!grepl(".kml$", file_name)) file_name = paste0(file_name, ".kml") xml_file = file.path(file_path, file_name) write_xml(doc, file = xml_file) } message(paste("output KML file:", xml_file)) } cf_save_kml = function(station, file_name = "my_stations_", file_path = "."){ if (!is(station, "cfStation")) stop("station must be a cfStation object") if (grepl(".kml$", file_name)) file_name = gsub(".kml$", "", file_name) save_KML(as(station, "data.frame"), file_name = file_name, file_path = normalizePath(file_path)) } cf_find_station = function(..., search = c("name", "region", "network", "latlong"), datatype, combine = c("all", "any"), status = c("open", "closed", "all")) { search = match.arg(arg = search) status = match.arg(arg = status) search_string = c(...) include_distances = FALSE cert = system.file("CurlSSL/cacert.pem", package = "RCurl") if (search == "latlong"){ if (length(search_string) != 3) stop("need exactly one longitude, latitude and radius") lat_long_rad = c("latitude", "longitude", "radius") if(is.null(names(search_string))){ names(search_string) = lat_long_rad message(paste("using", paste(lat_long_rad, search_string, sep = " = ", collapse = ", "))) } partial.match = pmatch(names(search_string), lat_long_rad) if (any(is.na(partial.match))) stop("names must be partially matched to latitude, longitude and radius") if (any(is.na(as.numeric(search_string)))) stop("latitude and longitude (and radius) need to be in decimal formats") lat = as.character(search_string[partial.match == 1]) long = as.character(search_string[partial.match == 2]) rad = as.character(search_string[partial.match == 3]) if (abs(as.numeric(long)) > 180 || abs(as.numeric(lat)) > 90) stop("use sensible latitudes and longitudes") } else { if (length(search_string) > 1) stop("only one search can be conducted at a time") search_string = as.character(c(...)) } param.list = switch(search, name = list(cstype = "name", cstnstr = search_string), region = { if (length(search_string) == 0) search_region = search_string = cf_region() else search_region = cf_region(search_string) search_string = unlist(strsplit(search_region, ","))[3] list(cstype = "region", cRegion = search_region) }, network = list(cstype = "net", cNet = search_string), latlong = { include_distances = TRUE list(cstype = "latlongc", clat1 = lat, clong1 = long, crad = rad) } ) param.list = c(param.list, mimeselection = "htmltable", Submit = "Get Station List", status = status) if (!missing(datatype)){ if (!is(datatype, "cfDatatype")) stop("datatype has to be a cfDatatype object") user = cf_user() cf_login(user) on.exit(cf_logout(user, msg = FALSE)) combine = switch(match.arg(arg = combine), all = "and", any = "or") cf_update_dt(datatype) param.list = c(param.list, ccomb_dt = combine) my_form = GET(modify_url(url = "https://cliflo.niwa.co.nz/pls/niwp/wstn.get_stn", query = param.list)) } else { my_form = GET(modify_url(url = "https://cliflo.niwa.co.nz/pls/niwp/wstn.get_stn_nodt", query = param.list)) } if (is.raw(my_form)) my_form = rawToChar(my_form) doc = read_html(my_form) doc_table = tail(html_table(doc, header = TRUE, fill = TRUE), 1)[[1]] doc_table$Start = dmy(doc_table$Start, tz = "NZ") doc_table$End[doc_table$End == "-"] = format(Sys.Date(), "%d-%m-%Y") doc_table$End = dmy(doc_table$End, tz = "NZ") span = doc_table$End %--% now(tzone = "NZ") open_station = (as.numeric(dseconds(span)) / (604800) < 4) if ((status == "open" && !any(open_station)) || (status == "closed" && all(open_station))) stop("no climate stations were found matching your search criteria", call. = FALSE) if (status == "open"){ doc_table = doc_table[open_station, ] open_station = open_station[open_station] } if (status == "closed") doc_table = doc_table[!open_station, ] station_df = data.frame( name = doc_table$Name, network = doc_table$NetworkNumber, agent = doc_table$AgentNumber, start_date = doc_table$Start, end_date = doc_table$End, open_station = switch(status, open = TRUE, closed = FALSE, all = open_station), distances = NA, latitude = doc_table$`Lat(dec deg)`, longitude = doc_table$`Long(dec deg)`, stringsAsFactors = FALSE, check.names = TRUE ) if (include_distances) { station_df$distances = doc_table$DistKm } new("cfStation", station_df) }
calibrate_external <- function( object, x, time, event, x_new, time_new, event_new, pred.at, ngroup = 5) { if (!("hdnom.model" %in% class(object))) { stop('object must be of class "hdnom.model"') } model <- object$model model_type <- object$type if (!("matrix" %in% class(x_new))) stop("x_new must be a matrix") if (length(pred.at) != 1L) stop("pred.at should only contain 1 time point") if (model_type %in% c("lasso", "alasso", "enet", "aenet")) { pred_list <- glmnet_calibrate_external_surv_prob_pred( model, x, x_new, Surv(time, event), pred.at ) } if (model_type %in% c("mcp", "mnet", "scad", "snet")) { pred_list <- ncvreg_calibrate_external_surv_prob_pred( model, x, x_new, Surv(time, event), pred.at ) } if (model_type %in% c("flasso")) { pred_list <- penalized_calibrate_external_surv_prob_pred( model, x, x_new, Surv(time, event), pred.at ) } pred_prob <- rep(NA, nrow(x_new)) for (i in 1L:length(pred_prob)) pred_prob[i] <- pred_list$p[i, pred_list$idx] grp <- cut(pred_prob, quantile(pred_prob, seq(0, 1, 1 / ngroup)), labels = 1L:ngroup) pred_prob_median <- tapply(pred_prob, grp, median) true_prob <- calibrate_external_surv_prob_true( pred_prob, grp, time_new, event_new, pred.at, ngroup ) prob <- cbind(pred_prob_median, true_prob) colnames(prob)[1L] <- "Predicted" if (model_type %in% c("lasso", "alasso", "enet", "aenet")) { class(prob) <- c("hdnom.calibrate.external", "glmnet.calibrate.external") } if (model_type %in% c("mcp", "mnet", "scad", "snet")) { class(prob) <- c("hdnom.calibrate.external", "ncvreg.calibrate.external") } if (model_type %in% c("flasso")) { class(prob) <- c("hdnom.calibrate.external", "penalized.calibrate.external") } attr(prob, "model.type") <- model_type attr(prob, "pred.at") <- pred.at attr(prob, "ngroup") <- ngroup attr(prob, "risk.group") <- grp attr(prob, "surv.time") <- time_new attr(prob, "surv.event") <- event_new prob }
HierarchicalClusterDists <-function(pDist,ClusterNo=0,Type="ward.D2",ColorTreshold=0,Fast=FALSE,...){ if(!inherits(pDist,'dist')) pDist=as.dist(pDist) if(isTRUE(Fast)&requireNamespace('fastcluster')){ hc <- fastcluster::hclust(pDist,method=Type) }else{ hc <- hclust(pDist,method=Type); } m=paste(Type,"LinkCluster/ "," N=",nrow(as.matrix(pDist))) if (ClusterNo>0){ Cls=cutree(hc,ClusterNo) return(list(Cls=Cls,Dendrogram=as.dendrogram(hc),Object=hc)) } else{ x=as.dendrogram(hc);plot(x, main=m,xlab="Number of Data Points N", ylab="Distance",sub=" ",leaflab ="none",...) axis(1,col="black",las=1) if (ColorTreshold!=0){ rect.hclust(hc, h=ColorTreshold,border="red")} else{ } return(list(Cls=NULL,Dendrogram=x,Object=hc)) } }
REmrt <- function(formula, data, vi, c = 1, maxL = 5, minsplit = 6, cp = 1e-5, minbucket = 3, xval = 10, lookahead = FALSE, ...){ Call <- match.call() indx <- match(c("formula", "data", "vi"), names(Call), nomatch = 0L) if (indx[1] == 0L) stop("a 'formula' argument is required") if (indx[3] == 0L) stop("The sampling variances need to be specified") if (!is.logical(lookahead)) stop("The 'lookahead' argument needs to be a logical value") if (maxL < 2 & (lookahead == TRUE) ) stop("The 'maxL' should be at least 2 when applying look-ahead strategy") temp <- Call[c(1L, indx)] temp[[1L]] <- quote(stats::model.frame) mf <- eval.parent(temp) cv.res <- Xvalid_all(REmrt_GS_, mf, maxL = maxL, n.fold = xval, minbucket = minbucket, minsplit = minsplit, cp = cp, lookahead = lookahead) mindex <- which.min(cv.res[, 1]) cp.minse <- cv.res[mindex,1] + c*cv.res[mindex,2] cp.row <- min(which(cv.res[,1]<= cp.minse)) if (cp.row == 1) { warning("no moderator effect was detected") y <- model.response(mf) vi <- c(t(mf["(vi)"])) wts <- 1/vi wy <- wts*y wy2 <- wts * y^2 n <- length(y) Q <- sum(wy2) - (sum(wy))^2/sum(wts) df <- nrow(mf) - 1 C <- sum(wts) - sum(wts^2)/sum(wts) tau2 <- max(0, (Q-df)/C) vi.star <- vi + tau2 g <- sum(y/vi.star)/sum(1/vi.star) pval.Q <- pchisq(Q, df, lower.tail = FALSE) se <- 1/sqrt(sum(1/vi.star)) zval <- g/se pval <- pnorm(abs(zval), lower.tail=FALSE)*2 ci.lb <- g - qnorm(0.975)*se ci.ub <- g + qnorm(0.975)*se res <- REmrt_GS_(mf, maxL = maxL, minsplit = minsplit, cp = cp, minbucket = minbucket, lookahead = lookahead) res.f <- list(n = n , Q = Q, df = df, pval.Q = pval.Q, tau2 = tau2, g = g, se = se, zval = zval, pval = pval, ci.lb = ci.lb, ci.ub = ci.ub, call = Call, data = mf, cv.res = cv.res, initial.tree = res$tree) } else{ y <- model.response(mf) vi <- c(t(mf["(vi)"])) res <- REmrt_GS_(mf, maxL = maxL, minsplit = minsplit, cp = cp, minbucket = minbucket, lookahead = lookahead) prunedTree <- res$tree[1:cp.row, ] tau2 <- res$tree$tau2[cp.row] vi.star <- vi + tau2 subnodes <- res$node.split[[cp.row]] wy.star <- y/vi.star n <- tapply(y, subnodes, length) g <- tapply(wy.star, subnodes, sum)/tapply(1/vi.star, subnodes, sum) df <- cp.row - 1 Qb <- res$tree$Qb[cp.row] pval.Qb <- pchisq(Qb, df, lower.tail = FALSE) se <- tapply(vi.star, subnodes, function(x) sqrt(1/sum(1/x))) zval <- g/se pval <- pnorm(abs(zval),lower.tail=FALSE)*2 ci.lb <- g - qnorm(0.975)*se ci.ub <- g + qnorm(0.975)*se mod.names <- unique(prunedTree$mod[!is.na(prunedTree$mod)]) mf$term.node <- subnodes res.f<- list(tree = prunedTree, n = n, moderators = mod.names, Qb = Qb, tau2 = tau2, df = df, pval.Qb = pval.Qb, g = g, se = se, zval =zval, pval = pval, ci.lb = ci.lb, ci.ub = ci.ub, call = Call, cv.res = cv.res, cpt = res$cpt, data = mf, initial.tree = res$tree) } class(res.f) <- "REmrt" res.f }
ord_norm <- function(marginal = list(), rho = NULL, support = list(), epsilon = 0.001, maxit = 1000, Spearman = FALSE) { if (!all(unlist(lapply(marginal, function(x) (sort(x) == x & min(x) > 0 & max(x) < 1))))) { stop("Error in given marginal distributions!") } if (!isSymmetric(rho) | !all(diag(rho) == 1)) { stop("Correlation matrix not valid!") } k_cat <- length(marginal) niter <- matrix(0, k_cat, k_cat) if (length(support) == 0) { for (i in 1:k_cat) { support[[i]] <- 1:(length(marginal[[i]]) + 1) } } rho0 <- rho rhoord <- norm_ord(marginal, rho, support, Spearman) rhoold <- rho for (q in 1:(k_cat - 1)) { for (r in (q + 1):k_cat) { if (rho0[q, r] == 0) { rho[q, r] <- 0 } else { it <- 0 while ((abs(rhoord[q, r] - rho0[q, r]) > epsilon) & it < maxit) { if (rho0[q, r] * (rho0[q, r]/rhoord[q, r]) <= -1) { rho[q, r] <- rhoold[q, r] * (1 + 0.1 * (1 - rhoold[q, r]) * -sign(rho0[q, r] - rhoord[q, r])) } if (rho0[q, r] * (rho0[q, r]/rhoord[q, r]) >= 1) { rho[q, r] <- rhoold[q, r] * (1 + 0.1 * (1 - rhoold[q, r]) * sign(rho0[q, r] - rhoord[q, r])) } if ((rho0[q, r] * (rho0[q, r]/rhoord[q, r]) > -1) & (rho0[q, r] * (rho0[q, r]/rhoord[q, r]) < 1)) { rho[q, r] <- rhoold[q, r] * (rho0[q, r]/rhoord[q, r]) } if (rho[q, r] > 1) rho[q, r] <- 1 if (rho[q, r] < -1) rho[q, r] <- -1 rho[r, q] <- rho[q, r] rhoord[r, q] <- norm_ord(list(marginal[[q]], marginal[[r]]), matrix(c(1, rho[q, r], rho[q, r], 1), 2, 2), list(support[[q]], support[[r]]), Spearman)[2] rhoord[q, r] <- rhoord[r, q] rhoold[q, r] <- rho[q, r] rhoold[r, q] <- rhoold[q, r] it <- it + 1 } niter[q, r] <- it niter[r, q] <- it } } } emax <- max(abs(rhoord - rho0)) list(SigmaC = rho, rhoO = rhoord, rho = rho0, niter = niter, maxerr = emax) }
require(bvpSolve) Gas<-function(x, y, par) { dy1 <- y[2] dy2 <- -2/x*y[2]-(y[1]^n) if (x < 1e-10) dy2<-0 list(c(dy1, dy2)) } x <-seq(0, 1, by = 0.01) n <- 5 print(system.time( sol <- bvpshoot(func = Gas, yini = c(y = NA, dy = 0), yend = c(sqrt(3/4), NA), x = x, guess = 0) )) plot(sol) curve(1/sqrt(1+(x^2)/3), type = "l", add = TRUE) print(system.time( Sol <- bvptwp(func = Gas, yini = c(NA, 0), yend = c(sqrt(3/4), NA), x = x, parms = NULL) )) lines(Sol, col = "red")
mergeSvmat <- function(m1, m2) { nr1 <- nrow(m1) nr2 <- nrow(m2) if ( nr1 > nr2 ) m2 <- rbind(m2, matrix(NA, nrow = nr1 - nr2, ncol = ncol(m2))) if ( nr2 > nr1 ) m1 <- rbind(m1, matrix(NA, nrow = nr2 - nr1, ncol = ncol(m1))) m0 <- cbind(m1, m2) m0 }
simCapHist <- function(state, cap = c(0.35, 0.4), recap = NULL, maxAge = NULL, verbose = TRUE){ inputName <- deparse(substitute(state)) stopifnotMatrix(state, allowNA=TRUE, numericOnly=TRUE) nYears <- ncol(state) nind <- nrow(state) nstage <- max(state, na.rm=TRUE) + 1 stopifnotProbability(cap, allowNA=FALSE) cap <- fixAmatrix(cap, nrow=nstage, ncol=nYears) if(is.null(recap)) { recap <- cap[-1, -1, drop=FALSE] } else { stopifnotProbability(recap, allowNA=FALSE) recap <- fixAmatrix(recap, nrow=nstage-1, ncol=nYears-1) } if(!is.null(maxAge)) { maxAge <- round(maxAge[1]) stopifnotBetween(maxAge, min=1, max=nstage, allowNA=FALSE) } if(verbose) { cat(paste0("The input object ", sQuote(inputName), " has ", nind, " individuals x ", nYears, " Years. Ages range from ", max(0, min(state, na.rm=TRUE)), " to ", max(state, na.rm=TRUE), ".\n")) cat(paste0("The ", sQuote("cap"), " matrix should be ", nstage, " x ", nYears, " and the ", sQuote("recap"), " matrix ", nstage-1, " x ", nYears-1, ".\n\n" )) } Px <- rbind(NA, cbind(NA, recap)) CP <- abind::abind(cap, Px, along=3) ch.age <- matrix(NA, nind, nYears) ctBefore <- rep(1, nind) for(t in 1:nYears) { alive <- which(state[, t] >= 0) index <- cbind(state[alive, t]+1, t, ctBefore[alive]) caped <- rbinom(length(alive), 1, CP[index]) == 1 caught <- alive[caped] ch.age[caught, t] <- state[caught, t] ctBefore[caught] <- 2 } incl <- rowSums(!is.na(ch.age)) >= 1 ch.age <- ch.age[incl,] ch.age <- ch.age + 1 index <- cbind(1:nrow(ch.age), getFirst(ch.age)) age <- ch.age[index] if(!is.null(maxAge)) age <- pmin(age, maxAge) ch <- (ch.age > 0) * 1 ch[is.na(ch)] <- 0 return(list(cap = cap, recap = recap, maxAge = maxAge, ch = ch, age = age)) }
get_legend <- function(plot) { get_plot_component(plot, "guide-box") }
context("landscape level lsm_l_cai_sd metric") landscapemetrics_landscape_landscape_value <- lsm_l_cai_sd(landscape) test_that("lsm_l_cai_sd is typestable", { expect_is(lsm_l_cai_sd(landscape), "tbl_df") expect_is(lsm_l_cai_sd(landscape_stack), "tbl_df") expect_is(lsm_l_cai_sd(landscape_brick), "tbl_df") expect_is(lsm_l_cai_sd(landscape_list), "tbl_df") }) test_that("lsm_l_cai_sd returns the desired number of columns", { expect_equal(ncol(landscapemetrics_landscape_landscape_value), 6) }) test_that("lsm_l_cai_sd returns in every column the correct type", { expect_type(landscapemetrics_landscape_landscape_value$layer, "integer") expect_type(landscapemetrics_landscape_landscape_value$level, "character") expect_type(landscapemetrics_landscape_landscape_value$class, "integer") expect_type(landscapemetrics_landscape_landscape_value$id, "integer") expect_type(landscapemetrics_landscape_landscape_value$metric, "character") expect_type(landscapemetrics_landscape_landscape_value$value, "double") })
test_that("can create parameters from list", { x <- list(a = bq_param(1, "integer"), b = "x", c = 1:3) p <- as_bq_params(x) expect_length(p, 3) expect_equal(p[[1]], bq_param_scalar(1, "integer", name = "a")) expect_equal(p[[2]], bq_param_scalar("x", name = "b")) expect_equal(p[[3]], bq_param_array(1:3, name = "c")) }) test_that("parameter json doesn't change without notice", { verify_output(test_path("test-bq-param-json.txt"), { as_bq_params(list( scalar = "a", vector = c("a", "b", "c") )) }) })
sectors_segmentation <- function(a, angle_width, return_angle = FALSE) { stopifnot(class(a) == "RasterLayer") stopifnot(class(return_angle) == "logical") stopifnot(length(angle_width) == 1) if (!.is_whole(360 / angle_width)) { stop( paste("angle_width should divide the 0 to 360", "range into a whole number of segments.") ) } intervals <- seq(0, 360, angle_width) c1 <- intervals[1:(length(intervals) - 1)] c2 <- intervals[2:length(intervals)] if (return_angle) { c3 <- (c1 + c2) / 2 } else { c3 <- 1:(length(intervals) - 1) } rcl <- matrix(c(c1, c2, c3), ncol = 3) reclassify(a, rcl) }
propdiff_ac <- function(y, x, formula, data){ call <- match.call() names_var <- all.vars(call, functions = FALSE) if(length(names_var) > 2) stop("Include only one independent variable in x or formula") if(!inherits(y,"formula")){ eval_prop <- eval(call[[1L]], parent.frame()) X <- data.frame(y, x) } else { call <- eval(call[[2L]], parent.frame()) X <- model.frame(call) colnames(X) <- c('y', 'x') } if(!all(X$x==1 | X$x==0)) stop("x variable should be a 0 - 1 variable") if(!all(X$y==1 | X$y==0)) stop("y variable should be a 0 - 1 variable") sub1 <- subset(X, x==1) sub0 <- subset(X, x==0) n1 <- nrow(sub1) n0 <- nrow(sub0) x1 <- nrow(subset(sub1, y==1)) x0 <- nrow(subset(sub0, y==1)) dfcom <- (n0+n1)-1 p0hat_ac <- (x0 + 1)/(n0 + 2) p1hat_ac <- (x1 + 1)/(n1 + 2) phat_diff_ac <- p1hat_ac - p0hat_ac se_phat_diff_ac <- sqrt((p0hat_ac * (1 - p0hat_ac)/(n0 + 2)) + (p1hat_ac * (1 - p1hat_ac)/(n1 + 2))) output <- matrix(c(phat_diff_ac, se_phat_diff_ac, dfcom), 1, 3) colnames(output) <- c("Prop diff AC", "SE", "dfcom") return(output) }
AM_emp_bayes_uninorm = function(y,scEmu=1,scEsig2=3,CVsig2=3){ n <- length(y) bary <- mean(y) s2y <- var(y) Emu <- bary Vmu <- s2y*scEmu Esig2 <- s2y/scEsig2 Vsig2 <- CVsig2^2*Esig2^2 m0 = Emu nu0 = 2*(Esig2)^2/Vsig2+4 sig02 = Esig2*(nu0-2)/nu0 k0 = sig02/Vmu * nu0/(nu0-2) return(AM_mix_hyperparams_uninorm(m0=m0,nu0=nu0,sig02=sig02,k0=k0)) }
`logLik.mlcm` <- function(object, ...) { if (object$method == "glm") val <- logLik(object$obj) else { val <- object$logLik attr(val, "df") <- length(object$par) class(val) <- "logLik" } val }
asggm <- function(x, ...) UseMethod("asggm") asggm.default <- function(x, iterations = 100000000, init = NULL, epsilon = 0.001, ...) { x <- as.matrix(x) if (!is.null(init)) { init <- as.matrix(init) } result <- rCSL(x, iterations, init, epsilon, ...) class(result) <- "asggm" result } asggm.formula <- function(formula, data=list(), ...) { mf <- model.frame(formula=formula, data=data) x <- model.matrix(attr(mf, "terms"), data=mf) y <- model.response(mf) result <- asggm.default(x, ...) result } genL = function(kNodes, spP) { L = matrix(0, kNodes, kNodes) for (i in 2:kNodes) { for (j in 1:(i-1)) { L[i,j] = (runif(1) < spP) * rnorm(1, 0, 1) } } for (k in 1:kNodes) { L[k,k] = rnorm(1, 1, 0.1) } L } genData = function(L, nSamples) { kNodes = nrow(L) xTemp = matrix(rnorm(kNodes*nSamples, mean = 0, sd = 1), nrow = nSamples, ncol = kNodes) x = xTemp%*%solve(L) x } rCSL = function(x, iterations = 500, init = NULL, epsilon = 1e-5, ansL = NULL){ LInit = init nSamples = nrow(x) kNodes = ncol(x) S = cov(x) * (nSamples-1) if (is.null(init)) { Sinv = ginv(S) LUSinv = expand(lu(Sinv)) LInit = as.matrix(LUSinv$L) } if (is.null(ansL)) { ansQ = LInit%*%t(LInit) } else { ansQ = ansL%*%t(ansL) } print(norm(ansQ-LInit%*%t(LInit),'f')) CSLOut = .Call(C_CSL, iterations, LInit, kNodes, nSamples, epsilon, S, ansQ, PACKAGE = "AdaptiveSparsity") CSLOut }
library(metaggR) E1 = c(50, 134, 206, 290, 326, 374) P1 = c(26, 92, 116, 218, 218, 206) out1 = round(knowledge_weighted_estimate(E1,P1), 4) E2 = c(50, 134, 206, 290, 326, 374, 200) P2 = c(26, 92, 116, 218, 218, 206, 200) out2 = round(knowledge_weighted_estimate(E2,P2), 4) test_that("Expected output is found", { expect_equal(out1, 329.305) expect_equal(out2, 314.8606) })
expand.sd <- function(x, ensemble, fiv=5) { sdx <- if (is.null(ncol(x))) sd(x) else apply(x, 2, sd) sdf <- c(sdx, apply(ensemble, 2, sd)) sdfa <- sdf/sdf[1] sdfd <- sdf[1]/sdf mx <- 1+(fiv/100) id <- which(sdfa < 1) if (length(id) > 0) sdfa[id] <- runif(n=length(id), min=1, max=mx) sdfdXsdfa <- sdfd[-1]*sdfa[-1] id <- which(floor(sdfdXsdfa) > 0) if (length(id) > 0) { if(length(id) > 1){ ensemble[,id] <- ensemble[,id] %*% diag(sdfdXsdfa[id]) } else { ensemble[,id] <- ensemble[,id] * sdfdXsdfa[id] } } if(is.ts(x)){ ensemble <- ts(ensemble, frequency=frequency(x), start=start(x)) } ensemble }
PrepText <- function(textdata, groupvar, textvar, node_type = c("groups","words"), tokenizer = c("words", "tweets"), pos = c("all", "nouns"), language = "english", remove_stop_words = FALSE, remove_numbers = NULL, compound_nouns = FALSE, udmodel_lang = NULL, ...) { textdata[[textvar]] <- iconv(textdata[[textvar]], to="UTF-8", sub='') if (tokenizer=="tweets") { textdata[[textvar]] <- gsub("&amp;|&lt;|&gt;|RT", "", textdata[[textvar]]) if (!is.null(remove_numbers) && isTRUE(remove_numbers)) { textdata[[textvar]]<-gsub("\\b\\d+\\b", "",textdata[[textvar]]) } } if(is.null(udmodel_lang)){ lang_mod <- udpipe_download_model(language = language) udmodel_lang <- udpipe_load_model(file = lang_mod$file_model) } if (isFALSE(compound_nouns)){ textdata_tokens <- as_tibble({{textdata}}) %>% select({{groupvar}}, {{textvar}}) %>% unnest_tokens(output = "word", input = {{textvar}}, token = {{tokenizer}}, ...) textdata_pos <- as.data.frame(udpipe_annotate(udmodel_lang, x = textdata_tokens$word, tagger = "default", parser = "none", tokenizer = "vertical")) textdata <- bind_cols(textdata_tokens, textdata_pos[, c("upos", "lemma")]) } if (isTRUE(compound_nouns)){ textdata_tokens <- as_tibble({{textdata}}) %>% select({{groupvar}}, {{textvar}}) %>% unnest_tokens(output = "word", input = {{textvar}}, token = {{tokenizer}}, strip_punct = FALSE, ...) textdata_tokens <- textdata_tokens %>% group_by_({{groupvar}}) %>% summarise(documents = paste(word, collapse = "\n")) textdata_dep <- as.data.frame(udpipe_annotate(udmodel_lang, x = textdata_tokens$documents, doc_id = textdata_tokens[[groupvar]], tagger = "default", parser = "default")) noun_compound <- which(textdata_dep$dep_rel=="compound") compound_elements <- split(noun_compound, cumsum(c(1, diff(noun_compound) != 1))) compound_bases <- mapply(`[[`, compound_elements, lengths(compound_elements))+1 all_compound_elements <- mapply(c, compound_elements, compound_bases, SIMPLIFY = FALSE) compound_nouns <- sapply(all_compound_elements, function(x) paste0(textdata_dep$lemma[x], collapse = " ")) textdata_dep$lemma[compound_bases] <- compound_nouns textdata_dep <- textdata_dep %>% filter(dep_rel!="compound" & upos!="PUNCT") textdata <- textdata_dep names(textdata)[1] <- groupvar } if (remove_stop_words) { textdata <- {{textdata}} %>% anti_join(get_stopwords(language = language), by = c("lemma" = "word")) } if (length(pos)>1){ warning(paste0("You did not specify `pos`. Function defaults to all parts of speech.")) pos <- "all" } if (pos=="nouns"){ textdata <- {{textdata}} %>% filter(upos%in%c("NOUN", "PROPN")) } if (length(node_type)>1){ warning(paste0("You did not specify a `node_type`. Returned nodes are ", groupvar, ".")) node_type <- "groups" } if (node_type=="groups"){ textdata <- {{textdata}} %>% group_by_({{groupvar}}) %>% count(lemma) %>% rename(count = n) } if (node_type=="words"){ textdata <- {{textdata}} %>% group_by(lemma) %>% count_({{groupvar}}) %>% rename(count = n) } return({{textdata}}) }
library(hamcrest) expected <- c(0x1.8dbc5abd8a8e8p+9 + 0x0p+0i, -0x1.b31363d04a5dep+6 + 0x1.e82768bd6d93ep+7i, -0x1.c994c7f989169p+7 + -0x1.99bdf505a1c5ep+6i, -0x1.c1ac32a1797eep+7 + -0x1.194437464e39ap+5i, 0x1.50c6fb0282d5ap+8 + -0x1.5c1154aed83fdp+3i, -0x1.f622187d5033bp+7 + 0x1.38b80aecc6c9p+5i, -0x1.51505e24c79ap+7 + -0x1.f19017326ed88p+7i, -0x1.31f51a313f7cbp+5 + -0x1.ffd78676c8bep+6i, 0x1.654e36dbddc5ep+8 + 0x1.616d2c5abe3c8p+7i, -0x1.046a8cc237dbfp+8 + -0x1.7d4986f45c159p+6i, -0x1.8e03e21e71dep+4 + -0x1.5f085d0271cp+7i, -0x1.203dcf46bfbaep+8 + -0x1.f623966da54fep+6i, 0x1.2fda176346c58p+2 + -0x1.7dfcb89e4d243p+4i, -0x1.7a0a6236cdbf1p+6 + -0x1.524d335558ba6p+7i, 0x1.837c5858be796p+5 + -0x1.3ebd2d04f2c01p+7i, -0x1.ab843afd7ff26p+7 + -0x1.6bad18ba484ffp+7i, 0x1.2550dbbb6f614p+8 + -0x1.41831704cd67ep+5i, -0x1.24c53c1bc9f12p+6 + 0x1.8d764336086c6p+6i, -0x1.45894745b2279p+5 + 0x1.b6d76adbc7a9p+1i, -0x1.67649d11c942dp+7 + 0x1.1c283c41f808cp+4i, 0x1.b84f1fffd7acep+7 + 0x1.6fa08be606788p+3i, -0x1.09c6fe361031cp+4 + 0x1.ba5972d3d8d94p+5i, 0x1.29d0b347b66ep+3 + -0x1.2de3cd42d78b6p+7i, 0x1.3a74d0231280ep+6 + 0x1.5d4ed829f573ep+6i, -0x1.7084f45cc2986p+3 + -0x1.04ffc6890e718p+5i, -0x1.0f69539dc45fep+7 + 0x1.741bebcf081d2p+7i, -0x1.3b75a3ddf8b29p+6 + 0x1.0e6805c52296bp+5i, -0x1.901cb3e40a013p+5 + -0x1.5cf4bbdf7c84ep+6i, -0x1.0300c887ceda5p+6 + 0x1.d6a41ebed3644p+6i, 0x1.e17814a9a9273p+5 + 0x1.ce9bd5977a65bp+6i, 0x1.55b9ac8079f0cp+3 + 0x1.24527bf64bef2p+5i, -0x1.28dc629e8bb1ep+7 + -0x1.229fe5320750ap+6i, 0x1.172a0e14576cap+5 + -0x1.e67bad298476p+1i, -0x1.9e9d41d7b9a58p+5 + -0x1.e07b51d4e2dp-4i, -0x1.ba0c5fc38aa22p+5 + -0x1.0205adf87da5cp+7i, 0x1.01ed6ddf7dffcp+5 + -0x1.4c996fe5c80aep+4i, -0x1.00a003799893ep+5 + 0x1.3af8def9a0926p+4i, -0x1.e9b454a67184cp+5 + 0x1.d5a3f3f64387ap+5i, 0x1.7553763b021ccp+4 + -0x1.304d44f0efb52p+6i, 0x1.7dfb06406ea77p+8 + -0x1.f4b4b04588c22p+4i, -0x1.148d84bc9a4cbp+6 + -0x1.84751c104e572p+5i, 0x1.7cba6d0b303b7p+5 + -0x1.c38ceb019cf48p+5i, 0x1.3cccd66fb3738p+6 + -0x1.4fb26574a9282p+5i, 0x1.585ff41442d32p+7 + 0x1.697509e1e51fep+6i, 0x1.6ba6479d269dcp+5 + -0x1.5b33a7166f2aap+5i, -0x1.5dba6077f4863p+6 + -0x1.62e070252c273p+6i, 0x1.469dbdee6018p+6 + 0x1.3381b822212aep+4i, 0x1.e5878a72d487p+6 + 0x1.571ded93a50fep+4i, 0x1.b5ac6105f97dcp+4 + -0x1.5bf3c01491ea1p+6i, -0x1.8d7f2d9a8d551p+5 + -0x1.27a612257781cp+5i, -0x1.02fe6071e0f18p+4 + -0x1.a82af48cd5674p+4i, 0x1.33a01a01f5e3ap+6 + -0x1.9278d6c374454p+4i, 0x1.f855b915cbc1p+2 + -0x1.365d550bc8e77p+4i, 0x1.1bb5c38946d51p+6 + -0x1.205149493e109p+6i, -0x1.81450ec4b7ee2p+6 + -0x1.2cf2ca3dfaf48p+7i, 0x1.2876d261cd86ap+6 + -0x1.1faf8afae93c5p+4i, 0x1.59c2db0196664p+3 + 0x1.594f7bc9efe4p+4i, 0x1.7ecbb2b760c0ep+2 + -0x1.ebef96ce6cf58p+4i, 0x1.3294bc2a9db26p+3 + -0x1.6e1ba58b656bp+6i, -0x1.aeb53d7decb94p+4 + 0x1.72a3a3730e8dap+4i, -0x1.5ec691ee6029cp+6 + 0x1.9d44fb25f6f1bp+5i, -0x1.404ddd933a2a2p+5 + 0x1.1bb35824e5728p+3i, 0x1.a0790470ed6e2p+4 + -0x1.1fbbba86e6dd1p+4i, 0x1.164ccf7a19488p+3 + 0x1.254ce4374a8c8p+5i, -0x1.cfa3f32b92977p+4 + 0x1.97af3da68bbf4p+3i, 0x1.07dbdfc7ceff7p+3 + 0x1.3e8ec4e9af178p+2i, 0x1.49704a43e5c7cp+2 + -0x1.f4b7394ce166p+0i, 0x1.5d5ed177224e5p+5 + -0x1.35afea832f1f7p+4i, 0x1.41f6ce81eef25p+5 + -0x1.42197ae1e9326p+4i, 0x1.a9b2b5e3801fep+5 + -0x1.cae95f04defd4p+4i, 0x1.657cb5060c3d9p+3 + 0x1.4393702ac553ap+4i, 0x1.07f0e9840db2ap+6 + 0x1.2ee1172d5f805p+4i, 0x1.c4411938b78c8p+4 + 0x1.f4ba9fb26f8a8p+3i, 0x1.b739b28f167c8p-2 + -0x1.8a841dc9ee0ap+3i, 0x1.3ef2592411828p+3 + -0x1.88b59ded14f5ap+4i, 0x1.b6c515a68dfffp+5 + 0x1.1edac0d33a1dfp+5i, 0x1.83687c4e65f1cp+5 + 0x1.93c890168a1fp+5i, 0x1.78a3853aa6872p+4 + -0x1.fc30b4110d421p+5i, 0x1.10fbfbc36ac42p+5 + 0x1.3735761dfb61ep+4i, 0x1.fc1beb2795882p+3 + 0x1.a2752827e109bp+3i, 0x1.e9b35e603e6cp+0 + 0x1.36009bc3c7e3bp+5i, 0x1.5791f10c11546p+4 + -0x1.2d7727ca611b7p+5i, -0x1.38a4d290ee462p+4 + -0x1.54b026baf0015p+4i, 0x1.0c8ff4937e2c9p+4 + -0x1.1cae29aab973bp+5i, 0x1.5524bfaac32fcp+4 + -0x1.53608ecae4e6ap+4i, -0x1.1a72619e47d9cp+1 + -0x1.7f9d5a2af9877p+5i, 0x1.0ae6168df8fa2p+5 + -0x1.cbe8f2c5c4311p+3i, 0x1.3ca16d6a5a7ep+2 + -0x1.bb591490ec7d7p+5i, 0x1.b733eab6425b8p+3 + 0x1.0e2be3c6df8dp+6i, -0x1.6f47e9938329cp+5 + -0x1.10ffc3f413c48p+5i, 0x1.59c8d7fc30c48p+1 + 0x1.c640b44e3e2dbp+2i, 0x1.7566aaddb9eb8p+5 + -0x1.1f2bdb891776dp+6i, -0x1.3115440e1d14ep+5 + -0x1.a602e0231357cp+4i, 0x1.0d4f68fea2cp-2 + -0x1.8df9fb8983b26p+6i, 0x1.4b2992b713edp+5 + -0x1.958a4f0aaa0dep+4i, 0x1.387606e40c586p+4 + -0x1.9b8ac09c932e8p+2i, 0x1.f2f00e01e6e8ep+3 + 0x1.9df1724cfbfe5p+5i, -0x1.08fa99810fd18p+6 + -0x1.9d02b8992b28dp+6i, -0x1.bfbd26be65f7cp+3 + -0x1.fc7baa33e2f32p+5i, -0x1.640705a7213b4p+2 + -0x1.40396a88ab993p+4i, -0x1.40852905a724ep+3 + 0x1.023c56947e13ep+5i, 0x1.ab32d9380b194p+4 + -0x1.f083a5d282414p+4i, -0x1.0d3cf9f224b6cp+5 + 0x1.c9cbd9299496ap+4i, 0x1.adcdf63bd997p+2 + -0x1.3450abfccf3e8p+1i, 0x1.2a687f0548929p+4 + 0x1.fa845d7adc5eep+5i, -0x1.23e9ea3ba13cbp+5 + -0x1.c68217d548c85p+5i, -0x1.a65963fd289ap+2 + -0x1.cffeb459474d9p+6i, 0x1.621f3f9dd761p+3 + -0x1.b7a925b25a358p+5i, 0x1.e40955a705ce4p+3 + -0x1.8ea9143a71abcp+4i, 0x1.12736dffe08aap+4 + -0x1.42111f8eb7dbdp+5i, -0x1.976b2435a4a39p+4 + -0x1.96c9a14c1bb7p+4i, 0x1.630530e3a1a48p+2 + -0x1.aaa90fafb95b7p+4i, 0x1.67e2d31e0e554p+3 + -0x1.b66c04403d05p-1i, 0x1.bfc78b95c9b36p+6 + 0x1.017eebed66bf8p+4i, 0x1.d2a0e536866cp+0 + 0x1.296c0c6cd0a5ep+3i, 0x1.63c1266418642p+4 + -0x1.4acc6434af04cp+4i, 0x1.57950f9defd38p+6 + 0x1.777681b58721p+4i, -0x1.1b8083f18d13ep+5 + 0x1.aaa04e39de134p+5i, 0x1.0a02cc056c472p+3 + -0x1.79d3cd244adffp+5i, 0x1.a9e92a9e135f7p+5 + -0x1.3ecb9bd00b8e8p+6i, -0x1.91e90d0241dbep+3 + 0x1.9d5c4667a88dp+5i, 0x1.0b51497d76a0cp+5 + -0x1.0a12d94d01d64p+4i, 0x1.dd6df2a3047a8p+3 + -0x1.24f126d28aeb5p+4i, 0x1.d9ff53f2ecd3cp+4 + 0x1.72d8d01ce4a44p+6i, -0x1.cb7420d0d2306p+5 + -0x1.17736c57bf999p+5i, 0x1.047aebbbc1652p+6 + -0x1.3c5e4eb67212cp+4i, 0x1.b94fdb06a438p+5 + 0x1.b127c3bfe7952p+4i, 0x1.01112b8e41b2cp+6 + -0x1.0f2f216249f7p+3i, -0x1.13e9c7c24fdd2p+6 + -0x1.4545abb22272cp+3i, 0x1.b53b5b59e6814p+5 + -0x1.1e3147592662cp+5i, 0x1.71c45885333d2p+3 + -0x1.fe031876d0482p+6i, 0x1.1026d3a78cc02p+6 + -0x1.1b31aa74519fcp+5i, -0x1.0595f2d8e09d3p+7 + -0x1.e3c4e56d06834p+4i, -0x1.560657eaec4a8p+5 + -0x1.bd4c57b1f24ap+5i, 0x1.2a422125b66fdp+6 + -0x1.1f39af9fe97c6p+6i, 0x1.8eab88c58a76p+6 + 0x1.30ed13cb75e1cp+6i, -0x1.3d7b01eecb795p+7 + -0x1.82587d4bb251fp+6i, 0x1.64b2fa9138a78p+4 + -0x1.ad5a2caac7393p+5i, 0x1.825fd3957cafap+5 + -0x1.903a6f2a0f69ap+5i, 0x1.e7c8b46bd3488p+4 + -0x1.925d2f7e42f14p+4i, -0x1.ca6856d644e7ap+6 + -0x1.8f03df3d0919p+5i, -0x1.bda5d34bc204p+2 + 0x1.d17ac53d0dc1cp+3i, -0x1.0a63056264ccap+5 + 0x1.f987b057aa1e4p+4i, 0x1.527ec4a5439d6p+6 + 0x1.f54f1d3a6f1d6p+5i, -0x1.395d8d58764dap+5 + -0x1.5db6821548a68p+6i, -0x1.c76741b22bc68p+4 + -0x1.200968c144af1p+5i, -0x1.0c3f0b625926cp+5 + 0x1.360d4c9e3538dp+6i, 0x1.128a67133ec3ep+5 + -0x1.3df198d716d34p+3i, -0x1.39d70611f2278p+4 + -0x1.5f098926de061p+5i, 0x1.781b2ae131128p+5 + 0x1.464b06bbec0dp+4i, -0x1.42ca8dc31f901p+5 + 0x1.0d207e9e21d58p+6i, 0x1.451ddf95233b6p+6 + -0x1.a74718bd102ebp+6i, 0x1.4a505db311bffp+6 + 0x1.3a4574f97a8cp+0i, 0x1.4b8d99d2fc90ep+4 + 0x1.40545bea8495cp+4i, 0x1.12cf4ae84dd88p+5 + 0x1.d77c582badb4p+3i, 0x1.e4c29e905fb9ep+7 + 0x1.fc272080a9e2p+4i, 0x1.ed468d3273688p+4 + 0x1.4b0c0f85e7955p+3i, 0x1.30e52fc7068bp+7 + -0x1.8b45aae60b31dp+6i, 0x1.efeb83d706c04p+6 + -0x1.3e8579cd2e047p+6i, 0x1.8942687925a89p+6 + -0x1.ef8547f03744cp+1i, 0x1.b357d608d96b4p+6 + 0x1.ae9672dae1b22p+4i, 0x1.3748b70ea84bbp+7 + -0x1.1cad3f694af73p+7i, 0x1.17dd2b5075bc8p+6 + 0x1.95a6aeda0307p+7i, 0x1.0879a1a40f26cp+2 + -0x1.eca486f656fa2p+2i, 0x1.ccd571f23e146p+6 + 0x1.05e3f8d333aecp+6i, 0x1.322fe3937e14ep+6 + 0x1.52c355077e514p+5i, 0x1.7882e849069p+8 + -0x1.ab8a60c2cb0a9p+5i, -0x1.96c660cac3c7cp+6 + 0x1.b490191665375p+7i, 0x1.5b485b6e4bec6p+3 + -0x1.cac8b45e9d535p+6i, 0x1.2c9276cfc60f2p+6 + -0x1.114e95c5cdbb7p+8i, 0x1.420dc339103aap+7 + -0x1.245ad56568fa2p+7i, -0x1.2691fe26e64e1p+6 + 0x1.1a4a9e1b64851p+7i, -0x1.059e87a3c4c62p+7 + -0x1.aee62e0bc96c6p+7i, 0x1.dfc63fe6a0736p+7 + -0x1.1d5ca6c13556p+6i, 0x1.42c924fa501b4p+7 + 0x1.0e201fffdfc87p+7i, -0x1.9817bd3c70d98p+8 + -0x1.49c272f618c72p+7i, 0x1.258e7ca26b8eep+7 + -0x1.15e7b3ecc36d2p+8i, 0x1.8698f2eb1eda4p+7 + -0x1.d9966bd97ca6p+7i, 0x1.4a4bdb7ef7495p+8 + 0x1.ae5afc7fb6e52p+3i, -0x1.3f7754fccc95p+8 + -0x1.f761bbb2860fcp+2i, 0x1.6957094c46d33p+6 + -0x1.717c2ad0cc3a2p+7i, 0x1.66200c405032p+3 + 0x1.849bf81b789e9p+7i, 0x1.23bf32f884d5p+5 + -0x1.76b44cb31a4e8p+4i, -0x1.bc1b7abc5953bp+7 + -0x1.89b1c8db8b414p+7i, 0x1.cb279d1656bc2p+4 + -0x1.e7cec97e86034p+4i, -0x1.dbcbcdf97e1p+5 + 0x1.d15e3e010b26cp+6i, 0x1.454661f02807cp+6 + 0x1.27f3df690643bp+5i, -0x1.3f5fbc7255e9ap+7 + -0x1.eceb71e8c547ap+5i, -0x1.e5af8055380dcp+5 + 0x1.d9a381fccd52ap+3i, -0x1.6f711381ec15p+6 + 0x1.c5baede87af1p+2i, 0x1.6756611f52926p+5 + 0x1.f41106b2aba7cp+5i, -0x1.6ca7a33858a15p+6 + -0x1.506dfd510037cp+6i, 0x1.248f53912ec88p+6 + 0x1.b229a2f5725f4p+5i, -0x1.57f9a860ae2e4p+6 + 0x1.cf141baef1a2cp+4i, 0x1.5b35563624625p+6 + 0x1.aa53a50293c9p+0i, -0x1.3841e98fb57b3p+4 + 0x1.39f7b2b9da232p+7i, 0x1.05876d2635df4p+6 + -0x1.60ea1b7c6a5ap-2i, 0x1.a5c82ea5ee8e4p+5 + 0x1.f8b189ff5c74p+7i, 0x1.cd60123de9b5cp+5 + 0x1.a8d890965e1c1p+2i, -0x1.1893f9ee98ff2p+6 + 0x1.b05efb2049469p+7i, 0x1.b6531f7b399acp+6 + 0x1.5accb1a13f17dp+3i, -0x1.0f6ab362ab8c4p+6 + 0x1.123b59cbbc688p+5i, 0x1.3e8f651e29194p+3 + 0x1.049cab3612e72p+7i, -0x1.05e961c529aa6p+5 + 0x1.9012f7712f796p+4i, 0x1.b7b624e0faab5p+5 + -0x1.788a3962179a6p+5i, -0x1.7d31d0503a2dcp+7 + 0x1.b33662a7fcb3cp+7i, 0x1.1d0feb7ebd867p+7 + -0x1.8391cf4b34f57p+5i, -0x1.e0e1985bf3cb6p+6 + 0x1.1e786d6d68db1p+5i, -0x1.df7d40f1d1668p+1 + 0x1.58d67d066d268p+6i, -0x1.96fb8058956fap+3 + 0x1.2d8b0d2ec4dfap+6i, 0x1.e815bbc4848dp+5 + -0x1.b1f3cf3b719f6p+3i, -0x1.0209d0cfd35b1p+4 + -0x1.5e44a839bc53ap+5i, -0x1.86418c65619aep+4 + -0x1.bff727410f4b9p+4i, 0x1.d726026c620a8p+3 + 0x1.2258c5acd2cp+5i, 0x1.2c8230b4c3a24p+3 + 0x1.247f6ef7bb3d3p+6i, -0x1.4037d3270094ep+5 + -0x1.2e1d6a47f9532p+5i, 0x1.84f10a1fe7b75p+7 + -0x1.1d318f0e86094p+3i, -0x1.49207ec732114p+6 + 0x1.036c66a4e48f2p+7i, 0x1.a8c2698bacc88p+5 + -0x1.093f79e816a77p+3i, 0x1.b09ec61422364p+6 + -0x1.610942e331338p+4i, 0x1.3494a7ba1c481p+6 + -0x1.72d89a8b1fa5ap+5i, -0x1.623ff507853fp+6 + 0x1.0131b047d75cdp+5i, 0x1.123889bf14024p+6 + 0x1.5b660ad3eb4fdp+4i, 0x1.9ceee518f032ap+3 + -0x1.c07b7bfac4706p+4i, 0x1.5778fb5d807d7p+2 + 0x1.bfd6aa3623e9dp+5i, 0x1.7a055827b1ca8p+2 + -0x1.d1e3d5a4b576cp+2i, 0x1.aaf4ba5f306d8p+3 + 0x1.38ae218be8f08p+4i, -0x1.8e2e6a9f29046p+6 + 0x1.bbe0bc604346p+2i, 0x1.34db2d5367fdbp+6 + 0x1.f4250d2a942d2p+3i, -0x1.6f0bf470b1ce6p+4 + 0x1.304bf19981723p+5i, -0x1.1ea4510dcc22cp+5 + 0x1.2e4816cee0321p+5i, -0x1.5f7bf84f306a4p+5 + -0x1.93948a5df28f5p+5i, -0x1.5e8c6f0661e11p+4 + 0x1.443a35ec0b6p-4i, 0x1.cd57bca32277p+2 + 0x1.afb09516deaa2p+2i, -0x1.fd7bdcdf33154p+6 + 0x1p-49i, 0x1.cd57bca322784p+2 + -0x1.afb09516deaf8p+2i, -0x1.5e8c6f0661dfcp+4 + -0x1.443a35ec0dp-4i, -0x1.5f7bf84f3069fp+5 + 0x1.93948a5df28ebp+5i, -0x1.1ea4510dcc21ep+5 + -0x1.2e4816cee0318p+5i, -0x1.6f0bf470b1cd1p+4 + -0x1.304bf19981722p+5i, 0x1.34db2d5367fdap+6 + -0x1.f4250d2a942b9p+3i, -0x1.8e2e6a9f29042p+6 + -0x1.bbe0bc6043414p+2i, 0x1.aaf4ba5f306f1p+3 + -0x1.38ae218be8ef7p+4i, 0x1.7a055827b1cc4p+2 + 0x1.d1e3d5a4b5764p+2i, 0x1.5778fb5d8086cp+2 + -0x1.bfd6aa3623ea1p+5i, 0x1.9ceee518f030bp+3 + 0x1.c07b7bfac472p+4i, 0x1.123889bf14023p+6 + -0x1.5b660ad3eb507p+4i, -0x1.623ff507853e8p+6 + -0x1.0131b047d75dcp+5i, 0x1.3494a7ba1c48ap+6 + 0x1.72d89a8b1fa4ep+5i, 0x1.b09ec6142235ep+6 + 0x1.610942e33132fp+4i, 0x1.a8c2698bacc7fp+5 + 0x1.093f79e816a49p+3i, -0x1.49207ec73210ep+6 + -0x1.036c66a4e48efp+7i, 0x1.84f10a1fe7b75p+7 + 0x1.1d318f0e860a8p+3i, -0x1.4037d3270096p+5 + 0x1.2e1d6a47f9525p+5i, 0x1.2c8230b4c3a48p+3 + -0x1.247f6ef7bb3dbp+6i, 0x1.d726026c620bap+3 + -0x1.2258c5acd2c01p+5i, -0x1.86418c656198ep+4 + 0x1.bff727410f4c4p+4i, -0x1.0209d0cfd35c1p+4 + 0x1.5e44a839bc53p+5i, 0x1.e815bbc4848d6p+5 + 0x1.b1f3cf3b719c8p+3i, -0x1.96fb805895734p+3 + -0x1.2d8b0d2ec4dfap+6i, -0x1.df7d40f1d16d8p+1 + -0x1.58d67d066d26cp+6i, -0x1.e0e1985bf3cb7p+6 + -0x1.1e786d6d68dbep+5i, 0x1.1d0feb7ebd865p+7 + 0x1.8391cf4b34f4fp+5i, -0x1.7d31d0503a2dfp+7 + -0x1.b33662a7fcb36p+7i, 0x1.b7b624e0faab6p+5 + 0x1.788a3962179a7p+5i, -0x1.05e961c529aaep+5 + -0x1.9012f7712f7a8p+4i, 0x1.3e8f651e29194p+3 + -0x1.049cab3612e71p+7i, -0x1.0f6ab362ab8c2p+6 + -0x1.123b59cbbc682p+5i, 0x1.b6531f7b399aep+6 + -0x1.5accb1a13f17ep+3i, -0x1.1893f9ee98ff6p+6 + -0x1.b05efb2049467p+7i, 0x1.cd60123de9b5cp+5 + -0x1.a8d890965e1bcp+2i, 0x1.a5c82ea5ee8dp+5 + -0x1.f8b189ff5c74p+7i, 0x1.05876d2635df6p+6 + 0x1.60ea1b7c69e4p-2i, -0x1.3841e98fb57cp+4 + -0x1.39f7b2b9da22ep+7i, 0x1.5b35563624628p+6 + -0x1.aa53a50293eap+0i, -0x1.57f9a860ae2e2p+6 + -0x1.cf141baef1a22p+4i, 0x1.248f53912ec8ap+6 + -0x1.b229a2f5725f2p+5i, -0x1.6ca7a33858a1ap+6 + 0x1.506dfd5100381p+6i, 0x1.6756611f52922p+5 + -0x1.f41106b2aba84p+5i, -0x1.6f711381ec15p+6 + -0x1.c5baede87af16p+2i, -0x1.e5af8055380ep+5 + -0x1.d9a381fccd50bp+3i, -0x1.3f5fbc7255e9cp+7 + 0x1.eceb71e8c547fp+5i, 0x1.454661f02807ep+6 + -0x1.27f3df690643dp+5i, -0x1.dbcbcdf97e0fep+5 + -0x1.d15e3e010b26ep+6i, 0x1.cb279d1656bcp+4 + 0x1.e7cec97e86038p+4i, -0x1.bc1b7abc5953cp+7 + 0x1.89b1c8db8b416p+7i, 0x1.23bf32f884d58p+5 + 0x1.76b44cb31a4dfp+4i, 0x1.66200c4050328p+3 + -0x1.849bf81b789e8p+7i, 0x1.6957094c46d3ap+6 + 0x1.717c2ad0cc3a3p+7i, -0x1.3f7754fccc952p+8 + 0x1.f761bbb28613p+2i, 0x1.4a4bdb7ef7498p+8 + -0x1.ae5afc7fb6ebp+3i, 0x1.8698f2eb1eda8p+7 + 0x1.d9966bd97ca62p+7i, 0x1.258e7ca26b8fp+7 + 0x1.15e7b3ecc36d2p+8i, -0x1.9817bd3c70d9ap+8 + 0x1.49c272f618c74p+7i, 0x1.42c924fa501b6p+7 + -0x1.0e201fffdfc89p+7i, 0x1.dfc63fe6a073bp+7 + 0x1.1d5ca6c13555cp+6i, -0x1.059e87a3c4c6ap+7 + 0x1.aee62e0bc96cep+7i, -0x1.2691fe26e64e8p+6 + -0x1.1a4a9e1b64855p+7i, 0x1.420dc339103b1p+7 + 0x1.245ad56568fa3p+7i, 0x1.2c9276cfc60f8p+6 + 0x1.114e95c5cdbb9p+8i, 0x1.5b485b6e4bed9p+3 + 0x1.cac8b45e9d538p+6i, -0x1.96c660cac3c8p+6 + -0x1.b490191665378p+7i, 0x1.7882e84906904p+8 + 0x1.ab8a60c2cb0b2p+5i, 0x1.322fe3937e151p+6 + -0x1.52c355077e51ep+5i, 0x1.ccd571f23e145p+6 + -0x1.05e3f8d333aeep+6i, 0x1.0879a1a40f328p+2 + 0x1.eca486f656ffp+2i, 0x1.17dd2b5075bc9p+6 + -0x1.95a6aeda03076p+7i, 0x1.3748b70ea84c4p+7 + 0x1.1cad3f694af77p+7i, 0x1.b357d608d96b1p+6 + -0x1.ae9672dae1b2dp+4i, 0x1.8942687925a9p+6 + 0x1.ef8547f0374p+1i, 0x1.efeb83d706c0cp+6 + 0x1.3e8579cd2e04ap+6i, 0x1.30e52fc7068b6p+7 + 0x1.8b45aae60b322p+6i, 0x1.ed468d3273688p+4 + -0x1.4b0c0f85e7955p+3i, 0x1.e4c29e905fb98p+7 + -0x1.fc272080a9e24p+4i, 0x1.12cf4ae84dd81p+5 + -0x1.d77c582badb28p+3i, 0x1.4b8d99d2fc914p+4 + -0x1.40545bea8495p+4i, 0x1.4a505db311bfcp+6 + -0x1.3a4574f97a998p+0i, 0x1.451ddf95233b6p+6 + 0x1.a74718bd102dcp+6i, -0x1.42ca8dc31f8f4p+5 + -0x1.0d207e9e21d5p+6i, 0x1.781b2ae13111cp+5 + -0x1.464b06bbec0c8p+4i, -0x1.39d70611f227p+4 + 0x1.5f098926de05ep+5i, 0x1.128a67133ec42p+5 + 0x1.3df198d716d3ep+3i, -0x1.0c3f0b625925cp+5 + -0x1.360d4c9e35388p+6i, -0x1.c76741b22bc66p+4 + 0x1.200968c144afcp+5i, -0x1.395d8d58764dp+5 + 0x1.5db6821548a63p+6i, 0x1.527ec4a5439dp+6 + -0x1.f54f1d3a6f1dep+5i, -0x1.0a63056264cc6p+5 + -0x1.f987b057aa1dap+4i, -0x1.bda5d34bc201p+2 + -0x1.d17ac53d0dc1p+3i, -0x1.ca6856d644e75p+6 + 0x1.8f03df3d09188p+5i, 0x1.e7c8b46bd348p+4 + 0x1.925d2f7e42fp+4i, 0x1.825fd3957cb07p+5 + 0x1.903a6f2a0f69cp+5i, 0x1.64b2fa9138a8p+4 + 0x1.ad5a2caac738ap+5i, -0x1.3d7b01eecb794p+7 + 0x1.82587d4bb2516p+6i, 0x1.8eab88c58a75fp+6 + -0x1.30ed13cb75e1dp+6i, 0x1.2a422125b66ffp+6 + 0x1.1f39af9fe97c4p+6i, -0x1.560657eaec4bcp+5 + 0x1.bd4c57b1f249ap+5i, -0x1.0595f2d8e09dp+7 + 0x1.e3c4e56d06834p+4i, 0x1.1026d3a78cc03p+6 + 0x1.1b31aa74519f4p+5i, 0x1.71c45885333eap+3 + 0x1.fe031876d047ep+6i, 0x1.b53b5b59e680cp+5 + 0x1.1e3147592661ep+5i, -0x1.13e9c7c24fdcap+6 + 0x1.4545abb22275p+3i, 0x1.01112b8e41b2bp+6 + 0x1.0f2f216249f38p+3i, 0x1.b94fdb06a4381p+5 + -0x1.b127c3bfe7952p+4i, 0x1.047aebbbc165p+6 + 0x1.3c5e4eb67212p+4i, -0x1.cb7420d0d2308p+5 + 0x1.17736c57bf992p+5i, 0x1.d9ff53f2ecd36p+4 + -0x1.72d8d01ce4a44p+6i, 0x1.dd6df2a3047cap+3 + 0x1.24f126d28aebfp+4i, 0x1.0b51497d769fcp+5 + 0x1.0a12d94d01d4ep+4i, -0x1.91e90d0241db8p+3 + -0x1.9d5c4667a88dp+5i, 0x1.a9e92a9e135f8p+5 + 0x1.3ecb9bd00b8dep+6i, 0x1.0a02cc056c478p+3 + 0x1.79d3cd244ae04p+5i, -0x1.1b8083f18d152p+5 + -0x1.aaa04e39de13ap+5i, 0x1.57950f9defd38p+6 + -0x1.777681b58721p+4i, 0x1.63c126641864cp+4 + 0x1.4acc6434af07p+4i, 0x1.d2a0e5368671p+0 + -0x1.296c0c6cd0a62p+3i, 0x1.bfc78b95c9b34p+6 + -0x1.017eebed66bf8p+4i, 0x1.67e2d31e0e564p+3 + 0x1.b66c04403cedp-1i, 0x1.630530e3a1a68p+2 + 0x1.aaa90fafb95b8p+4i, -0x1.976b2435a4a3cp+4 + 0x1.96c9a14c1bb88p+4i, 0x1.12736dffe08bp+4 + 0x1.42111f8eb7db5p+5i, 0x1.e40955a705cecp+3 + 0x1.8ea9143a71acp+4i, 0x1.621f3f9dd7608p+3 + 0x1.b7a925b25a36p+5i, -0x1.a65963fd2892p+2 + 0x1.cffeb459474dep+6i, -0x1.23e9ea3ba13dp+5 + 0x1.c68217d548c8fp+5i, 0x1.2a687f0548929p+4 + -0x1.fa845d7adc5edp+5i, 0x1.adcdf63bd9994p+2 + 0x1.3450abfccf45p+1i, -0x1.0d3cf9f224b68p+5 + -0x1.c9cbd92994969p+4i, 0x1.ab32d9380b18dp+4 + 0x1.f083a5d28242bp+4i, -0x1.40852905a7247p+3 + -0x1.023c56947e146p+5i, -0x1.640705a72139dp+2 + 0x1.40396a88ab9a8p+4i, -0x1.bfbd26be65f86p+3 + 0x1.fc7baa33e2f3bp+5i, -0x1.08fa99810fd1p+6 + 0x1.9d02b8992b291p+6i, 0x1.f2f00e01e6ebp+3 + -0x1.9df1724cfbfe9p+5i, 0x1.387606e40c59bp+4 + 0x1.9b8ac09c9332p+2i, 0x1.4b2992b713ec8p+5 + 0x1.958a4f0aaa0e4p+4i, 0x1.0d4f68fea338p-2 + 0x1.8df9fb8983b2p+6i, -0x1.3115440e1d14cp+5 + 0x1.a602e02313563p+4i, 0x1.7566aaddb9eb9p+5 + 0x1.1f2bdb891776ap+6i, 0x1.59c8d7fc30c9p+1 + -0x1.c640b44e3e2f4p+2i, -0x1.6f47e99383298p+5 + 0x1.10ffc3f413c4ep+5i, 0x1.b733eab6425b4p+3 + -0x1.0e2be3c6df8d6p+6i, 0x1.3ca16d6a5a828p+2 + 0x1.bb591490ec7d6p+5i, 0x1.0ae6168df8f8ap+5 + 0x1.cbe8f2c5c433p+3i, -0x1.1a72619e47dbp+1 + 0x1.7f9d5a2af986ap+5i, 0x1.5524bfaac330cp+4 + 0x1.53608ecae4e47p+4i, 0x1.0c8ff4937e2f8p+4 + 0x1.1cae29aab9741p+5i, -0x1.38a4d290ee494p+4 + 0x1.54b026baf0026p+4i, 0x1.5791f10c11554p+4 + 0x1.2d7727ca611b3p+5i, 0x1.e9b35e603e7bp+0 + -0x1.36009bc3c7e5p+5i, 0x1.fc1beb279589cp+3 + -0x1.a2752827e105dp+3i, 0x1.10fbfbc36ac3fp+5 + -0x1.3735761dfb61ep+4i, 0x1.78a3853aa68a4p+4 + 0x1.fc30b4110d421p+5i, 0x1.83687c4e65f18p+5 + -0x1.93c890168a1eap+5i, 0x1.b6c515a68dff5p+5 + -0x1.1edac0d33a1d9p+5i, 0x1.3ef2592411836p+3 + 0x1.88b59ded14f4ep+4i, 0x1.b739b28f16a4p-2 + 0x1.8a841dc9ee0d2p+3i, 0x1.c4411938b78b5p+4 + -0x1.f4ba9fb26f89fp+3i, 0x1.07f0e9840db26p+6 + -0x1.2ee1172d5f807p+4i, 0x1.657cb5060c3edp+3 + -0x1.4393702ac5537p+4i, 0x1.a9b2b5e3801f4p+5 + 0x1.cae95f04defd7p+4i, 0x1.41f6ce81eef2ap+5 + 0x1.42197ae1e931ap+4i, 0x1.5d5ed177224d9p+5 + 0x1.35afea832f1fcp+4i, 0x1.49704a43e5c7cp+2 + 0x1.f4b7394ce16dp+0i, 0x1.07dbdfc7cf014p+3 + -0x1.3e8ec4e9af15ep+2i, -0x1.cfa3f32b92968p+4 + -0x1.97af3da68bbe2p+3i, 0x1.164ccf7a1947cp+3 + -0x1.254ce4374a8c4p+5i, 0x1.a0790470ed6e2p+4 + 0x1.1fbbba86e6ddp+4i, -0x1.404ddd933a29dp+5 + -0x1.1bb35824e571cp+3i, -0x1.5ec691ee60296p+6 + -0x1.9d44fb25f6f1p+5i, -0x1.aeb53d7decb87p+4 + -0x1.72a3a3730e8cap+4i, 0x1.3294bc2a9db1cp+3 + 0x1.6e1ba58b656adp+6i, 0x1.7ecbb2b760c3p+2 + 0x1.ebef96ce6cf46p+4i, 0x1.59c2db0196673p+3 + -0x1.594f7bc9efe2cp+4i, 0x1.2876d261cd864p+6 + 0x1.1faf8afae93b4p+4i, -0x1.81450ec4b7eddp+6 + 0x1.2cf2ca3dfaf48p+7i, 0x1.1bb5c38946d56p+6 + 0x1.205149493e108p+6i, 0x1.f855b915cbc0cp+2 + 0x1.365d550bc8e7ep+4i, 0x1.33a01a01f5e3bp+6 + 0x1.9278d6c374443p+4i, -0x1.02fe6071e0f18p+4 + 0x1.a82af48cd5682p+4i, -0x1.8d7f2d9a8d54cp+5 + 0x1.27a612257781ep+5i, 0x1.b5ac6105f97e5p+4 + 0x1.5bf3c01491eap+6i, 0x1.e5878a72d486fp+6 + -0x1.571ded93a5104p+4i, 0x1.469dbdee6017cp+6 + -0x1.3381b822212cp+4i, -0x1.5dba6077f4862p+6 + 0x1.62e070252c271p+6i, 0x1.6ba6479d269e3p+5 + 0x1.5b33a7166f2b4p+5i, 0x1.585ff41442d2fp+7 + -0x1.697509e1e5202p+6i, 0x1.3cccd66fb3738p+6 + 0x1.4fb26574a927ep+5i, 0x1.7cba6d0b303bep+5 + 0x1.c38ceb019cf48p+5i, -0x1.148d84bc9a4c8p+6 + 0x1.84751c104e57p+5i, 0x1.7dfb06406ea76p+8 + 0x1.f4b4b04588c04p+4i, 0x1.7553763b021dcp+4 + 0x1.304d44f0efb56p+6i, -0x1.e9b454a67185cp+5 + -0x1.d5a3f3f643877p+5i, -0x1.00a0037998941p+5 + -0x1.3af8def9a0923p+4i, 0x1.01ed6ddf7dff4p+5 + 0x1.4c996fe5c80a4p+4i, -0x1.ba0c5fc38aa24p+5 + 0x1.0205adf87da5ap+7i, -0x1.9e9d41d7b9a5p+5 + 0x1.e07b51d4e296p-4i, 0x1.172a0e14576c4p+5 + 0x1.e67bad298473cp+1i, -0x1.28dc629e8bb22p+7 + 0x1.229fe5320751p+6i, 0x1.55b9ac8079f08p+3 + -0x1.24527bf64beefp+5i, 0x1.e17814a9a9268p+5 + -0x1.ce9bd5977a664p+6i, -0x1.0300c887cedabp+6 + -0x1.d6a41ebed3644p+6i, -0x1.901cb3e40a02p+5 + 0x1.5cf4bbdf7c854p+6i, -0x1.3b75a3ddf8b29p+6 + -0x1.0e6805c52295ep+5i, -0x1.0f69539dc4604p+7 + -0x1.741bebcf081dp+7i, -0x1.7084f45cc295cp+3 + 0x1.04ffc6890e72p+5i, 0x1.3a74d0231280bp+6 + -0x1.5d4ed829f573bp+6i, 0x1.29d0b347b66fp+3 + 0x1.2de3cd42d78b5p+7i, -0x1.09c6fe361030cp+4 + -0x1.ba5972d3d8d9p+5i, 0x1.b84f1fffd7ad4p+7 + -0x1.6fa08be60679p+3i, -0x1.67649d11c9435p+7 + -0x1.1c283c41f805cp+4i, -0x1.45894745b2272p+5 + -0x1.b6d76adbc7acp+1i, -0x1.24c53c1bc9f12p+6 + -0x1.8d764336086cep+6i, 0x1.2550dbbb6f615p+8 + 0x1.41831704cd672p+5i, -0x1.ab843afd7ff28p+7 + 0x1.6bad18ba48501p+7i, 0x1.837c5858be7a9p+5 + 0x1.3ebd2d04f2c05p+7i, -0x1.7a0a6236cdbf4p+6 + 0x1.524d335558baap+7i, 0x1.2fda176346c4ep+2 + 0x1.7dfcb89e4d25p+4i, -0x1.203dcf46bfbb3p+8 + 0x1.f623966da550fp+6i, -0x1.8e03e21e71dd8p+4 + 0x1.5f085d0271c02p+7i, -0x1.046a8cc237dc2p+8 + 0x1.7d4986f45c161p+6i, 0x1.654e36dbddc61p+8 + -0x1.616d2c5abe3cfp+7i, -0x1.31f51a313f7cbp+5 + 0x1.ffd78676c8bedp+6i, -0x1.51505e24c79a2p+7 + 0x1.f19017326ed8ep+7i, -0x1.f622187d50342p+7 + -0x1.38b80aecc6c88p+5i, 0x1.50c6fb0282d5dp+8 + 0x1.5c1154aed839ap+3i, -0x1.c1ac32a1797f2p+7 + 0x1.194437464e3a2p+5i, -0x1.c994c7f98916cp+7 + 0x1.99bdf505a1c64p+6i, -0x1.b31363d04a5e5p+6 + -0x1.e82768bd6d943p+7i ) assertThat(stats:::fft(z=c(10.3769689360695, 3.89045925409435, -3.93155451710684, 0.153573831713806, -1.04783961013626, -10.1855221959647, 11.8164076174811, -9.13994840621895, 0.409935688496592, 13.2988916104618, -11.7236495512547, 21.9262694854519, 12.6040322122819, -0.0863389609485683, 8.34489120015472, 0.310744867853963, -2.23658861252138, 0.658485206085705, -0.0626673941677851, 7.15513965208027, -0.544128893465904, 5.15423501914293, 4.38448175005372, -0.904842472948961, 0.2775805339831, 0.0308803035634717, 1.34107711032436, -0.153497084592585, 2.04816126107792, -2.11526610039823, 0.246943158442734, -1.14124422902151, -3.11218782007273, -0.0163700627418178, -0.488896649580686, -1.1019570312459, 3.35075365952912, 1.66547490755441, -6.49717335906863, -3.28052359211361, 1.23382310767056, -2.45138055885215, 2.51250126384136, -0.0271116962217204, -0.184040319437394, 12.7866433215337, -1.89941080707841, 3.05008694702956, 6.87739140997331, 2.89443301018167, 0.271820241238419, 4.37619088250706, -3.06388151778674, -1.59959606140044, 0.0575989655674461, -6.24610181567183, 1.74556589836128, -3.05199216148515, 0.774706271640412, 5.44992810383449, 0.159833531324632, 2.03351604615711, 7.80690182082059, 3.11758148188629, 1.01854292767765, 3.06313714268799, 0.827574352820896, 2.61821735617707, -0.152711153261593, 3.755751628488, -1.11473538386617, 0.946614760904571, 4.08138403449373, 4.20025614960369, -1.30585383873611, 2.27036359053031, -0.926932925805462, -4.54873881923498, -0.50336876143755, -2.56745936136268, -3.04877242697759, -1.00312586744339, -0.00378416410938027, 0.910936003569616, -0.631836778269796, 0.510312858996498, -2.92354765268597, 1.10306943710905, 2.29919314724886, -1.87321991824532, 2.4669927172813, 0.358068294514524, 0.00380337099259803, -0.446125627069793, -1.52406424795409, -1.27463878805092, 2.21614137904318, 1.57193247595263, 14.5538884413041, 3.46710714198206, 4.72468305506638, -1.3430860747435, -3.73077013865106, 1.85065852710899, -5.72157328464128, 8.04692769378591, 3.73767929810661, 3.91410448017768, 20.2083152902785, 10.6098562733865, 0.746637293717183, 21.5974966419513, 3.31389859654455, 3.74620415248632, 3.93945666527088, 1.04854360474392, 11.0991587817478, -0.108113528335645, 9.48006382222252, 4.44585462178544, 0.378751233957525, 7.0190297014427, 3.66002216500259, -1.76539244980976, 3.25318377221019, -0.88865832368273, -1.51609931996814, 0.147678530659628, -1.16225659547769, 3.71587870050204, 0.722792979291185, 3.50083088449924, -2.9117023595986, -2.05390228093703, -0.315243770486965, -5.50388497599763, -0.00114163532909583, -1.86494321520475, -1.02433707269956, 4.54030595396632, 2.00659149496241, 8.65809262650767, -0.914156893940845, 8.89026596299435, -0.432425692663963, 4.00091211785122, -0.00157543022378994, 0.426724000693651, -1.5904030942015, -4.00797439268442, 1.47033499195149, -8.55952219222385, -0.0339456146506701, -7.59604542821247, -2.58322051937268, -4.13512803226304, 1.37229917927048, 0.0274893895715603, 1.58059546423238, 8.14239081294032, 0.64869446178064, 3.75300129619135, 0.174009679849268, -3.03602470744253, 2.36560638519996, -9.83417912223005, 3.04791887457806, 0.241980113098912, -5.74314033347827, 1.35663812594123, 5.12707802573771, -3.58448178561661, -2.79800729651505, 4.65676741779916, -8.45736651450507, 8.42669691286806, -4.89435777341983, 0.222665608472774, 8.30638128802811, -0.536805354217068, 3.83307992433144, 3.13945565388085, 1.26089287254575, -0.338219593845652, 0.360488736792198, 0.734597041451225, 0.0728413663988549, -0.0429550163681092, -11.2011972251507, 1.56261634397771, -1.76243263631728, 0.652625493305959, -1.50658004885206, 0.0459572791590621, -0.127876619784889, 0.19304916147501, 0.00218853418649851, -1.65063768818996, -4.88570605637489, -2.41209867567644, -4.25832397816502, -0.805185114119198, 3.33322274466961, 0.514720128060231, 2.77892141035896, -0.209282184888904, -0.170382349915121, -3.00276694891811, -5.25727205970852, -1.98951523670804, -6.99835926329422, 3.80964768181405, -5.90374298388259, 3.69188601654013, 0.0205876925890607, 0.874412719083682, 1.35488109350467, -3.36105879584621, 6.39035798915636, -2.03018244802635, -4.66941941501268, 7.31365481029368, -6.19318963206328, 4.36120630810118, 0.0338305965829966, 1.12454173124518, 4.75904294590333, 7.20109610507202, 7.47220296925565, 19.1011524554177, 0.512577730274398, 4.09872245077606, 25.0373154555524, -3.29091201528813, 20.9920288970487, -1.93460975629614, 19.2531281930142, 17.6305655467313, 4.7850918303363, 29.4761966407364, 0.871908392280801, 0.67689279778011, 11.9808083722274, 0.161412730539107, -0.573355058656647, 1.55726832796194, -2.64815750641634, -4.48866255852029, 0.087321273330414, -2.47854417662451, -3.8934047030487, 0.653073718295956, -3.86438927896759, -0.246959693611369, 0.0153288129725248, -1.3276943870494, -1.12502173353602, 2.68459698838179, 0.172641247948193, 0.903203794314268, 6.7262930418349, 1.41890458032118, 8.18094875658254, 12.588663602125, -0.0705008213560822, 12.6968048940513, 7.11120508411365, -8.56630679620647, 7.98432447821734, -7.93641960579158, -6.5222810590097, 6.30353764577881, -13.9094507206464, 9.50654018575499, 1.84639314861588, 0.975225680148488, 3.21068149621976, 7.27889285339685, -0.724655129113075, 6.48136682671913, 2.37428685168903, -1.77292014815311, 9.27555187597246, -2.13463614063622, 4.5191956838301, -0.417677112657389, -0.430421481648482, 7.83437004292491, 0.00654811630061692, 1.10720677966209, 1.98302898348775, -0.496062225765873, 5.75611244362558, -0.513597650609158, 1.64026304481457, 2.0217179731425, -0.798783993760926, 5.53457992600542, 0.0272914502036241, 2.12999002351161, 2.41041725954075, -1.37910035055917, 1.2165298492145, -1.64436417884747, -4.7050584679401, 1.70371436704242, -4.9332687985093, -0.619273213223634, 3.47898519645994, -10.443205862248, 0.936021640733324, 2.4692323300256, -2.1955901738986, -12.2494573373206, 6.86417665422336, -4.94086593963677, -6.46982704972001, 0.392024021306113, -4.43626734897662, 3.20488240956549, -0.958001093044012, -3.3226181264167, 5.70928470845902, 18.0729402759155, 0.230908525305196, 18.595024652723, 5.13294542703369, 3.35180160365077, 6.03420958009988, -1.43147086062516, 7.37262740571157, 6.06271946632758, 0.342894568539505, 18.0866722512402, -0.423076916529202, 12.1393062765802, 19.9934949716361, -11.141339473657, 16.4430390306652, 12.5191721668165, -9.43482186380282, 13.1896690340484, -1.12271237376982, -0.605348681021117, 15.0372078768461, -5.44382882596991, 20.7525986522452, 19.7052740534224, -1.36525215271322, 38.3737794032807, 11.0853361159213, 5.02034100011704, 12.1016292474391, 0.745337338431947, 7.32444528196261, 13.665264859792, -0.251738578321636, 14.0649291718406, 1.51001740974391, 3.32458817448286, 12.1751078878389, -4.61683116707482, -4.31108386069503, 3.80654337409129, 0.363135519231101, -3.18102612052386, -0.0862401933358587, 2.13622253957576, 4.08672655508491, 0.121758917719383, 1.92546012659766, 1.47270264260665, 0.788427817572375, 0.743446486020762, -0.36822547861602, 0.0732044030160237, -3.13550022030171, -0.947397306382955, 2.38173777491002, -0.644005039073536, 0.705740803875437, 1.9811363516207, 0.265233414626984, 3.34673835342333, 4.94946567227928, -0.119077067070534, 8.88221257501631, 3.38910111935763, -1.34259542556317, 7.30915933507739, -3.84151696886724, -2.53505068393537, 2.28976851041053, -8.0058582634631, 6.47778324925114, -1.7551706978962, -8.82366954632182, 6.3045047452422, 1.90201947677604, 2.9724850743811, 7.22307457478924, 0.702356639281829, 10.9472983124947, 7.78229461230583, 2.44879552266434, 7.39135440092572, 2.23636774265743, 8.54625500300522, 11.6222411948503, 2.46056533756523, 7.05066861111783, 2.73739016146123, 2.26982606069236, 8.82341963996966, -1.16259018234679, 1.89034122140649, 0.144739030331505, -2.39998690309872, 4.77109640665146, -0.277711810619188, -0.107934943159429, -0.196332839172401, -0.300202118442095, -2.2425515102205, -1.35135349279852, 0.215865686786687, -0.23476020767084, -0.100097031422697, -3.3360204087269, -0.191712121367934, 0.0305212696108644, 0.151642722513465, -0.853677272237406, -0.659749705060806, 6.84020336911474, 1.79717777036246, 1.30884624039607, 0.675302239102553, -4.98357726244878, 4.6876288314099, -3.14055491695949, 1.84338798510326, 10.4621374387921, -0.229477430047214, 14.3790391811734, 4.62115597977753, -0.793972589610387, 11.4135812319289, 1.95468734170381, 0.269942430520268, -4.07233175461121, -1.0195134394264, -11.7308112056738, -0.147931417869988, -10.3882047247032, -3.57730374528671, 1.53088269017508, -7.17040132012077, -4.09758228750414, 0.190623376789762, 1.05918085649034, -4.43682411456323, -4.27963307557612, -1.43184592061964, -16.781852832601, 4.52942726860158, -10.8210179935055, -12.8210219881286 )) , identicalTo( expected, tol = 1e-6 ) )
library(sensR) RUN <- FALSE op <- options() options("digits" = 7) options(help_type = "html") options("width" = 75) options("SweaveHooks" = list(fig=function() par(mar=c(4,4,.5,0)+.5))) options(continue=" ") G.test <- function(x, ...) { ct <- eval.parent(chisq.test(x, correct = FALSE)) ct$data.name <- deparse(substitute(x)) o <- ct$observed e <- ct$expected ct$statistic <- 2 * sum(ifelse(o == 0, 0, o * log(o/e))) names(ct$statistic) <- "G-squared" ct$p.value <- with(ct, pchisq(statistic, parameter, lower = FALSE)) ct$method <- "Likelihood ratio Chi-squared test" return(ct) } pd <- seq(0, 1-1e-5, length = 1e2) coef.twoAFC <- coef(rescale(pd = pd, method = "twoAFC")) coef.threeAFC <- coef(rescale(pd = pd, method = "threeAFC")) pd <- seq(0, 1-1e-2, length = 1e2) coef.triangle <- coef(rescale(pd = pd, method = "triangle")) coef.duotrio <- coef(rescale(pd = pd, method = "duotrio")) tail(coef.duotrio) tail(coef.twoAFC) tail(coef.threeAFC) tail(coef.triangle) dPrime <- seq(1e-5, 6, len = 1e2) gd1 <- psyderiv(dPrime, method = "twoAFC") gd2 <- psyderiv(dPrime, method = "threeAFC") gd3 <- psyderiv(dPrime, method = "duotrio") gd4 <- psyderiv(dPrime, method = "triangle") getOption("SweaveHooks")[["fig"]]() plot(c(0, 6), c(.3, 1), type = "n", xlab = "d-prime", ylab = "P(correct answer)", axes = FALSE) axis(1) axis(2, las = 1) with(coef.twoAFC, lines(d.prime, pc, lty = 1)) with(coef.threeAFC, lines(d.prime, pc, lty = 2)) with(coef.duotrio, lines(d.prime, pc, lty = 3)) with(coef.triangle, lines(d.prime, pc, lty = 4)) legend("topleft", legend = c("2-AFC", "3-AFC", "duo-trio", "triangle"), lty = 1:4, bty = "n") getOption("SweaveHooks")[["fig"]]() plot(c(0, 6), c(0, 1), type = "n", xlab = "d-prime", ylab = "P(discrimination)", axes = FALSE) axis(1) axis(2, las = 1) with(coef.twoAFC, lines(d.prime, pd, lty = 1)) with(coef.threeAFC, lines(d.prime, pd, lty = 2)) with(coef.duotrio, lines(d.prime, pd, lty = 3)) with(coef.triangle, lines(d.prime, pd, lty = 4)) legend("topleft", legend = c("2-AFC", "3-AFC", "duo-trio", "triangle"), lty = 1:4, bty = "n") getOption("SweaveHooks")[["fig"]]() plot(c(0.3, 1), c(0, 1), type = "n", ylab = "P(correct answer)", xlab = "P(discrimination)", axes = FALSE) axis(1); axis(2, las = 1) segments(c(1/3, .5), 0, 1, 1, lty = 1:2) legend("topleft", legend = c("3-AFC and triangle", "2-AFC and duo-trio"), lty = 1:2, bty = "n") getOption("SweaveHooks")[["fig"]]() plot(c(0, 6), c(0, .31), type = "n", axes = FALSE, xlab = "d-prime", ylab = "Grad(psychometic function)") axis(1); axis(2, las = 1) lines(dPrime, gd1, lty = 1) lines(dPrime, gd2, lty = 2) lines(dPrime, gd3, lty = 3) lines(dPrime, gd4, lty = 4) legend("topright", legend = c("2-AFC", "3-AFC", "duo-trio", "triangle"), lty = 1:4, bty = "n") rescale(pc = 0.25, method = "triangle") rescale(pd = 0.2, std.err = 0.12, method = "triangle") discrim(10, 15, method = "threeAFC", statistic = "likelihood") discrim(4, 15, method = "threeAFC", test = "similarity", pd0 = 0.2, statistic = "exact") getOption("SweaveHooks")[["fig"]]() fm1 <- discrim(10, 15, method = "threeAFC", statistic = "exact") confint(fm1) plot(profile(fm1)) getOption("SweaveHooks")[["fig"]]() fm1 <- discrim(10, 15, method = "threeAFC", statistic = "exact") confint(fm1) plot(profile(fm1)) 1 - pbinom(q = 15 - 1, size = 20, prob = 0.5) 1 - pbinom(q = 14 - 1, size = 20, prob = 0.5) i <- 0 while (1 - pbinom(q = i, size = 20, prob = 0.5) > 0.05) { i <- i + 1 } i + 1 findcr(sample.size = 20, alpha = 0.05, p0 = 0.5) 1 - pbinom(q = 15 - 1, size = 20, prob = 3/4) discrimPwr(pdA = 0.5, sample.size = 20, alpha = 0.05, pGuess = 1/2) discrimPwr(pdA = 0.5, pd0 = 0.1, sample.size = 20, alpha = 0.05, pGuess = 1/2) discrimPwr(pdA = 0, pd0 = 1/3, sample.size = 100, alpha = 0.05, pGuess = 1/2, test = "similarity") discrimPwr(pdA = 1/5, pd0 = 1/3, sample.size = 100, alpha = 0.05, pGuess = 1/2, test = "similarity") set.seed(12345) xx <- rbinom(10000, 20, 3/4) sum(xx == 0) pp <- 1 - pbinom(xx-1, 20, 1/2) sum(pp <= 0.05) (power <- mean(pp <= 0.05)) (se.power <- sqrt(power * (1 - power) / 1e4)) power + c(-1,1) * qnorm(.975) * se.power ss <- 275:325 (pd <- coef(rescale(d.prime = .9, method = "triangle"))$pd) pwr <- sapply(ss, function(x) discrimPwr(pdA = pd, sample.size = x, pGuess = 1/3)) pwrN <- sapply(ss, function(x) discrimPwr(pdA = pd, sample.size = x, pGuess = 1/3, statistic = "normal")) getOption("SweaveHooks")[["fig"]]() plot(range(ss), c(0.74, max(pwrN)), type = "n", xlab = "sample size", ylab = "power", axes = FALSE) lines(ss, pwr, type = "l") points(ss, pwr, pch = 20, cex = .8) abline(h = 0.8, lty = 2) lines(ss, pwrN, col = "blue") legend("topleft", legend = c("exact binomial", "normal approx.", "target power"), lty = c(1, 1, 2), pch = c(20, NA, NA), col = c(1, "blue", 1), pt.cex = .8) axis(2, las = 1) axis(1, at = c(275, 297, 297+21, 325)) segments(297, 0.6, 297, discrimPwr(pd, sample.size = 297, pGuess = 1/3), lty = 3) segments(297+21, 0.6, 297+21, discrimPwr(pd, sample.size = 297+21, pGuess = 1/3), lty = 3) getOption("SweaveHooks")[["fig"]]() xcr <- sapply(ss, function(ss) findcr(ss, p0 = 1/3)) plot(ss, xcr, type = "l", axes = FALSE, ylab = "Critical value", xlab = "Sample size") points(ss, xcr, pch = 20) axis(1); axis(2) getOption("SweaveHooks")[["fig"]]() aa <- sapply(ss, function(n) 1 - pbinom(findcr(n, p0 = 1/3) - 1, n, 1/3)) plot(ss, aa, pch = 20, ylim = c(0.03, .05), axes = FALSE, ylab = "Actual alpha-level", xlab = "Sample size") lines(ss, aa, lty = 1) axis(1); axis(2) (pd <- coef(rescale(d.prime = .9, method = "triangle"))$pd) discrimSS(pdA = pd, pd0 = 0, target.power = 0.8, alpha = 0.05, pGuess = 1/3, test = "difference", statistic = "exact") discrimSS(pdA = pd, pd0 = 0, target.power = 0.8, alpha = 0.05, pGuess = 1/3, test = "difference", statistic = "normal")
caltheta <- function(fixdist, pd=NULL, gender=NULL, eye = c("left", "right")) { if (is.null(c(pd, gender))) stop("the value of either pd or gender has to be provided") if (!is.null(pd)) { stopifnot(length(pd) == 1, is.numeric(pd)) } if (!is.null(gender)) { stopifnot(gender %in% c("male", "female")) } if (getOption("warn") > 0) { stopifnot(is.numeric(fixdist), length(fixdist) == 2, eye %in% c("left", "right")) } if (is.null(pd)){ pd <- ifelse(gender== "female", .ddivfEnv$pd_gender[1], .ddivfEnv$pd_gender[2]) } if (eye == "left") { theta <- atan2(-pd/2 - fixdist[2], fixdist[1]) } else { theta <- atan2(pd/2 - fixdist[2], fixdist[1]) } return(theta) }
xparse_glimmer_formula <- function( formula , data ) { nobars <- function(term) { if (!('|' %in% all.names(term))) return(term) if (is.call(term) && term[[1]] == as.name('|')) return(NULL) if (length(term) == 2) { nb <- nobars(term[[2]]) if (is.null(nb)) return(NULL) term[[2]] <- nb return(term) } nb2 <- nobars(term[[2]]) nb3 <- nobars(term[[3]]) if (is.null(nb2)) return(nb3) if (is.null(nb3)) return(nb2) term[[2]] <- nb2 term[[3]] <- nb3 term } findbars <- function(term) { if (is.name(term) || !is.language(term)) return(NULL) if (term[[1]] == as.name("(")) return(findbars(term[[2]])) if (!is.call(term)) stop("term must be of class call") if (term[[1]] == as.name('|')) return(term) if (length(term) == 2) return(findbars(term[[2]])) c(findbars(term[[2]]), findbars(term[[3]])) } subbars <- function(term) { if (is.name(term) || !is.language(term)) return(term) if (length(term) == 2) { term[[2]] <- subbars(term[[2]]) return(term) } stopifnot(length(term) >= 3) if (is.call(term) && term[[1]] == as.name('|')) term[[1]] <- as.name('+') for (j in 2:length(term)) term[[j]] <- subbars(term[[j]]) term } hasintercept <- function(term) { attr( terms(term) , "intercept" )==1 } f_nobars <- nobars( formula ) if ( class(f_nobars)=="name" & length(f_nobars)==1 ) { f_nobars <- nobars( as.formula( paste( deparse(formula) , "+ 1" ) ) ) } fixef <- colnames( model.matrix( f_nobars , data ) ) mdat <- model.matrix( subbars( formula ) , data ) outcome_name <- deparse( f_nobars[[2]] ) outcome <- model.frame( f_nobars , data )[,1] if ( class(outcome)=="matrix" ) { outcome_name <- colnames( outcome )[1] } if ( formula == nobars(formula) ) { ranef <- list() } else { var <- findbars( formula ) ranef <- list() for ( i in 1:length(var) ) { name <- all.vars( var[[i]][[3]] ) if ( FALSE ) { if ( TRUE ) { if ( class( data[[name]] )!="integer" ) { stop( paste( "Grouping variables must be integer type. '" , name , "' is instead of type: " , class( data[[name]] ) , "." , sep="" ) ) } if ( min(data[[name]]) != 1 ) stop( paste( "Group variable '" , name , "' doesn't start at index 1." , sep="" ) ) ulist <- unique( data[[name]] ) diffs <- ulist[2:length(ulist)] - ulist[1:(length(ulist)-1)] if ( any(diffs != 1) ) stop( paste( "Group variable '" , name , "' is not contiguous." , sep="" ) ) } else { mdat[,name] <- as.integer( as.factor( mdat[,name] ) ) } } v <- var[[i]][[2]] if ( class(v)=="numeric" ) { ranef[[ name ]] <- "(Intercept)" } else { f <- as.formula( paste( "~" , deparse( v ) , sep="" ) ) ranef[[ name ]] <- colnames( model.matrix( f , data ) ) } } } list( y=outcome , yname=outcome_name , fixef=fixef , ranef=ranef , dat=as.data.frame(mdat) ) } glimmer <- function( formula , data , family=gaussian , prefix=c("b_","v_") , default_prior="dnorm(0,10)" , ... ) { undot <- function( astring ) { astring <- gsub( "." , "_" , astring , fixed=TRUE ) astring <- gsub( ":" , "_X_" , astring , fixed=TRUE ) astring <- gsub( "(" , "" , astring , fixed=TRUE ) astring <- gsub( ")" , "" , astring , fixed=TRUE ) astring } family.orig <- family if ( class(family)=="function" ) { family <- do.call(family,args=list()) } link <- family$link family <- family$family family_liks <- list( gaussian = "dnorm( mu , sigma )", binomial = "dbinom( size , p )", poisson = "dpois( lambda )" ) lm_names <- list( gaussian = "mu", binomial = "p", poisson = "lambda" ) link_names <- list( gaussian = "identity", binomial = "logit", poisson = "log" ) if ( class(formula)!="formula" ) stop( "Input must be a glmer-style formula." ) if ( missing(data) ) stop( "Need data" ) f <- formula flist <- alist() prior_list <- alist() pf <- xparse_glimmer_formula( formula , data ) pf$yname <- undot(pf$yname) dtext <- family_liks[[family]] if ( family=="binomial" ) { if ( class(pf$y)=="matrix" ) { pf$dat[[pf$yname]] <- pf$y[,1] pf$dat[[concat(pf$yname,"_size")]] <- apply(pf$y,1,sum) dtext <- concat("dbinom( ",concat(pf$yname,"_size")," , p )") } else { pf$dat[[pf$yname]] <- pf$y dtext <- concat("dbinom( 1 , p )") } } else { pf$dat[[pf$yname]] <- pf$y } flist[[1]] <- concat( as.character(pf$yname) , " ~ " , dtext ) flm <- "" for ( i in 1:length(pf$fixef) ) { aterm <- undot(pf$fixef[i]) newterm <- "" if ( aterm=="Intercept" ) { newterm <- aterm prior_list[[newterm]] <- default_prior } else { par_name <- concat( prefix[1] , aterm ) newterm <- concat( par_name , "*" , aterm ) prior_list[[par_name]] <- default_prior } if ( i > 1 ) flm <- concat( flm , " +\n " ) flm <- concat( flm , newterm ) } vlm <- "" num_group_vars <- length(pf$ranef) if ( num_group_vars > 0 ) { for ( i in 1:num_group_vars ) { group_var <- undot(names(pf$ranef)[i]) members <- list() for ( j in 1:length(pf$ranef[[i]]) ) { aterm <- undot(pf$ranef[[i]][j]) newterm <- "" var_prefix <- prefix[2] if ( num_group_vars>1 ) var_prefix <- concat( var_prefix , group_var , "_" ) if ( aterm=="Intercept" ) { par_name <- concat( var_prefix , aterm ) newterm <- concat( par_name , "[" , group_var , "]" ) } else { par_name <- concat( var_prefix , aterm ) newterm <- concat( par_name , "[" , group_var , "]" , "*" , aterm ) } members[[par_name]] <- par_name if ( i > 1 | j > 1 ) vlm <- concat( vlm , " +\n " ) vlm <- concat( vlm , newterm ) } if ( length(members)>1 ) { gvar_name <- concat( "c(" , paste(members,collapse=",") , ")" , "[" , group_var , "]" ) prior_list[[gvar_name]] <- concat( "dmvnorm2(0,sigma_" , group_var , ",Rho_" , group_var , ")" ) prior_list[[concat("sigma_",group_var)]] <- concat( "dcauchy(0,2)" ) prior_list[[concat("Rho_",group_var)]] <- concat( "dlkjcorr(2)" ) } else { gvar_name <- concat( members[[1]] , "[" , group_var , "]" ) prior_list[[gvar_name]] <- concat( "dnorm(0,sigma_" , group_var , ")" ) prior_list[[concat("sigma_",group_var)]] <- concat( "dcauchy(0,2)" ) } pf$dat[[group_var]] <- coerce_index( data[[group_var]] ) } } if ( family=="gaussian" ) { prior_list[["sigma"]] <- "dcauchy(0,2)" } lm_name <- lm_names[[family]] if ( vlm=="" ) lm_txt <- concat( flm ) else lm_txt <- concat( flm , " +\n " , vlm ) lm_left <- concat( link , "(" , lm_name , ")" ) if ( link=="identity" ) lm_left <- lm_name flist[[2]] <- concat( lm_left , " <- " , lm_txt ) for ( i in 1:length(prior_list) ) { pname <- names(prior_list)[i] p_txt <- prior_list[[i]] flist[[i+2]] <- concat( pname , " ~ " , p_txt ) } flist_txt <- "alist(\n" for ( i in 1:length(flist) ) { flist_txt <- concat( flist_txt , " " , flist[[i]] ) if ( i < length(flist) ) flist_txt <- concat( flist_txt , ",\n" ) } flist_txt <- concat( flist_txt , "\n)" ) flist2 <- eval(parse(text=flist_txt)) names(pf$dat) <- sapply( names(pf$dat) , undot ) pf$dat[['Intercept']] <- NULL cat(flist_txt) cat("\n") invisible(list(f=flist2,d=pf$dat)) } if ( FALSE ) { library(rethinking) data(chimpanzees) f0 <- pulled.left ~ prosoc.left*condition - condition m0 <- glimmer( f0 , chimpanzees , family=binomial ) f1 <- pulled.left ~ (1|actor) + prosoc.left*condition - condition m1 <- glimmer( f1 , chimpanzees , family=binomial ) f2 <- pulled.left ~ (1+prosoc.left|actor) + prosoc.left*condition - condition m2 <- glimmer( f2 , chimpanzees , family=binomial ) data(UCBadmit) f3 <- cbind(admit,reject) ~ (1|dept) + applicant.gender m3 <- glimmer( f3 , UCBadmit , binomial ) m3s <- map2stan( m3$f , data=m3$d ) f4 <- cbind(admit,reject) ~ (1+applicant.gender|dept) + applicant.gender m4 <- glimmer( f4 , UCBadmit , binomial ) m4s <- map2stan( m4$f , data=m4$d ) data(Trolley) f5 <- response ~ (1|id) + (1|story) + action + intention + contact m5 <- glimmer( f5 , Trolley ) m5s <- map2stan( m5$f , m5$d , sample=FALSE ) f6 <- response ~ (1+action+intention|id) + (1+action+intention|story) + action + intention + contact m6 <- glimmer( f6 , Trolley ) m6s <- map2stan( m6$f , m6$d , sample=TRUE ) }
ginv <- function(x, tol = sqrt(.Machine$double.eps)) { dnx <- dimnames(x) if(is.null(dnx)) dnx <- vector("list", 2) s <- svd(x) nz <- s$d > tol * s$d[1] structure( if(any(nz)) s$v[, nz] %*% (t(s$u[, nz])/s$d[nz]) else x, dimnames = dnx[2:1]) } threesls<-function(y,reg,iv){ N<-length(y) df<-nrow(reg)-ncol(reg) th<-crossprod(iv,iv) thx<-crossprod(iv,reg) xhat<-iv%*%ginv(th)%*%thx beta<-ginv(crossprod(xhat,reg))%*%crossprod(xhat,y) yhat<-reg%*%beta res<-y-yhat resvar<-sum(res^2)/(N) varcoef<-resvar*ginv(crossprod(xhat,xhat)) sd<-sqrt(diag(varcoef)) st<-beta/sd rsq<-(cor(yhat,y))^2 sig<-crossprod(res) sig<-sig/(length(y)) bb<-kronecker(sig,iv) b<-crossprod(iv,bb) b<-ginv(b) a<-crossprod(iv,reg) c<-crossprod(iv,y) d<-ginv(t(a)%*%b%*%a) beta<-d%*%crossprod(a,b)%*%c pval<- 2*pt(-abs(st),df=df) list(beta=beta,sd=sd,st=st,pval=pval,rsq=rsq) } tsls <- function(x,...){UseMethod("tsls") } tsls.default <- function(y,x,h,...) { x<-as.matrix(x) h<-as.matrix(h) y<-as.numeric(y) est <- threesls(y,x,h) est$call <- match.call() class(est) <- "tsls" est } print.tsls <- function(x,...) { cat("Call:\n") print(x$call) cat("\nCoefficients:\n") print(x$coefficients) } summary.tsls<-function(object,...) { result <- cbind(object$beta,object$sd, object$st,object$pval) colnames(result) <- c("Estimates", "Std.Err", "T-value", "P-Value") cat("Formula:") print(object$equa) cat("\nRsquared :",object$rsq,"\n") printCoefmat(result,has.Pvalue=TRUE) } tsls.formula <-function(formula,data=list(),...) { mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0) mf <- mf[c(1, m)] f <- Formula(formula) mf[[1]] <- as.name("model.frame") mf$formula <- f mf <- eval(mf, parent.frame()) x <- model.matrix(f, data = mf, rhs = 1) h <- model.matrix(f, data = mf, rhs = 2) y <- model.response(mf) est <- tsls.default(y,x,h,...) est$call <- match.call() est$equa <- formula est }
sim2dist <- function(x, maxSim = 1){ stopifnot(is.matrix(x)) stopifnot(isSymmetric(x)) stopifnot(maxSim >= max(x)) d <- maxSim - x return(as.dist(d)) }
`mlcm` <- function(x, ...) { UseMethod("mlcm") }
vcov.gamlss <- function (object, type = c("vcov", "cor", "se", "coef", "all"), robust = FALSE, hessian.fun = c("R", "PB"), ...) { HessianPB<-function (pars, fun, ..., .relStep = (.Machine$double.eps)^(1/3), minAbsPar = 0) { pars <- as.numeric(pars) npar <- length(pars) incr <- ifelse(abs(pars) <= minAbsPar, minAbsPar * .relStep, abs(pars) * .relStep) baseInd <- diag(npar) frac <- c(1, incr, incr^2) cols <- list(0, baseInd, -baseInd) for (i in seq_along(pars)[-npar]) { cols <- c(cols, list(baseInd[, i] + baseInd[, -(1:i)])) frac <- c(frac, incr[i] * incr[-(1:i)]) } indMat <- do.call("cbind", cols) shifted <- pars + incr * indMat indMat <- t(indMat) Xcols <- list(1, indMat, indMat^2) for (i in seq_along(pars)[-npar]) { Xcols <- c(Xcols, list(indMat[, i] * indMat[, -(1:i)])) } coefs <- solve(do.call("cbind", Xcols), apply(shifted, 2, fun, ...))/frac Hess <- diag(coefs[1 + npar + seq_along(pars)], ncol = npar) Hess[row(Hess) > col(Hess)] <- coefs[-(1:(1 + 2 * npar))] list(mean = coefs[1], gradient = coefs[1 + seq_along(pars)], Hessian = (Hess + t(Hess))) } type <- match.arg(type) hessian.fun <- match.arg(hessian.fun) if (!is.gamlss(object)) stop(paste("This is not an gamlss object", "\n", "")) coefBeta <- list() for (i in object$par) { if (length(eval(parse(text=paste(paste("object$",i, sep=""),".fix==TRUE", sep=""))))!=0) { ff <- eval(parse(text=paste(paste(paste(object$family[1],"()$", sep=""), i, sep=""),".linkfun", sep=""))) fixvalue <- ff( fitted(object,i)[1]) names(fixvalue) <- paste("fixed",i, sep=" ") coefBeta <- c(coefBeta, fixvalue) } else { if (!is.null(unlist(attr(terms(formula(object, i), specials = .gamlss.sm.list), "specials")))) warning(paste("Additive terms exists in the ", i, "formula. \n " ,"Standard errors for the linear terms maybe are not appropriate")) nonNAcoef <- !is.na(coef(object, i)) coefBeta <- c(coefBeta, coef(object, i)[nonNAcoef]) } } betaCoef <- unlist(coefBeta) like.fun <- gen.likelihood(object) hess <- if (hessian.fun=="R" ) optimHess(betaCoef, like.fun) else HessianPB(betaCoef, like.fun)$Hessian varCov <- try(solve(hess), silent = TRUE) if (any(class(varCov)%in%"try-error")||any(diag(varCov)<0)) { varCov <- try(solve(HessianPB(betaCoef, like.fun)$Hessian), silent = TRUE) if (any(class(varCov)%in%"try-error")) stop("the Hessian matrix is singular probably the model is overparametrised") } rownames(varCov) <- colnames(varCov) <- rownames(hess) se <- sqrt(diag(varCov)) corr <- cov2cor(varCov) coefBeta <- unlist(coefBeta) if (robust) { K <- get.K(object) varCov <- varCov%*%K%*%varCov se <- sqrt(diag(varCov)) corr <- cov2cor(varCov) } switch(type, vcov = varCov, cor = corr, se = se, coef = coefBeta, all = list(coef = coefBeta, se = se, vcov = varCov, cor = corr)) }
source("ESEUR_config.r") brew_col=rainbow_hcl(3) funcs=read.csv(paste0(ESEUR_dir, "evolution/functions/ev_funcmod.tsv.xz"), as.is=TRUE, sep="\t") revdate=read.csv(paste0(ESEUR_dir, "evolution/functions/ev_rev_date.csv.xz"), as.is=TRUE) funcs$date=revdate$date_time[funcs$revid %in% revdate$revid] merge_move=function(df) { deleted=subset(df, typemod == "D") added=subset(df, typemod == "A") return (cbind(nrow(deleted), nrow(added))) } all_moves=ddply(funcs, .(func_name), merge_move) table(all_moves[, 2:3]) count_mods=function(df) { df=subset(df, typemod != "D") num_mods=nrow(df) num_authors=length(unique(df$author)) return(cbind(num_mods, num_authors)) } mod_count=ddply(funcs, .(filename,func_name), count_mods) total_mods=ddply(mod_count, .(num_mods, num_authors), nrow) plot_mods=function(X) { par(new=X != 1) t=subset(total_mods, num_authors == X) plot(t$num_mods, t$V1, type="l", col=brew_col[X], log="y", xlab="Modifications", ylab="Functions", xlim=xbounds, ylim=ybounds) } xbounds=c(1, 15) ybounds=c(1, max(total_mods$V1)) pal_col=rainbow_hcl(5) dummy=sapply(1:5, plot_mods) legend(x="topright",legend=c("1 author", "2 authors", "3 authors", "4 authors", "5 authors"), bty="n", fill=brew_col) plot_layout(1, 2) all_mods=ddply(total_mods, .(num_mods), function(df) sum(df$V1)) plot(all_mods$num_mods, all_mods$V1, log="y", xlim=c(0, 50), xlab="Modifications", ylab="Functions") a_mod=glm(V1 ~ num_mods, data=all_mods[2:15, ], family=quasipoisson) lines(1:15, predict(a_mod, newdata=data.frame(num_mods=1:15), type="response"), col=brew_col[2]) s=exp(a_mod$coefficients[2]) M_t=s/(1-s) author_mods=ddply(total_mods, .(num_authors), function(df) sum(df$V1)) plot(author_mods$num_authors, author_mods$V1, log="y", xlab="Authors", ylab="Functions") a_authors=glm(V1 ~ num_authors, data=author_mods[2:20, ], family=quasipoisson) lines(1:20, predict(a_authors, newdata=data.frame(num_authors=1:20), type="response"), col=brew_col[2]) s=exp(a_authors$coefficients[2]) M_t=s/(1-s)
print.l1.reg <- function (x, ...) { cat ("\n Call: \n") print (x$call) cat (" cat (" cat ("\n Lambda used:", x$lambda, "\n") cat ("\n") cat ("\n Intercept: \n") print (x$intercept) cat ("\n Selected Coefficient Estimates: \n") print (cbind(Predictor=rownames(x$X)[x$selected+1],Estimate=x$estimate[x$selected]),justify="centre") cat ("\n Number of Active Variables: \n") print (x$nonzeros) }
discoveries <- function(hommel, ix, incremental=FALSE, alpha=0.05) { m <- length(hommel@p) if (missing(ix) & incremental==FALSE) { k <- m ix <- hommel@sorter } if (missing(ix) & incremental==TRUE) { stop('Found incremental=TRUE but missing ix.') } if (!missing(ix)) { k <- length(hommel@p[ix]) } if (any(is.na(hommel@p[ix]))) stop('NAs produced by selecting with ix.') if (k == 0) { warning('empty selection') return(0) } h <- findHalpha(hommel@jumpalpha, alpha, m) simesfactor <- hommel@simesfactor[h+1] allsortedp <- hommel@p[hommel@sorter] ix_sortedp <- integer(m) names(ix_sortedp) <- names(hommel@p) ix_sortedp[hommel@sorter] <- 1:m ix_sortedp <- ix_sortedp[ix] discoveries <- findDiscoveries(ix_sortedp, allsortedp, simesfactor, h, alpha, k, m) if(!incremental) return(discoveries[k+1]) else return(discoveries[-1]) } tdp <- function(hommel, ix, incremental=FALSE, alpha=0.05) { m <- length(hommel@p) if (missing(ix)) { k <- m d <- discoveries(hommel, incremental=incremental, alpha=alpha) } else { k <- length(hommel@p[ix]) d <- discoveries(hommel, ix, incremental=incremental, alpha=alpha) } d/k } fdp <- function(hommel, ix, incremental = FALSE, alpha=0.05) { 1-tdp(hommel, ix, incremental=incremental, alpha=alpha) }
context("test-basic_yaml_results") if (!rmarkdown::pandoc_available()) testthat::skip("Pandoc not found") test_that("Basic YAML is rendered correctly", { rslt <- yml_empty() %>% yml_author( c("Yihui Xie", "Hadley Wickham"), affiliation = rep("RStudio", 2) ) %>% yml_date("07/04/2019") %>% yml_output( pdf_document( keep_tex = TRUE, includes = includes2(after_body = "footer.tex") ) ) %>% yml_latex_opts(biblio_style = "apalike") %>% stringify_yaml() yaml_string <- "--- author: - name: Yihui Xie affiliation: RStudio - name: Hadley Wickham affiliation: RStudio date: 07/04/2019 output: pdf_document: keep_tex: true includes: after_body: footer.tex biblio-style: apalike ---" expect_equal(rslt, yaml_string) }) test_that("output fields render correctly", { rslts <- yml_empty() %>% yml_output(html_document()) %>% stringify_yaml() yaml_string <- "--- output: html_document ---" expect_equal(rslts, yaml_string) }) test_that("LaTeX options render correctly", { rslt <- yml_empty() %>% yml_author("Malcolm Barrett") %>% yml_output(pdf_document()) %>% yml_latex_opts( fontfamily = "Fira Sans Thin", fontsize = "11pt", links_as_notes = TRUE ) %>% stringify_yaml() yaml_string <- "--- author: Malcolm Barrett output: pdf_document fontfamily: Fira Sans Thin fontsize: 11pt links-as-notes: true ---" expect_equal(rslt, yaml_string) }) test_that("Code chunk is rendered correctly", { rslt <- code_chunk({ yml_empty() %>% yml_author("Malcolm Barrett") %>% yml_output(pdf_document()) }, chunk_name = "yml_example") yaml_string <- '```{r yml_example} yml_empty() %>% yml_author("Malcolm Barrett") %>% yml_output(pdf_document()) ```' expect_equal(rslt, yaml_string) })
demvn <- function(y, X, log = FALSE, verbose = TRUE, alpha=2, beta=1.25) { if( !is.matrix(y) ) y <- matrix(y, 1, length(y)) tmp <- robCov( t(X), alpha = alpha, beta = beta ) if( length(tmp$lowVar) ) stop("The columns of X indexed ", tmp$lowVar, " have zero variance.") llk <- apply(y, 1, function(input) .demvn(y = input, L = tmp, log = log) ) return(llk) } .demvn <- function(y, L, log) { rss <- sum( (L$E%*%as.vector(y-L$mY))^2 ) llk <- -rss/2 - L$half.ldet.V - log(2 * pi) * length(y) / 2 if( !log ) llk <- exp( llk ) return(llk) }
library(knitr) opts_chunk$set(echo = TRUE) if (requireNamespace("Cairo", quietly = TRUE)) { opts_chunk$set(dev='CairoPNG') } par_hook = function(before, options, envir) { if(before) { do.call(par, options$par) } } knit_hooks$set(par = par_hook) library(dexter) library(dplyr) library(tidyr) select = dplyr::select sim_PV = function(theta, delta) { nit = length(delta) sim_func = r_score( tibble(item_id=1:nit, item_score=1, delta=delta)) simulated_data = sim_func(theta) parms = fit_enorm(simulated_data) pv = plausible_values(simulated_data, parms, nPV = 10) plot(x=c(min(theta)-.5, max(theta)+.5), y=0:1, main=paste(nit, "items"), bty='l', type='n', xlab=bquote(theta), ylab = bquote(Fn(theta))) select(pv, starts_with('PV')) %>% lapply(function(x) lines(ecdf(x-mean(x)), col=rgb(.7,.7,.7,.5))) lines(ecdf(theta-mean(theta))) } theta = rnorm(300) delta = runif(50, -2, 1) sim_PV(theta, delta) grp = sample(2, 300, replace = TRUE, prob = c(.5,.5)) theta = rnorm(300, mean = c(-2,2)[grp], sd = c(1,1)[grp]) plot(density(theta),bty='l',main='') par(mfrow=c(1,3)) sim_PV(theta, delta[1:10]) sim_PV(theta, delta[1:20]) sim_PV(theta, delta) sim_PV2 = function(theta, delta) { nit = length(delta) sim_func = r_score( tibble(item_id=1:nit, item_score=1, delta=delta)) simulated_data = sim_func(theta) parms = fit_enorm(simulated_data, method="Bayes", nDraws = 50) plot(x=c(min(theta)-.5, max(theta)+.5), y=0:1, main=paste(nit, "items"), bty='l', type='n', xlab=bquote(theta), ylab = bquote(Fn(theta))) which.draw = 5*(1:10) for (iter in 1:10) { pv = plausible_values(simulated_data, parms, use_draw=which.draw[iter]) lines(ecdf(pv$PV1-mean(pv$PV1)), col=rgb(.7,.7,.7,.5)) } lines(ecdf(theta-mean(theta))) } sim_PV2(theta, delta[1:10]) sim_PV2(theta, delta[1:20]) sim_PV2(theta, delta) sim_PV3 = function(theta, delta, group) { nit = length(delta) sim_func = r_score( tibble(item_id=1:nit, item_score=1, delta=delta)) simulated_data = sim_func(theta) parms = fit_enorm(simulated_data) simulated_data = simulated_data %>% as_tibble() %>% mutate(person_id=row_number(), group=group) %>% gather(key='item_id', value='item_score', -person_id, -group) pv = plausible_values(simulated_data, parms, covariates='group',nPV = 10) plot(x=c(min(theta)-.5, max(theta)+.5), y=0:1, main=paste(nit, "items"), bty='l', type='n', xlab=bquote(theta), ylab = bquote(Fn(theta))) select(pv, starts_with('PV')) %>% lapply(function(x) lines(ecdf(x-mean(x)), col=rgb(.7,.7,.7,.5))) lines(ecdf(theta-mean(theta))) } sim_PV3(theta, delta[1:10],grp) sim_PV3(theta, delta[1:20],grp) sim_PV3(theta, delta,grp)
plot_signal <- function(z, f, size=0.75, limits=range(f)) { if(is(z$sA, 'sparseMatrix')){ z$sA <- summary(z$sA) } x <- z$xy[, 1] y <- z$xy[, 2] ind_i <- z$sA[, 1] ind_j <- z$sA[, 2] y1 <- x[ind_j] y2 <- y[ind_j] df1 <- data.frame(x = x, y = y) df2 <- data.frame(x = x[ind_i], y = y[ind_i], y1 = y1, y2 = y2) p2 <- ggplot(df1, aes(x, y)) + geom_segment(aes(x = x, y = y, xend = y1, yend = y2), color = "gray", data = df2) + geom_point(size = size, aes(colour = f)) + scale_colour_distiller(palette = "Spectral", limits = limits) + theme_void() + theme( legend.text=element_text(size=8), legend.key.size = unit(0.8,"line"), legend.margin = margin(0.0,0.0,0.0,0.0), plot.margin = unit(c(0.01,0.01,0.01,0.01), "cm")) print(p2) }
cleannames <- function(objnames, no_dots = FALSE){ objnames[objnames == ""] <- NA_character_ is_missing <- is.na(objnames) objnames[is_missing] <- as.character(seq_len(length(objnames)))[is_missing] if(isTRUE(no_dots)) objnames <- gsub(".", "_", objnames, fixed = TRUE) make.unique(objnames) }
prl_fictitious_rp_woa <- hBayesDM_model( task_name = "prl", model_name = "fictitious_rp_woa", model_type = "", data_columns = c("subjID", "choice", "outcome"), parameters = list( "eta_pos" = c(0, 0.5, 1), "eta_neg" = c(0, 0.5, 1), "beta" = c(0, 1, 10) ), regressors = list( "ev_c" = 2, "ev_nc" = 2, "pe_c" = 2, "pe_nc" = 2, "dv" = 2 ), postpreds = c("y_pred"), preprocess_func = prl_preprocess_func)