code
stringlengths
1
13.8M
NULL backsolve_float32 = function(r, x, k=ncol(r), upper.tri=TRUE, transpose=FALSE) { if (is.integer(r)) { if (is.float(x)) r = fl(r) } if (is.integer(x)) { if (is.float(r)) x = fl(x) } if (is.double(r) || is.double(x)) { if (is.float(r)) r = dbl(r) if (is.float(x)) x = dbl(x) backsolve(r, x, k, upper.tri, transpose) } else { if (!is.numeric(k) || k < 1 || k > nrow(r) || is.na(k)) stop("invalid 'k' argument") ret = .Call(R_backsolve_spm, DATA(r), DATA(x), as.integer(upper.tri), as.integer(transpose), as.integer(k)) float32(ret) } } forwardsolve_float32 = function(l, x, k=ncol(l), upper.tri=FALSE, transpose=FALSE) { backsolve_float32(l, x, k, upper.tri, transpose) } setMethod("backsolve", signature(r="float32", x="float32"), backsolve_float32) setMethod("backsolve", signature(r="float32", x="BaseLinAlg"), backsolve_float32) setMethod("backsolve", signature(r="BaseLinAlg", x="float32"), backsolve_float32) setMethod("forwardsolve", signature(l="float32", x="float32"), forwardsolve_float32) setMethod("forwardsolve", signature(l="float32", x="BaseLinAlg"), forwardsolve_float32) setMethod("forwardsolve", signature(l="BaseLinAlg", x="float32"), forwardsolve_float32)
Visualizer3Point <- function(A, pointsToDraw, colour, label, name){ if(is.na(colour)){ colour="black" } X=rbind(c(0,0),c(1,0),c(0.5, sqrt(0.75))) vertices = bary2cart(X,pointsToDraw) graphics::points(vertices[1],vertices[2],pch=4,col=colour) if(label == TRUE) { setLabels(A, pointsToDraw, name) } }
vmap <- function(EXPR, ..., SIMPLIFY = TRUE) { if (is.factor(EXPR)) EXPR <- as.character.factor(EXPR) res <- lapply(EXPR, switch, ...) if (SIMPLIFY) simplify2array(res) else res } qrank <- function(x, ...) { rank(x = x, ...) / length(x) } normalize <- function(x, min = 0, max = 1, na.rm = FALSE) { if (all(is.na(x))) return(rep(0, length(x))) if (!is.numeric(x)) stop("x must be numeric") x <- unclass(x) if (min > max) stop("min <= max must be satisfied") if (all(x == 0, na.rm = na.rm)) return(x) xmax <- max(x, na.rm = na.rm) xmin <- min(x, na.rm = na.rm) if (xmax == xmin) return(rep(1, length(x))) min + (max - min) * (x - xmin) / (xmax - xmin) } proportion <- function(x, na.rm = FALSE) { x / max(abs(x), na.rm = na.rm) }
with_id <- function(source_file, id) { if (is.null(source_file$parsed_content)) { return(data.frame()) } source_file$parsed_content[id, ] }
emptyBands <- function(...) { input <- list(...) if (length(input) < 2) { stop("emptyBands requires two or more TDSC objects") } x <- c() y <- c() for (i in 1:length(input)) { if (typeof(input[[i]]) != "S4" | class(input[[i]]) != "tdsc") { stop("Inputs to emptyBands must be TDSC objects.") } s_matrix <- input[[i]]@s_matrix x <- c(x, rep(i, length(s_matrix))) y <- c(y, as.numeric(rownames(s_matrix))) } uy <- unique(y) ay <- 1:max(uy) m <- ay[!(ay %in% uy)] return(list(missing=m, plot=cbind(x,y))) }
check_nrow <- function(x, nrow = TRUE, x_name = substitute(x), error = TRUE) { x_name <- chk_deparse(x_name) check_length_internal(nrow) check_flag_internal(error) check_n(x, n = nrow(x), range = nrow, x_name = x_name, n_name = "row", error = error) invisible(x) }
library(testthat) library(operator.tools) test_that( 'opetators', { context( 'Function: is.operator' ) for( op in operators() ) expect_that( is.operator( as.name(op)), is_true(), paste( op, "is not an operator." ) ) context( 'Function: can.operator' ) for( op in operators() ) expect_that( can.operator(op), is_true(), paste( op, "cannot be coercised into an operator." ) ) context('Function: as.operator') for( op in operators() ) expect_that( is.operator( as.operator(op) ), is_true() , paste( op, 'was not successfully coerced to an operator.' ) ) })
summary.BchronRSLRun <- function(object, type = c("parameters", "RSL", "rate", "accel"), age_grid = NULL, ...) { cat("Posterior Medians with 95% credible intervals...\n") type <- match.arg(type, several.ok = TRUE) if ("parameters" %in% type) { cat("Power Lower Median Upper \n") pow.names <- c("mean", "linear", "quadratic", "cubic", "quartic", "quintic") for (j in 1:(object$degree + 1)) { cat(pow.names[j], round(stats::quantile(object$samples[, j], probs = c(0.025, 0.5, 0.975)), 4), "\n") } } if (is.null(age_grid)) { age_low <- apply(object$BchronologyRun$thetaPredict, 2, stats::quantile, probs = 0.025) age_med <- apply(object$BchronologyRun$thetaPredict, 2, stats::quantile, probs = 0.5) age_high <- apply(object$BchronologyRun$thetaPredict, 2, stats::quantile, probs = 0.975) age_grid <- seq(max(age_low), min(age_high), length = 100) } age_grid_use <- age_grid / 1000 pred.lines <- matrix(NA, ncol = length(age_grid_use), nrow = nrow(object$samples)) if ("RSL" %in% type) { degmat <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) X.pred <- matrix(rep(age_grid_use - object$const, object$degree + 1), ncol = object$degree + 1) X.pred <- (X.pred^degmat) for (i in 1:nrow(pred.lines)) { pred.lines[i, ] <- X.pred %*% matrix(object$samples[i, ], ncol = 1, nrow = object$degree + 1) } pred.med <- apply(pred.lines, 2, stats::quantile, probs = 0.5) pred.low <- apply(pred.lines, 2, stats::quantile, probs = 0.025) pred.high <- apply(pred.lines, 2, stats::quantile, probs = 0.975) df <- data.frame( "Age" = age_grid, "RSL_2.5" = pred.low, "RSL_50" = pred.med, "RSL_97.5" = pred.high ) print(df) } if ("rate" %in% type) { degmat <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) degmat_rate <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) - 1 X.pred <- matrix(rep(age_grid_use - object$const, object$degree + 1), ncol = object$degree + 1) X.pred <- -degmat * (X.pred^degmat_rate) for (i in 1:nrow(pred.lines)) { pred.lines[i, ] <- X.pred %*% matrix(object$samples[i, ], ncol = 1, nrow = object$degree + 1) } pred.med <- apply(pred.lines, 2, stats::quantile, probs = 0.5) pred.low <- apply(pred.lines, 2, stats::quantile, probs = 0.025) pred.high <- apply(pred.lines, 2, stats::quantile, probs = 0.975) df <- data.frame( "Age" = age_grid, "RSL_rate_2.5" = pred.low, "RSL_rate_50" = pred.med, "RSL_rate_97.5" = pred.high ) print(df) } if ("accel" %in% type) { degmat <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) degmat_rate <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) - 1 degmat_accel <- matrix(rep(0:(object$degree), each = length(age_grid_use)), nrow = length(age_grid_use), ncol = object$degree + 1 ) - 2 X.pred <- matrix(rep(age_grid_use - object$const, object$degree + 1), ncol = object$degree + 1) X.pred <- degmat * (degmat - 1) * (X.pred^degmat_accel) for (i in 1:nrow(pred.lines)) { pred.lines[i, ] <- X.pred %*% matrix(object$samples[i, ], ncol = 1, nrow = object$degree + 1) } pred.med <- apply(pred.lines, 2, stats::quantile, probs = 0.5) pred.low <- apply(pred.lines, 2, stats::quantile, probs = 0.025) pred.high <- apply(pred.lines, 2, stats::quantile, probs = 0.975) df <- data.frame( "Age" = age_grid, "RSL_accel_2.5" = pred.low, "RSL_accel_50" = pred.med, "RSL_accel_97.5" = pred.high ) print(df) } }
if (getRversion() < 3.3) { absolute.units <- getFromNamespace("absolute.units", "grid") absolute.units.unit <- getFromNamespace("absolute.units.unit", "grid") absolute.units.unit.list <- getFromNamespace("absolute.units.unit.list", "grid") absolute.units.unit.arithmetic <- getFromNamespace("absolute.units.unit.arithmetic", "grid") backport_unit_methods <- function() { registerS3method("absolute.units", "unit", absolute.units.unit) registerS3method("absolute.units", "unit.list", absolute.units.unit.list) registerS3method("absolute.units", "unit.arithmetic", absolute.units.unit.arithmetic) } } else { backport_unit_methods <- function() {} } if (getRversion() < 3.5) { isFALSE <- function(x) is.logical(x) && length(x) == 1L && !is.na(x) && !x }
context("Test MSE_functions") library(openMSE) MPs <- avail("MP", 'DLMtool') MSE <- runMSE(testOM, MPs=MPs, checkMPs = FALSE) testthat::test_that("Converge", { testthat::expect_error(Converge(MSE), NA) }) testthat::test_that("checkMSE", { testthat::expect_error(checkMSE(MSE), NA) }) testthat::test_that("Sub by MP", { MPs1 <- MSE@MPs[1:3] MPs2 <- MSE@MPs[4:MSE@nMPs] testthat::expect_error(t1 <- Sub(MSE, MPs=MPs1), NA) testthat::expect_error(t2 <- Sub(MSE, MPs=MPs2), NA) }) testthat::test_that("Sub by sim", { nsim <- MSE@nsim sims1 <- 1:ceiling((nsim/2)) sims2 <- (max(sims1)+1):nsim testthat::expect_error(t1 <<- Sub(MSE, sim=sims1), NA) testthat::expect_error(t2 <<- Sub(MSE, sim=sims2), NA) }) testthat::test_that("joinMSE", { testthat::expect_error(newMSE <<- joinMSE(list(t1, t2)), NA) }) testthat::test_that("joinMSE returns same object", { testthat::expect_true(all(summary(newMSE, silent=TRUE) == summary(MSE, silent=TRUE))) })
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(c(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE))")); do.call(`all`, argv); }, o=expected);
make_marker_names <- function(x){ x$marker_names <- paste(x$chr, x$start, x$end, sep="_") toMatch <- c("chr", "start", "end") toMatch <- paste("^", toMatch, "$", sep="") matches <- grep(paste(toMatch,collapse="|"), colnames(x)) x <- x[,-matches] return(x[,c("marker_names", "marker")]) }
test_that("udunits error messages", { expect_error(set_units(1:3, "qqq"), "qqq") }) test_that("udunits low-level functions work", { expect_silent(units:::R_ut_get_dimensionless_unit_one()) a <- units:::R_ut_parse("m") b <- units:::R_ut_parse("g") expect_error(units:::R_convert_doubles(a, b, 1:10), "not convertible") units:::R_ut_offset("foo", "kg", -10) expect_equal(set_units(set_units(1, kg), foo), set_units(11, foo)) remove_unit(name="foo") units:::R_ut_scale("foo", "kg", 2) expect_equal(set_units(set_units(2, kg), foo), set_units(1, foo)) remove_unit(name="foo") expect_silent(units:::R_ut_divide(a, b)) expect_silent(units:::R_ut_multiply(a, b)) expect_silent(units:::R_ut_invert(a)) expect_silent(sq <- units:::R_ut_raise(a, 2L)) expect_error(units:::R_ut_raise(a, 2L:3L), "length 1") expect_silent(units:::R_ut_root(sq, 2L)) expect_error(units:::R_ut_root(a, 2L:3L), "length 1") expect_silent(units:::R_ut_log(a, 10.0)) expect_error(units:::R_ut_log(a, c(2, 10.0)), "length 1") expect_error(units:::R_ut_log(a, -10.0), "positive") expect_silent(units:::R_ut_format(a)) expect_silent(units:::R_ut_format(a, ascii = TRUE)) expect_silent(units:::R_ut_format(sq, names = TRUE)) expect_silent(units:::R_ut_format(sq, definition = TRUE)) expect_silent(units:::R_ut_set_encoding("ascii")) expect_silent(units:::R_ut_set_encoding("iso-8859-1")) expect_silent(units:::R_ut_set_encoding("latin1")) expect_silent(units:::R_ut_set_encoding("utf8")) expect_silent(ud_set_encoding("utf8")) expect_error(units:::R_ut_set_encoding("foo")) expect_error(units:::R_ut_get_symbol("foo")) expect_error(units:::R_ut_get_name("foo")) }) test_that("udunits database can be read", { skip_if_not_installed("xml2") expect_message(valid_udunits(), "udunits") expect_message(valid_udunits_prefixes(), "udunits") })
SplitStealData <- rbind( do(187) * data.frame(agegroup = "Under40", decision = "Split"), do(195) * data.frame(agegroup = "Under40", decision = "Steal"), do(116) * data.frame(agegroup = "Over40", decision = "Split"), do(76) * data.frame(agegroup = "Over40", decision = "Steal") )
lambda0_k = function(t, fit1, fit2, tilde_theta = 1, M_vec2) { out = 1:length(t) * 0 for (i in 1:length(t)) { if (sum(fit1$time[fit1$n.event!=0] <= t[i]) == 0 | sum(fit2$time[fit2$n.event != 0] <= t[i]) == 0) { out[i] = NA } else { D1 = max((fit1$n.event - fit1$n.risk)[fit1$time <= t[i] & fit1$n.event != 0]) / M_vec2[1] D2 = max((fit2$n.event - fit2$n.risk)[fit2$time <= t[i] & fit2$n.event != 0]) / M_vec2[2] if (D1 != (-D2)) { out[i] = uniroot(a_1_k, interval = c(D1 + 0.0001, -D2 - 0.0001), tol = 0.0001, fit1 = fit1, fit2 = fit2, t = t[i], tilde_theta = tilde_theta, M_vec2 = M_vec2)$root } else { out[i] = D1 } } } return(out) }
NULL setMethod( f="print", signature="SummaryForecastData", definition=function(x, digits=3, ...){ print(x@summaryData, na.print="", digits=digits) } ) setMethod( f="show", signature="SummaryForecastData", definition=function(object){ print(object@summaryData, na.print="", digits=3) } ) setMethod( f="print", signature="ForecastData", definition=function(x, digits=3, ...){ cat("* Prediction Calibration = \n"); if(length(x@predCalibration)>0) {print(x@predCalibration, na.print="", digits=digits);} else{print("Nothing Here")} cat("* Prediction Test = \n"); if(length(x@predTest)>0) {print(x@predTest, na.print="", digits=digits);} else{print("Nothing Here")} cat("* Outcome Calibration = \n"); if(length(x@outcomeCalibration)>0) {print(x@outcomeCalibration, na.print="", digits=digits);} else{print("Nothing Here")} cat("* Outcome Test = \n"); if(length(x@outcomeTest)>0) {print(x@outcomeTest, na.print="", digits=digits);} else{print("Nothing Here")} cat("* Model Names = \n ");print(x@modelNames, na.print=""); } ) setMethod( f="show", signature="ForecastData", definition=function(object){ if (length(object@predCalibration)==0) { cat("* Prediction Calibration = \n"); if(length(object@predCalibration)>0) {print(object@predCalibration, na.print="", digits=1);} else{print("Nothing Here")} cat("* Prediction Test = \n"); if(length(object@predTest)>0) {print(object@predTest, na.print="", digits=1);} else{print("Nothing Here")} cat("* Outcome Calibration = \n"); if(length(object@outcomeCalibration)>0) {print(object@outcomeCalibration, na.print="", digits=1);} else{print("Nothing Here")} cat("* Outcome Test = \n"); if(length(object@outcomeTest)>0) {print(object@outcomeTest, na.print="", digits=1);} else{print("Nothing Here")} cat("* Model Names = \n ");print(object@modelNames, na.print=""); } else{ nrowCal=min(10,nrow(object@predCalibration)) nrowTest=min(10,nrow(object@predTest)) cat("* Prediction Calibration = \n"); if(length(object@predCalibration)>0) {print(object@predCalibration[1:nrowCal,1:ncol(object@predCalibration),1], na.print="", digits=2);} else{print("Nothing Here")} cat("* Prediction Test = \n"); if(length(object@predTest)>0) {print(object@predTest[1:nrowTest,1:ncol(object@predTest),1], na.print="", digits=2);} else{print("Nothing Here")} cat("* Outcome Calibration = \n"); if(length(object@outcomeCalibration)>0) {print(print(object@outcomeCalibration[1:nrowCal]),na.print="", digits=2);} else{print("Nothing Here")} cat("* Outcome Test = \n"); if(length(object@outcomeTest)>0) {print(object@outcomeTest[1:nrowTest], na.print="", digits=2);} else{print("Nothing Here")} cat("* Model Names = \n ");print(object@modelNames,na.print=""); } } )
lsoda <- function(y, times, func, parms, rtol=1e-6, atol=1e-6, jacfunc=NULL, jactype = "fullint", rootfunc = NULL, verbose = FALSE, nroot = 0, tcrit = NULL, hmin=0, hmax=NULL, hini=0, ynames=TRUE, maxordn = 12, maxords = 5, bandup = NULL, banddown = NULL, maxsteps = 5000, dllname=NULL, initfunc=dllname, initpar=parms, rpar=NULL, ipar=NULL, nout=0, outnames=NULL, forcings=NULL, initforc = NULL, fcontrol = NULL, events = NULL, lags=NULL, ...) { if (! is.null(rootfunc)) return(lsodar (y, times, func, parms, rtol, atol, jacfunc, jactype, rootfunc, verbose, nroot, tcrit, hmin, hmax, hini, ynames, maxordn, maxords, bandup, banddown, maxsteps, dllname, initfunc, initpar, rpar, ipar, nout, outnames, forcings, initforc, fcontrol, events, lags, ...)) if (is.list(func)) { if (!is.null(jacfunc) & "jacfunc" %in% names(func)) stop("If 'func' is a list that contains jacfunc, argument 'jacfunc' should be NULL") if (!is.null(initfunc) & "initfunc" %in% names(func)) stop("If 'func' is a list that contains initfunc, argument 'initfunc' should be NULL") if (!is.null(dllname) & "dllname" %in% names(func)) stop("If 'func' is a list that contains dllname, argument 'dllname' should be NULL") if (!is.null(initforc) & "initforc" %in% names(func)) stop("If 'func' is a list that contains initforc, argument 'initforc' should be NULL") if (!is.null(events$func) & "eventfunc" %in% names(func)) stop("If 'func' is a list that contains eventfunc, argument 'events$func' should be NULL") if ("eventfunc" %in% names(func)) { if (! is.null(events)) events$func <- func$eventfunc else events <- list(func = func$eventfunc) } if (!is.null(func$jacfunc)) jacfunc <- func$jacfunc if (!is.null(func$initfunc)) initfunc <- func$initfunc if (!is.null(func$dllname)) dllname <- func$dllname if (!is.null(func$initforc)) initforc <- func$initforc func <- func$func } hmax <- checkInput (y, times, func, rtol, atol, jacfunc, tcrit, hmin, hmax, hini, dllname) n <- length(y) if (!is.numeric(maxordn)) stop("`maxordn' must be numeric") if(maxordn < 1 || maxordn > 12) stop("`maxord' must be >1 and <=12") if (!is.numeric(maxords)) stop("`maxords' must be numeric") if(maxords < 1 || maxords > 5) stop("`maxords' must be >1 and <=5") if (jactype == "fullint" ) jt <- 2 else if (jactype == "fullusr" ) jt <- 1 else if (jactype == "bandusr" ) jt <- 4 else if (jactype == "bandint" ) jt <- 5 else stop("'jactype' must be one of 'fullint', 'fullusr', 'bandusr' or 'bandint'") if (jt %in% c(4,5) && is.null(bandup)) stop("'bandup' must be specified if banded Jacobian") if (jt %in% c(4,5) && is.null(banddown)) stop("'banddown' must be specified if banded Jacobian") if (is.null(banddown)) banddown <-1 if (is.null(bandup )) bandup <-1 if (jt %in% c(1,4) && is.null(jacfunc)) stop ("'jacfunc' NOT specified; either specify 'jacfunc' or change 'jactype'") Ynames <- attr(y,"names") JacFunc <- NULL flist<-list(fmat=0,tmat=0,imat=0,ModelForc=NULL) ModelInit <- NULL Eventfunc <- NULL events <- checkevents(events, times, Ynames, dllname) if (! is.null(events$newTimes)) times <- events$newTimes if (jt == 4 && banddown>0) erow<-matrix(data=0, ncol=n, nrow=banddown) else erow<-NULL if (is.character(func) | inherits(func, "CFunc")) { DLL <- checkDLL(func, jacfunc, dllname, initfunc, verbose, nout, outnames) ModelInit <- DLL$ModelInit Func <- DLL$Func JacFunc <- DLL$JacFunc Nglobal <- DLL$Nglobal Nmtot <- DLL$Nmtot if (! is.null(forcings)) flist <- checkforcings(forcings,times,dllname,initforc,verbose,fcontrol) if (is.null(ipar)) ipar<-0 if (is.null(rpar)) rpar<-0 Eventfunc <- events$func if (is.function(Eventfunc)) rho <- environment(Eventfunc) else rho <- NULL } else { if(is.null(initfunc)) initpar <- NULL rho <- environment(func) if (ynames) { Func <- function(time,state) { attr(state,"names") <- Ynames unlist(func (time,state,parms,...)) } Func2 <- function(time,state) { attr(state,"names") <- Ynames func (time,state,parms,...) } JacFunc <- function(time,state) { attr(state,"names") <- Ynames rbind(jacfunc(time,state,parms,...),erow) } if (! is.null(events$Type)) if (events$Type == 2) Eventfunc <- function(time,state) { attr(state,"names") <- Ynames events$func(time,state,parms,...) } } else { Func <- function(time,state) unlist(func (time,state,parms,...)) Func2 <- function(time,state) func (time,state,parms,...) JacFunc <- function(time,state) rbind(jacfunc(time,state,parms,...),erow) if (! is.null(events$Type)) if (events$Type == 2) Eventfunc <- function(time,state) events$func(time,state,parms,...) } FF <- checkFunc(Func2,times,y,rho) Nglobal<-FF$Nglobal Nmtot <- FF$Nmtot if (! is.null(events$Type)) if (events$Type == 2) checkEventFunc(Eventfunc,times,y,rho) if (jt %in% c(1,4)) { tmp <- eval(JacFunc(times[1], y), rho) if (!is.matrix(tmp)) stop("Jacobian function, 'jacfunc' must return a matrix\n") dd <- dim(tmp) if((jt ==4 && any(dd != c(bandup+banddown+banddown+1,n))) || (jt ==1 && any(dd != c(n,n)))) stop("Jacobian dimension not ok") } } if(jt %in% c(1,2)) lmat <- n^2+2 else if(jt %in% c(4,5)) lmat <- (2*banddown+bandup+1)*n+2 lrn = 20+n*(maxordn+1)+ 3*n lrs = 20+n*(maxords+1)+ 3*n +lmat lrw = max(lrn,lrs) liw = 20 + n iwork <- vector("integer",20) rwork <- vector("double",20) rwork[] <- 0. iwork[] <- 0 iwork[1] <- banddown iwork[2] <- bandup iwork[6] <- maxsteps if (maxordn != 12) iwork[8] <- maxordn if (maxords != 5) iwork[9] <- maxords if (verbose) iwork[5] = 1 if(! is.null(tcrit)) rwork[1] <- tcrit rwork[5] <- hini rwork[6] <- hmax rwork[7] <- hmin if (! is.null(times)) itask <- ifelse (is.null (tcrit), 1,4) else itask <- ifelse (is.null (tcrit), 2,5) if(is.null(times)) times<-c(0,1e8) if (verbose) printtask(itask,func,jacfunc) storage.mode(y) <- storage.mode(times) <- "double" IN <-1 lags <- checklags(lags,dllname) on.exit(.C("unlock_solver")) out <- .Call("call_lsoda",y,times,Func,initpar, rtol, atol, rho, tcrit, JacFunc, ModelInit, Eventfunc, as.integer(verbose), as.integer(itask), as.double(rwork), as.integer(iwork), as.integer(jt), as.integer(Nglobal), as.integer(lrw),as.integer(liw), as.integer(IN), NULL, 0L, as.double(rpar), as.integer(ipar), 0L, flist, events, lags, PACKAGE="deSolve") out <- saveOut(out, y, n, Nglobal, Nmtot, func, Func2, iin=c(1,12:21), iout=c(1:3,14,5:9,15:16), nr = 5) attr(out, "type") <- "lsoda" if (verbose) diagnostics(out) out }
library(caret) x <- cbind(x_train,y_train) fitControl <- trainControl( method = "repeatedcv", number = 4, repeats = 4) fit <- train(y ~ ., data = x, method = "gbm", trControl = fitControl,verbose = FALSE) predicted= predict(fit,x_test,type= "prob")[,2] require(caret) x <- cbind(x_train,y_train) TrainControl <- trainControl( method = "repeatedcv", number = 10, repeats = 4) model<- train(y ~ ., data = x, method = "xgbLinear", trControl = TrainControl,verbose = FALSE) model<- train(y ~ ., data = x, method = "xgbTree", trControl = TrainControl,verbose = FALSE) predicted <- predict(model, x_test) library(RLightGBM) data(example.binary) num_iterations <- 100 config <- list(objective = "binary", metric="binary_logloss,auc", learning_rate = 0.1, num_leaves = 63, tree_learner = "serial", feature_fraction = 0.8, bagging_freq = 5, bagging_fraction = 0.8, min_data_in_leaf = 50, min_sum_hessian_in_leaf = 5.0) handle.data <- lgbm.data.create(x) lgbm.data.setField(handle.data, "label", y) handle.booster <- lgbm.booster.create(handle.data, lapply(config, as.character)) lgbm.booster.train(handle.booster, num_iterations, 5) pred <- lgbm.booster.predict(handle.booster, x.test) sum(y.test == (y.pred > 0.5)) / length(y.test) lgbm.booster.save(handle.booster, filename = "/tmp/model.txt") set.seed(1) require(titanic) require(caret) require(catboost) tt <- titanic::titanic_train[complete.cases(titanic::titanic_train),] data <- as.data.frame(as.matrix(tt), stringsAsFactors = TRUE) drop_columns = c("PassengerId", "Survived", "Name", "Ticket", "Cabin") x <- data[,!(names(data) %in% drop_columns)]y <- data[,c("Survived")] fit_control <- trainControl(method = "cv", number = 4,classProbs = TRUE) grid <- expand.grid(depth = c(4, 6, 8),learning_rate = 0.1,iterations = 100, l2_leaf_reg = 1e-3, rsm = 0.95, border_count = 64) report <- train(x, as.factor(make.names(y)),method = catboost.caret,verbose = TRUE, preProc = NULL,tuneGrid = grid, trControl = fit_control) print(report) importance <- varImp(report, scale = FALSE) print(importance)
setDefaultsLKinfo.LKSphere <- function(object, ...) { object$floorAwght<- 1.0 if( object$distance.type == "Euclidean"){ dType<- "GreatCircle" attr(dType, "Radius" ) <- 1.0 object$distance.type <- dType } if (object$nlevel == 1 & is.na(object$alpha[1])) { object$alpha <- list(1.0) } if( !is.null( object$fixedFunction)){ object$fixedFunction <- "LKrigDefaultFixedFunction" object$fixedFunctionArgs$m <- 1 } if (is.na(object$a.wght)) { object$a.wght <- 1.1 } return(object) } LKrigSetupLattice.LKSphere<- function(object, x=NULL, verbose, ... ){ if( is.null(x)){ x<- object$x } startingLevel<- object$setupArgs$startingLevel LKinfo<- object if( class( LKinfo)[1] != "LKinfo") { stop("object needs to an LKinfo object") } rangeLocations<- apply( x,2, "range") nlevel<- LKinfo$nlevel if( is.null(x)){ x<- cbind( c(-90,90), c( -180,180)) } if (is.null(startingLevel)) { stop("Need to specify startingLevel initial geodesic grid level") } if (startingLevel+nlevel-1 > 8){ stop("startingLevel+nlevel-1 cannot exceed 8") }else{ R<- seq(startingLevel,startingLevel+nlevel-1,1) Rmax<- max(R) } delta<- 1.408/ 2^( 0:(Rmax-1) ) delta.save<- delta[R] MultiGrid<- IcosahedronGrid(Rmax) grid.all.levels<- list() grid3d.all.levels<- list() mLevel<- rep(NA,nlevel) for(l in (1:nlevel) ){ grid3d<- MultiGrid[[ l + (startingLevel -1) ]] gridTemp<- toSphere( grid3d ) ind<- gridTemp[,1] >= rangeLocations[1,1] & gridTemp[,1] <= rangeLocations[2,1] & gridTemp[,2] >= rangeLocations[1,2] & gridTemp[,2] <= rangeLocations[2,2] ind2<- (1:length( ind)) <= 12 grid.all.levels[[l]]<- gridTemp[ ind, ] grid3d.all.levels[[l]]<- grid3d[ ind, ] numberNodes<- sum( ind) if( numberNodes <= 3){ stop("must have at least 4 nodes at lowest resolution in the spatial domain. Try increasing startLevels or increasing the boundaries of the spatial domain.") } mLevel[l]<- nrow( grid.all.levels[[l]] ) } m<- sum(mLevel) offset <- as.integer(c(0, cumsum(mLevel))) out<- list( m=m, offset=offset, mLevel=mLevel, delta=delta.save, rangeLocations=rangeLocations, startingLevel=startingLevel, grid=grid.all.levels, grid3d= grid3d.all.levels) return(out) } LKrigSAR.LKSphere = function(object, Level, ...) { if( Level>7){ stop("can not handle more than 7 levels")} grid <- object$latticeInfo$grid[[Level]] grid3d <- object$latticeInfo$grid3d[[Level]] delta <- object$latticeInfo$delta[[Level]] a.wght <- object$a.wght[[Level]] dType<- object$distance.type n <- nrow(grid) B = LKDist( grid[,1:2], grid[,1:2], delta = delta, distance.type= dType) ind1<- B$ind[,1] ind2<- B$ind[,2] raTemp<- rep( NA, length( ind1)) Diagonal<- ind1==ind2 if( sum( Diagonal)!= nrow(grid)) { stop( "Number of diagonal elements in B different from grid")} raTemp[ Diagonal ] <- a.wght for (I in 1:n ){ indNeighbors <- (ind1 == I) & !Diagonal J<- ind2[ indNeighbors ] nJ<- length(J) x1<- grid3d[J,] x0<- grid3d[I,] u<- projectionSphere( x0,x1) X<- cbind( rep( 1,nJ), u ) if( nJ>=3){ c2<- c( (X)%*%(solve( t(X)%*%X, c( 1,0,0) ) )) } else{ c2<- 1/nJ } raTemp[ indNeighbors ]<- -1*c2 } B$ra<- raTemp return(B) } LKrigLatticeCenters.LKSphere<- function(object, Level, ... ){ return( object$latticeInfo$grid[[Level]] ) }
table.Variability <- function (R, scale = NA, geometric = TRUE, digits = 4) { y = checkData(R) columns = ncol(y) columnnames = colnames(y) if(is.na(scale)) { freq = periodicity(R) switch(freq$scale, minute = {stop("Data periodicity too high")}, hourly = {stop("Data periodicity too high")}, daily = {scale = 252}, weekly = {scale = 52}, monthly = {scale = 12}, quarterly = {scale = 4}, yearly = {scale = 1} ) } for(column in 1:columns) { z = c(MeanAbsoluteDeviation(y[,column,drop=FALSE]), StdDev.annualized(y[,column,drop=FALSE], scale = scale)/sqrt(scale), StdDev.annualized(y[,column,drop=FALSE], scale = scale)) znames = c("Mean Absolute deviation", paste0(freq$scale," Std Dev"), "Annualized Std Dev") if(column == 1) { resultingtable = data.frame(Value = z, row.names = znames) } else { nextcolumn = data.frame(Value = z, row.names = znames) resultingtable = cbind(resultingtable, nextcolumn) } } colnames(resultingtable) = columnnames ans = base::round(resultingtable, digits) ans }
aspell <- function(files, filter, control = list(), encoding = "unknown", program = NULL, dictionaries = character()) { program <- aspell_find_program(program) if(is.na(program)) stop("No suitable spell-checker program found") if(inherits(files, "Rd")) files <- list(files) files_are_names <- is.character(files) filter_args <- list() if(missing(filter) || is.null(filter)) { filter <- if(!files_are_names) { function(ifile, encoding) { if(inherits(ifile, "srcfile")) readLines(ifile$filename, encoding = encoding, warn = FALSE) else if(inherits(ifile, "connection")) readLines(ifile, encoding = encoding, warn = FALSE) else { as.character(ifile) } } } else NULL } else if(is.character(filter)) { filter_name <- filter[1L] filter <- aspell_filter_db[[filter_name]] if(is.null(filter)) warning(gettextf("Filter '%s' is not available.", filter_name), domain = NA) } else if(is.list(filter)) { filter_name <- filter[[1L]][1L] filter_args <- filter[-1L] filter <- aspell_filter_db[[filter_name]] if(is.null(filter)) warning(gettextf("Filter '%s' is not available.", filter_name), domain = NA) } else if(!is.function(filter)) stop("Invalid 'filter' argument.") encoding <- rep_len(encoding, length(files)) verbose <- getOption("verbose") db <- data.frame(Original = character(), File = character(), Line = integer(), Column = integer(), stringsAsFactors = FALSE) db$Suggestions <- list() tfile <- tempfile("aspell") on.exit(unlink(tfile)) if(length(dictionaries)) { paths <- aspell_find_dictionaries(dictionaries) ind <- paths == "" if(any(ind)) { warning(gettextf("The following dictionaries were not found:\n%s", paste(sprintf(" %s", dictionaries[ind]), collapse = "\n")), domain = NA) paths <- paths[!ind] } if(length(paths)) { words <- unlist(lapply(paths, readRDS), use.names = FALSE) personal <- tempfile("aspell_personal") on.exit(unlink(personal), add = TRUE) aspell_write_personal_dictionary_file(words, personal, program = program) control <- c(control, "-p", shQuote(personal)) } } control <- as.character(control) fnames <- names(files) files <- as.list(files) for (i in seq_along(files)) { file <- files[[i]] if(files_are_names) fname <- file else { fname <- if(inherits(file, "srcfile")) file$filename else attr(attr(file, "srcref"), "srcfile")$filename if(is.null(fname)) fname <- fnames[i] if(is.null(fname)) fname <- "<unknown>" } enc <- encoding[i] if(verbose) message(gettextf("Processing file %s", fname), domain = NA) lines <- if(is.null(filter)) readLines(file, encoding = enc, warn = FALSE) else { do.call(filter, c(list(file, encoding = enc), filter_args)) } control <- c(control, attr(lines, "control")) writeLines(paste0("^", lines), tfile) out <- tools:::.system_with_capture(program, c("-a", control), stdin = tfile) if(out$status != 0L) stop(gettextf("Running aspell failed with diagnostics:\n%s", paste(out$stderr, collapse = "\n")), domain = NA) lines <- out$stdout[-1L] pos <- cumsum(lines == "") + 1L if(any(ind <- startsWith(lines, "&"))) { info <- strsplit(lines[ind], ": ", fixed = TRUE) one <- strsplit(sapply(info, `[`, 1L), " ", fixed = TRUE) two <- strsplit(sapply(info, `[`, 2L), ", ", fixed = TRUE) db1 <- data.frame(Original = as.character(sapply(one, `[`, 2L)), File = fname, Line = pos[ind], Column = as.integer(sapply(one, `[`, 4L)), stringsAsFactors = FALSE) db1$Suggestions <- two db <- rbind(db, db1) } if(any(ind <- startsWith(lines, " one <- strsplit(lines[ind], " ", fixed = TRUE) db1 <- data.frame(Original = as.character(sapply(one, `[`, 2L)), File = fname, Line = pos[ind], Column = as.integer(sapply(one, `[`, 3L)), stringsAsFactors = FALSE) db1$Suggestions <- vector("list", length(one)) db <- rbind(db, db1) } } class(db) <- c("aspell", "data.frame") db } format.aspell <- function(x, sort = TRUE, verbose = FALSE, indent = 2L, ...) { if(!nrow(x)) return(character()) if(sort) x <- x[order(x$Original, x$File, x$Line, x$Column), ] from <- split(sprintf("%s:%d:%d", x$File, x$Line, x$Column), x$Original) if(verbose) { unlist(Map(function(w, f, s) { sprintf("Word: %s\nFrom: %s\n%s", w, paste0(c("", rep.int(" ", length(f) - 1L)), f, collapse = "\n"), paste(strwrap(paste("Suggestions:", paste(s[[1L]], collapse = " ")), exdent = 6L, indent = 0L), collapse = "\n")) }, names(from), from, split(x$Suggestions, x$Original))) } else { sep <- sprintf("\n%s", strrep(" ", indent)) paste(names(from), sapply(from, paste, collapse = sep), sep = sep) } } print.aspell <- function(x, ...) { if(nrow(x)) writeLines(paste(format(x, ...), collapse = "\n\n")) invisible(x) } summary.aspell <- function(object, ...) { words <- sort(unique(object$Original)) if(length(words)) { writeLines("Possibly mis-spelled words:") print(words) } invisible(words) } aspell_filter_db <- new.env(hash = FALSE) aspell_find_program <- function(program = NULL) { check <- !is.null(program) || !is.null(names(program)) if(is.null(program)) program <- getOption("aspell_program") if(is.null(program)) program <- c("aspell", "hunspell", "ispell") program <- Filter(nzchar, Sys.which(program))[1L] if(!is.na(program) && check) { out <- c(system(sprintf("%s -v", program), intern = TRUE), "")[1L] if(grepl("really Aspell", out)) names(program) <- "aspell" else if(grepl("really Hunspell", out)) names(program) <- "hunspell" else if(grepl("International Ispell", out)) names(program) <- "ispell" else names(program) <- NA_character_ } program } aspell_dictionaries_R <- "en_stats" aspell_find_dictionaries <- function(dictionaries, dirnames = character()) { dictionaries <- as.character(dictionaries) if(!(n <- length(dictionaries))) return(character()) dirnames <- c(file.path(R.home("share"), "dictionaries"), dirnames) if(any(ind <- !endsWith(dictionaries, ".rds"))) dictionaries[ind] <- sprintf("%s.rds", dictionaries[ind]) out <- character(n) ind <- grepl(.Platform$file.sep, dictionaries, fixed = TRUE) if(length(pos <- which(ind))) { pos <- pos[file_test("-f", dictionaries[pos])] out[pos] <- normalizePath(dictionaries[pos], "/") } if(length(pos <- which(!ind))) { out[pos] <- find_files_in_directories(dictionaries[pos], dirnames) } out } aspell_inspect_context <- function(x) { x <- split(x, x$File) y <- Map(function(f, x) { lines <- readLines(f, warn = FALSE)[x$Line] cbind(f, x$Line, substring(lines, 1L, x$Column - 1L), x$Original, substring(lines, x$Column + nchar(x$Original))) }, names(x), x) y <- data.frame(do.call(rbind, y), stringsAsFactors = FALSE) names(y) <- c("File", "Line", "Left", "Original", "Right") class(y) <- c("aspell_inspect_context", "data.frame") y } print.aspell_inspect_context <- function(x, ...) { s <- split(x, x$File) nms <- names(s) for(i in seq_along(s)) { e <- s[[i]] writeLines(c(sprintf("File '%s':", nms[i]), sprintf(" Line %s: \"%s\", \"%s\", \"%s\"", format(e$Line), gsub("\"", "\\\"", e$Left), e$Original, gsub("\"", "\\\"", e$Right)), "")) } invisible(x) } aspell_control_R_manuals <- list(aspell = c("--master=en_US", "--add-extra-dicts=en_GB", "--mode=texinfo", "--add-texinfo-ignore=acronym", "--add-texinfo-ignore=deftypefun", "--add-texinfo-ignore=deftypefunx", "--add-texinfo-ignore=findex", "--add-texinfo-ignore=enindex", "--add-texinfo-ignore=include", "--add-texinfo-ignore=ifclear", "--add-texinfo-ignore=ifset", "--add-texinfo-ignore=math", "--add-texinfo-ignore=macro", "--add-texinfo-ignore=multitable", "--add-texinfo-ignore=node", "--add-texinfo-ignore=pkg", "--add-texinfo-ignore=printindex", "--add-texinfo-ignore=set", "--add-texinfo-ignore=vindex", "--add-texinfo-ignore-env=menu", "--add-texinfo-ignore=CRANpkg" ), hunspell = c("-d en_US,en_GB")) aspell_R_manuals <- function(which = NULL, dir = NULL, program = NULL, dictionaries = aspell_dictionaries_R) { if(is.null(dir)) dir <- tools:::.R_top_srcdir_from_Rd() files <- if(is.null(which)) { Sys.glob(file.path(dir, "doc", "manual", "*.texi")) } else { ind <- which(which == basename(tools::file_path_sans_ext(which))) which[ind] <- file.path(dir, "doc", "manual", sprintf("%s.texi", which[ind])) which } program <- aspell_find_program(program) aspell(files, control = aspell_control_R_manuals[[names(program)]], program = program, dictionaries = dictionaries) } aspell_control_R_Rd_files <- list(aspell = c("--master=en_US", "--add-extra-dicts=en_GB"), hunspell = c("-d en_US,en_GB")) aspell_R_Rd_files <- function(which = NULL, dir = NULL, drop = "\\references", program = NULL, dictionaries = aspell_dictionaries_R) { files <- character() if(is.null(dir)) dir <- tools:::.R_top_srcdir_from_Rd() if(is.null(which)) { which <- tools:::.get_standard_package_names()$base files <- c(file.path(dir, "doc", "NEWS.Rd"), file.path(dir, "src", "gnuwin32", "CHANGES.Rd")) files <- files[file_test("-f", files)] } files <- c(files, unlist(lapply(file.path(dir, "src", "library", which, "man"), tools::list_files_with_type, "docs", OS_subdirs = c("unix", "windows")), use.names = FALSE)) program <- aspell_find_program(program) aspell(files, filter = list("Rd", drop = drop), control = aspell_control_R_Rd_files[[names(program)]], program = program, dictionaries = dictionaries) } aspell_package_Rd_files <- function(dir, drop = c("\\author", "\\references"), control = list(), program = NULL, dictionaries = character()) { dir <- normalizePath(dir, "/") subdir <- file.path(dir, "man") files <- if(dir.exists(subdir)) tools::list_files_with_type(subdir, "docs", OS_subdirs = c("unix", "windows")) else character() meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" defaults <- .aspell_package_defaults(dir, encoding)$Rd_files if(!is.null(defaults)) { if(!is.null(d <- defaults$drop)) drop <- d if(!is.null(d <- defaults$control)) control <- d if(!is.null(d <- defaults$program)) program <- d if(!is.null(d <- defaults$dictionaries)) { dictionaries <- aspell_find_dictionaries(d, file.path(dir, ".aspell")) } if(!is.null(d <- defaults$personal)) control <- c(control, sprintf("-p %s", shQuote(file.path(dir, ".aspell", d)))) } macros <- tools::loadPkgRdMacros(dir, macros = file.path(R.home("share"), "Rd", "macros", "system.Rd")) aspell(files, filter = list("Rd", drop = drop, macros = macros), control = control, encoding = encoding, program = program, dictionaries = dictionaries) } aspell_control_R_vignettes <- list(aspell = c("--mode=tex", "--master=en_US", "--add-extra-dicts=en_GB", "--add-tex-command='code p'", "--add-tex-command='pkg p'", "--add-tex-command='CRANpkg p'" ), hunspell = c("-t", "-d en_US,en_GB")) aspell_R_vignettes <- function(program = NULL, dictionaries = aspell_dictionaries_R) { files <- Sys.glob(file.path(tools:::.R_top_srcdir_from_Rd(), "src", "library", "*", "vignettes", "*.Rnw")) program <- aspell_find_program(program) aspell(files, filter = "Sweave", control = aspell_control_R_vignettes[[names(program)]], program = program, dictionaries = dictionaries) } aspell_control_package_vignettes <- list(aspell = c("--add-tex-command='citep oop'", "--add-tex-command='Sexpr p'", "--add-tex-command='code p'", "--add-tex-command='pkg p'", "--add-tex-command='proglang p'", "--add-tex-command='samp p'" )) aspell_package_vignettes <- function(dir, control = list(), program = NULL, dictionaries = character()) { dir <- tools::file_path_as_absolute(dir) vinfo <- tools::pkgVignettes(dir = dir) files <- vinfo$docs if(!length(files)) return(aspell(character())) meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" defaults <- .aspell_package_defaults(dir, encoding)$vignettes if(!is.null(defaults)) { if(!is.null(d <- defaults$control)) control <- d if(!is.null(d <- defaults$program)) program <- d if(!is.null(d <- defaults$dictionaries)) { dictionaries <- aspell_find_dictionaries(d, file.path(dir, ".aspell")) } if(!is.null(d <- defaults$personal)) control <- c(control, sprintf("-p %s", shQuote(file.path(dir, ".aspell", d)))) } program <- aspell_find_program(program) fgroups <- split(files, vinfo$engines) egroups <- split(vinfo$encodings, vinfo$engines) do.call(rbind, Map(function(fgroup, egroup, engine) { engine <- tools::vignetteEngine(engine) aspell(fgroup, filter = engine$aspell$filter, control = c(engine$aspell$control, aspell_control_package_vignettes[[names(program)]], control), encoding = egroup, program = program, dictionaries = dictionaries) }, fgroups, egroups, names(fgroups) ) ) } aspell_filter_db$R <- function(ifile, encoding = "unknown", ignore = character()) { pd <- get_parse_data_for_message_strings(ifile, encoding) if(is.null(pd) || !NROW(pd)) return(character()) pd$text <- substring(pd$text, 2L, nchar(pd$text) - 1L) pd$text <- gsub("(^|[^\\])\\\\[fnrt]", "\\1 ", pd$text) pd$text <- gsub( "([^\\])\\\\[fnrt]", "\\1 ", pd$text) ind <- pd$caller == "gettextf" if(any(ind)) { pd$text[ind] <- gsub("(^|[^%])%[dioxXfeEgGaAs]", "\\1 ", pd$text[ind]) pd$text[ind] <- gsub(" ([^%])%[dioxXfeEgGaAs]", "\\1 ", pd$text[ind]) } lines <- readLines(ifile, encoding = encoding, warn = FALSE) lines_in_pd <- sort(unique(c(pd$line1, pd$line2))) tab <- Map(function(tp, nc) { if(tp[1L] == -1L) return(NULL) widths <- rep.int(1, nc) for(i in tp) { cols <- cumsum(widths) widths[i] <- 8 - (cols[i] - 1) %% 8 } cumsum(widths) }, gregexpr("\t", lines[lines_in_pd], fixed = TRUE), nchar(lines[lines_in_pd])) names(tab) <- lines_in_pd lines[lines_in_pd] <- gsub("[^\t]", " ", lines[lines_in_pd]) lines[-lines_in_pd] <- "" for(entry in split(pd, seq_len(NROW(pd)))) { line1 <- entry$line1 line2 <- entry$line2 col1 <- entry$col1 col2 <- entry$col2 if(line1 == line2) { if(length(ptab <- tab[[as.character(line1)]])) { col1 <- which(ptab == col1) + 1L col2 <- which(ptab == col2) - 1L } substring(lines[line1], col1, col2) <- entry$text } else { texts <- unlist(strsplit(entry$text, "\n", fixed = TRUE)) n <- length(texts) if(length(ptab <- tab[[as.character(line1)]])) { col1 <- which(ptab == col1) + 1L } substring(lines[line1], col1) <- texts[1L] pos <- seq(from = 2L, length.out = n - 2L) if(length(pos)) lines[line1 + pos - 1] <- texts[pos] if(length(ptab <- tab[[as.character(line2)]])) { col2 <- which(ptab == col2) - 1L } substring(lines[line2], 1L, col2) <- texts[n] } } blank_out_ignores_in_lines(lines, ignore) } get_parse_data_for_message_strings <- function(file, encoding = "unknown") { exprs <- suppressWarnings(tools:::.parse_code_file(file = file, encoding = encoding, keep.source = TRUE)) if(!length(exprs)) return(NULL) pd <- getParseData(exprs) parents <- pd$parent names(parents) <- pd$id gpids <- function(ids) parents[as.character(parents[as.character(ids)])] ind <- (pd$token == "SYMBOL_FUNCTION_CALL") & !is.na(match(pd$text, c("warning", "stop", "message", "packageStartupMessage", "gettext", "gettextf", "ngettext"))) funs <- pd$text[ind] ids <- gpids(pd$id[ind]) calls <- getParseText(pd, ids) table <- pd[pd$token == "STR_CONST", ] table$text <- getParseText(table, table$id) pos <- match(gpids(table$id), ids) ind <- !is.na(pos) table <- split(table[ind, ], factor(pos[ind], seq_along(ids))) extract_message_strings <- function(fun, call, table) { call <- parse(text = call)[[1L]] call <- call[ as.character(call) != "..." ] mc <- as.list(match.call(get(fun, envir = .BaseNamespaceEnv), call)) args <- if(fun == "gettextf") mc["fmt"] else if(fun == "ngettext") mc[c("msg1", "msg2")] else { if(!is.null(names(mc))) mc <- mc[!nzchar(names(mc))] mc[-1L] } strings <- as.character(args[vapply(args, is.character, TRUE)]) texts <- vapply(parse(text = table$text), as.character, "") pos <- which(!is.na(match(texts, strings))) cbind(table[pos, ], caller = rep.int(fun, length(pos))) } do.call(rbind, Map(extract_message_strings, as.list(funs), as.list(calls), table)) } aspell_R_R_files <- function(which = NULL, dir = NULL, ignore = c("[ \t]'[^']*'[ \t[:punct:]]", "[ \t][[:alnum:]_.]*\\(\\)[ \t[:punct:]]"), program = NULL, dictionaries = aspell_dictionaries_R) { if(is.null(dir)) dir <- tools:::.R_top_srcdir_from_Rd() if(is.null(which)) which <- tools:::.get_standard_package_names()$base files <- unlist(lapply(file.path(dir, "src", "library", which, "R"), tools::list_files_with_type, "code", OS_subdirs = c("unix", "windows")), use.names = FALSE) program <- aspell_find_program(program) aspell(files, filter = list("R", ignore = ignore), control = aspell_control_R_Rd_files[[names(program)]], program = program, dictionaries = dictionaries) } aspell_package_R_files <- function(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) { dir <- tools::file_path_as_absolute(dir) subdir <- file.path(dir, "R") files <- if(dir.exists(subdir)) tools::list_files_with_type(subdir, "code", OS_subdirs = c("unix", "windows")) else character() meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" defaults <- .aspell_package_defaults(dir, encoding)$R_files if(!is.null(defaults)) { if(!is.null(d <- defaults$ignore)) ignore <- d if(!is.null(d <- defaults$control)) control <- d if(!is.null(d <- defaults$program)) program <- d if(!is.null(d <- defaults$dictionaries)) { dictionaries <- aspell_find_dictionaries(d, file.path(dir, ".aspell")) } } program <- aspell_find_program(program) aspell(files, filter = list("R", ignore = ignore), control = control, encoding = encoding, program = program, dictionaries = dictionaries) } aspell_filter_db$pot <- function (ifile, encoding = "unknown", ignore = character()) { lines <- readLines(ifile, encoding = encoding, warn = FALSE) ind <- grepl("^msgid[ \t]", lines) do_entry <- function(s) { out <- character(length(s)) i <- 1L out[i] <- blank_out_regexp_matches(s[i], "^msgid[ \t]+\"") while(startsWith(s[i <- i + 1L], '"')) out[i] <- sub("^\"", " ", s[i]) if(grepl("^msgid_plural[ \t]", s[i])) { out[i] <- blank_out_regexp_matches(s[i], "^msgid_plural[ \t]+\"") while(startsWith(s[i <- i + 1L], '"')) out[i] <- sub("^\"", " ", s[i]) } out } entries <- split(lines, cumsum(ind)) lines <- c(character(length(entries[[1L]])), as.character(do.call(c, lapply(entries[-1L], do_entry)))) lines <- sub("\"[ \t]*$", " ", lines) blank_out_ignores_in_lines(lines, ignore) } aspell_package_pot_files <- function(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) { dir <- tools::file_path_as_absolute(dir) subdir <- file.path(dir, "po") files <- if(dir.exists(subdir)) Sys.glob(file.path(subdir, "*.pot")) else character() meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" program <- aspell_find_program(program) aspell(files, filter = list("pot", ignore = ignore), control = control, encoding = encoding, program = program, dictionaries = dictionaries) } aspell_R_C_files <- function(which = NULL, dir = NULL, ignore = c("[ \t]'[[:alnum:]_.]*'[ \t[:punct:]]", "[ \t][[:alnum:]_.]*\\(\\)[ \t[:punct:]]"), program = NULL, dictionaries = aspell_dictionaries_R) { if(is.null(dir)) dir <- tools:::.R_top_srcdir_from_Rd() if(is.null(which)) which <- tools:::.get_standard_package_names()$base if(!is.na(pos <- match("base", which))) which[pos] <- "R" files <- sprintf("%s.pot", file.path(dir, "src", "library", which, "po", which)) files <- files[file_test("-f", files)] program <- aspell_find_program(program) aspell(files, filter = list("pot", ignore = ignore), control = aspell_control_R_Rd_files[[names(program)]], program = program, dictionaries = dictionaries) } aspell_package_C_files <- function(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) { dir <- tools::file_path_as_absolute(dir) files <- file.path(dir, "po", paste(basename(dir), "pot", collapse = ".")) files <- files[file_test("-f", files)] meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" defaults <- .aspell_package_defaults(dir, encoding)$C_files if(!is.null(defaults)) { if(!is.null(d <- defaults$ignore)) ignore <- d if(!is.null(d <- defaults$control)) control <- d if(!is.null(d <- defaults$program)) program <- d if(!is.null(d <- defaults$dictionaries)) { dictionaries <- aspell_find_dictionaries(d, file.path(dir, ".aspell")) } } program <- aspell_find_program(program) aspell(files, filter = list("pot", ignore = ignore), control = control, encoding = encoding, program = program, dictionaries = dictionaries) } aspell_filter_db$dcf <- function(ifile, encoding, keep = c("Title", "Description"), ignore = character()) { lines <- readLines(ifile, encoding = encoding, warn = FALSE) line_has_tags <- grepl("^[^[:blank:]][^:]*:", lines) tags <- sub(":.*", "", lines[line_has_tags]) lines[line_has_tags] <- blank_out_regexp_matches(lines[line_has_tags], "^[^:]*:") lines <- split(lines, cumsum(line_has_tags)) ind <- is.na(match(tags, keep)) lines[ind] <- lapply(lines[ind], function(s) rep.int("", length(s))) ind <- !ind lines[ind] <- lapply(lines[ind], paste0, " ") lines <- unlist(lines, use.names = FALSE) blank_out_ignores_in_lines(lines, ignore) } aspell_package_description <- function(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) { dir <- tools::file_path_as_absolute(dir) files <- file.path(dir, "DESCRIPTION") meta <- tools:::.get_package_metadata(dir, installed = FALSE) if(is.na(encoding <- meta["Encoding"])) encoding <- "unknown" defaults <- Sys.getenv("_R_ASPELL_USE_DEFAULTS_FOR_PACKAGE_DESCRIPTION_", "TRUE") defaults <- if(tools:::config_val_to_logical(defaults)) { .aspell_package_defaults(dir, encoding)$description } else NULL if(!is.null(defaults)) { if(!is.null(d <- defaults$ignore)) ignore <- d if(!is.null(d <- defaults$control)) control <- d if(!is.null(d <- defaults$program)) program <- d if(!is.null(d <- defaults$dictionaries)) { dictionaries <- aspell_find_dictionaries(d, file.path(dir, ".aspell")) } } program <- aspell_find_program(program) aspell(files, filter = list("dcf", ignore = ignore), control = control, encoding = encoding, program = program, dictionaries = dictionaries) } aspell_filter_db$md <- function(ifile, encoding = "UTF-8") { x <- readLines(ifile, encoding = encoding, warn = FALSE) n <- nchar(x) y <- strrep(rep.int(" ", length(x)), n) md <- commonmark::markdown_xml(x, extensions = TRUE, sourcepos = TRUE) doc <- xml2::xml_ns_strip(xml2::read_xml(md)) pos <- strsplit(xml2::xml_attr(xml2::xml_find_all(doc, "//text[@sourcepos]"), "sourcepos"), "[:-]") for(p in pos) { p <- as.integer(p) l1 <- p[1L]; c1 <- p[2L]; l2 <- p[3L]; c2 <- p[4L] if(l1 < l2) { w <- seq(l1 + 1L, l2 - 1L) if(length(w)) y[w] <- x[w] substring(y[l1], c1, n[l1]) <- substring(x[l1], c1, n[l1]) substring(y[l2], 1L, c2) <- substring(x[l2], 1L, c2) } else { substring(y[l1], c1, c2) <- substring(x[l1], c1, c2) } } y } aspell_package <- function(dir, control = list(), program = NULL, dictionaries = character()) { args <- list(dir = dir, program = program, control = control, dictionaries = dictionaries) a <- rbind(do.call(aspell_package_description, args), do.call(aspell_package_Rd_files, args), do.call(aspell_package_vignettes, args), do.call(aspell_package_R_files, args), do.call(aspell_package_C_files, args)) if(nrow(a)) { a$File <- tools:::.file_path_relative_to_dir(a$File, dirname(dir)) } a } aspell_write_personal_dictionary_file <- function(x, out, language = "en", program = NULL) { if(inherits(x, "aspell")) x <- sort(unique(x$Original)) program <- aspell_find_program(program) if(is.na(program)) stop("No suitable spell check program found.") if(names(program) == "aspell") { header <- sprintf("personal_ws-1.1 %s %d UTF-8", language, length(x)) x <- enc2utf8(x) } else { header <- NULL } writeLines(c(header, x), out, useBytes = TRUE) } .aspell_package_defaults <- function(dir, encoding = "unknown") { dfile <- file.path(dir, ".aspell", "defaults.R") if(!file_test("-f", dfile)) return(NULL) exprs <- parse(dfile, encoding = encoding) envir <- new.env() for(e in exprs) eval(e, envir) as.list(envir) } blank_out_regexp_matches <- function(s, re, ...) { m <- gregexpr(re, s, ...) regmatches(s, m) <- Map(function(n) strrep(" ", n), lapply(regmatches(s, m), nchar)) s } blank_out_ignores_in_lines <- function(lines, ignore) { args <- list() if(is.list(ignore)) { args <- ignore[-1L] ignore <- ignore[[1L]] } for(re in ignore[nzchar(ignore)]) lines <- do.call(blank_out_regexp_matches, c(list(lines, re), args)) lines } find_files_in_directories <- function(basenames, dirnames) { dirnames <- dirnames[dir.exists(dirnames)] dirnames <- normalizePath(dirnames, "/") out <- character(length(basenames)) pos <- seq_along(out) for(dir in dirnames) { paths <- file.path(dir, basenames[pos]) ind <- file_test("-f", paths) out[pos[ind]] <- paths[ind] pos <- pos[!ind] if(!length(pos)) break } out }
"pdfgam" <- function(x,para) { if(length(para$para) == 2) { ALPHA <- para$para[1] BETA <- para$para[2] f <- dgamma(x, ALPHA, scale=BETA) names(f) <- NULL f[! is.finite(f)] <- NA f[is.na(f)] <- 0 return(f) } else if(length(para$para) == 3) { MU <- para$para[1]; SIGMA <- para$para[2]; NU <- para$para[3] Z <- (x/MU)^NU theta <- 1/(SIGMA^2*abs(NU)^2) lGT <- suppressWarnings(lgamma(theta)) if(! is.finite(lGT) | abs(NU) < 1e-06) { lf <- -log(x) - 0.5*log(2*pi) - log(SIGMA) - (1/(2*SIGMA^2)) * (log(x)-log(MU))^2 } else { lf <- theta*log(theta) + theta*log(Z) + log(abs(NU)) - theta*Z - lGT - log(x) } f <- exp(lf) names(f) <- NULL f[! is.finite(f)] <- NA f[is.na(f)] <- 0 return(f) } else { stop("should not be here in logic flow") } }
Sigma0.lo <- function(para, map, ref, model, nsample, outcome){ nmodel <- length(map$bet) nlam <- max(map$lam) n <- nrow(ref) the <- para[map$the] fx <- as.matrix(ref[, names(the), drop = FALSE]) exp.x.the <- exp(as.vector(fx %*% the)) y <- exp.x.the / (1 + exp.x.the) hess <- matrix(0, nrow = nlam, ncol = nlam) info <- matrix(0, nrow = nlam, ncol = nlam) offset <- max(map$the) for(i in 1:nmodel){ id1 <- c(alp.index.lo(map, i), map$bet[[i]]) gam1 <- para[id1] rx1 <- as.matrix(ref[, names(gam1), drop = FALSE]) exp.x.gam1 <- exp(as.vector(rx1 %*% gam1)) y1 <- exp.x.gam1 / (1 + exp.x.gam1) hess[id1 - offset, id1 - offset] <- -nsample[i, i] * (t(rx1) %*% (rx1 * y1 * (1 - y1))) / n for(j in i:nmodel){ id2 <- c(alp.index.lo(map, j), map$bet[[j]]) gam2 <- para[id2] rx2 <- as.matrix(ref[, names(gam2), drop = FALSE]) exp.x.gam2 <- exp(as.vector(rx2 %*% gam2)) y2 <- exp.x.gam2 / (1 + exp.x.gam2) tmp <- t(rx1) %*% (rx2 * (y * (1 - y1 - y2) + y1 * y2)) / n info[id1 - offset, id2 - offset] <- nsample[i, j] * tmp info[id2 - offset, id1 - offset] <- t(info[id1 - offset, id2 - offset]) rm(rx2) } rm(rx1) } V <- solve(hess) %*% info %*% solve(hess) id <- map$all.bet V <- V[id - offset, id - offset, drop = FALSE] colnames(V) <- names(para)[id] rownames(V) <- names(para)[id] V }
except=function(index,K,nstu){ list_l<-list() for(i in 1:K){ list_k<-list() for(j in 1:nstu){ if(index[j,i]==2) list_k<-c(list_k,j) } list_l[[i]]<-list_k } return(list_l) }
"lawyers.covariates"
library(approximator) library(emulator) set.seed(0) D1.1d <- matrix(1:6) source("subsets_1d.R") "basis.1d" <- function (x) { out <- cbind(1,x) colnames(out) <- c("const","x") return(out) } source("hpafun_1d.R") hpa.1d <- hpa.fun.1d(1:9) source("datamaker_1d.R") z.1d <- generate.1d.observations(D1=D1.1d, subsets=subsets.1d, basis.fun=basis.1d, hpa=hpa.1d, betas = NULL, export.truth=FALSE) jj.H <- H.fun.app(D1=D1.1d, subsets=subsets.1d , basis=basis.1d , hpa=hpa.1d) a1 <- opt.1(D=D1.1d , z=z.1d , basis=basis.1d , subsets=subsets.1d , hpa=hpa.1d) a2 <- opt.gt.1(level=2 , D=D1.1d , z=z.1d , basis=basis.1d , subsets=subsets.1d , hpa=hpa.1d) jj.ans <- mdash.fun(3,D1=D1.1d,subsets=subsets.1d,hpa=a2,z=z.1d,basis=basis.1d) jj.var <- c_fun(x=as.matrix(4),xdash=as.matrix(5),subsets=subsets.1d,hpa=hpa.1d)
read_builtin <- function(x, package = NULL) { warn_to_error <- function(e) { stop(conditionMessage(e), call. = FALSE) } check_string(x) check_string(package, optional = TRUE) tryCatch( warning = function(e) warn_to_error(e), expr = { res <- utils::data(list = x, package = package, envir = environment(), verbose = FALSE) get(res[[1]], envir = environment()) } ) }
library(knitLatex) knitr::opts_chunk$set(collapse = TRUE) cars <- mtcars[1:10,1:5] lTab(cars) lTab(cars, label = 'tab:mytable') lTab(cars, caption.head = 'my caption in head') lTab(cars, firsthead = 'f1 & f2 & f3 & f4 & f5 \\\\', caption.firsthead = 'my caption in firsthead') lTab(cars, caption.foot = 'my caption in foot') lTab(cars, lastfoot = '\\hline', caption.lastfoot = 'my caption in last foot') lTab(cars, booktabs = TRUE) lTab(cars, booktabs = TRUE, midrule = '\\hline') lTab(cars, head = 'col1 & col 2 & col3 & \\eta & col5 \\\\') lTab(cars, head = NULL) lTab(cars, head = '', midrule = NULL) lTab(cars, firsthead = 'f1 & f2 & f3 & f4 & f5 \\\\') lTab(cars, toprule = NULL, midrule = NULL, firsthead = '\\toprule\nf1 & f2 & f3 & f4 & f5 \\\\\nmidrule', head = '\\hline\n col1 & col2 & col3 & cll4 & col5 \\\\\n\\hline') lTab(cars, toprule = NULL, midrule = NULL, firsthead = '\\toprule\nf1 & f2 & f3 & f4 & f5 \\\\\nmidrule', head = '\\toprule') lTab(cars, rows = TRUE) lTab(cars, rows = TRUE, head = 'rows & col1 & col2 & col3 & \\eta & col5 \\\\') lTab(cars, rowsep = '\\hline') lTab(cars, rowsep = '\\midrule') lTab(cars, coldef ='rlc|l|p{5cm}') lTab(cars, colsep = '|')
as_ggsideCoord <- function(coord) UseMethod("as_ggsideCoord") as_ggsideCoord.default <- function(coord){ abort(glue("No known method to make {class(coord)[1]} ggside friendly")) } as_ggsideCoord.CoordCartesian <- function(coord){ if (class(coord)[1L]!="CoordCartesian") abort(glue("No known method to make {class(coord)[1]} ggside friendly")) ggplot2::ggproto("CoordSide", CoordSideCartesian, limits = coord$limits, expand = coord$expand, default = coord$default, clip = coord$clip) } as_ggsideCoord.CoordSide <- function(coord) { coord } CoordSideCartesian <- ggplot2::ggproto( "CoordSideCartesian", CoordCartesian, render_bg = function(panel_params, theme) { panel_type <- eval(quote(self$layout[self$layout$PANEL==i,]$PANEL_TYPE), sys.parent(2)) if (is.element(panel_type, c("x", "y"))) { ggside_guide_grid( theme, panel_params$x$break_positions_minor(), panel_params$x$break_positions(), panel_params$y$break_positions_minor(), panel_params$y$break_positions(), side = panel_type ) } else { guide_grid( theme, panel_params$x$break_positions_minor(), panel_params$x$break_positions(), panel_params$y$break_positions_minor(), panel_params$y$break_positions() ) } }, render_fg = ggside_render_fg, render_axis_h = function (panel_params, theme) { panel_type <- panel_params$ggside_panel_type if (panel_type=="y") { list(top = ggside_panel_guides_grob(panel_params$guides, position = "top", theme = theme), bottom = ggside_panel_guides_grob(panel_params$guides, position = "bottom", theme = theme)) } else { list(top = panel_guides_grob(panel_params$guides, position = "top", theme = theme), bottom = panel_guides_grob(panel_params$guides, position = "bottom", theme = theme)) } }, render_axis_v = function (panel_params, theme) { panel_type <- panel_params$ggside_panel_type if (panel_type=="x") { list(left = ggside_panel_guides_grob(panel_params$guides, position = "left", theme = theme), right = ggside_panel_guides_grob(panel_params$guides, position = "right", theme = theme)) } else { list(left = panel_guides_grob(panel_params$guides, position = "left", theme = theme), right = panel_guides_grob(panel_params$guides, position = "right", theme = theme)) } } ) as_ggsideCoord.CoordTrans <- function(coord) { ggplot2::ggproto("CoordSide", CoordSideTrans, trans = coord$trans, limits = coord$limits, expand = coord$expand, clip = coord$clip) } CoordSideTrans <- ggplot2::ggproto( "CoordSideTrans", CoordTrans, render_bg = function(panel_params, theme) { panel_type <- eval(quote(self$layout[self$layout$PANEL==i,]$PANEL_TYPE), sys.parent(2)) if (is.element(panel_type, c("x", "y"))) { ggside_guide_grid( theme, panel_params$x.minor, panel_params$x.major, panel_params$y.minor, panel_params$y.major, side = panel_type ) } else { guide_grid( theme, panel_params$x.minor, panel_params$x.major, panel_params$y.minor, panel_params$y.major ) } }, render_fg = ggside_render_fg, render_axis_h = function (panel_params, theme) { arrange <- panel_params$x.arrange %||% c("secondary","primary") panel_type <- panel_params$ggside_panel_type if (is.element(panel_type, c("x", "main"))) { list(top = render_axis(panel_params, arrange[1], "x", "top", theme), bottom = render_axis(panel_params, arrange[2], "x", "bottom", theme)) } else { list(top = ggside_render_axis(panel_params, arrange[1], "x", "top", theme), bottom = ggside_render_axis(panel_params, arrange[2], "x", "bottom", theme)) } }, render_axis_v = function (panel_params, theme) { arrange <- panel_params$x.arrange %||% c("primary","secondary") panel_type <- panel_params$ggside_panel_type if (is.element(panel_type, c("y", "main"))) { list(left = render_axis(panel_params, arrange[1], "y", "left",theme), right = render_axis(panel_params, arrange[2], "y", "right", theme)) } else { list(left = ggside_render_axis(panel_params, arrange[1], "y", "left",theme), right = ggside_render_axis(panel_params, arrange[2], "y", "right", theme)) } } ) as_ggsideCoord.CoordFixed<- function(coord){ ggplot2::ggproto("CoordSide", CoordSideFixed, limits = coord$limits, ratio = coord$ratio, expand = coord$expand, clip = coord$clip) } CoordSideFixed <- ggplot2::ggproto( "CoordSideFixed", CoordFixed, render_bg = function(panel_params, theme) { panel_type <- eval(quote(self$layout[self$layout$PANEL==i,]$PANEL_TYPE), sys.parent(2)) if (is.element(panel_type, c("x", "y"))) { ggside_guide_grid( theme, panel_params$x.minor, panel_params$x.major, panel_params$y.minor, panel_params$y.major, side = panel_type ) } else { guide_grid( theme, panel_params$x.minor, panel_params$x.major, panel_params$y.minor, panel_params$y.major ) } }, render_fg = ggside_render_fg, render_axis_h = function (panel_params, theme) { panel_type <- panel_params$ggside_panel_type if (is.element(panel_type, c("x", "main"))) { list(top = panel_guides_grob(panel_params$guides, position = "top", theme = theme), bottom = panel_guides_grob(panel_params$guides, position = "bottom", theme = theme)) } else { list(top = ggside_panel_guides_grob(panel_params$guides, position = "top", theme = theme), bottom = ggside_panel_guides_grob(panel_params$guides, position = "bottom", theme = theme)) } }, render_axis_v = function (panel_params, theme) { panel_type <- panel_params$ggside_panel_type if (is.element(panel_type, c("y", "main"))) { list(left = panel_guides_grob(panel_params$guides, position = "left", theme = theme), right = panel_guides_grob(panel_params$guides, position = "right", theme = theme)) } else { list(left = ggside_panel_guides_grob(panel_params$guides, position = "left", theme = theme), right = ggside_panel_guides_grob(panel_params$guides, position = "right", theme = theme)) } } )
D_jacknife <- function(Dvalues, D.base, block.size=FALSE){ D_sites <- Dvalues[1,] ABBA_sites <- Dvalues[2,] BABA_sites <- Dvalues[3,] D_sites <- D_sites[!is.na(D_sites)] ABBA_sites <- ABBA_sites[!is.na(D_sites)] BABA_sites <- BABA_sites[!is.na(D_sites)] if(!block.size){ D_sd <- sd(D_sites,na.rm=TRUE) D_err <- D_sd/sqrt(length(D_sites)) D_Z <- D.base / D_err D_p <- 2*pnorm(-abs(D_Z)) return(list(z=D_Z, pval=D_p)) } n.sites <- length(D_sites) width <- block.size jump <- 1 if(n.sites<block.size){ return(list(z=NaN, pval=NaN)) } repeatlength <- ceiling( (n.sites-width+1)/jump ) D_sim <- rep(NaN,repeatlength) for(zz in 1:repeatlength){ start <- ((zz-1) * jump + 1) end <- ((zz-1) * jump + width) window <- start:end ABBA <- ABBA_sites[-window] BABA <- BABA_sites[-window] D_sim[zz] <- ( sum(ABBA, na.rm=TRUE) - sum(BABA, na.rm=TRUE) ) / ( sum(ABBA, na.rm=TRUE) + sum(BABA, na.rm=TRUE) ) } D_sd <- sd(D_sim,na.rm=TRUE) D_err <- D_sd/sqrt(repeatlength) D_Z <- D.base / D_err D_p <- 2*pnorm(-abs(D_Z)) return(list(z=D_Z, pval=D_p)) }
setOldClass("gam") setMethod(f = "predictCells", signature = c(models = "SingleCellExperiment"), definition = function(models, gene){ if (is(gene, "character")) { if (!all(gene %in% rownames(models))) { stop("Not all gene IDs are present in the models object.") } id <- match(gene, rownames(models)) } else id <- gene dm <- colData(models)$tradeSeq$dm X <- colData(models)$tradeSeq$X betaMat <- rowData(models)$tradeSeq$beta[[1]] beta <- betaMat[id,] yhat <- exp(t(X %*% t(beta)) + matrix(dm$offset, nrow = length(gene), ncol = nrow(X), byrow = TRUE)) colnames(yhat) <- colnames(models) rownames(yhat) <- gene return(yhat) } ) setMethod(f = "predictCells", signature = c(models = "list"), definition = function(models, gene){ if (is(gene, "character")) { if (!all(gene %in% rownames(models))) { stop("The gene ID is not present in the models object.") } id <- which(rownames(models) %in% gene) } else { id <- gene } yhat <- t(sapply(models[id], "[[", "fitted.values")) rownames(yhat) <- gene return(yhat) } )
NULL validator <- function(..., .file, .data) new('validator',... , .file = .file, .data=.data) setRefClass("validator" , fields = list(._language = "character") , contains = "expressionset" , methods = list( initialize = function(..., .file, .data){ ini_validator(.self,...,.file=.file, .data=.data) } , is_linear = function() linear(.self) , linear_coefficients = function(...) get_linear_coefficients(.self, ...) ) ) ini_validator <- function(obj, ..., .file, .data){ check_primitives() if (missing(.file) && missing(.data) ){ .ini_expressionset_cli(obj, ..., .prefix="V") obj$._options <- .PKGOPT i <- validating(obj) | is_tran_assign(obj) if ( !all(i) ){ invalid <- sapply(which(!i),function(k) deparse(expr(obj[[k]]))) wrn <- sprintf("\n[%03d] %s",which(!i), invalid) warning(paste0( "Invalid syntax detected, the following expressions have been ignored:" , paste0(wrn,collapse="") ), call.=FALSE) obj$rules <- obj$rules[i] } } else if (!missing(.file)) { .ini_expressionset_yml(obj, file=.file, .prefix="V") } else if (!missing(.data)){ .ini_expressionset_df(obj, dat=.data, .prefix="V") i <- validating(obj) | is_tran_assign(obj) if (!all(i)){ r <- paste(which(!i),collapse=", ") warning("Invalid syntax detected, ignoring rows ",r) obj$rules <- obj$rules[i] } obj$._options <- .PKGOPT } for ( r in seq_along(obj)){ if ( is.null( meta(obj[[r]])$language ) ) { meta(obj[[r]],"language") <- paste("validate",utils::packageVersion("validate")) } if (is.null( meta(obj[[r]])$severity)) { meta(obj[[r]],"severity") <- "error" } } } check_primitives <- function(){ prim <- c("<","<=","==","!=",">=",">","%in%") for ( p in prim ) if (!identical(body(p),body(getFromNamespace(p,"base")))) warning(sprintf("Using implementation of %s that differs from base::`%s`",p,p)) } get_linear_coefficients <- function(x, normalize=TRUE,...){ x <- x[x$is_linear()] calls <- .get_exprs(x,lin_eq_eps=0, lin_ineq_eps=0) cols <- unique(unlist(lapply(calls, var_from_call))) rows <- names(x) bA <- matrix(0 , nrow = length(rows) , ncol = length(cols) + 1 , dimnames = list(validator=rows, variable=c('CONSTANT',cols) ) ) lcoef <- lapply(calls, function(x) coefficients(left(x))) rcoef <- lapply(calls, function(x) coefficients(right(x))) for ( i in seq_along(lcoef) ){ cls <- names(lcoef[[i]]) bA[i,cls] <- lcoef[[i]] cls <- names(rcoef[[i]]) bA[i,cls] <- bA[i,cls] - rcoef[[i]] } operators <- sapply(sapply(calls,`[[`,1),deparse) if (normalize){ bA <- bA * operatorsign[operators] operators <- normed_operators[operators] } list(A=bA[,-1,drop=FALSE],b = -1*bA[,1,drop=FALSE],operators=operators) } setMethod("+", c("validator","validator"), function(e1, e2){ v <- validator() v$rules <- c(e1$rules, e2$rules) names(v) <- make.names(names(v),unique=TRUE) v }) setMethod("plot","validator" , function( x , y , use_blocks = TRUE , col = c(" , cex = 1 , show_legend = TRUE , ... ){ if (show_legend){ oldpar <- par(xpd=TRUE, mar=c(7,4,3,3)) on.exit(par(oldpar)) } use_blocks <- isTRUE(use_blocks) show_legend <- isTRUE(show_legend) if (length(x) < 1){ message("No rules to be plotted") return(invisible()) } blocks <- if (use_blocks){ x$blocks() } A <- variables(x, as = "matrix") Z <- A Z[A] <- 2 Z[A & x$is_linear()] <- 1 is.na(Z) <- Z == 0 if (use_blocks){ rule_order <- unlist(blocks) var_order <- unlist(lapply(blocks, function(b){variables(x[b])})) Z <- Z[rule_order, var_order, drop = FALSE] } Z <- t(Z) ylim <- c(1, ncol(Z)) + c(-0.5, 0.5) graphics::image( x = seq_len(nrow(Z)) , y = seq_len(ncol(Z)) , z = Z , col = col , las = 1 , xlab = "variables" , ylab= "rules" , xaxt = "n" , yaxt = "n" ) axis(2, at=seq_len(ncol(Z)), labels = colnames(Z), las=1) var_text <- which(Z > 0, arr.ind = TRUE) var_text <- data.frame(var_text) var_text$labels <- colnames(A)[var_text$variable] text( x = var_text$variable , y = var_text$rule , labels = var_text$labels , cex = cex ) if (use_blocks){ h <- sapply(x$blocks(), length) h <- c(0,cumsum(h)) + 0.5 v <- lapply(blocks, function(b){variables(x[b])}) v <- sapply(v, length) v <- c(0,cumsum(v)) + 0.5 graphics::rect( xleft = utils::head(v, -1) , xright = utils::tail(v, -1) , ybottom = utils::head(h, -1) , ytop = utils::tail(h, -1) , lty = 2 , border ="gray30") } if (show_legend){ legend( x = 0.5 , y = 0.2 , legend = c("linear rule", "other") , fill=col , bty="n" ) } F <- factor(Z, levels=c(1,2), labels = c("linear", "other")) dim(F) <- dim(Z) dimnames(F) <- dimnames(Z) invisible(F) })
testthat::test_that( "methods for fhir_body() create identical results", { b1 <- fhir_body(content = "gender=female&_summary=count", type="application/x-www-form-urlencoded") b2 <- fhir_body(content = list("gender"="female", "_summary"= "count")) testthat::expect_identical(b1, b2) } ) testthat::test_that( "errors are thrown for incorrect input", { testthat::expect_error(fhir_body(content = "a")) testthat::expect_error(fhir_body(content = c("a", "b"), type="a")) } )
download_monthly_synop <- function(path = ".", date, ...) { file <- paste0("synop.", date, ".csv.gz") dir.create(file.path(path, "data-raw"), showWarnings = FALSE) utils::download.file(url = paste(metsyn_url(), file, sep = "/"), destfile = file.path(path, "data-raw", paste0("monthly_", file)), ...) invisible(NULL) }
expcub00 <- function(m,pai,csi){(m-1)*pai*(0.5-csi)+(m+1)/2}
test_that("`plot.see_rope()` works", { if (require("bayestestR") && require("rstanarm")) { set.seed(123) m <- stan_glm(Sepal.Length ~ Petal.Width * Species, data = iris, refresh = 0 ) result <- rope(m) expect_s3_class(plot(result), "gg") } })
condensity <- function(bws, xeval, yeval, condens, conderr = NA, congrad = NA, congerr = NA, ll = NA, ntrain, trainiseval = FALSE, gradients = FALSE, rows.omit = NA){ if (missing(bws) | missing(xeval) | missing(yeval) | missing(condens) | missing(ntrain)) stop("improper invocation of condensity constructor") if (length(rows.omit) == 0) rows.omit <- NA d <- list( xbw = bws$xbw, ybw = bws$ybw, bws = bws, xnames = bws$xnames, ynames = bws$ynames, nobs = nrow(xeval), xndim = bws$xndim, yndim = bws$yndim, xnord = bws$xnord, xnuno = bws$xnuno, xncon = bws$xncon, ynord = bws$ynord, ynuno = bws$ynuno, yncon = bws$yncon, pscaling = bws$pscaling, ptype = bws$ptype, pcxkertype = bws$pcxkertype, puxkertype = bws$puxkertype, poxkertype = bws$poxkertype, pcykertype = bws$pcykertype, puykertype = bws$puykertype, poykertype = bws$poykertype, xeval = xeval, yeval = yeval, condens = condens, conderr = conderr, congrad = congrad, congerr = congerr, log_likelihood = ll, ntrain = ntrain, trainiseval = trainiseval, gradients = gradients, rows.omit = rows.omit, nobs.omit = ifelse(identical(rows.omit,NA), 0, length(rows.omit))) class(d) <- "condensity" return(d) } print.condensity <- function(x, digits=NULL, ...){ cat("\nConditional Density Data: ", x$ntrain, " training points,", ifelse(x$trainiseval, "", paste(" and ", x$nobs, " evaluation points,\n", sep="")), " in ", x$xndim + x$yndim, " variable(s)", "\n(", x$yndim, " dependent variable(s), and ", x$xndim, " explanatory variable(s))\n\n", sep="") print(matrix(x$ybw,ncol=x$yndim,dimnames=list(paste("Dep. Var. ",x$pscaling,":",sep=""),x$ynames))) print(matrix(x$xbw,ncol=x$xndim,dimnames=list(paste("Exp. Var. ",x$pscaling,":",sep=""),x$xnames))) cat(genDenEstStr(x)) cat(genBwKerStrs(x$bws)) cat("\n\n") if(!missing(...)) print(...,digits=digits) invisible(x) } fitted.condensity <- function(object, ...){ object$condens } se.condensity <- function(x){ x$conderr } gradients.condensity <- function(x, errors = FALSE, ...) { if(!errors) return(x$congrad) else return(x$congerr) } predict.condensity <- function(object, se.fit = FALSE, ...) { tr <- eval(npcdens(bws = object$bws, ...), envir = parent.frame()) if(se.fit) return(list(fit = fitted(tr), se.fit = se(tr), df = tr$nobs, log.likelihood = tr$ll)) else return(fitted(tr)) } plot.condensity <- function(x, ...) { npplot(bws = x$bws, ...) } summary.condensity <- function(object, ...){ cat("\nConditional Density Data: ", object$ntrain, " training points,", ifelse(object$trainiseval, "", paste(" and ", object$nobs, " evaluation points,\n", sep="")), " in ", object$xndim + object$yndim, " variable(s)", "\n(", object$yndim, " dependent variable(s), and ", object$xndim, " explanatory variable(s))\n\n", sep="") cat(genOmitStr(object)) print(matrix(object$ybw,ncol=object$yndim,dimnames=list(paste("Dep. Var. ",object$pscaling,":",sep=""),object$ynames))) print(matrix(object$xbw,ncol=object$xndim,dimnames=list(paste("Exp. Var. ",object$pscaling,":",sep=""),object$xnames))) cat(genDenEstStr(object)) cat(genBwKerStrs(object$bws)) cat('\n\n') }
MeanSampler <- function(form,data, max.sample.size=30, show.sample=FALSE) { if (!("manipulate" %in% installed.packages())) { return(cat(paste0("You must be on R Studio with package manipulate installed\n", "in order to run this function."))) } data <- data[complete.cases(data),] dcurven <- 512 prsd <- with(data,ParseFormula(form)) varname <- as.character(prsd$rhs) numvar <- data[,varname] pop.mean <- mean(numvar) if (max.sample.size>length(numvar)) { stop("Sample size must be less than pop size") } sampmeans <- NULL nprev <- NULL beginning <- TRUE dpop <- NULL manipulate( n=slider(1,max.sample.size,step=1,initial=1, label="Sample Size n"), {OurSample <- sample(numvar,n,replace=FALSE) samp.mean <- mean(OurSample) if (!identical(n,nprev)) { sampmeans <<- NULL } if (!beginning) sampmeans <<- c(sampmeans,samp.mean) if (show.sample && !beginning) { cat("The sample was\n") print(OurSample) } if (!beginning) { cat("x-bar was",round(samp.mean,3),"\n") cat("mu is",round(pop.mean,3),"\n") } nprev <<- n if (beginning) { dpop <<- density(numvar,n=1024,from=min(numvar),to=max(numvar)) plot(dpop$x,dpop$y,type="l",col="red",lwd=2, xlab=varname,ylab="Density", main="Population Distribution") } else { if(length(sampmeans) >=2) { dsamp <- density(sampmeans,n=dcurven,from=min(numvar),to=max(numvar)) plot(dsamp$x,dsamp$y,type="l",col="blue", xlab="x-bar",ylab="Estimated Density", main="Distribution of Sample Means") points(dpop$x,dpop$y,type="l",col="red",lwd=2) rug(sampmeans) points(samp.mean,0,col="blue",pch=19) abline(v=pop.mean,lwd=1.5,col="red") legend(x="topright",legend=c("Population","Sample Means"),col=c("red","blue"),lwd=c(2,1)) } } beginning <<- FALSE } ) }
odds.indo2malay <- function (x) { malay <- x malay[] <- NA_real_ malay[which(x <= -1 | x >= 1)] <- -1 / x[which(x <= -1 | x >= 1)] malay }
HierarchicalClust <- function(W,K = 5, method = "ward.D2", flagDiagZero=FALSE, verbose = FALSE, ...){ W <- checking.gram.similarityMatrix(W, flagDiagZero=flagDiagZero, verbose = verbose) if(verbose){message("CALCULATION OF THE GRAPH")} graph <- hclust(as.dist(1-W), method = method,...) if(verbose){plot(graph)} out <- list(cluster = cutree(graph,K)) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(edcpR) data(vegdata1, vegdata2, package = "edcpR")
find_name <- function(dataset,pattern){ vec<-grep(pattern,names(dataset)) list(rang=vec,valeur=names(dataset)[vec]) }
hamming.neighbors <- function(source, targets){ results<-list() distances<-hamming.distance(source, targets) for (distance in sort(unique(distances))){ results[distance]=list(names(which(distances==distance))) } return(results) }
ggiNEXT <- function(x, type=1, se=TRUE, facet.var="none", color.var="site", grey=FALSE){ UseMethod("ggiNEXT", x) } ggiNEXT.iNEXT <- function(x, type=1, se=TRUE, facet.var="none", color.var="site", grey=FALSE){ TYPE <- c(1, 2, 3) SPLIT <- c("none", "order", "site", "both") if(is.na(pmatch(type, TYPE)) | pmatch(type, TYPE) == -1) stop("invalid plot type") if(is.na(pmatch(facet.var, SPLIT)) | pmatch(facet.var, SPLIT) == -1) stop("invalid facet variable") if(is.na(pmatch(color.var, SPLIT)) | pmatch(color.var, SPLIT) == -1) stop("invalid color variable") type <- pmatch(type, 1:3) facet.var <- match.arg(facet.var, SPLIT) color.var <- match.arg(color.var, SPLIT) if(facet.var=="order") color.var <- "site" if(facet.var=="site") color.var <- "order" options(warn = -1) z <- fortify(x, type=type) options(warn = 0) if(ncol(z) ==7) {se <- FALSE} datatype <- unique(z$datatype) if(color.var=="none"){ if(levels(factor(z$order))>1 & "site"%in%names(z)){ warning("invalid color.var setting, the iNEXT object consists multiple sites and orders, change setting as both") color.var <- "both" z$col <- z$shape <- paste(z$site, z$order, sep="-") }else if("site"%in%names(z)){ warning("invalid color.var setting, the iNEXT object consists multiple orders, change setting as order") color.var <- "site" z$col <- z$shape <- z$site }else if(levels(factor(z$order))>1){ warning("invalid color.var setting, the iNEXT object consists multiple sites, change setting as site") color.var <- "order" z$col <- z$shape <- factor(z$order) }else{ z$col <- z$shape <- rep(1, nrow(z)) } }else if(color.var=="order"){ z$col <- z$shape <- factor(z$order) }else if(color.var=="site"){ if(!"site"%in%names(z)){ warning("invalid color.var setting, the iNEXT object do not consist multiple sites, change setting as order") z$col <- z$shape <- factor(z$order) } z$col <- z$shape <- z$site }else if(color.var=="both"){ if(!"site"%in%names(z)){ warning("invalid color.var setting, the iNEXT object do not consist multiple sites, change setting as order") z$col <- z$shape <- factor(z$order) } z$col <- z$shape <- paste(z$site, z$order, sep="-") } zz=z z$method[z$method=="observed"]="interpolated" z$lty <- z$lty <- factor(z$method, levels=unique(c("interpolated", "extrapolated"), c("interpolation", "interpolation", "extrapolation"))) z$col <- factor(z$col) data.sub <- zz[which(zz$method=="observed"),] g <- ggplot(z, aes_string(x="x", y="y", colour="col")) + geom_point(aes_string(shape="shape"), size=5, data=data.sub) g <- g + geom_line(aes_string(linetype="lty"), lwd=1.5) + guides(linetype=guide_legend(title="Method"), colour=guide_legend(title="Guides"), fill=guide_legend(title="Guides"), shape=guide_legend(title="Guides")) + theme(legend.position = "bottom", legend.title=element_blank(), text=element_text(size=18), legend.key.width = unit(1.2,"cm")) if(type==2L) { g <- g + labs(x="Number of sampling units", y="Sample coverage") if(datatype=="abundance") g <- g + labs(x="Number of individuals", y="Sample coverage") } else if(type==3L) { g <- g + labs(x="Sample coverage", y="Species diversity") } else { g <- g + labs(x="Number of sampling units", y="Species diversity") if(datatype=="abundance") g <- g + labs(x="Number of individuals", y="Species diversity") } if(se) g <- g + geom_ribbon(aes_string(ymin="y.lwr", ymax="y.upr", fill="factor(col)", colour="NULL"), alpha=0.2) if(facet.var=="order"){ if(length(levels(factor(z$order))) == 1 & type!=2){ warning("invalid facet.var setting, the iNEXT object do not consist multiple orders.") }else{ g <- g + facet_wrap(~order, nrow=1) if(color.var=="both"){ g <- g + guides(colour=guide_legend(title="Guides", ncol=length(levels(factor(z$order))), byrow=TRUE), fill=guide_legend(title="Guides")) } } } if(facet.var=="site"){ if(!"site"%in%names(z)) { warning("invalid facet.var setting, the iNEXT object do not consist multiple sites.") }else{ g <- g + facet_wrap(~site, nrow=1) if(color.var=="both"){ g <- g + guides(colour=guide_legend(title="Guides", nrow=length(levels(factor(z$order)))), fill=guide_legend(title="Guides")) } } } if(facet.var=="both"){ if(length(levels(factor(z$order))) == 1 | !"site"%in%names(z)){ warning("invalid facet.var setting, the iNEXT object do not consist multiple sites or orders.") }else{ g <- g + facet_wrap(site~order) if(color.var=="both"){ g <- g + guides(colour=guide_legend(title="Guides", nrow=length(levels(factor(z$site))), byrow=TRUE), fill=guide_legend(title="Guides")) } } } if(grey){ g <- g + theme_bw(base_size = 18) + scale_fill_grey(start = 0, end = .4) + scale_colour_grey(start = .2, end = .2) + guides(linetype=guide_legend(title="Method"), colour=guide_legend(title="Guides"), fill=guide_legend(title="Guides"), shape=guide_legend(title="Guides")) + theme(legend.position="bottom", legend.title=element_blank()) } g <- g + theme(legend.box = "vertical") return(g) } ggiNEXT.default <- function(x, ...){ stop( "iNEXT doesn't know how to deal with data of class ", paste(class(x), collapse = "/"), call. = FALSE ) } fortify.iNEXT <- function(model, data = model$iNextEst, type = 1, ...) { datatype <- ifelse(names(model$DataInfo)[2]=="n","abundance","incidence") z <- data if(class(z) == "list"){ z <- data.frame(do.call("rbind", z), site=rep(names(z), sapply(z, nrow))) rownames(z) <- NULL }else{ z$site <- "" } if(ncol(z)==6) { warning("invalid se setting, the iNEXT object do not consist confidence interval") se <- FALSE }else if(ncol(z)>6) { se <- TRUE } if(type==1L) { z$x <- z[,1] z$y <- z$qD if(se){ z$y.lwr <- z[,5] z$y.upr <- z[,6] } }else if(type==2L){ if(length(unique(z$order))>1){ z <- subset(z, order==unique(z$order)[1]) } z$x <- z[,1] z$y <- z$SC if(se){ z$y.lwr <- z[,8] z$y.upr <- z[,9] } }else if(type==3L){ z$x <- z$SC z$y <- z$qD if(se){ z$y.lwr <- z[,5] z$y.upr <- z[,6] } } z$datatype <- datatype z$plottype <- type if(se){ data <- z[,c("datatype","plottype","site","method","order","x","y","y.lwr","y.upr")] }else{ data <- z[,c("datatype","plottype","site","method","order","x","y")] } data }
"EMPIRgridder2" <- function(empgrid=NULL, ...) { if(is.null(empgrid)) { warning("The gridded empirical copula (say from EMPIRgrid) is NULL") return(NULL) } if(! is.list(empgrid)) { warning("The gridded empirical copula is expected as a list from EMPIRgrid") return(NULL) } deluv <- empgrid$deluv empcop <- empgrid$empcop rc <- dim(empcop) n <- rc[1] if(n != rc[2]) { warning("grid is not square!") return(NA) } if(deluv != 1/(n-1)) { warning("concerns over value of deluv, not congruent with matrix size") } the.deriv <- matrix(nrow=n, ncol=n) for(i in 1:n) { section <- empcop[i,] diff.section <- diff(section) derivative <- c(0, diff.section/deluv) the.deriv[i,] <- derivative } for(i in 2:n) { the.deriv[,i] <- the.deriv[,i]/the.deriv[n,i] } the.deriv[,1] <- rep(NA, n) for(i in 2:n) { if(length(the.deriv[! is.finite(the.deriv[,i])]) > 0) { warning("found nonfinite values on column=",i," in grid derivative") next } } attributes(the.deriv) <- list(dim=dim(empcop), rownames=empgrid$u, colnames=empgrid$v, message="use the columns!, wrt V") return(the.deriv) }
replace_consecutive <- function(x, by = "", fun_for_identical = base::identical ) { if (length(x) < 2) { return(x) } is_consecutive <- mapply(fun_for_identical, x = x[1:length(x) - 1], y = x[2:length(x)], USE.NAMES = FALSE) is_consecutive <- c(FALSE, is_consecutive) x[is_consecutive] <- by return(x) }
readVpc<-function (vpc.results = NULL, npc.results = NULL, verbose = FALSE,...) { if (is.null(vpc.results) & is.null(npc.results)) { cat(paste("Both the arguments vpc.results and npc.results are NULL\n")) cat(paste("One of these must be defined\n")) return(NULL) } if (!is.null(vpc.results) & !is.null(npc.results)) { cat(paste("Both the arguments vpc.results and npc.results are defined\n")) cat(paste("ONLY one of these may be defined\n")) return(NULL) } vpc <- FALSE npc <- FALSE if (!is.null(vpc.results)) vpc <- TRUE if (!is.null(npc.results)) npc <- TRUE if (vpc) filename <- vpc.results if (npc) filename <- npc.results if (file.exists(filename)[1]) { if (verbose) cat(paste(" Reading", filename, "\n")) scannedFile <- scan(filename, sep = "\n", what = character(), quiet = TRUE, blank.lines.skip = FALSE) } blank.line.pat <- "^$" if (vpc) { table.start.pat <- "VPC results" table.head.pat <- "<=" } if (npc) { table.start.pat <- "NPC results" table.head.pat <- "points below PI" } table.start <- grep(table.start.pat, scannedFile) num.tables <- length(table.start) table.head <- grep(table.head.pat, scannedFile) blank.line <- grep(blank.line.pat, scannedFile) table.stop <- c() for (i in 1:num.tables) { for (j in 1:length(blank.line)) { if (table.start[i] > blank.line[j]) next if (table.start[i] < blank.line[j]) { table.stop <- c(table.stop, blank.line[j] - 1) break } } } table.rows.to.read <- table.stop - table.head dv.pat <- "Dependent variable" idv.pat <- "Independent variable" mod.pat <- "Modelfile" dv.idv.table.start <- grep(dv.pat, scannedFile) dv.idv.table.stop <- NULL for (j in 1:length(blank.line)) { if (dv.idv.table.start > blank.line[j]) next if (dv.idv.table.start < blank.line[j]) { dv.idv.table.stop <- blank.line[j] - 1 break } } dv.idv.table <- read.table(filename, skip = dv.idv.table.start - 1, nrows = dv.idv.table.stop - dv.idv.table.start, sep = ",", comment.char = "", header = T, strip.white = TRUE) dv.var <- paste(dv.idv.table[[grep("Dependent.variable", names(dv.idv.table))]]) model.file <- paste(dv.idv.table[[grep("Modelfile", names(dv.idv.table))]]) if (vpc) idv.var <- paste(dv.idv.table[[grep("Independent.variable", names(dv.idv.table))]]) cat.tables <- F cen.tables <- F cat.boundaries <- NULL lloq <- NA uloq <- NA pred.corr <- FALSE var.corr <- FALSE add.feats.row <- grep("Additional.feature", scannedFile) if (length(add.feats.row) != 0) { for (i in 1:length(add.feats.row)) { if (length(grep("Categorization", scannedFile[add.feats.row[i] + 1])) != 0) { cat.tables <- T boundary.table <- read.table(filename, skip = add.feats.row[i] + 1, nrows = 1, sep = ",", fill = T, comment.char = "", strip.white = TRUE, header = T) boundary.rows <- grep("Boundary", names(boundary.table)) cat.boundaries <- boundary.table[, boundary.rows] } if (length(grep("Censored.data", scannedFile[add.feats.row[i] + 1])) != 0) { cen.tables <- T censored.table <- read.table(filename, skip = add.feats.row[i] + 1, nrows = 1, sep = ",", fill = T, comment.char = "", strip.white = TRUE, header = T) lloq <- censored.table$LLOQ uloq <- censored.table$ULOQ } if (length(grep("Prediction.correction", scannedFile[add.feats.row[i] + 1])) != 0) { pred.corr <- T } if (length(grep("Variability.correction", scannedFile[add.feats.row[i] + 1])) != 0) { var.corr <- T } } } by.interval <- NULL strata.names <- NULL if (num.tables > 1) { bin.table <- vector("list", num.tables + 1) strata.names <- c() tmp.interval <- c() for (i in 1:num.tables) { strata.pat <- "strata" strata.line <- scannedFile[table.start[i]] strata.start <- regexpr(strata.pat, strata.line) + 7 if (strata.start == 6) { tmp.strata <- NULL tmp.interval <- NULL } else { strata.stop <- regexpr(",", strata.line) - 1 if (strata.stop == -2) strata.stop <- regexpr("$", strata.line) tmp.strata <- substring(strata.line, strata.start, strata.stop) strata.var.stop <- regexpr(" ", tmp.strata) - 1 strata.int.start <- regexpr(" ", tmp.strata) + 1 strata.var <- substring(tmp.strata, 1, strata.var.stop) strata.int <- substring(tmp.strata, strata.int.start) tmp.strata = gsub("\\[", ">= ", tmp.strata) tmp.strata = gsub("\\]", paste(" >=", strata.var, sep = " "), tmp.strata) tmp.strata = gsub("\\(", "> ", tmp.strata) tmp.strata = gsub("\\)", paste(" >", strata.var, sep = " "), tmp.strata) tmp.strata = gsub("\\;", " \\& ", tmp.strata) tmp.strata = gsub(" = ", " == ", tmp.strata) } strata.names <- c(strata.names, tmp.strata) if (!is.null(tmp.strata)) { if (regexpr(">", tmp.strata) != -1) { semi.loc <- regexpr("\\;", strata.int) lt.GE.loc <- regexpr("\\[", strata.int) lt.GT.loc <- regexpr("\\(", strata.int) rt.LE.loc <- regexpr("\\]", strata.int) rt.LT.loc <- regexpr("\\)", strata.int) strata.int.low <- substring(strata.int, 1, semi.loc - 1) strata.int.low <- gsub("\\[", "", strata.int.low) strata.int.low <- gsub("\\(", "", strata.int.low) strata.int.low <- gsub(" ", "", strata.int.low) strata.int.low <- as.numeric(strata.int.low) strata.int.high <- substring(strata.int, semi.loc + 1) strata.int.high <- gsub("\\]", "", strata.int.high) strata.int.high <- gsub("\\)", "", strata.int.high) strata.int.high <- gsub(" ", "", strata.int.high) strata.int.high <- as.numeric(strata.int.high) interval.length <- strata.int.high - strata.int.low add.to.ends <- interval.length * 1e-07 if (lt.GT.loc != -1) strata.int.low <- strata.int.low + add.to.ends if (rt.LT.loc != -1) strata.int.high <- strata.int.high - add.to.ends tmp.interval <- c(tmp.interval, strata.int.low, strata.int.high) } } bin.table[[i]] <- read.table(filename, skip = table.head[i] - 1, nrows = table.rows.to.read[i], sep = ",", comment.char = "", header = T, strip.white = TRUE, blank.lines.skip = FALSE) } if (length(tmp.interval) != 0) { by.interval <- matrix(tmp.interval, nrow = num.tables, ncol = 2, byrow = T) } bin.table[[num.tables + 1]] <- strata.names } else { bin.table <- read.table(filename, skip = table.head - 1, nrows = table.rows.to.read, sep = ",", comment.char = "", header = T, strip.white = TRUE, blank.lines.skip = FALSE) } for (i in 1:num.tables) { if (num.tables == 1) { tmp.table <- bin.table } else { tmp.table <- bin.table[[i]] } if (vpc) { tmp.table$X <- NULL tmp.table$X.1 <- NULL names(tmp.table)[1] <- "lower" names(tmp.table)[2] <- "upper" names(tmp.table)[3] <- "nobs" } if (npc) { names(tmp.table)[1] <- "PI" tmp.table$PI <- as.numeric(sub("% PI", "", tmp.table$PI)) } tmp.names <- names(tmp.table) tmp.names <- sub("X\\.*", "", tmp.names) tmp.names <- gsub("_", ".", tmp.names) tmp.names <- gsub("\\.+", "\\.", tmp.names) tmp.names <- gsub("\\.$", "", tmp.names) names(tmp.table) <- tmp.names if (num.tables == 1) { bin.table <- tmp.table } else { bin.table[[i]] <- tmp.table } } table.multiples = 1 if (cat.tables) table.multiples = table.multiples + 1 if (cen.tables) table.multiples = table.multiples + 1 if (table.multiples > 1) { bin.table.cont <- vector("list", num.tables/table.multiples) if (cat.tables) bin.table.cat <- vector("list", num.tables/table.multiples) if (cen.tables) bin.table.cen <- vector("list", num.tables/table.multiples) sub.i <- 0 for (ii in seq(1, num.tables, by = table.multiples)) { sub.i <- sub.i + 1 bin.table.cont[[sub.i]] <- bin.table[[ii]] } if (sub.i == 1) bin.table.cont <- bin.table.cont[[sub.i]] cen.start = 2 if (table.multiples == 3) { cat.start = 3 } else { cat.start = 2 } if (cen.tables) { sub.i <- 0 for (ii in seq(cen.start, num.tables, by = table.multiples)) { sub.i <- sub.i + 1 bin.table.cen[[sub.i]] <- bin.table[[ii]] } if (sub.i == 1) bin.table.cen <- bin.table.cen[[sub.i]] } else { bin.table.cen <- NULL } if (cat.tables) { sub.i <- 0 for (ii in seq(cat.start, num.tables, by = table.multiples)) { sub.i <- sub.i + 1 bin.table.cat[[sub.i]] <- bin.table[[ii]] } if (sub.i == 1) bin.table.cat <- bin.table.cat[[sub.i]] } else { bin.table.cat <- NULL } if (cat.tables) { num.tables.cat <- num.tables/table.multiples } else { num.tables.cat <- NULL } if (cen.tables) { num.tables.cen <- num.tables/table.multiples } else { num.tables.cen <- NULL } num.tables.cont <- num.tables/table.multiples strata.names <- strata.names[seq(1, num.tables, by = table.multiples)] } else { bin.table.cont <- bin.table bin.table.cat <- NULL bin.table.cen <- NULL num.tables.cont <- num.tables num.tables.cat <- NULL num.tables.cen <- NULL } if (npc) return(list(model.file = model.file, dv.var = dv.var, idv.var = NULL, num.tables = num.tables, result.tables = bin.table)) if (vpc) return(list(model.file = model.file, dv.var = dv.var, idv.var = idv.var, num.tables = num.tables.cont, by.interval = by.interval, result.tables = bin.table.cont, strata.names = strata.names, num.tables.cat = num.tables.cat, result.tables.cat = bin.table.cat, cat.boundaries = cat.boundaries, num.tables.cen = num.tables.cen, result.tables.cen = bin.table.cen, lloq = lloq, uloq = uloq, pred.corr = pred.corr, var.corr = var.corr)) }
CovFMean= function(M=NULL, optns = list()){ if(is.list(M)){ n=length(M) } else { if(!is.array(M)){ stop('M must be an array or a list') } n=dim(M)[3] } if(n==1){ stop("Sample size n should be at least 2") } x=matrix(1:n,nrow=n,ncol=1) xout=matrix((n+1)/2) if (is.null(optns$metric)){ metric="frobenius" } else { metric=optns$metric } if(!metric%in%c("frobenius","power","cholesky","log_cholesky")){ stop("metric choice not supported.") } if(metric=="frobenius"){ res <- list(Mout=GFRCov(x=x, y=NULL,M=M,xout=xout,optns = optns)$Mout,optns=optns) } else if(metric=="power"){ res <- list(Mout=GFRCovPower(x=x, y=NULL,M=M,xout=xout,optns = optns)$Mout,optns=optns) } else { if (is.null(M)) stop("M must be input for Cholesky and log-Cholesky metrics; y does not apply.") res <- list(Mout=GFRCovCholesky(x=x, M=M, xout=xout, optns = optns)$Mout,optns=optns) } class(res) <- "covReg" return(res) }
expand.mat <- function(mat, vec) { out = matrix(0, nrow = as.numeric(nrow(mat)) * as.numeric(length(vec)), ncol = as.numeric(ncol(mat) + 1)) for (i in 1:ncol(mat)) out[, i] = mat[, i] out[, ncol(mat) + 1] = rep(vec, each = nrow(mat)) return(out) }
cloneGitHubRepo <- function(repoURL, repoDir = NULL, default = FALSE, ...){ stopifnot((is.character(repoDir) & length(repoDir) == 1) | is.null(repoDir)) stopifnot( is.logical( default ), length( default ) == 1 ) repoURLsplitted <- strsplit(repoURL, "/")[[1]] if (is.null(repoDir)) { repoDir <-tail(repoURLsplitted,1) } if (!file.exists(repoDir)) { dir.create(repoDir) } git2r::clone(repoURL, repoDir, ...) -> repo2return if (default) { archivist::aoptions('repoDir', repoDir) archivist::aoptions('user', tail(repoURLsplitted,2)[1]) archivist::aoptions('repo', tail(repoURLsplitted,1)) } return(repo2return) }
setGeneric("exp_date", function(object) standardGeneric("exp_date")) setMethod("exp_date", "anlz", function(object) object@"exp_date") setGeneric("exp_date<-", function(object, value) standardGeneric("exp_date<-")) setMethod("exp_date<-", signature(object="anlz"), function(object, value) { if ( "exp_date" %in% slotNames(object) ){ object@"exp_date" <- value } else { warning("exp_date is not in slotNames of object") } return(object) })
rm(list = ls()) if(TRUE){ library(testthat) library(lavaSearch2) } lava.options(symbols = c("~","~~")) context("matrixPower") matrixPower <- lavaSearch2:::matrixPower M <- matrix(rnorm(2e2),20,10) Sigma <- var(M) test_that("square root", { Sigma.half <- matrixPower(Sigma, power = 1/2, symmetric = FALSE) expect_true(all(abs(crossprod(Sigma.half)-Sigma) < 1e-12)) }) test_that("inverse", { Sigma.m1 <- matrixPower(Sigma, power = -1, symmetric = FALSE) expect_equal(Sigma.m1 %*% Sigma,diag(1,NROW(Sigma),NCOL(Sigma))) })
optistart <- function(eloobject, burnin = 0, spread = 200, runs = 2000, doplot = FALSE, initialcohort = TRUE) { allids <- eloobject$allids n <- length(allids) normprob <- eloobject$misc["normprob"] == "1" w <- eloobject$logtable$winner l <- eloobject$logtable$loser kval <- eloobject$kvals startval <- eloobject$startvalues resmat <- matrix(ncol = length(allids), nrow = runs) colnames(resmat) <- allids logliks <- numeric(runs) for(i in 1:nrow(resmat)) { svals <- rnorm(n, mean = startval, sd = spread) svals <- round(svals - mean(svals) + startval) logliks[i] <- likelo(fastelo(WINNER = w, LOSER = l, ALLIDS = allids, KVALS = kval, STARTVALUES = svals, NORMPROB = normprob), burnin = burnin) resmat[i, ] <- svals } original <- likelo(fastelo(WINNER = w, LOSER = l, ALLIDS = allids, KVALS = kval, STARTVALUES = rep(startval, n), NORMPROB = normprob)) if (doplot) { x <- hist(logliks, breaks = 50, plot = FALSE) plot(x, ylim = c(0, max(x$counts)*1.05), yaxs = "i", las = 1, main = "") box() abline(v = original, col = "red", lwd = 2) } list(best = resmat[which.max(logliks), ], val = max(logliks), original = original, resmat = resmat, logliks = logliks) }
context("Ops") test_ops <- function(fun, x, y, ...) { if (missing(y)) { result_l <- fun(as_lvec(x), ...) result_r <- fun(x, ...) expect_that(as_rvec(result_l), equals(result_r)) } else { result_l <- fun(as_lvec(x), as_lvec(y), ...) result_r <- fun(x, y, ...) expect_that(as_rvec(result_l), equals(result_r)) } } test_that("numeric operators work", { set.seed(1) x <- rnorm(10) x[c(3, 8)] <- NA y <- c(1,1,2,2,3,3,4,4,5,6) operators <- list(`+`, `-`, `*`, `/`, `%%`, `%/%`) for (op in operators) { test_ops(op, x, 4) test_ops(op, x, y) test_ops(op, 4, x) expect_error(test_ops(op, 1:3, x)) test_ops(op, as_lvec(numeric(0)), 4) } }) test_that("logical operators work on numeric vectors", { set.seed(1) x <- 1:10 x[c(3, 8)] <- NA y <- 11:2 operators <- list(`==`, `!=`, `<`, `<=`, `>=`, `>`) for (op in operators) { test_ops(op, x, 4) test_ops(op, x, y) test_ops(op, 4, x) expect_error(test_ops(op, 1:3, x)) test_ops(op, as_lvec(numeric(0)), 4) } }) test_that("logical operators work", { set.seed(1) x <- sample(c(TRUE, FALSE), 10, replace=TRUE) x[c(3, 8)] <- NA y <- sample(c(TRUE, FALSE), 10, replace=TRUE) x[c(2, 8)] <- NA operators <- list(`&`, `|`, `==`, `!=`, `<`, `<=`, `>=`, `>`) for (op in operators) { test_ops(op, x, 4) test_ops(op, x, y) test_ops(op, 4, x) expect_error(test_ops(op, 1:3, x)) test_ops(op, as_lvec(logical(0)), 4) } }) test_that("unary operators work", { set.seed(1) x <- sample(c(TRUE, FALSE), 10, replace=TRUE) x[c(3, 8)] <- NA y <- rnorm(10) y[c(3, 8)] <- NA operators <- list(`+`, `-`, `!`) for (op in operators) { test_ops(op, x) test_ops(op, y) test_ops(op, as_lvec(logical(0))) test_ops(op, as_lvec(numeric(0))) } })
lmeForm <- structure(function ( rd, prim.cov = FALSE, resp = NULL, covar = NULL, lev.rm = NULL ) { if(is.null(resp)) resp <- cClass(rd, 'numeric')[1L] if(is.null(covar)) covar <- cClass(rd, 'integer')[1L] covar. <- paste('~',covar,sep = ' ') covar <- paste(resp,'~',covar,sep = ' ') f <- cClass(rd, 'factor') if(is.numeric(lev.rm)) lev.rm <- f[lev.rm] nf <- rev(f[!f%in%lev.rm]) sep. <- ' | ' if(length(nf) == 0) sep. <- '' fc <- paste(nf,collapse = '/') fr <- paste(covar,fc,sep = sep.) fr <- formula(fr,showEnv = FALSE) if(prim.cov)fr <- covar. return(fr) } , ex=function(){ data(Prings05,envir = environment()) form1 <- lmeForm(Prings05,prim.cov = FALSE) print(form1) form2 <- lmeForm(Prings05,lev.rm = 'sample') form2 <- lmeForm(Prings05,lev.rm = 1) gdata <- groupedData(lmeForm(Prings05,lev.rm = 1), data = Prings05) plot(gdata,groups = ~ sample) })
convertInitDesignToGrid = function(init, lower, upper, blocks) { if (class(init) == "matrix") init = as.data.frame(init) stopifnot(is.data.frame(init)) dims = ncol(init) - 1L if (missing(lower)) { lower = apply(init[,seq_len(dims)], 2L, min) } else if (length(lower) == 1L) { lower = rep(lower, dims) } if (missing(upper)) { upper = apply(init[, seq_len(dims)], 2L, max) } else if (length(upper) == 1L) { upper = rep(upper, dims) } if (missing(blocks)) { blocks = rep(10L, dims) } else if (length(blocks) == 1L) { blocks = as.integer(rep(blocks, dims)) } block.widths = (upper - lower) / blocks cp = cumprod(c(1L, blocks)) init$cell.ID = vapply(BBmisc::seq_row(init), function(init.row) { z = as.numeric(init[init.row, seq_len(dims)]) cell.ID = vapply(seq_len(dims), function(dim) { as.integer(cp[dim] * floor((z[dim] - lower[dim]) / block.widths[dim])) }, integer(1L)) as.integer(sum(cell.ID - cp[seq_along(blocks)] * (z == upper))) }, integer(1L)) init$cell.ID = init$cell.ID + 1L return(init) }
printCond <- function(v, warn=FALSE) { if (warn) warning(" Note that you are attempting to plot a 'main effect' in a model that contains an interaction. This is potentially misleading; you may wish to consider using the 'by' argument.", call.=FALSE) p <- ncol(v$fit)-4 X <- v$fit[, 1:p, drop=FALSE] X <- X[,-which(names(X) == v$meta$x), drop=FALSE] constant.columns <- which(sapply(X, function(x) all(x==x[1]))) varying.columns <- setdiff(1:ncol(X), constant.columns) for (j in 1:ncol(X)) if (is.factor(X[,j])) X[,j] <- as.character(X[,j]) cat("Conditions used in construction of plot\n") for (j in varying.columns) { x <- paste(unique(X[,j]), collapse= " / ") cat(names(X)[j], ": ", x, "\n", sep="") } for (j in constant.columns) { cat(names(X)[j], ": ", X[1,j], "\n", sep="") } }
print.jmodelTM <- function (x, digits = max(4, getOption("digits") - 4), ...) { result = x cat("Joint modeling fitting of longitudinal and survival data by ML\n") cat("\nCoefficients:\n") cat("\tLongitudinal Process\n") print(round(result$coefficients$beta, digits)) cat("\tSurvival Process\n") phis <- c(result$coefficients$phi, result$coefficients$alpha) print(round(phis, digits)) cat("\nVariance Components:\n") Bsigma <- result$coefficients$Bsigma ncz <- if(length(Bsigma) == 1) 1 else nrow(Bsigma) SD <- if (ncz == 1) sqrt(Bsigma) else sqrt(diag(Bsigma)) SD <- c(SD, result$coefficients$Ysigma) if (ncz > 1) { corr <- cov2cor(Bsigma) corr[upper.tri(corr, TRUE)] <- 0 corr <- rbind(corr, rep(0, ncz)) tempMat <- round(cbind(SD, corr[ , - ncz]), digits) tempMat <- apply(tempMat, 2, sprintf, fmt = "% .4f") tempMat[tempMat == tempMat[1, 2]] <- "" tempMat[1, -1] <- abbreviate(colnames(tempMat)[- 1], 6) colnames(tempMat) <- c(colnames(tempMat)[1], rep("", ncz - 1)) Mat <- data.frame(tempMat, check.rows = FALSE, check.names = FALSE) colnames(Mat) <- c("StdDev", "Corr", if (ncz > 2) rep(" ", ncz - 2) else NULL) rownames(Mat) <- c(dimnames(Bsigma)[[1]], "Residual") } else { Mat <- data.frame("StdDev" = SD, row.names = c(names(Bsigma), "Residual"), check.rows = FALSE, check.names = FALSE) } print(if(!is.numeric(Mat)) Mat else round(Mat, digits)) cat("\nLog-likelihood:", result$logLik, "\n") cat("Number of Observations:", result$N, "\n") cat("Number of Subjects:", result$n, "\n") invisible(result) }
source("ESEUR_config.r") library("prefmod") dorn=read.csv(paste0(ESEUR_dir, "odds-and-ends/dorn-scores.csv.xz"), as.is=TRUE) num_answers=apply(dorn, 1, function(X) length(which(!is.na(X)))-1) ratings=subset(dorn[, -1], num_answers == 20) sal = pattL.fit(ratings, nitems = ncol(ratings), resptype="rating")
library(tidyverse) devtools::load_all() library(googledrive) gs4_auth_testing() ss <- test_sheet_create() gs4_browse(ss)
library(PTXQC) require(methods) context("createReport.R") test_that("createReport", { local_zip = tempfile(fileext=".zip") target_url = "https://raw.githubusercontent.com/cbielow/PTXQC_data/master/txt_Ecoli.zip" dl = NULL tryCatch({ dl = download.file(target_url, destfile = local_zip, quiet = TRUE) }, silent = TRUE, warning = function(w) { }, error = function(err) { tryCatch({ dl = download.file(target_url, destfile = local_zip, method='curl', quiet = TRUE) }, silent = TRUE, warning = function(w) { }, error = function(err2) { print("Internet down. Aborting test gracefully") return(); }) }) if (is.null(dl)) return() unzip(local_zip, exdir = tempdir()) txt_folder = file.path(tempdir(), "txt") expect_equal(getMQPARValue(paste0(txt_folder, "/mqpar.xml"), "//firstSearchTol"), "20") expect_equal(getMQPARValue(paste0(txt_folder, "/mqpar.xml"), "//matchingTimeWindow"), "0.7") expect_equal(getMQPARValue(paste0(txt_folder, "/mqpar.xml"), "//string[parent::filePaths|parent::Filenames]", allow_multiple = TRUE), c("M:\\projects\\QC\\ecoli_small\\Toni_20120502_GM_Ecoli_01.raw", "M:\\projects\\QC\\ecoli_small\\Toni_20120502_GM_Ecoli_02.raw")) yaml_obj = list() r = createReport(txt_folder, NULL, yaml_obj) expect_equal(c("yaml_file", "heatmap_values_file", "R_plots_file", "filename_sorting", "mzQC_file", "log_file", "report_file_prefix", "report_file_PDF", "report_file_HTML"), names(r)) rep_files = c(r[["report_file_PDF"]], r[["report_file_HTML"]]) print(list.files(path = txt_folder)) for (f in rep_files) { cat("Checking file ", f, "\n") if (file.exists(f)) expect_equal(file.info(f)$size > 50*1024, TRUE) } expect_equal(file.exists(r[["heatmap_values_file"]]), TRUE) d_heatmap = read.delim(r[["heatmap_values_file"]]) expect_equal(dim(d_heatmap)[1], 2) expect_equal(dim(d_heatmap)[2] >= 22, TRUE) expect_equal(as.character(d_heatmap$fc.raw.file), c("..Ecoli_01", "..Ecoli_02")) expect_equal(file.exists(r[["filename_sorting"]]), TRUE) d_filenamesort = read.delim(r[["filename_sorting"]], comment.char=" expect_equal(dim(d_filenamesort), c(2, 3)) expect_equal(as.character(d_filenamesort$new.Name), c("..Ecoli_01", "..Ecoli_02")) no_volatile = function(file) { lines = readLines(file, warn = FALSE) grep("\"creationDate\"|\"contactName\"|\"location\"|\"version\"", lines, invert = TRUE, value = TRUE) } expect_equal(no_volatile(r[["mzQC_file"]]), no_volatile(system.file("./examples/report_ecoli_small.mzQC", package="PTXQC"))) unlink(local_zip) unlink(txt_folder, recursive = TRUE) })
context("test-tornado_survreg") test_that("survreg tornado works", { gtest <- survival::survreg(survival::Surv(futime, fustat) ~ ecog.ps + rx, survival::ovarian, dist = 'weibull', scale = 1) torn <- tornado(gtest, modeldata = survival::ovarian, type = "PercentChange", alpha = 0.10) expect_equal(class(torn), "tornado_plot") g <- plot(torn, plot = FALSE, xlabel = "Survival Time") g <- g + ggtitle("Test: survival regression") plot(g) mydat <- survival::ovarian mydat$resid.ds <- factor(mydat$resid.ds) gtest <- survival::survreg(survival::Surv(futime, fustat) ~ ecog.ps + rx + resid.ds, mydat, dist = 'weibull', scale = 1) torn <- tornado(gtest, modeldata = mydat, type = "PercentChange", alpha = 0.10) expect_equal(class(torn), "tornado_plot") g <- plot(torn, plot = FALSE, xlabel = "Survival Time") g <- g + ggtitle("Test: survival regression with factor") plot(g) })
icdglm.fit <- function(x, y, weights = rep.int(1, NROW(x)), indicator = rep.int(0, NROW(x)), family = binomial(link = "logit"), control = list()) { if (any(is.na(x))) { stop("icdglm.fit: NAs in x. Please apply expand_data first!", call. = FALSE) } control <- do.call("glm.control", control) x <- as.matrix(x) y <- as.numeric(y) weights <- as.numeric(weights) indicator <- as.numeric(indicator) dat <- apply(x, 1, paste, collapse = ";") incomplete.obs <- weights != 1 incomplete.indexes <- which(incomplete.obs) sum.weights <- sum(weights) conv <- FALSE dev.old <- 0 group.indicator <- rep.int(NA, length(indicator)) unique.indicator <- unique(indicator) for (i in incomplete.indexes) { group.indicator[i] <- which(unique.indicator == indicator[i]) } weights.x.obs <- as.numeric(rep.int(NA, NROW(x))) matchdat <- match(dat, unique(dat)) for (iter in 1L:control$maxit) { iterations <- iter fit1 <- suppressWarnings(glm.fit(x = x, y = y, family = family, weights = weights)) if (fit1$converged == FALSE) { warning("glm.fit: algorithm did not converge", call. = FALSE) break } if (family$family == "binomial") { weights.y <- predict.glm(fit1, type = "response") weights.y[y == 0] <- 1 - weights.y[y == 0] } else if (family$family == "Gamma") { weights.y <- predict.glm(fit1, type = "response") print(weights.y) weights.y <- dgamma(family$linkinv(y - weights.y), 1) print(weights.y) stop() } else { } sum1 <- unlist(lapply(unique(dat)[matchdat], function(x) sum(weights[match(dat, x, 0) > 0]))) weights.x.obs <- sum1 / sum.weights product.weights <- weights.x.obs * weights.y sum.group.weights <- rowsum(product.weights, group = indicator, reorder = FALSE) for (i in incomplete.indexes) { sum2 <- sum.group.weights[group.indicator[i],] weights[i] <- product.weights[i] / sum2 } dev.new <- fit1$deviance dev <- abs(dev.new - dev.old) / (0.1 + abs(dev.new)) if (control$trace) { cat("Deviance deviation = ", dev, " Iterations = ", iter, "\n", sep = "") } if (abs(dev.new - dev.old) / (0.1 + abs(dev.new)) < control$epsilon) { conv <- TRUE break } else { dev.old <- dev.new } } if (!conv) { warning("icdglm.fit: algorithm did not converge", call. = FALSE) } Phi <- summary.glm(fit1)$dispersion X.tilde <- as.matrix(x) W <- Diagonal(length(y), weights) W.inv <- Diagonal(length(y), 1 / weights) M.tilde <- Diagonal(length(y), fit1$weights) M.tilde.2 <- Diagonal(length(y), fit1$weights^2) V.tilde.inv.2 <- Diagonal(length(y), (1 / family$variance(fit1$fitted.values))^2) H.tilde.2 <- Diagonal(length(y), (y - fit1$fitted.values)^2) info.mat <- t(X.tilde) %*% M.tilde %*% ( Diagonal(length(y), 1 - ((fit1$weights / Phi * (1 - weights) / weights * ((y - fit1$fitted.values) / family$variance(fit1$fitted.values))^2)))) %*% X.tilde info.mat <- as.matrix(info.mat) print(iter) print(family) print(y) print(weights) print(fit1$weights) print(fit1$fitted.values) print(info.mat) qr1 <- list(qr = chol(info.mat), pivot = 1:(fit1$rank), rank = fit1$rank, class = "qr") icdglm.fit <- list(x = x, y = fit1$y, new.weights = weights, indicator = indicator, glm.fit.data = fit1, coefficients = fit1$coefficients, qr = qr1, residuals = fit1$residuals, fitted.values = fit1$fitted.values, effects = fit1$effects, R = fit1$R, rank = fit1$rank, family = fit1$family, linear.predictors = fit1$linear.predictors, deviance = fit1$deviance, aic = fit1$aic, null.deviance = fit1$null.deviance, iter = iterations, weights = fit1$weights, prior.weights = fit1$prior.weights, df.residual = sum.weights - NCOL(x), df.null = sum.weights - 1, converged = conv, boundary = fit1$boundary ) return(icdglm.fit) }
dmi <- function(Data){ dimD <- dim(Data) nmis <- sapply(Data,function(x) sum(is.na(x))) obs_mono <- dimD[1] - nmis stillNA <- integer(dimD[2]) for(i in 1:dimD[2]){ stillNA[i] <- sum(is.na(Data[1:obs_mono[i],i])) } return(1 - sum(stillNA)/sum(nmis)) }
summary.gamlss <- function(object, n.sim = 100, prob.lev = 0.05, ...){ bs <- SE <- Vb <- epds <- sigma2.st <- sigma2 <- nu.st <- nu <- est.RHOb <- XX <- Xt <- V <- 1 cont1par <- c(object$VC$m1d, object$VC$bl) cont2par <- c(object$VC$m2,object$VC$m2d) cont3par <- c(object$VC$m3,object$VC$m3d) n <- object$n lf <- length(object$coefficients) if(object$VC$surv.flex == FALSE) Vb <- object$Vb else Vb <- object$Vb.t SE <- sqrt(diag(Vb)) bs <- rMVN(n.sim, mean = object$coefficients, sigma = Vb) susutsnR <- susutsn(object, bs, lf, cont1par, cont2par, cont3par, prob.lev, type = "gamls") CIsig2 <- susutsnR$CIsig21 CInu <- susutsnR$CInu1 CImu <- susutsnR$CImu mu <- susutsnR$mu if(object$VC$gc.l == TRUE) gc() susuR <- susu(object, SE, Vb, informative = object$VC$informative) tableN <- susuR$tableN table <- susuR$table rm(bs, SE, Vb, XX, Xt, V) res <- list(tableP1=table[[1]], tableP2=table[[2]], tableP3=table[[3]], tableP4=table[[4]], tableP5=table[[5]], tableP6=table[[6]], tableP7=table[[7]], tableP8=table[[8]], tableNP1=tableN[[1]], tableNP2=tableN[[2]], tableNP3=tableN[[3]], tableNP4=tableN[[4]], tableNP5=tableN[[5]], tableNP6=tableN[[6]], tableNP7=tableN[[7]], tableNP8=tableN[[8]], n=n, sigma2=object$sigma2, sigma=object$sigma2, Model = object$Model, nu=object$nu, sigma2.a=object$sigma2.a, sigma.a=object$sigma2.a, nu.a=object$nu.a, formula = object$formula, formula1=object$gam1$formula, formula2=object$gam2$formula, formula3=object$gam3$formula, formula4=object$gam4$formula, formula5=object$gam5$formula, formula6=object$gam6$formula, formula7=object$gam7$formula, formula8=object$gam8$formula, t.edf=object$t.edf, CImu = CImu, mu = mu, CIsig=CIsig2, CInu=CInu, margins = object$margins, l.sp1 = object$l.sp1, l.sp2 = object$l.sp2, l.sp3 = object$l.sp3, l.sp4 = object$l.sp4, l.sp5 = object$l.sp5, l.sp6 = object$l.sp6, l.sp7 = object$l.sp7, l.sp8 = object$l.sp8, X2.null = is.null(object$X2), univar.gamlss = TRUE, surv.flex = object$surv.flex, K1 = NULL, robust = object$robust, indx = object$fit$indx) class(res) <- "summary.gamlss" res }
RsTest <- function(formula, data, alpha = 0.05, na.rm = TRUE, verbose = TRUE) { dp=as.character(formula) DNAME <- paste(dp[[2L]], "and", dp[[3L]]) METHOD <- "RS test" TEST <- "RS" if (na.rm){ completeObs <- complete.cases(data) data <- data[completeObs,] } if (any(colnames(data)==dp[[3L]])==FALSE) stop("The name of group variable does not match the variable names in the data. The group variable must be one factor.") if (any(colnames(data)==dp[[2L]])==FALSE) stop("The name of response variable does not match the variable names in the data.") y = data[, dp[[2L]]] group = data[, dp[[3L]]] if (!is.factor(group)) stop("The group variable must be a factor.") if (!is.numeric(y)) stop("The response must be a numeric variable.") n <- length(y) x.levels <- levels(factor(group)) k<-NROW(x.levels) aRS=0;LRS=0; Cvar=0;Cort=0 a=1 b<- y.n <- NULL for (i in x.levels) { y.n[i] <- length(y[group==i]) } for (i in 1:k) { b[i] = i-1 Cort=Cort+y.n[i]*(i-1)/n } for (i in 1:k) { Cvar=Cvar+y.n[i]*(b[i]-Cort)^2 } r <- rank(y) ' Calculating aRS ' for (i in 1:n){ if (r[i]>((n+1)/2)) aRS[i]=0 else aRS[i]=r[i]-(n+1)/2 } for (i in 1:k) { for (j in 1:y.n[i]){ LRS=LRS+b[i]*aRS[a] a=a+1 }} ERS=n*Cort*mean(aRS) VRS=Cvar*var(aRS) Z=(LRS-ERS)/sqrt(VRS) p.value=1-pnorm(Z, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE) if (verbose) { cat("---------------------------------------------------------","\n", sep = " ") cat(" Test :", METHOD, "\n", sep = " ") cat(" data :", DNAME, "\n\n", sep = " ") cat(" Statistic =", LRS, "\n", sep = " ") cat(" Mean =", ERS, "\n", sep = " ") cat(" Variance =", VRS, "\n", sep = " ") cat(" Z =", Z, "\n", sep = " ") cat(" Asymp. p-value =", p.value, "\n\n", sep = " ") cat(if (p.value > alpha) {" Result : Null hypothesis is not rejected."} else {" Result : Null hypothesis is rejected."}, "\n") cat("---------------------------------------------------------","\n\n", sep = " ") } result <- list() result$statistic <- LRS result$mean <- ERS result$variance <- VRS result$Z <- Z result$p.value <- p.value result$alpha <- alpha result$method <- METHOD result$data <- data result$formula <- formula attr(result, "class") <- "owt" invisible(result) }
tune.ltrcrrf <- function(formula, data, id, mtryStart = NULL, stepFactor = 2, time.eval = NULL, time.tau = NULL, ntreeTry = 100L, bootstrap = c("by.sub","by.root","by.node","by.user","none"), samptype = c("swor","swr"), sampfrac = 0.632, samp = NULL, na.action = "na.omit", trace = TRUE, doBest = FALSE, plot = FALSE, ntime, nsplit = 10L, nodesizeTry = max(ceiling(sqrt(nrow(data))), 15), nodedepth = NULL) { Call <- match.call() indx <- match(c('formula', 'id'), names(Call), nomatch = 0) if (indx[1] == 0) stop("a formula argument is required") yvar.names <- all.vars(formula(paste(as.character(formula)[2], "~ .")), max.names = 1e7) yvar.names <- yvar.names[-length(yvar.names)] if (length(yvar.names) == 4){ yvar.names = yvar.names[2:4] } n <- nrow(data) bootstrap <- match.arg(bootstrap) samptype <- match.arg(samptype) Rtimes <- data[, yvar.names[2]] xvar.names <- attr(terms(formula), 'term.labels') nvar <- length(xvar.names) if (is.null(mtryStart)){ mtryStart <- ceiling(sqrt(nvar)) } if (missing(ntime)){ ntime = sort(unique(Rtimes[data[, yvar.names[3]] == 1])) } if (indx[2] == 0){ data$id <- 1:n } else { names(data)[names(data) == deparse(substitute(id))] <- "id" } data <- data[, c("id", yvar.names, xvar.names)] if (na.action == "na.omit") { takeid = which(complete.cases(data) == 1) } else if (na.action == "na.impute") { takeid = 1:n } else { stop("na.action can only be either 'na.omit' or 'na.pass'.") } id.sub <- unique(data$id[takeid]) n.seu <- length(takeid) n.sub <- length(id.sub) Rtimes <- Rtimes[takeid] if (n.seu == n.sub){ if (is.null(time.eval)){ time.eval <- c(0, sort(unique(Rtimes))) } if (bootstrap == "by.sub") bootstrap = "by.root" } else { if (is.null(time.eval)){ time.eval <- c(0, sort(unique(Rtimes)), seq(max(Rtimes), 1.5 * max(Rtimes), length.out = 50)[-1]) } if (is.null(time.tau)){ time.tau <- sapply(1:n.sub, function(ii){ 1.5 * max(Rtimes[data$id[takeid] == id.sub[ii]]) }) } } errorOOB_mtry <- function(eformula, edata, id, emtryTest, etpnt, etau, entreeTry, enodesizeTry, enodedepth, ensplit, ebootstrap, esamptype, esampfrac, esamp, ena.action, entime){ rrfOOB <- ltrcrrf(formula = eformula, data = edata, id = id, mtry = emtryTest, ntree = entreeTry, nodesize = enodesizeTry, nodedepth = enodedepth, nsplit = ensplit, bootstrap = ebootstrap, samptype = esamptype, sampfrac = esampfrac, samp = esamp, na.action = ena.action, ntime = entime) predOOB <- predictProb(object = rrfOOB, time.eval = etpnt, time.tau = etau, OOB = TRUE) errorOOB <- sbrier_ltrc(obj = predOOB$survival.obj, id = predOOB$survival.id, pred = predOOB, type = "IBS") rm(rrfOOB) rm(predOOB) return(errorOOB) } errorOld <- errorOOB_mtry(eformula = formula, edata = data, id = id, emtryTest = mtryStart, etpnt = time.eval, etau = time.tau, entreeTry = ntreeTry, enodesizeTry = nodesizeTry, enodedepth = nodedepth, ensplit = nsplit, ebootstrap = bootstrap, esamptype = samptype, esampfrac = sampfrac, esamp = samp, ena.action = na.action, entime = ntime) if (errorOld < 0) stop("Initial setting gave 0 error and no room for improvement.") if (trace) { cat("mtry = ", mtryStart, " OOB Brier score = ", errorOld, "\n") } oobError <- list() oobError[[1]] <- errorOld names(oobError)[1] <- mtryStart for (direction in c("left", "right")) { if (trace) cat("Searching", direction, "...\n") mtryCur <- mtryStart while (mtryCur != nvar) { mtryOld <- mtryCur mtryCur <- if (direction == "left") { max(1, ceiling(mtryCur / stepFactor)) } else { min(nvar, floor(mtryCur * stepFactor)) } if (mtryCur == mtryOld) break errorCur <- errorOOB_mtry(eformula = formula, edata = data, id = id, emtryTest = mtryCur, etpnt = time.eval, etau = time.tau, entreeTry = ntreeTry, enodesizeTry = nodesizeTry, enodedepth = nodedepth, ensplit = nsplit, ebootstrap = bootstrap, esamptype = samptype, esampfrac = sampfrac, esamp = samp, ena.action = na.action, entime = ntime) if (trace) { cat("mtry = ", mtryCur, "\tOOB error = ", errorCur, "\n") } oobError[[as.character(mtryCur)]] <- errorCur errorOld <- errorCur } } mtry <- sort(as.numeric(names(oobError))) res_all <- unlist(oobError[as.character(mtry)]) res_all <- cbind(mtry = mtry, OOBError = res_all) res <- res_all[which.min(res_all[, 2]), 1] if (plot) { res = res_all plot(res_all, xlab = expression(m[try]), ylab = "OOB Error", type = "o", log = "x", xaxt = "n") axis(1, at = res_all[, "mtry"]) } if (doBest) { res <- ltrcrrf(formula = formula, data = data, id = id, mtry = res, ntree = ntreeTry, nodesize = nodesizeTry, nodedepth = nodedepth, nsplit = nsplit, ntime = ntime, bootstrap = bootstrap, samptype = samptype, sampfrac = sampfrac, samp = samp, na.action = na.action) } return(res) }
coxvar <- function(x, y, ic, offset = rep(0., length(y)), coxstuff.obj = NULL) { nx <- nrow(x) n <- length(y) yy <- y + (ic == 0.) * (1e-06) otag <- order(yy) y <- y[otag] ic <- ic[otag] x <- x[, otag, drop = F] offset <- offset[otag] if(is.null(coxstuff.obj)) { coxstuff.obj <- coxstuff(x, y, ic, offset = offset) } nf <- coxstuff.obj$nf fail.times <- coxstuff.obj$fail.times s <- coxstuff.obj$s d <- coxstuff.obj$d dd <- coxstuff.obj$dd nn <- coxstuff.obj$nn nno <- coxstuff.obj$nno x2<- x^2 oo <- (1.:n)[y >= fail.times[1] ] sx<-(1/nno[1])*rowSums(x[, oo] * exp(offset[oo])) s<-(1/nno[1])*rowSums(x2[, oo] * exp(offset[oo])) w <- d[1] * (s - sx * sx) for(i in 2.:nf) { oo <- (1.:n)[y >= fail.times[i-1] & y < fail.times[i] ] sx<-(1/nno[i])*(nno[i-1]*sx-rowSums(x[, oo,drop=F] * exp(offset[oo]))) s<-(1/nno[i])*(nno[i-1]*s-rowSums(x2[, oo,drop=F] * exp(offset[oo]))) w <- w + d[i] * (s - sx * sx) } return(w) }
r_obj = function() { system.file("extdata", "r_obj.txt", package="rayvertex") }
get_complete_authors = function(id, pubid, delay = .4, initials = TRUE) { get_author = function(id, pubid) { auths = "" site <- getOption("scholar_site") url_template = paste0(site, "/citations?view_op=view_citation&citation_for_view=%s:%s") url = sprintf(url_template, id, pubid) url1 <- get_scholar_resp(url[1]) %>% read_html() auths = as.character(rvest::html_node(url1, ".gsc_oci_value") %>% rvest::html_text()) return(auths) } if (length(pubid) == 1) { auths <- get_author(id, pubid) } else{ if(length(pubid) > 50){ stop("Requesting author lists for more than 50 publications risks google identifying you as a bot and blocking your ip range (429 errors).") } min_delay = delay - .5 max_delay = delay + .5 if(min_delay < 0) min_delay <- 0 if(delay == 0) max_delay <- 0 pb = utils::txtProgressBar(min = 1, max = length(pubid), style = 3) i = 1 auths <- sapply(pubid, function(x) { delay <- sample(seq(min_delay, max_delay, by = .001), 1) Sys.sleep(delay) auth <- get_author(id, x) i <<- i + 1 utils::setTxtProgressBar(pb, i) return(auth) }) close(pb) } if (initials) { auths = sapply(auths, format_authors) } auths } format_authors = function(string) { authors = trimws(unlist(strsplit(string, ","))) format_author = function(author){ words = trimws(unlist(strsplit(author, " "))) lastname = words[length(words)] first = words[!words %in% lastname] first = gsub("\\B[a-z]","",first, perl = TRUE) first = paste(first, collapse = "") trimws(paste(first, lastname)) } authors = sapply(authors, format_author) paste(authors, collapse = ", ") }
blavTech <- function(blavobject, what, ...) { blavInspect(blavobject, what, ...) } blavInspect <- function(blavobject, what, ...) { stopifnot(inherits(blavobject, "blavaan")) what <- tolower(what) dotdotdot <- list(...) dotNames <- names(dotdotdot) add.labels <- TRUE if(any(dotNames == "add.labels")) add.labels <- dotdotdot$add.labels jagtarget <- lavInspect(blavobject, "options")$target == "jags" blavwhats <- c("start", "starting.values", "inits", "psrf", "ac.10", "neff", "mcmc", "draws", "samples", "n.chains", "cp", "dp", "postmode", "postmean", "postmedian", "hpd", "jagnames", "stannames", "fscores", "lvs", "fsmeans", "lvmeans", "mcobj", "rhat", "n_eff", "nchain", "nchains") blavnofit <- c("start", "starting.values", "inits", "n.chains", "cp", "dp", "jagnames", "stannames", "nchain", "nchains") nowhats <- c("mi", "modindices", "modification.indices", "wls.est", "wls.obs", "wls.v") if(what %in% blavwhats){ if(!(what %in% blavnofit) & !blavobject@Options$do.fit){ stop(paste0("blavaan ERROR: ", what, " does not exist when do.fit = FALSE")) } if(jagtarget){ idx <- blavobject@ParTable$jagpnum idx <- idx[!is.na(idx)] } else { idx <- blavobject@ParTable$stansumnum if("pxnames" %in% names(blavobject@ParTable)){ drows <- grepl("^def", blavobject@ParTable$pxnames) } else { drows <- grepl("def", blavobject@ParTable$mat) } idx <- idx[blavobject@ParTable$free > 0 | drows] } labs <- lav_partable_labels(blavobject@ParTable, type = "free") if(what %in% c("start", "starting.values", "inits")){ blavobject@external$inits } else if(what %in% c("psrf", "ac.10", "neff", "rhat", "n_eff")){ if(jagtarget){ mcmcsumm <- blavobject@external$mcmcout$summaries } else { mcmcsumm <- rstan::summary(blavobject@external$mcmcout)$summary } if(what %in% c("psrf", "rhat")){ if(jagtarget){ OUT <- mcmcsumm[idx,'psrf'] } else { OUT <- mcmcsumm[idx,'Rhat'] } }else if(what == "ac.10"){ if(jagtarget){ OUT <- mcmcsumm[idx,'AC.10'] } else { stop("blavaan ERROR: autocorrelation stat currently unavailable for Stan.") } } else { if(jagtarget){ OUT <- mcmcsumm[idx,'SSeff'] } else { OUT <- mcmcsumm[idx,'n_eff'] } } if(add.labels) names(OUT) <- labs OUT } else if(what %in% c("mcmc", "draws", "samples", "hpd")){ pt <- blavobject@ParTable pt$free[pt$op == ":="] <- max(pt$free, na.rm = TRUE) + 1:sum(pt$op == ":=") labs <- lav_partable_labels(pt, type = "free") draws <- make_mcmc(blavobject@external$mcmcout) draws <- lapply(draws, function(x) mcmc(x[,idx])) draws <- mcmc.list(draws) if(what == "hpd"){ pct <- .95 if("level" %in% dotNames) pct <- dotdotdot$level draws <- mcmc(do.call("rbind", draws)) draws <- HPDinterval(draws, pct) if(add.labels) rownames(draws) <- labs } draws } else if(what == "mcobj"){ blavobject@external$mcmcout } else if(what %in% c("fscores","lvs","fsmeans","lvmeans")){ if(jagtarget){ etas <- any(blavobject@external$mcmcout$monitor == "eta") } else { etas <- any(grepl("^eta", rownames(blavobject@external$stansumm))) } lvmn <- lavInspect(blavobject, "mean.lv") if(inherits(lvmn, "list")){ lvmn <- lvmn[[1]] } nlv <- length(lvmn) if(nlv == 0) stop("blavaan ERROR: no latent variables are in the model") if(!etas) stop("blavaan ERROR: factor scores not saved; set save.lvs=TRUE") nsamp <- sum(lavInspect(blavobject, "nobs")) draws <- make_mcmc(blavobject@external$mcmcout, blavobject@external$stanlvs) drawcols <- grep("^eta", colnames(draws[[1]])) if(jagtarget){ drawcols <- drawcols[1:(nlv * nsamp)] } else { nfound <- length(drawcols)/nsamp drawcols <- drawcols[as.numeric(matrix(1:length(drawcols), nsamp, nfound, byrow=TRUE)[,1:nlv])] } draws <- lapply(draws, function(x) mcmc(x[,drawcols])) mis <- any(is.na(unlist(blavobject@Data@X))) if(blavobject@Options$target == "stan" & mis){ rorig <- sapply(blavobject@Data@Mp, function(x) unlist(x$case.idx)) cids <- sapply(blavobject@Data@Mp, function(x) x$case.idx) if(nlv > 1){ norig <- length(rorig) rord <- rep(NA, nlv*norig) for(i in 1:nlv){ rord[((i-1)*norig + 1):(i*norig)] <- i*rorig } } else { rord <- rorig } rsamps <- rep(NA, nlv*norig) for(j in 1:nlv){ tmpsamp <- rep(NA, norig) cumn <- 0 for(i in 1:length(cids)){ tmpids <- cids[[i]] ncase <- length(tmpids) tmpsamp[(cumn + 1):(cumn + ncase)] <- (j-1)*norig + tmpids cumn <- cumn + ncase } rsamps[((j-1)*norig + 1):(j*norig)] <- tmpsamp } for(j in 1:length(draws)){ draws[[j]][,rsamps] <- draws[[j]] } } draws <- mcmc.list(draws) if((what %in% c("lvmeans", "fsmeans")) | ("means" %in% dotdotdot)){ br <- TRUE if(jagtarget){ summ <- blavobject@external$mcmcout$summaries summname <- "Mean" br <- FALSE } else { summ <- blavobject@external$stansumm summname <- "mean" } mnrows <- grep("^eta", rownames(summ)) draws <- matrix(summ[mnrows,summname], nsamp, length(mnrows)/nsamp, byrow=br)[,1:nlv,drop=FALSE] colnames(draws) <- names(lvmn) if(blavobject@Options$target == "stan" & mis){ draws[rorig,] <- draws } } draws } else if(what %in% c("n.chains", "nchain", "nchains")){ draws <- make_mcmc(blavobject@external$mcmcout) length(draws) } else if(what == "cp"){ blavobject@Options$cp } else if(what == "dp"){ blavobject@Options$dp } else if(what %in% c("postmode", "postmean", "postmedian")){ if(jagtarget){ mcmcsumm <- blavobject@external$mcmcout$summaries } else { mcmcsumm <- rstan::summary(blavobject@external$mcmcout)$summary } if(what == "postmean"){ if(jagtarget){ OUT <- mcmcsumm[idx,'Mean'] } else { OUT <- mcmcsumm[idx,'mean'] } }else if(what == "postmedian"){ if(jagtarget){ OUT <- mcmcsumm[idx,'Median'] } else { OUT <- mcmcsumm[idx,'50%'] } } else { if(jagtarget){ OUT <- mcmcsumm[idx,'Mode'] } else { stop("blavaan ERROR: Modes unavailable for Stan.") } } if(add.labels) names(OUT) <- labs OUT } else if(what == "jagnames"){ if(!jagtarget) stop("blavaan ERROR: JAGS was not used for model estimation.") OUT <- blavobject@ParTable$pxnames[blavobject@ParTable$free > 0] OUT <- OUT[order(blavobject@ParTable$free[blavobject@ParTable$free > 0])] if(add.labels) names(OUT) <- labs OUT } else if(what == "stannames"){ if(jagtarget) stop("blavaan ERROR: Stan was not used for model estimation.") mcmcsumm <- rstan::summary(blavobject@external$mcmcout)$summary OUT <- rownames(mcmcsumm)[idx] if(add.labels) names(OUT) <- labs OUT } } else if(what %in% nowhats){ stop(paste("blavaan ERROR: argument", what, "not available for Bayesian models.")) } else { lavargs <- c(dotdotdot, list(object = blavobject, what = what)) do.call("lavInspect", lavargs) } }
context("match.closest") test_that("match.closest", { expect_error(match.closest(1, c(0, -1, 3)), "sorted non-decreasingly") expect_equal(match.closest(1.001, 1:10), 1) expect_equal(match.closest(1.4, 1:10), 1) expect_equal(match.closest(9.8, 1:10), 10) expect_equal(match.closest(11.1, 1:10), 10) expect_equal(match.closest(4:5, 4.8, tolerance=1), c(1, 1)) expect_equal(match.closest(c(0.5, 1.5, exp(1), pi), 1:10), c(1, 2, 3, 3)) }) test_that("match.closest, length(table) == 1", { expect_equal(match.closest(1:3, 0, nomatch=0, tolerance=0), c(0, 0, 0)) expect_equal(match.closest(1:3, 1, nomatch=0, tolerance=0), c(1, 0, 0)) expect_equal(match.closest(1:3, 2, nomatch=0, tolerance=0), c(0, 1, 0)) expect_equal(match.closest(1:3, 3, nomatch=0, tolerance=0), c(0, 0, 1)) expect_equal(match.closest(1:3, 4, nomatch=0, tolerance=0), c(0, 0, 0)) }) test_that("match.closest, tolerance", { expect_error(match.closest(1, 1, tolerance=1, nomatch=1:2), "Length of .*nomatch.* has to be one") expect_warning(match.closest(1, 1, tolerance=-1), ".*tolerance.* < 0 is meaningless") expect_equal(match.closest(1.001, 1:10, tolerance=0), NA_integer_) expect_equal(suppressWarnings(match.closest(c(1,2,3.1), 1:3, tolerance=-1)), c(1, 2, NA_integer_)) expect_equal(match.closest(1.001, 1:10, tolerance=0, nomatch=-1), -1) expect_equal(match.closest(1.4, 1:10, tolerance=0.4), 1) })
epval_Chen2010_samecov <- function(sam1, sam2, perm.iter = 1000, seeds){ n1 <- dim(sam1)[1] n2 <- dim(sam2)[1] tau <- (n1 + n2)/(n1*n2) n <- n1 + n2 - 2 p <- dim(sam1)[2] sam <- rbind(sam1, sam2) diff <- colMeans(sam1) - colMeans(sam2) col.sum1 <- colSums(sam1) col.sum2 <- colSums(sam2) rm1 <- sum(col.sum1^2) - sum(diag(sam1 %*% t(sam1))) rm2 <- sum(col.sum2^2) - sum(diag(sam2 %*% t(sam2))) chen2010.stat <- rm1/(n1*(n1 - 1)) + rm2/(n2*(n2 - 1)) - 2*sum(col.sum1*col.sum2)/(n1*n2) chen2010.stat <- as.numeric(chen2010.stat) chen2010.stat.perm <- numeric(perm.iter) for(i in 1:perm.iter){ if(!is.null(seeds)) set.seed(seeds[i]) perm <- sample(1:(n1 + n2)) sam.perm <- sam[perm,] sam1.perm <- sam.perm[1:n1,] sam2.perm <- sam.perm[(n1 + 1):(n1 + n2),] diff.perm <- colMeans(sam1.perm) - colMeans(sam2.perm) col.sum1.perm <- colSums(sam1.perm) col.sum2.perm <- colSums(sam2.perm) rm1.perm <- sum(col.sum1.perm^2) - sum(diag(sam1.perm%*%t(sam1.perm))) rm2.perm <- sum(col.sum2.perm^2) - sum(diag(sam2.perm%*%t(sam2.perm))) chen2010.stat.perm[i] <- rm1.perm/(n1*(n1 - 1)) + rm2.perm/(n2*(n2 - 1)) - 2*sum(col.sum1.perm*col.sum2.perm)/(n1*n2) chen2010.stat.perm[i] <- as.numeric(chen2010.stat.perm[i]) } chen2010.pval <- (sum(chen2010.stat.perm >= chen2010.stat) + 1)/(perm.iter + 1) names(chen2010.pval) <- "Chen2010" out <- NULL out$sam.info <- c("n1" = n1, "n2" = n2, "p" = p) out$cov.assumption <- "the two groups have same covariance" out$method <- "permutation" out$pval <- chen2010.pval return(out) }
c( Mod1Step4updateB <- function(input){ suppressWarnings(B <- sqrt(1-input$Mod1Step4_Vi-input$Mod1Step4_Ve)) return(ifelse(is.finite(B), B, 0)) }, output$Mod1Step4_hidden <- renderUI({ list( numericInput("Mod1Step4_Tmax", "", Modules_VAR$Tmax$max), shinyMatrix::matrixInput("Mod1Step4_Vind", value = matrix(c(input$Mod1Step4_Vi, rep(0,(nb.IS*nb.IS)-1)), nb.IS), class = "numeric"), numericInput("Mod1Step4_Vbx","", 1-input$Mod1Step4_Vi-input$Mod1Step4_Ve), shinyMatrix::matrixInput("Mod1Step4_B", value = matrix(c(0,Mod1Step4updateB(input),0,0),1), class = "numeric"), checkboxInput("Mod1Step4_X1_state", "", value = TRUE), checkboxInput("Mod1Step4_X1_sto_state", "", value = TRUE), numericInput("Mod1Step4_X1_sto_V","", 1, min = 0, max = 1, step = 0.001) ) }), outputOptions(output, "Mod1Step4_hidden", suspendWhenHidden = FALSE), output$Mod1Step4_Vbx_txt <- renderUI({ if(!testInput(input$Mod1Step4_Vbx, Modules_VAR$Vbx, FALSE, FALSE)){ output <- span(strong(round(input$Mod1Step4_Vbx,2),class="alert alert-danger")) }else{ output <- span(round(input$Mod1Step4_Vbx,2)) } p(HTML(paste(strong(Modules_VAR$Vbx$label),output,""))) }), Mod1Step4_output <- reactive({ if(input$Mod1Step4_Run == 0) return(NULL) isolate({ updateCheckboxInput(session, "isRunning", value = TRUE) data <- squid::squidR(input, module="Mod1Step4") LMR <- lme4::lmer(Phenotype ~ 1 + X1 + (1|Individual), data = data$sampled_data) FIXEF <- lme4::fixef(LMR) SE.FIXEF <- arm::se.fixef(LMR) RANDEF <- as.data.frame(lme4::VarCorr(LMR))$vcov data$Vp <- round(var(data$sampled_data$Phenotype),2) data$Vi <- round(RANDEF[1],2) data$Ve <- round(RANDEF[2],2) data$B0 <- round(FIXEF["(Intercept)"],2) data$se.B0 <- round(SE.FIXEF["(Intercept)"],2) data$B1 <- round(FIXEF["X1"],2) data$se.B1 <- round(SE.FIXEF["X1"],2) data$phenotypeMean <- round(mean(data$sampled_data$Phenotype),2) updateCheckboxInput(session, "isRunning", value = FALSE) return(data) }) }), output$Mod1Step4_plot1 <- renderPlot({ data <- Mod1Step4_output() if(!is.null(data)){ isolate({ ggplot2::ggplot(data$sampled_data, ggplot2::aes(x = X1, y = Phenotype)) + ggplot2::geom_point() + ggplot2::geom_smooth(method = "lm", se = FALSE) + ggplot2::xlab("Environment") + ggplot2::ylab("Phenotype") + ggplot2::ggtitle(bquote(italic(beta[(estimated)]) == .(data$B1) %+-% .(data$se.B1) ~~ (italic(beta[(true)]) == .(round(input$Mod1Step4_B[1,2],2))))) }) }else{defaultPlot()} }), output$Mod1Step4_plot2 <- renderPlot({ data <- Mod1Step4_output() if(!is.null(data)){ isolate({ ggplot2::ggplot(data$sampled_data, ggplot2::aes(x = X1, y = Phenotype, color = as.factor(Individual), group = as.factor(Individual))) + ggplot2::geom_point() + ggplot2::geom_smooth(method = "lm", se = FALSE) + ggplot2::xlab("Environment") + ggplot2::ylab("Phenotype per individual") }) }else{defaultPlot()} }), output$Mod1Step4_summary_table <- renderUI({ data <- Mod1Step4_output() myTable <- data.frame("True" = c(paste("Population intercept ($",EQ3$mean0,"$) = 0"), paste("Individual variance ($V_",NOT$devI,"$) =",input$Mod1Step4_Vi), paste("Measurement variance ($V_",NOT$mError,"$) =",input$Mod1Step4_Ve), "Mean of the trait ($\\mu$) = 0", paste("Slope of environmental effect ($",NOT$mean,"$) =",round(input$Mod1Step4_B[1,2],2))), "Estimated" = c(paste("Population estimated mean ($",NOT$mean,"'_0$) = ", ifelse(!is.null(data),paste(data$B0,"\U00b1", data$se.B0, sep=" "),"...")), paste("Individual variance in sample ($V'_",NOT$devI,"$) = ", ifelse(!is.null(data),data$Vi,"...")), paste("Residual variance of sample ($V'_",NOT$residualUpper,"$) = ", ifelse(!is.null(data),data$Ve,"...")), paste("Sampled mean of the trait ($\\mu'$) = ", ifelse(!is.null(data),data$phenotypeMean,"...")), paste("Estimated slope of environmental effect ($",NOT$mean,"'$) = ", ifelse(!is.null(data),paste(data$B1,"\U00b1", data$se.B1, sep=" "),"..."))) ) getTable(myTable) }), observe({ if(!testInput(input$Mod1Step4_Vbx, Modules_VAR$Vbx, FALSE, FALSE)){ disableActionButton("Mod1Step4_Run", session, "true") }else{ disableActionButton("Mod1Step4_Run", session, "false") } }), output$Mod1Step4_error_Vbx <- renderUI({testInput(input$Mod1Step4_Vbx, Modules_VAR$Vbx, FALSE, TRUE)}) )
discrete_gamma <- function(using_terms, max_size=10, shape=10, rate=4) { n_terms <- length(using_terms) dist <- dgamma(seq(max_size), shape=shape, rate=rate) dens <- log(dist/sum(dist)) function(phi) { x <- length(phi) if (x > max_size) -Inf else dens[x] - lchoose(n_terms, x) } }
require(optimx) f1<-function(xx){ ((3*xx+2)*xx-5)*xx+4 } g1 <- function(xx){ gg <- 9*xx*xx+4*xx -5 } x0 <- .1234 lb <- -1 ub <- 10 cat("R has optimize function for [1D] functions\n") aoptimize <- optimize(f1, c(-1, 10)) print(aoptimize) cat("or we can use optim() with method='Brent' \n") abrent <- optim(x0, f1, lower=lb, upper=ub, method="Brent", control=list(trace=0)) print(abrent) ansone<-opm(x0, f1, g1, method = c("Rvmmin", "Rcgmin"), control=list(trace=0)) ansone.sum<-summary(ansone, order=value) print(ansone.sum) x0 = 1 cat("Start with x0=1. Use optim() with method='Brent' \n") abrent1 <- optim(x0, f1, lower=lb, upper=ub, method="Brent", control=list(trace=0)) print(abrent1) ansone1<-opm(x0, f1, g1, lower=lb, upper=ub, method = c("Rvmmin", "Rcgmin"), control=list(trace=0)) ansone1.sum<-summary(ansone1, order=value) print(ansone1.sum)
add_busy_gif <- function(src, timeout = 100, position = c("top-right", "top-left", "bottom-right", "bottom-left", "full-page", "free"), margins = c(10, 10), overlay_color = "rgba(0, 0, 0, 0.5)", overlay_css = NULL, height = "50px", width = "50px") { busy_gif( src = src, timeout = timeout, position = position, margins = margins, overlay_color = overlay_color, overlay_css = overlay_css, height = height, width = width, type = "auto" ) } use_busy_gif <- function(src, timeout = 100, position = c("top-right", "top-left", "bottom-right", "bottom-left", "full-page", "free"), margins = c(10, 10), overlay_color = "rgba(0, 0, 0, 0.5)", overlay_css = NULL, height = "50px", width = "50px") { busy_gif( src = src, timeout = timeout, position = position, margins = margins, overlay_color = overlay_color, overlay_css = overlay_css, height = height, width = width, type = "manual" ) } play_gif <- function(session = shiny::getDefaultReactiveDomain()) { session$sendCustomMessage( type = "shinybusy-play-gif", message = dropNulls(list()) ) } stop_gif <- function(session = shiny::getDefaultReactiveDomain()) { session$sendCustomMessage( type = "shinybusy-stop-gif", message = dropNulls(list()) ) } busy_gif <- function(src, timeout = 100, position = c("top-right", "top-left", "bottom-right", "bottom-left", "full-page", "free"), margins = c(10, 10), overlay_color = "rgba(0, 0, 0, 0.5)", overlay_css = NULL, height = "50px", width = "50px", type = "auto") { stopifnot(length(margins) == 2) marg1 <- validateCssUnit(margins[1]) marg2 <- validateCssUnit(margins[2]) position <- match.arg(position) style <- switch( EXPR = position, "top-right" = sprintf("top:%s; right:%s;", marg1, marg2), "top-left" = sprintf("top:%s; left:%s;", marg1, marg2), "bottom-right" = sprintf("bottom:%s; right:%s;", marg1, marg2), "bottom-left" = sprintf("bottom:%s; left:%s;", marg1, marg2), "full-page" = "top:0; bottom:0; right:0; left:0; margin:auto;", "free" = "" ) gif_tag <- tags$div( class = "shinybusy", style = style, style = if (position != "full-page") paste0("height:", validateCssUnit(height), ";"), style = if (position != "full-page") paste0("width:", validateCssUnit(width), ";"), tags$img( src = src, class = "freezeframe freezeframe-responsive shinybusy-freezeframe", class = if (position == "full-page") "shinybusy-full-page" ) ) if (position == "full-page") { gif_tag <- tagList( tags$div( class = "shinybusy shinybusy-overlay", style = sprintf("background-color: %s;", overlay_color), style = if (!is.null(overlay_css)) overlay_css, gif_tag ) ) } gif_tag <- tagList( gif_tag, tags$script( type = "application/json", `data-for` = "shinybusy", toJSON(list( timeout = timeout, mode = "gif", position = position, type = type ), auto_unbox = TRUE, json_verbatim = TRUE) ) ) attachDependencies( x = gif_tag, value = list( html_dependency_freezeframe(), html_dependency_shinybusy() ) ) } logo_silex <- function() { "shinybusy/silex/logo_rouge.gif" }
library(sp) data(meuse) coordinates(meuse) = ~x+y data(meuse.grid) gridded(meuse.grid) = ~x+y meuse.g <- gstat(id="zn", formula=log(zinc)~1, data=meuse, nmax = 10) meuse.g <- gstat(meuse.g, "cu", log(copper)~1, meuse, nmax = 10) meuse.g <- gstat(meuse.g, "cd", log(cadmium)~1, meuse, nmax = 10) meuse.g <- gstat(meuse.g, "pb", log(lead)~1, meuse, nmax = 10) meuse.g <- gstat(meuse.g, model=vgm(1, "Sph", 900, 1), fill.all=T) x <- variogram(meuse.g, cutoff=1000) meuse.fit = fit.lmc(x, meuse.g) plot(x, model = meuse.fit) z <- predict(meuse.fit, newdata = meuse.grid) library(lattice) pl1 <- spplot(z["zn.pred"], main="log-zinc predictions") pl2 <- spplot(z["cu.pred"], main="log-copper predictions") pl3 <- spplot(z["cd.pred"], main="log-cadmium predictions") pl4 <- spplot(z["pb.pred"], main="log-lead predictions") print(pl1, split = c(1,1,2,2), more=TRUE) print(pl2, split = c(1,2,2,2), more=TRUE) print(pl3, split = c(2,1,2,2), more=TRUE) print(pl4, split = c(2,2,2,2)) z$zn.se = sqrt(z$zn.var) z$cu.se = sqrt(z$cu.var) z$pb.se = sqrt(z$pb.var) z$cd.se = sqrt(z$cd.var) pl1 <- spplot(z["zn.se"], main="log-zinc std.err.") pl2 <- spplot(z["cu.se"], main="log-copper std.err.") pl3 <- spplot(z["cd.se"], main="log-cadmium std.err.") pl4 <- spplot(z["pb.se"], main="log-lead st.err.") print(pl1, split = c(1,1,2,2), more=TRUE) print(pl2, split = c(1,2,2,2), more=TRUE) print(pl3, split = c(2,1,2,2), more=TRUE) print(pl4, split = c(2,2,2,2)) rm(meuse.g, x, meuse.fit, z) q <- quantile(meuse$zinc, seq(.1,.9,.1)) meuse.i <- gstat(id = "zn1", formula = I(zinc < q[1])~1, data = meuse, nmax = 7, beta = .1, set = list(order = 4, zero = 1e-5)) meuse.i <- gstat(meuse.i, "zn2", I(zinc < q[2])~1, meuse, nmax = 7, beta=.2) meuse.i <- gstat(meuse.i, "zn3", I(zinc < q[3])~1, meuse, nmax = 7, beta=.3) meuse.i <- gstat(meuse.i, "zn4", I(zinc < q[4])~1, meuse, nmax = 7, beta=.4) meuse.i <- gstat(meuse.i, "zn5", I(zinc < q[5])~1, meuse, nmax = 7, beta=.5) meuse.i <- gstat(meuse.i, "zn6", I(zinc < q[6])~1, meuse, nmax = 7, beta=.6) meuse.i <- gstat(meuse.i, "zn7", I(zinc < q[7])~1, meuse, nmax = 7, beta=.7) meuse.i <- gstat(meuse.i, "zn8", I(zinc < q[8])~1, meuse, nmax = 7, beta=.8) meuse.i <- gstat(meuse.i, "zn9", I(zinc < q[9])~1, meuse, nmax = 7, beta=.9) meuse.i <- gstat(meuse.i, model=vgm(1, "Sph", 900, 1), fill.all=T) x <- variogram(meuse.i, cutoff=1000) meuse.fit = fit.lmc(x, meuse.i) plot(x, model = meuse.fit) z <- predict(meuse.fit, newdata = meuse.grid) spplot(z, c(3,5,7,9,11,13,15,17,19), names.attr = paste("est.Pr(Zn < ", q, ")", sep = ""))
context("extract_lsm") sample_points <- matrix(c(10, 5, 25, 15, 5, 25), ncol = 2, byrow = TRUE) x1 <- c(1, 5, 15, 10) y1 <- c(1, 5, 15, 25) x2 <- c(10, 25) y2 <- c(5, 5) sample_lines <- sp::SpatialLines(list(sp::Lines(list(sp::Line(cbind(x1, y1)), sp::Line(cbind(x2, y2))), ID = "a"))) test_that("extract_lsm returns correct metrics", { patch_area <- extract_lsm(landscape, y = sample_points, what = "lsm_p_area", type = "aggregation metric", verbose = FALSE) expect_true(all(patch_area$metric == "area")) patch_core <- extract_lsm(landscape, y = sample_points, type = "core area metric", full_name = TRUE, verbose = FALSE) expect_true(all(patch_core$type == "core area metric")) patch_all <- extract_lsm(landscape, y = sample_points, verbose = FALSE) expect_true(all(unique(patch_all$metric) == list_lsm(level = "patch")[,1])) }) test_that("extract_lsm works for lines", { result <- extract_lsm(landscape, y = sample_lines, what = "lsm_p_area", verbose = FALSE) expect_is(result, "tbl_df") expect_true(all(result$metric %in% "area")) }) test_that("extract_lsm forwards arguments to calculate_lsm", { result <- extract_lsm(landscape, y = sample_points, what = "lsm_p_core", edge_depth = 100, verbose = FALSE) expect_true(all(result$value == 0)) }) test_that("extract_lsm uses extract_ids", { result <- extract_lsm(landscape, y = sample_points, extract_id = c(5, 25, 15), what = "lsm_p_area", verbose = FALSE) expect_equal(result$extract_id, expected = c(5, 15, 25)) result_wrong_id <- extract_lsm(landscape, y = sample_points, extract_id = c(1, 5, 25, 15), what = "lsm_p_area", verbose = FALSE) expect_equal(result_wrong_id$extract_id, expected = 1:3) }) test_that("extract_lsm works for all data types", { result_stack <- extract_lsm(landscape = landscape_stack, y = sample_points, what = "lsm_p_area", verbose = FALSE) result_brick <- extract_lsm(landscape = landscape_brick, y = sample_points, what = "lsm_p_area", verbose = FALSE) result_list <- extract_lsm(landscape = landscape_list, y = sample_points, what = "lsm_p_area", verbose = FALSE) expect_is(result_stack, "tbl_df") expect_is(result_brick, "tbl_df") expect_is(result_list, "tbl_df") expect_equal(object = result_stack$layer, expected = c(1, 1, 1, 2, 2, 2)) expect_equal(object = result_brick$layer, expected = c(1, 1, 1, 2, 2, 2)) expect_equal(object = result_list$layer, expected = c(1, 1, 1, 2, 2, 2)) expect_true("area" %in% result_stack$metric) expect_true("area" %in% result_brick$metric) expect_true("area" %in% result_list$metric) }) test_that("extract_lsm returns warnings", { expect_warning(extract_lsm(landscape, y = sample_points, extract_id = c(15, 25, 5, 1), what = "lsm_p_area"), regexp = "Length of extract_id is not identical to length of y. Using 1...n as extract_id.", fixed = TRUE) }) test_that("extract_lsm throws errors", { expect_error(extract_lsm(landscape, y = sample_points, what = "lsm_l_ta", verbose = FALSE), regexp = "'extract_lsm()' only takes patch level metrics.", fixed = TRUE) expect_error(extract_lsm(landscape, y = 1:3), regexp = "'y' must be a matrix, SpatialPoints, SpatialLines or sf point geometries.", fixed = TRUE) })
Counter <- function(data, num_sets, start_col, name_of_sets, nintersections, mbar_color, order_mat, aggregate, cut, empty_intersects, decrease){ temp_data <- list() Freqs <- data.frame() end_col <- as.numeric(((start_col + num_sets) -1)) for( i in 1:num_sets){ temp_data[i] <- match(name_of_sets[i], colnames(data)) } Freqs <- data.frame(count(data[ ,as.integer(temp_data)])) colnames(Freqs)[1:num_sets] <- name_of_sets if(is.null(empty_intersects) == F){ empty <- rep(list(c(0,1)), times = num_sets) empty <- data.frame(expand.grid(empty)) colnames(empty) <- name_of_sets empty$freq <- 0 all <- rbind(Freqs, empty) Freqs <- data.frame(all[!duplicated(all[1:num_sets]), ], check.names = F) } Freqs <- Freqs[!(rowSums(Freqs[ ,1:num_sets]) == 0), ] if(tolower(aggregate) == "degree"){ for(i in 1:nrow(Freqs)){ Freqs$degree[i] <- rowSums(Freqs[ i ,1:num_sets]) } order_cols <- c() for(i in 1:length(order_mat)){ order_cols[i] <- match(order_mat[i], colnames(Freqs)) } for(i in 1:length(order_cols)){ logic <- decrease[i] Freqs <- Freqs[order(Freqs[ , order_cols[i]], decreasing = logic), ] } } else if(tolower(aggregate) == "sets") { Freqs <- Get_aggregates(Freqs, num_sets, order_mat, cut) } delete_row <- (num_sets + 2) Freqs <- Freqs[ , -delete_row] for( i in 1:nrow(Freqs)){ Freqs$x[i] <- i Freqs$color <- mbar_color } if(is.na(nintersections)){ nintersections = nrow(Freqs) } Freqs <- Freqs[1:nintersections, ] Freqs <- na.omit(Freqs) return(Freqs) } Make_main_bar <- function(Main_bar_data, Q, show_num, ratios, customQ, number_angles, number.colors, ebar, ylabel, ymax, scale_intersections, text_scale, attribute_plots, plot.title){ bottom_margin <- (-1)*0.65 if(is.null(attribute_plots) == FALSE){ bottom_margin <- (-1)*0.45 } if(length(text_scale) > 1 && length(text_scale) <= 6){ y_axis_title_scale <- text_scale[1] y_axis_tick_label_scale <- text_scale[2] intersection_size_number_scale <- text_scale[6] } else{ y_axis_title_scale <- text_scale y_axis_tick_label_scale <- text_scale intersection_size_number_scale <- text_scale } if(is.null(Q) == F){ inter_data <- Q if(nrow(inter_data) != 0){ inter_data <- inter_data[order(inter_data$x), ] } else{inter_data <- NULL} } else{inter_data <- NULL} if(is.null(ebar) == F){ elem_data <- ebar if(nrow(elem_data) != 0){ elem_data <- elem_data[order(elem_data$x), ] } else{elem_data <- NULL} } else{elem_data <- NULL} if(is.null(ymax) == T){ ten_perc <- ((max(Main_bar_data$freq)) * 0.1) ymax <- max(Main_bar_data$freq) + ten_perc } if(ylabel == "Intersection Size" && scale_intersections != "identity"){ ylabel <- paste("Intersection Size", paste0("( ", scale_intersections, " )")) } if(scale_intersections == "log2"){ Main_bar_data$freq <- round(log2(Main_bar_data$freq), 2) ymax <- log2(ymax) } if(scale_intersections == "log10"){ Main_bar_data$freq <- round(log10(Main_bar_data$freq), 2) ymax <- log10(ymax) } Main_bar_plot <- (ggplot(data = Main_bar_data, aes_string(x = "x", y = "freq")) + scale_y_continuous(trans = scale_intersections) + ylim(0, ymax) + geom_bar(stat = "identity", width = 0.6, fill = Main_bar_data$color) + scale_x_continuous(limits = c(0,(nrow(Main_bar_data)+1 )), expand = c(0,0), breaks = NULL) + xlab(NULL) + ylab(ylabel) +labs(title = NULL) + theme(panel.background = element_rect(fill = "white"), plot.margin = unit(c(0.5,0.5,bottom_margin,0.5), "lines"), panel.border = element_blank(), axis.title.y = element_text(vjust = -0.8, size = 8.3*y_axis_title_scale), axis.text.y = element_text(vjust=0.3, size=7*y_axis_tick_label_scale))) if((show_num == "yes") || (show_num == "Yes")){ if(is.null(number.colors)) { Main_bar_plot <- (Main_bar_plot + geom_text(aes_string(label = "freq"), size = 2.2*intersection_size_number_scale, vjust = -1, angle = number_angles, colour = Main_bar_data$color)) } else { Main_bar_plot <- (Main_bar_plot + geom_text(aes_string(label = "freq"), size = 2.2*intersection_size_number_scale, vjust = -1, angle = number_angles, colour = number.colors)) } } bInterDat <- NULL pInterDat <- NULL bCustomDat <- NULL pCustomDat <- NULL bElemDat <- NULL pElemDat <- NULL if(is.null(elem_data) == F){ bElemDat <- elem_data[which(elem_data$act == T), ] bElemDat <- bElemDat[order(bElemDat$x), ] pElemDat <- elem_data[which(elem_data$act == F), ] } if(is.null(inter_data) == F){ bInterDat <- inter_data[which(inter_data$act == T), ] bInterDat <- bInterDat[order(bInterDat$x), ] pInterDat <- inter_data[which(inter_data$act == F), ] } if(length(customQ) != 0){ pCustomDat <- customQ[which(customQ$act == F), ] bCustomDat <- customQ[which(customQ$act == T), ] bCustomDat <- bCustomDat[order(bCustomDat$x), ] } if(length(bInterDat) != 0){ Main_bar_plot <- Main_bar_plot + geom_bar(data = bInterDat, aes_string(x="x", y = "freq"), fill = bInterDat$color, stat = "identity", position = "identity", width = 0.6) } if(length(bElemDat) != 0){ Main_bar_plot <- Main_bar_plot + geom_bar(data = bElemDat, aes_string(x="x", y = "freq"), fill = bElemDat$color, stat = "identity", position = "identity", width = 0.6) } if(length(bCustomDat) != 0){ Main_bar_plot <- (Main_bar_plot + geom_bar(data = bCustomDat, aes_string(x="x", y = "freq2"), fill = bCustomDat$color2, stat = "identity", position ="identity", width = 0.6)) } if(length(pCustomDat) != 0){ Main_bar_plot <- (Main_bar_plot + geom_point(data = pCustomDat, aes_string(x="x", y = "freq2"), colour = pCustomDat$color2, size = 2, shape = 17, position = position_jitter(width = 0.2, height = 0.2))) } if(length(pInterDat) != 0){ Main_bar_plot <- (Main_bar_plot + geom_point(data = pInterDat, aes_string(x="x", y = "freq"), position = position_jitter(width = 0.2, height = 0.2), colour = pInterDat$color, size = 2, shape = 17)) } if(length(pElemDat) != 0){ Main_bar_plot <- (Main_bar_plot + geom_point(data = pElemDat, aes_string(x="x", y = "freq"), position = position_jitter(width = 0.2, height = 0.2), colour = pElemDat$color, size = 2, shape = 17)) } Main_bar_plot <- (Main_bar_plot + geom_vline(xintercept = 0, color = "gray0") + geom_hline(yintercept = 0, color = "gray0")) if(!is.na(plot.title)) { Main_bar_plot <- c(Main_bar_plot + ggtitle(plot.title)) } Main_bar_plot <- ggplotGrob(Main_bar_plot) return(Main_bar_plot) }
acceptance.rate<-function(mcmc.chain) sum(mcmc.chain[2:length(mcmc.chain)]!=mcmc.chain[1:(length(mcmc.chain)-1)])/length(mcmc.chain)
read_ext0 <- function(ext.file) { if (!file.exists(ext.file)) { return(data.frame()) } s <- scan(ext.file, what = "character", sep = "\n", quiet = TRUE) tab.rows <- grep("TABLE", s) if (length(tab.rows) == 0) { return(data.frame()) } cut.points <- c(tab.rows, length(s) + 1) headings <- s[tab.rows] headings <- gsub("^TABLE NO.\\s+[0-9]+:\\s", "", headings) headings <- gsub(": Goal.*", "", headings) dlist <- lapply(seq_along(tab.rows), function(i) { if ((cut.points[i] + 1) > (cut.points[i + 1] - 1)) { return(data.frame()) } d <- s[(cut.points[i] + 1):(cut.points[i + 1] - 1)] tmp <- file() writeLines(d, tmp) d <- utils::read.table(tmp, header = TRUE) d$EST.NO <- i d$EST.NAME <- headings[i] match_obj <- grepl("OBJ$", names(d)) if (length(which(match_obj)) > 1) stop("more than one OBJ column. debug") names(d)[match_obj] <- "OBJ" d$OBJ <- as.numeric(as.character(d$OBJ)) d$TYPE <- NA d$TYPE[d$ITERATION >= 0] <- "ITER" d$TYPE[d$ITERATION > -1000000000 & d$ITERATION < 0] <- "BURN" d$TYPE[d$ITERATION == -1000000000] <- "FINAL" d$TYPE[d$ITERATION == -1000000001] <- "SE" d$TYPE[d$ITERATION == -1000000002] <- "EIGEN" d$TYPE[d$ITERATION == -1000000003] <- "CONDNUM" d$EVALUATION <- grepl("Evaluation", d$EST.NAME) close(tmp) d }) do.call(rbind, dlist) } read_ext <- function(r, trans = FALSE) { UseMethod("read_ext") } read_ext.default <- function(r, trans = FALSE) { base_nm_run_path <- file.path(run_dir_path(r), "NM_run1") d <- read_ext0(file.path(base_nm_run_path, "psn.ext")) if (!trans) { return(d) } p_info <- param_info(file.path(base_nm_run_path, "psn.mod")) for (i in seq_len(nrow(p_info))) { pi <- p_info[i, ] names(d)[names(d) %in% pi$parameter & !is.na(pi$name)] <- pi$name if (pi$trans %in% "LOG") { d[, pi$name][d$ITERATION > -1000000000] <- exp(d[, pi$name][d$ITERATION > -1000000000]) } else if (pi$trans %in% "LOGIT") { d[, pi$name][d$ITERATION > -1000000000] <- stats::plogis(d[, pi$name][d$ITERATION > -1000000000]) } } d } read_ext.nm_list <- function(r, trans = FALSE) { exts <- lapply(r, read_ext) names(exts) <- NULL exts }
context("test biotech cett poly others parsers") library(dbparser) library(testthat) library(XML) library(tibble) library(purrr) biotech <- "drugbank_record_biotech.xml" database_connection <- dbConnect(RSQLite::SQLite(), ":memory:") test_that( desc = "Read database", code = { expect_true(read_drugbank_xml_db( system.file("extdata", biotech, package = "dbparser") )) } ) test_that( desc = "Read drug carriers polypeptides external identifiers that", code = { expect_equal( nrow( carriers_polypep_ex_ident() ), 0 ) expect_true(is_tibble(carriers_polypep_ex_ident())) expect_error( carriers_polypep_ex_ident(TRUE) ) } ) test_that( desc = "Read drug carriers polypeptides syn that", code = { expect_equal( nrow(carriers_polypeptides_syn()), 0 ) expect_true(is_tibble(carriers_polypeptides_syn())) expect_error(carriers_polypeptides_syn(TRUE)) } ) test_that( desc = "Read drug carriers polypeptides go classifiers that", code = { expect_equal( nrow(carriers_polypeptides_go()), 0 ) expect_true(is_tibble(carriers_polypeptides_go())) expect_error(carriers_polypeptides_go(TRUE)) } ) test_that( desc = "Read drug carriers polypeptides pfams that", code = { expect_equal( nrow(carriers_polypeptides_pfams()), 0 ) expect_true(is_tibble(carriers_polypeptides_pfams())) expect_error(carriers_polypeptides_pfams(TRUE)) } ) test_that( desc = "Read drug enzymes polypeptides external identifiers attributes", code = { expect_equal( nrow(enzymes_polypep_ex_ident()), 0 ) expect_true(is_tibble(enzymes_polypep_ex_ident())) expect_error( enzymes_polypep_ex_ident(TRUE) ) } ) test_that( desc = "Read drug enzymes polypeptides syn attributes", code = { expect_equal( nrow(enzymes_polypeptides_syn()), 0 ) expect_true(is_tibble(enzymes_polypeptides_syn())) expect_error(enzymes_polypeptides_syn(TRUE)) } ) test_that( desc = "Read drug enzymes polypeptides pfams attributes", code = { expect_equal( nrow(enzymes_polypeptides_pfams()), 0 ) expect_true(is_tibble(enzymes_polypeptides_pfams())) expect_error(enzymes_polypeptides_pfams(TRUE)) } ) test_that( desc = "Read drug enzymes polypeptides go classifiers attributes", code = { expect_equal( nrow(enzymes_polypeptides_go()), 0 ) expect_true(is_tibble(enzymes_polypeptides_go())) expect_error(enzymes_polypeptides_go(TRUE)) } ) test_that( desc = "Read drug targ polypeptides external identifiers attributes", code = { expect_match( as.character( targets_polypep_ex_ident() [["identifier"]][1] ), "HGNC:3535" ) expect_true(is_tibble(targets_polypep_ex_ident())) expect_error( targets_polypep_ex_ident(TRUE) ) } ) test_that( desc = "Read drug targ polypeptides syn attributes", code = { expect_match( as.character(targets_polypeptides_syn() [["synonym"]][1]), "3.4.21.5" ) expect_true(is_tibble(targets_polypeptides_syn())) expect_error(targets_polypeptides_syn(TRUE)) } ) test_that( desc = "Read drug targ polypeptides pfams attributes", code = { expect_match( as.character(targets_polypeptides_pfams() [["name"]][1]), "Gla" ) expect_true(is_tibble(targets_polypeptides_pfams())) expect_error(targets_polypeptides_pfams(TRUE)) } ) test_that( desc = "Read drug targ polypeptides go classifiers attributes", code = { expect_match( as.character(targets_polypeptides_go() [["description"]][1]), "blood microparticle" ) expect_true(is_tibble(targets_polypeptides_go())) expect_error(targets_polypeptides_go(TRUE)) } ) test_that( desc = "Read drug transporters polypeptides external identifiers attributes", code = { expect_equal( nrow(transporters_polypep_ex_ident()), 0 ) expect_true(is_tibble(transporters_polypep_ex_ident())) expect_error( transporters_polypep_ex_ident(TRUE) ) } ) test_that( desc = "Read drug transporters polypeptides syn attributes", code = { expect_equal( nrow(transporters_polypeptides_syn()), 0 ) expect_true(is_tibble(transporters_polypeptides_syn())) expect_error(transporters_polypeptides_syn(TRUE)) } ) test_that( desc = "Read drug transporters polypeptides pfams attributes", code = { expect_equal( nrow(transporters_polypeptides_pfams()), 0 ) expect_true(is_tibble(transporters_polypeptides_pfams())) expect_error(transporters_polypeptides_pfams(TRUE)) } ) test_that( desc = "Read drug transporters polypeptides go classifiers attributes", code = { expect_equal( nrow(transporters_polypeptides_go()), 0 ) expect_true(is_tibble(transporters_polypeptides_go())) expect_error(transporters_polypeptides_go(TRUE)) } ) dbDisconnect(database_connection)
cquad_pseudo <- function(id, yv, X=NULL, be=NULL,w = rep(1,n),Ttol=10){ input_data = cbind(id,yv,X) sorted_data = input_data[order(input_data[,1],decreasing=FALSE),] id = sorted_data[,1] yv = sorted_data[,2] X = sorted_data[,-(1:2)] pid = id r = length(pid) label = unique(pid) n = length(label) if(is.null(X)) k=0 else{X = as.matrix(X); k = ncol(X)} if(k>0) Xv = X if(k>0) for(j in 1:k){ flag = TRUE for(i in 1:n){ il = label[i] if(max(X[pid==il,j])-min(X[pid==il,j])>0) flag = FALSE } if(flag) stop("at least one covariate without variability within unit") } varnames = NULL if(k>0){ if(is.null(colnames(X))) for(j in 1:k) varnames = c(varnames,paste("X",j,sep="")) else varnames = colnames(X) } varnames = c(varnames,"y_lag") Tv = rep(0,n) ind = id for(i in 1:n) Tv[i] = sum(ind==label[i]) TT0 = max(Tv) Tv = Tv-1 TT = max(Tv) balanced = all(Tv==TT) if(balanced){ largeT = (TT>Ttol) Y = t(matrix(yv,TT0,n)) if(k>0) XX = array(Xv,c(TT0,n,k)) if(!largeT){ ZZ = sq(TT); sZZ = rowSums(ZZ)} } if(k==0){ be = 0 Q = rep(0.5,length(yv)) }else{ cat("First step estimation\n") out = cquad_basic(id,yv,X,dyn=FALSE,Ttol=Ttol) be0 = be = out$coefficients; scv0 = out$scv; J0 = out$J Q = rep(0,length(yv)) for(i in 1:n){ il = label[i] y_i = yv[pid==il] if(all(y_i==0)) q_i = rep(0,length(y_i)) else if(all(y_i==1)) q_i = rep(1,length(y_i)) else{ if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) int = x_i%*%be al = 0 q_i = exp(int); q_i = q_i/(1+q_i) lk1 = as.vector(y_i%*%log(q_i)+(1-y_i)%*%log(1-q_i)); lk1o = -Inf while(abs(lk1-lk1o)>10^-10){ lk1o = lk1 dal = sum(y_i-q_i)/sum(q_i*(1-q_i)) mdal = abs(dal) if(mdal>0.5) dal = dal/mdal*0.5 al = al+dal q_i = exp(al+int); q_i = q_i/(1+q_i) lk1 = as.vector(y_i%*%log(q_i)+(1-y_i)%*%log(1-q_i)) } } Q[pid==il] = q_i } be = c(be,0) } Sc = matrix(0,n,1) it = 0; lk = -Inf; lk0 = -Inf zero1 = c(rep(0,k),1) cat("Second step estimation\n") cat(" |--------------|--------------|--------------|\n") cat(" | iteration | lk | lk-lko |\n") cat(" |--------------|--------------|--------------|\n") while(abs(lk-lk0)>10^-6 | it==0){ it = it+1; lk0 = lk scv = sco = matrix(0,n,k+1) lk = 0; J = 0 for(i in 1:n){ if(Tv[i]>1){ largeT=(Tv[i]>Ttol) il = label[i] y_i = yv[pid==il]; y_i0 = y_i[1]; y_i = y_i[-1] q_i = Q[pid==il]; q_i = q_i[-1] sui = sum(y_i) if(sui>0 & sui<Tv[i]){ if(!largeT){ if(balanced) Z = ZZ[sZZ==sui,] else Z = sq(Tv[i],sui) if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) if(k>0) x_i = rbind(cbind(x_i[-1,],0),zero1) else x_i = as.matrix(c(rep(0,Tv[i]),1)) if(Tv[i]==2) Z = cbind(Z,y_i0*(Z[,1]-q_i[1])+Z[,1]*(Z[,2]-q_i[2])) else Z = cbind(Z,y_i0*(Z[,1]-q_i[1])+ rowSums(Z[,1:Tv[i]-1]*(Z-rep(1,nrow(Z))%o%q_i)[,2:Tv[i]])) xb = x_i%*%be den = exp(Z%*%xb) sden = sum(den) y_i = c(y_i,y_i0*(y_i[1]-q_i[1])+sum(y_i[1:Tv[i]-1]*(y_i-q_i)[2:Tv[i]])) pc_i = as.vector(exp(y_i%*%xb))/sden lk = lk+w[i]*log(pc_i) Zt = t(Z) pp_i = as.vector(den/sden) e_i = Zt%*%pp_i scv[i,] = scv[i,] + w[i]*(t(y_i-e_i)%*%x_i) V_i = Zt%*%diag(pp_i)%*%Z-e_i%*%t(e_i) J = J - w[i]*(t(x_i)%*%V_i%*%x_i) } else{ if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) if(k>0) x_i = rbind(cbind(x_i[-1,],0),zero1) else x_i = as.matrix(c(rep(0,Tv[i]),1)) xb = x_i%*%be out = quasi_sym_pseudo(xb,-q_i,sui,y0=y_i0) y_i = c(y_i,y_i0*(y_i[1]-q_i[1])+sum(y_i[1:Tv[i]-1]*(y_i-q_i)[2:Tv[i]])) pc_i = as.vector(exp(y_i%*%xb))/out$f lk = lk+w[i]*log(pc_i) scv[i,] = scv[i,] + w[i]*(t(y_i-out$dl1)%*%x_i) J = J - w[i]*(t(x_i)%*%out$Dl2%*%x_i) } } } } sc = colSums(scv) iJ = solve(J) dbe = -iJ%*%sc mdbe = max(abs(dbe)) if(mdbe>0.5) dbe = dbe/mdbe*0.5 be = be+dbe cat("",sprintf("%12g", c(it,lk,lk-lk0)), "\n", sep = " | ") } cat(" |--------------|--------------|--------------|\n") be = as.vector(be) Va = iJ%*%(t(scv)%*%scv)%*%t(iJ) if(k==0){ Va2 = Va }else{ scv1 = cbind(scv0,scv) J10 = matrix(0,k+1,k) for(j in 1:k){ be1 = be0; be1[j] = be1[j]+10^-6 Q1 = rep(0,length(yv)) for(i in 1:n){ il = label[i] y_i = yv[pid==il] if(all(y_i==0)) q_i = rep(0,length(y_i)) else if(all(y_i==1)) q_i = rep(1,length(y_i)) else{ if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) int = x_i%*%be1 al = 0 q_i = exp(int); q_i = q_i/(1+q_i) lk1 = as.vector(y_i%*%log(q_i)+(1-y_i)%*%log(1-q_i)); lk1o = -Inf while(abs(lk1-lk1o)>10^-6){ lk1o = lk1 dal = sum(y_i-q_i)/sum(q_i*(1-q_i)) mdal = abs(dal) if(mdal>0.5) dal = dal/mdal*0.5 al = al+dal q_i = exp(al+int); q_i = q_i/(1+q_i) lk1 = as.vector(y_i%*%log(q_i)+(1-y_i)%*%log(1-q_i)) } } Q1[pid==il] = q_i } sc1 = rep(0,k+1) for(i in 1:n){ if(Tv[i]>1){ largeT = (Tv[i]>Ttol) il = label[i] y_i = yv[pid==il]; y_i0 = y_i[1]; y_i = y_i[-1] q_i = Q1[pid==il]; q_i = q_i[-1] sui = sum(y_i) if(sui>0 & sui<Tv[i]){ if(!largeT){ if(balanced) Z = ZZ[sZZ==sui,] else Z = sq(Tv[i],sui) if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) if(k>0) x_i = rbind(cbind(x_i[-1,],0),zero1) else x_i = as.matrix(c(rep(0,Tv[i]),1)) if(Tv[i]==2) Z = cbind(Z,y_i0*(Z[,1]-q_i[1])+Z[,1]*(Z[,2]-q_i[2])) else Z = cbind(Z,y_i0*(Z[,1]-q_i[1])+ rowSums(Z[,1:Tv[i]-1]*(Z-rep(1,nrow(Z))%o%q_i)[,2:Tv[i]])) xb = x_i%*%be den = exp(Z%*%xb) sden = sum(den) y_i = c(y_i,y_i0*(y_i[1]-q_i[1])+sum(y_i[1:Tv[i]-1]*(y_i-q_i)[2:Tv[i]])) Zt = t(Z) pp_i = as.vector(den/sden) e_i = Zt%*%pp_i sc1 = sc1+w[i]*(t(y_i-e_i)%*%x_i) } else{ if(k==0) x_i = NULL else x_i = as.matrix(Xv[pid==il,]) if(k>0) x_i = rbind(cbind(x_i[-1,],0),zero1) else x_i = as.matrix(c(rep(0,Tv[i]),1)) xb1 = x_i%*%be y_i = c(y_i,y_i0*(y_i[1]-q_i[1])+sum(y_i[1:Tv[i]-1]*(y_i-q_i)[2:Tv[i]])) out = quasi_sym_pseudo(xb1,-q_i,sui,y0=y_i0) sc1 = sc1+w[i]*(t(y_i-out$dl1)%*%x_i) } } } } J10[,j] = (sc1-sc)*10^6 } J1 = rbind(cbind(J0,matrix(0,k,k+1)), cbind(J10,J)) iJ1 = solve(J1) Va2 = iJ1%*%(t(scv1)%*%scv1)%*%(iJ1) Va2 = Va2[-(1:k),-(1:k)] } se = sqrt(diag(Va)) se2 = sqrt(diag(Va2)) lk = as.vector(lk) names(be) = varnames colnames(Va) = rownames(Va) = varnames colnames(scv) = varnames rownames(J) = colnames(J) = varnames names(se) = varnames names(se2) = varnames out = list(formula=formula,lk=lk,coefficients=be,vcov=Va,scv=scv,J=J,se=se,ser=se2,Tv=Tv,call=match.call()) class(out) = c("cquad","panelmodel") return(out) }
setMethod(f=".exportTab", signature=signature(x="AbstractMassObject"), definition=function(x, file="", row.names=FALSE, col.names=FALSE, ...) { write.table(as.matrix(x), file=file, row.names=row.names, col.names=col.names, ... ) }) setMethod(f=".exportCsv", signature=signature(x="AbstractMassObject"), definition=function(x, file="", sep=",", row.names=FALSE, col.names=TRUE, ...) { .exportTab(x, file=file, sep=sep, row.names=row.names, col.names=col.names, ...) })
"PointsUpdate" <- function(X,coeff,nbrs,index,remove,pointsin,weights,lengths){ r<-which(pointsin==remove) N<-length(pointsin); if ((r>=2)&(r<=(N-1))){ lengths[index]<-as.row(lengths[index]) weights<-as.row(weights) lengths[index]<-lengths[index]+lengths[r]*weights } else{ if(r==1){ lengths[2]<-lengths[2]+lengths[1] } if(r==N){ lengths[N-1]<-lengths[N-1]+lengths[N] } } alpha<-matrix(0,1,length(nbrs)); if (length(nbrs)>=2){ alpha<-lengths[r]*lengths[index]/(sum(lengths[index]^2)) coeff[pointsin[index]]<-coeff[pointsin[index]]+alpha*coeff[remove] } else{ q<-which(pointsin==nbrs) alpha<-lengths[r]/lengths[q] coeff[pointsin[q]]<-coeff[pointsin[q]]+alpha*coeff[remove] } return(list(coeff=coeff,lengths=lengths,r=r,N=N,weights=weights,alpha=alpha)) }
library("igraph") library("viridisLite") library("highcharter") library("purrr") library("purrr") library("dplyr") ds <- map(seq(5), function(x){ list(data = cummean(rnorm(100, 2, 5)), name = x) }) highchart() %>% hc_plotOptions(series = list(marker = list(enabled = FALSE))) %>% hc_add_series_list(ds) n <- 3 set.seed(100) data <- map(seq(n), function(x){ xc <- round(rnorm(1, sd = 2), 2) yc <- round(rnorm(1, sd = 2), 2) dt <- cbind(rnorm(200, xc), rnorm(200, yc)) dt <- tbl_df(dt) setNames(dt, c("x", "y")) dt }) ds1 <- map(seq(n), function(x){ dt <- data[[x]] dt <- convex_hull(as.matrix(dt)) dt <- list_parse2(as.data.frame(dt$rescoords)) list(data = dt, name = sprintf("polygon %s", x), type = "polygon", id = paste0("s", x)) }) ds2 <- map(seq(n), function(x){ dt <- data[[x]] dt <- list_parse2(as.data.frame(dt)) list(data = dt, name = sprintf("points %s", x), type = "scatter", linkedTo = paste0("s", x)) }) cols <- hex_to_rgba(substr(viridis(n), 0, 7), alpha = 0.5) highchart() %>% hc_colors(colors = cols) %>% hc_add_series_list(ds1) %>% hc_add_series_list(ds2) data("economics_long", package = "ggplot2") head(economics_long) ds <- economics_long %>% group_by(variable) %>% do(ds = list( data = list_parse2(data.frame(datetime_to_timestamp(.$date), .$value01)) )) %>% {map2(.$variable, .$ds, function(x, y){ append(list(name = x), y) })} highchart() %>% hc_xAxis(type = "datetime") %>% hc_add_series_list(ds)
get_gamma_bounds <- function(y, tau) { check_tau(tau) zz <- normalize_by_tau(y, tau) if (min(zz) >= 0) { bounds <- c("lower" = 0, "upper" = Inf) } else { bounds <- c("lower" = -1/exp(1)/max(zz), "upper" = -1/exp(1)/min(zz)) } return(bounds) }
"TML.logWeibull" <- function(X,y,cu=1.855356,initial=c("S","input"),otp=c("adaptive","fixed"), cov=c("no","parametric","nonparametric"),input=NULL,iv=1,nrep=0, seed=1313,maxit=100,tol=0.0001,gam=0.2,nitmon=FALSE,fastS=TRUE,...){ X <- as.matrix(X) n <- length(y); np <- ncol(X); cl <- Izero(cu) ips <- 2; xk <- 1.717817; beta <- 0.5 namat <- matrix(NA,nrow=np,ncol=np) nares <- list(th0=NA,v0=NA,th1=rep(NA,np),v1=NA,tl=NA,tu=NA,CV0=namat,V0=NA,CV1=namat,V1=NA, alpha=NA,tn=NA,beta=NA,wi=rep(NA,n)) if (all(X[1,]!=1)) {cat("First column of the X matrix must be ones!\n"); return(nares)} if (initial=="S") if (fastS) { set.seed(seed) zctrl <- lmrob.control(...) z <- lmrob.S(X,y,zctrl); th0 <- z$coef; v0 <- z$scale} else { if (np <= 2 & n <= 500) iopt <- 3 else iopt <- 1; if (nrep!=0) iopt <- 2 z <- hysestz(X,y,nq=np+1,iopt=iopt,intch=1,nrep=nrep,tols=tol,tolr=tol, iseed=seed,ipsi=4,xk=xk,beta=beta) th0 <- z$theta[1:np]; v0 <- z$smin b0 <- -0.1352; th0[1] <- th0[1]-b0*v0} if (initial=="input") {z <- input; v0 <- z$v; th0 <- z$tau} nares <- list(th0=th0,v0=v0,th1=rep(NA,np),v1=NA,tl=NA,tu=NA,CV0=namat,V0=NA,CV1=namat,V1=NA, alpha=NA,tn=NA,beta=NA,wi=rep(NA,n)) re <- y-as.vector(X%*%as.matrix(th0)); rs <- re/v0 tp <- adaptw(sort(rs),cl,cu,otp); if (is.na(tp$tu)) return(nares) wi <- tPsiw(rs,tp$tl,tp$tu) yr <- y[wi!=0 | rs==0] Xr <- X[wi!=0 | rs==0,,drop=FALSE] tp$tn <- length(yr) z <- MLwp(Xr,yr,th0,v0,iv,n,tp,gamm=gam,maxit,tol,nitmon) res <- list(th0=th0,v0=v0,th1=z$th1,v1=z$v1,nit=z$nit,tl=tp$tl,tu=tp$tu, alpha=tp$alpha,tn=tp$tn,beta=tp$beta,wi=(wi!=0)*1) if (cov!="no") {l <- cl; u <- cu; if (otp=="adaptive") {l <- tp$tl; u <- tp$tu} if (cov=="nonparametric") K <- Cov2.w(X,y,l,u,z$th1,z$v1,opt="averages") if (cov=="parametric" ) K <- CovE.w(X,y,l,u,z$th1,z$v1) res <- c(res,list(CV0=K$CV0,CV1=K$CV1))} res}
Res_soil <- function(x, r_soil_inleaf = 2941, r_soil_outleaf = 2941){ db <- x LAI_Total <- db$BAI + db$LAI if((max(LAI_Total, na.rm=T) == min(LAI_Total, na.rm=T)) & (r_soil_inleaf == r_soil_outleaf)){ r_soil0 <- rep(r_soil_inleaf, nrow(db)) r_soil <- cbind.data.frame(Dates = db$Dates, Resist_soil = r_soil0) }else{ fit_r_soil <- lm(c(r_soil_inleaf,r_soil_outleaf)~c(max(LAI_Total, na.rm=T),min(LAI_Total, na.rm=T))) r_soil0 <- fit_r_soil$coefficients[1]+fit_r_soil$coefficients[2]*LAI_Total r_soil <- cbind.data.frame(Dates = db$Dates, Resist_soil = r_soil0) } return(r_soil) }
test.welch <- function(formula, data, alternative = c("two.sided", "less", "greater"), conf.level = 0.95, hypo = TRUE, descript = TRUE, effsize = FALSE, weighted = FALSE, ref = NULL, correct = FALSE, digits = 2, p.digits = 4, as.na = NULL, check = TRUE, output = TRUE, ...) { if (isTRUE(missing(formula))) { stop("Please specify a formula using the argument 'formula'", call. = FALSE) } if (isTRUE(missing(data))) { stop("Please specify a matrix or data frame for the argument 'x'.", call. = FALSE) } if (isTRUE(is.null(data))) { stop("Input specified for the argument 'data' is NULL.", call. = FALSE) } var.formula <- all.vars(as.formula(formula)) group.var <- attr(terms(formula[-2L]), "term.labels") y.var <- var.formula[-grep(group.var, var.formula)] if (isTRUE(!is.logical(check))) { stop("Please specify TRUE or FALSE for the argument 'check'.", call. = FALSE) } if (isTRUE(check)) { var.data <- !var.formula %in% colnames(data) if (isTRUE(any(var.data))) { stop(paste0("Variables specified in the the formula were not found in 'data': ", paste(var.formula[which(var.data)], collapse = ", ")), call. = FALSE) } if (isTRUE(length(group.var) != 1L)) { stop("Please specify a formula with only one grouping variable.", call. = FALSE) } if (isTRUE(length(y.var) != 1L)) { stop("Please specify a formula with only one outcome variable.", call. = FALSE) } if (isTRUE(!is.logical(descript))) { stop("Please specify TRUE or FALSE for the argument 'descript'.", call. = FALSE) } if (isTRUE(!all(alternative %in% c("two.sided", "less", "greater")))) { stop("Character string in the argument 'alternative' does not match with \"two.sided\", \"less\", or \"greater\".", call. = FALSE) } if (isTRUE(!is.logical(effsize))) { stop("Please specify TRUE or FALSE for the argument 'effsize'.", call. = FALSE) } if (isTRUE(!is.logical(weighted))) { stop("Please specify TRUE or FALSE for the argument 'weighted'.", call. = FALSE) } if (isTRUE(!is.logical(correct))) { stop("Please specify TRUE or FALSE for the argument 'correct'.", call. = FALSE) } if (isTRUE(conf.level >= 1L || conf.level <= 0L)) { stop("Please specifiy a numeric value between 0 and 1 for the argument 'conf.level'.", call. = FALSE) } if (isTRUE(!is.logical(hypo))) { stop("Please specify TRUE or FALSE for the argument 'hypo'.", call. = FALSE) } if (isTRUE(!is.logical(descript))) { stop("Please specify TRUE or FALSE for the argument 'descript'.", call. = FALSE) } if (isTRUE(digits %% 1L != 0L || digits < 0L)) { stop("Please specify a positive integer number for the argument 'digits'.", call. = FALSE) } if (isTRUE(p.digits %% 1L != 0L || p.digits < 0L)) { stop("Please specify a positive integer number for the argument 'p.digits'.", call. = FALSE) } if (isTRUE(!is.logical(output))) { stop("Please specify TRUE or FALSE for the argument 'output'.", call. = FALSE) } } if (isTRUE(!is.null(as.na))) { data[, y.var] <- misty::as.na(data[, y.var], na = as.na, check = check) data.miss <- vapply(data[, y.var, drop = FALSE], function(y) all(is.na(y)), FUN.VALUE = logical(1)) if (any(data.miss)) { stop(paste0("After converting user-missing values into NA, following variables are completely missing: ", paste(names(which(data.miss)), collapse = ", ")), call. = FALSE) } } y <- unlist(data[, y.var]) group <- unlist(data[, group.var]) if (isTRUE(all(c("two.sided", "less", "greater") %in% alternative))) { alternative <- "two.sided" } if (isTRUE(length(unique(group)) == 2)) { ci <- misty::ci.mean.diff(formula = formula, data = data, paired = FALSE, alternative = alternative, conf.level = conf.level, check = FALSE, output = FALSE)$result d <- misty::cohens.d(formula = formula, data = data, paired = FALSE, mu = 0, weighted = weighted, cor = TRUE, ref = ref, correct = correct, alternative = alternative, conf.level = conf.level, group = NULL, split = NULL, sort.var = FALSE, check = FALSE, output = FALSE)$result welch <- t.test(formula = formula, data = data, alternative = switch(alternative, two.sided = "two.sided", greater = "less", less = "greater"), paired = FALSE, var.equal = FALSE) result <- data.frame(cbind(ci[, -which(colnames(ci) %in% c("variable", "between", "low", "upp"))], se = c(NA, welch$stderr), t = c(NA, welch$statistic)*-1, df = c(NA, welch$parameter), pval = c(NA, welch$p.value), d = d$d, low = d$low, upp = d$upp), row.names = NULL) sample <- "two" } else { ci <- misty::ci.mean(y, group = group, output = FALSE)$result[, -c(2, 5)] aov.table <- summary(aov(y ~ factor(group)))[[1]] ss.m <- aov.table[["Sum Sq"]][1] df.m <- aov.table[["Df"]][1] ms.r <- aov.table[["Mean Sq"]][2] ss.t <- sum(aov.table[["Sum Sq"]]) eta.sq <- ss.m / ss.t omega.sq<- (ss.m - df.m*ms.r) / (ss.t + ms.r) omega.sq <- ifelse(omega.sq < 0, 0, omega.sq) welch <- oneway.test(formula = formula, data = data, var.equal = FALSE) result <- list(descript = ci, test = data.frame(F = welch$statistic, df1 = welch$parameter["num df"], df2 = welch$parameter["denom df"], pval = welch$p.value, eta.sq = eta.sq, omega.sq = omega.sq, row.names = NULL)) sample <- "multiple" } object <- list(call = match.call(), type = "test.welch", sample = sample, data = data.frame(y, group, stringsAsFactors = FALSE), args = list(formula = formula, alternative = alternative, conf.level = conf.level, hypo = hypo, descript = descript, digits = digits, effsize = effsize, weighted = weighted, ref = ref, correct = correct, p.digits = p.digits, as.na = as.na, check = check, output = output), result = result) class(object) <- "misty.object" if (isTRUE(output)) { print(object, check = FALSE) } return(invisible(object)) }
ql <- function(query, ...) { jsonlite::fromJSON(cont( gh_POST(gsub("\n", "", query), ...) )) }
print.survfit <- function(x, scale=1, digits = max(options()$digits - 4, 3), print.rmean = getOption('survfit.print.rmean'), rmean = getOption('survfit.rmean'), ...) { if (!is.null(cl<- x$call)) { cat("Call: ") dput(cl) cat("\n") } omit <- x$na.action if (length(omit)) cat(" ", naprint(omit), "\n") savedig <- options(digits=digits) on.exit(options(savedig)) if (!missing(print.rmean) && is.logical(print.rmean) && missing(rmean)) { if (print.rmean) rmean <- 'common' else rmean <- 'none' } else { if (is.null(rmean)) { if (is.logical(print.rmean)) { if (print.rmean) rmean <- 'common' else rmean <- 'none' } else rmean <- 'none' } if (is.numeric(rmean)) { if (is.null(x$start.time)) { if (rmean < min(x$time)) stop("Truncation point for the mean is < smallest survival") } else if (rmean < x$start.time) stop("Truncation point for the mean is < smallest survival") } else { rmean <- match.arg(rmean, c('none', 'common', 'individual')) if (length(rmean)==0) stop("Invalid value for rmean option") } } temp <- survmean(x, scale=scale, rmean) mtemp <- if (is.matrix(temp$matrix)) temp$matrix else matrix(temp$matrix, nrow=1, dimnames=list(NULL, names(temp$matrix))) if (all(mtemp[,2] == mtemp[,3])){ cname <- dimnames(mtemp)[[2]] mtemp <- mtemp[,-2, drop=FALSE] cname <-cname[-2] cname[2] <- "n" dimnames(mtemp)[[2]] <- cname } if (all(mtemp[,1] == mtemp[,2])) mtemp <- mtemp[,-1, drop=FALSE] if (rmean != 'none') { dd <- dimnames(mtemp) dd[[2]] <- ifelse(dd[[2]]=="rmean", "rmean*", dd[[2]]) dimnames(mtemp) <- dd print(mtemp) if (rmean == 'individual') cat(" * restricted mean with variable upper limit\n") else cat(" * restricted mean with upper limit = ", format(temp$end.time[1]), "\n") } else print(mtemp) invisible(x) } survmean <- function(x, scale=1, rmean) { if (!is.null(x$start.time)) start.time <- x$start.time else start.time <- min(0, x$time) pfun <- function(nused, time, surv, n.risk, n.event, lower, upper, start.time, end.time) { minmin <- function(y, x) { tolerance <- .Machine$double.eps^.5 keep <- (!is.na(y) & y <(.5 + tolerance)) if (!any(keep)) NA else { x <- x[keep] y <- y[keep] if (abs(y[1]-.5) <tolerance && any(y< y[1])) (x[1] + x[min(which(y<y[1]))])/2 else x[1] } } if (!is.na(end.time)) { hh <- ifelse((n.risk-n.event)==0, 0, n.event /(n.risk *(n.risk -n.event))) keep <- which(time <= end.time) if (length(keep) ==0) { temptime <- end.time tempsurv <- 1 hh <- 0 } else { temptime <- c(time[keep], end.time) tempsurv <- c(surv[keep], surv[max(keep)]) hh <- c(hh[keep], 0) } n <- length(temptime) delta <- diff(c(start.time, temptime)) rectangles <- delta * c(1, tempsurv[-n]) varmean <- sum( cumsum(rev(rectangles[-1]))^2 * rev(hh)[-1]) mean <- sum(rectangles) + start.time } else { mean <- 0 varmean <- 0 } med <- minmin(surv, time) if (!is.null(upper)) { upper <- minmin(upper, time) lower <- minmin(lower, time) c(nused, max(n.risk), n.risk[1], sum(n.event), sum(mean), sqrt(varmean), med, lower, upper) } else c(nused, max(n.risk), n.risk[1], sum(n.event), sum(mean), sqrt(varmean), med, 0, 0) } stime <- x$time/scale if (is.numeric(rmean)) rmean <- rmean/scale surv <- x$surv plab <- c("records", "n.max", "n.start", "events", "rmean", "se(rmean)", "median", paste(x$conf.int, c("LCL", "UCL"), sep='')) ncols <- 9 if (is.matrix(surv) && !is.matrix(x$n.event)) x$n.event <- matrix(rep(x$n.event, ncol(surv)), ncol=ncol(surv)) if (is.null(x$strata)) { if (rmean=='none') end.time <- NA else if (is.numeric(rmean)) end.time <- rmean else end.time <- max(stime) if (is.matrix(surv)) { out <- matrix(0, ncol(surv), ncols) for (i in 1:ncol(surv)) { if (is.null(x$conf.int)) out[i,] <- pfun(x$n, stime, surv[,i], x$n.risk, x$n.event[,i], NULL, NULL, start.time, end.time) else out[i,] <- pfun(x$n, stime, surv[,i], x$n.risk, x$n.event[,i], x$lower[,i], x$upper[,i], start.time, end.time) } dimnames(out) <- list(dimnames(surv)[[2]], plab) } else { out <- matrix(pfun(x$n, stime, surv, x$n.risk, x$n.event, x$lower, x$upper, start.time, end.time), nrow=1) dimnames(out) <- list(NULL, plab) } } else { nstrat <- length(x$strata) stemp <- rep(1:nstrat,x$strata) last.time <- (rev(stime))[match(1:nstrat, rev(stemp))] if (rmean=='none') end.time <- rep(NA, nstrat) else if (is.numeric(rmean)) end.time <- rep(rmean, nstrat) else if (rmean== 'common') end.time <- rep(max(last.time), nstrat) else end.time <- last.time if (is.matrix(surv)) { ns <- ncol(surv) out <- matrix(0, nstrat*ns, ncols) if (is.null(dimnames(surv)[[2]])) dimnames(out) <- list(rep(names(x$strata), ns), plab) else { cname <- outer(names(x$strata), dimnames(surv)[[2]], paste, sep=", ") dimnames(out) <- list(c(cname), plab) } k <- 0 for (j in 1:ns) { for (i in 1:nstrat) { who <- (stemp==i) k <- k+1 if (is.null(x$lower)) out[k,] <- pfun(x$n[i], stime[who], surv[who,j], x$n.risk[who], x$n.event[who,j], NULL, NULL, start.time, end.time[i]) else out[k,] <- pfun(x$n[i], stime[who], surv[who,j], x$n.risk[who], x$n.event[who,j], x$lower[who,j], x$upper[who,j], start.time, end.time[i]) } } } else { out <- matrix(0, nstrat, ncols) dimnames(out) <- list(names(x$strata), plab) for (i in 1:nstrat) { who <- (stemp==i) if (is.null(x$lower)) out[i,] <- pfun(x$n[i], stime[who], surv[who], x$n.risk[who], x$n.event[who], NULL, NULL, start.time, end.time[i]) else out[i,] <- pfun(x$n[i], stime[who], surv[who], x$n.risk[who], x$n.event[who], x$lower[who], x$upper[who], start.time, end.time[i]) } } } if (is.null(x$lower)) out <- out[,1:7, drop=F] if (rmean=='none') out <- out[,-(5:6), drop=F] list(matrix=out[,,drop=T], end.time=end.time) }
PREPS$rcmdcheck <- function(state, path = state$path, quiet) { path <- normalizePath(path) state$rcmdcheck <- try(rcmdcheck(path, quiet = quiet), silent = quiet) if(inherits(state$rcmdcheck, "try-error")) { warning("Prep step for rcmdcheck failed.") } state }
.CIRCOS.ENV = new.env() resetGlobalVariable = function() { assign(".SECTOR.DATA", NULL, envir = .CIRCOS.ENV) assign(".CELL.DATA", NULL, envir = .CIRCOS.ENV) assign(".CURRENT.TRACK.INDEX", 0, envir = .CIRCOS.ENV) assign(".CURRENT.SECTOR.INDEX", NULL, envir = .CIRCOS.ENV) } resetGlobalVariable() circos.par = function(..., RESET = FALSE, READ.ONLY = NULL, LOCAL = FALSE, ADD = FALSE) {} circos.par = setGlobalOptions( start.degree = list( .value = 0, .length = 1, .class = "numeric", .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'start.degree' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) }), gap.degree = list( .value = 1, .class = "numeric", .validate = function(x) { all(x >= 0 & x < 360) }, .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'gap.degree' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) } ), gap.after = list(.synonymous = "gap.degree"), track.margin = list( .value = c(0.01, 0.01), .length = 2, .class = "numeric" ), unit.circle.segments = 500, cell.padding = list( .value = c(0.02, 1, 0.02, 1), .length = c(2, 4), .class = "numeric", .filter = function(x) { if(length(x) == 2) x = c(x, x) o.cell.padding = circos.par("cell.padding") if(is.circos.initialized()){ return(c(x[1], o.cell.padding[2], x[3], o.cell.padding[4])) } else { return(x) } }), default.track.height = list( .value = 0.2, .visible = FALSE, .filter = function(x) { warning_wrap("`default.track.height` is replaced by `track.height`, ignore this setting.") return(x) }), track.height = 0.2, points.overflow.warning = TRUE, circle.margin = list( .value = c(0, 0, 0, 0), .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'circle.margin' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } if(any(x <= 0)) { stop_wrap("The value of `circle.margin` should be positive.") } if(length(x) == 1) { x = rep(x, 4) } else if(length(x) == 2) { x = rep(x, each = 2) } else if(length(x) == 4) { } else { stop_wrap("Length of `circle.margin` can only be 1, 2, or 4.") } return(x) } ), canvas.xlim = list( .value = function() { c(-(1 + .v$circle.margin[1]), (1 + .v$circle.margin[2])) }, .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'canvas.xlim' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) }), canvas.ylim = list( .value = function() { c(-(1 + .v$circle.margin[3]), (1 + .v$circle.margin[4])) }, .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'canvas.ylim' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) }), major.by.degree = 10, clock.wise = list( .value = TRUE, .filter = function(x) { if(is.circos.initialized()){ warning_wrap("'clock.wise' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) }), xaxis.clock.wise = list( .value = TRUE, .filter = function(x) { if(is.circos.initialized()){ stop_wrap("'xaxis.clock.wise' can only be modified before `circos.initialize`, or maybe you forgot to call `circos.clear` in your last plot.") } return(x) }), lend = list( .value = NULL, .visible = FALSE, .private = TRUE), ljoin = list( .value = NULL, .visible = FALSE, .private = TRUE), '__tempdir__' = list( .value = ".", .private = TRUE, .filter = function(x) {dir.create(x, showWarnings = FALSE); return(x)}, .visible = FALSE), '__omar__' = list( .value = FALSE, .private = TRUE, .visible = FALSE), '__tempenv__' = list( .value = new.env(parent = emptyenv()), .private = TRUE, .visible = FALSE), message = TRUE, help = list(.synonymous = "message"), ring = list( .value = FALSE, .private = TRUE, .visible = FALSE ) ) is.circos.initialized = function() { .SECTOR.DATA = get(".SECTOR.DATA", envir = .CIRCOS.ENV) return(! is.null(.SECTOR.DATA)) } circos.initialize = function( sectors = NULL, x = NULL, xlim = NULL, sector.width = NULL, factors = sectors, ring = FALSE) { resetGlobalVariable() .SECTOR.DATA = get(".SECTOR.DATA", envir = .CIRCOS.ENV) .CELL.DATA = get(".CELL.DATA", envir = .CIRCOS.ENV) if(is.null(factors)) { if(is.matrix(xlim) || is.data.frame(xlim)) { if(is.null(rownames(xlim))) { stop_wrap("Since `sectors` is not specified, row names of `xlim` are taken as `sectors`, thus `xlim` should be a two-column matrix with row names.") } else { factors = rownames(xlim) } } else { stop_wrap("Since `sectors` is not specified, row names of `xlim` are taken as `sectors`, thus `xlim` should be a two-column matrix with row names.") } } if(is.numeric(factor)) { warning_wrap("Your `sectors` is numeric, it will be converted to characters internally.") } if(any(factors == "")) { stop_wrap("`sectors` cannot contain empty strings.") } if(! is.factor(factors)) { if(length(factors) == length(unique(factors))) { factors = factor(factors, levels = factors) } else { factors = factor(factors) } } factors = factor(as.character(factors), intersect(levels(factors), as.character(factors))) le = levels(factors) if(ring) { if(length(le) != 1) { stop_wrap("There should be only one sector under 'ring' mode.") } circos.par$ring = TRUE circos.par$gap.degree = 0 circos.par$cell.padding = c(circos.par$cell.padding[1], 0, circos.par$cell.padding[3], 0) circos.par$points.overflow.warning = FALSE } else { circos.par$ring = FALSE } if(!is.null(x)) { x = as.numeric(x) } if(is.vector(xlim)) { if(length(xlim) != 2) { stop_wrap("Since `xlim` is vector, it should have length of 2.") } xlim = as.numeric(xlim) min.value = rep(xlim[1], length(le)) max.value = rep(xlim[2], length(le)) } else if(is.matrix(xlim) || is.data.frame(xlim)) { if(dim(xlim)[1] != length(le) || dim(xlim)[2] != 2) { stop_wrap("Since `xlim` is a matrix, it should have same number of rows as the length of the level of `sectors` and number of columns of 2.") } if(!is.null(rownames(xlim))) { if(length(setdiff(le, rownames(xlim))) == 0) { xlim = xlim[le, ,drop = FALSE] } } if(is.data.frame(xlim)) xlim = as.matrix(xlim) xlim2 = as.numeric(xlim) dim(xlim2) = dim(xlim) dimnames(xlim2) = dimnames(xlim) xlim = xlim2 min.value = apply(xlim, 1, function(x) x[1]) max.value = apply(xlim, 1, function(x) x[2]) } else if(is.vector(x)) { if(length(x) != length(factors)) { stop_wrap("Length of `x` and length of `sectors` differ.") } min.value = tapply(x, factors, min) max.value = tapply(x, factors, max) } else { stop_wrap("You should specify either `x` or `xlim`.") } cell.padding = circos.par("cell.padding") sector.range = max.value - min.value n.sector = length(le) sector = vector("list", 7) names(sector) = c("factor", "min.value", "max.value", "start.degree", "end.degree", "min.data", "max.data") sector[["factor"]] = le sector[["min.data"]] = min.value sector[["max.data"]] = max.value gap.degree = circos.par("gap.degree") if(!is.null(names(gap.degree))) { if(length(setdiff(le, names(gap.degree))) == 0) { gap.degree = gap.degree[le] } } if(length(gap.degree) == 1) { gap.degree = rep(gap.degree, n.sector) } else if(length(gap.degree) != n.sector) { stop_wrap("Since `gap.degree` parameter has length larger than 1, it should have same length as the number of sectors.") } start.degree = circos.par("start.degree") clock.wise = circos.par("clock.wise") if(360 - sum(gap.degree) <= 0) { stop_wrap("Maybe your `gap.degree` is too large so that there is no space to allocate sectors.") } if(is.null(sector.width)) { unit = (360 - sum(gap.degree)) / sum(sector.range) for(i in seq_len(n.sector)) { if(sector.range[i] == 0) { stop_wrap("Range of the sector ('", le[i] ,"') cannot be 0. You might need to set the second and the fourth values in `circos.par$cell.padding` to 0.") } if(clock.wise) { sector[["start.degree"]][i] = ifelse(i == 1, start.degree, sector[["end.degree"]][i-1] - gap.degree[i-1]) sector[["end.degree"]][i] = sector[["start.degree"]][i] - sector.range[i]*unit } else { sector[["end.degree"]][i] = ifelse(i == 1, start.degree, sector[["start.degree"]][i-1] + gap.degree[i-1]) sector[["start.degree"]][i] = sector[["end.degree"]][i] + sector.range[i]*unit } } } else { if(length(sector.width) == 1) { sector.width = rep(sector.width, n.sector) } else if(length(sector.width) != n.sector) { stop_wrap("Since you manually set the width for each sector, the length of `sector.width` should be either 1 or as same as the number of sectors.") } sector.width.percentage = sector.width / sum(sector.width) degree.per.sector = (360 - sum(gap.degree)) * sector.width.percentage if(any(degree.per.sector <= 0)) { stop_wrap("Maybe your `gap.degree` is too large so that there is no space to allocate sectors.") } for(i in seq_len(n.sector)) { if(sector.range[i] == 0) { stop_wrap("Range of the sector (", le[i] ,") cannot be 0.") } if(clock.wise) { sector[["start.degree"]][i] = ifelse(i == 1, start.degree, sector[["end.degree"]][i-1] - gap.degree[i-1]) sector[["end.degree"]][i] = sector[["start.degree"]][i] - degree.per.sector[i] } else { sector[["end.degree"]][i] = ifelse(i == 1, start.degree, sector[["start.degree"]][i-1] + gap.degree[i-1]) sector[["start.degree"]][i] = sector[["end.degree"]][i] + degree.per.sector[i] } } } if(clock.wise) { sector[["start.degree"]] = sector[["start.degree"]] + 360 sector[["end.degree"]] = sector[["end.degree"]] + 360 } if(any(cell.padding[2] + cell.padding[4] >= sector[["start.degree"]] - sector[["end.degree"]])) { stop_wrap("Summation of cell padding on x-direction are larger than the width for some sectors. You can e.g. set 'circos.par(cell.padding = c(0.02, 0, 0.02, 0))' or remove tiny sectors.") } min.value = min.value - cell.padding[2]/(sector[["start.degree"]] - sector[["end.degree"]] - cell.padding[2] - cell.padding[4])*sector.range max.value = max.value + cell.padding[4]/(sector[["start.degree"]] - sector[["end.degree"]] - cell.padding[2] - cell.padding[4])*sector.range sector[["min.value"]] = min.value sector[["max.value"]] = max.value sector = as.data.frame(sector, stringsAsFactors = FALSE) .SECTOR.DATA = sector .CELL.DATA = vector("list", length = length(le)) names(.CELL.DATA) = le for(i in seq_along(.CELL.DATA)) { .CELL.DATA[[ le[i] ]] = vector("list", length = 0) } assign(".SECTOR.DATA", .SECTOR.DATA, envir = .CIRCOS.ENV) assign(".CELL.DATA", .CELL.DATA, envir = .CIRCOS.ENV) assign(".CURRENT.SECTOR.INDEX", .SECTOR.DATA[1, "factor"], envir = .CIRCOS.ENV) circos.par("__omar__" = FALSE) if(identical(par("mar"), c(5.1, 4.1, 4.1, 2.1))) { circos.par("__omar__" = TRUE) par(mar = c(1, 1, 1, 1)) } plot(circos.par("canvas.xlim"), circos.par("canvas.ylim"), type = "n", ann = FALSE, axes = FALSE, asp = 1) return(invisible(NULL)) } circos.clear = function() { resetGlobalVariable() if(circos.par("__omar__")) { circos.par("__omar__" = FALSE) par(mar = c(5.1, 4.1, 4.1, 2.1)) } tmpdir = circos.par("__tempdir__") circos.par(RESET = TRUE) circos.par("__tempdir__" = tmpdir) empty_env(circos.par("__tempenv__")) return(invisible(NULL)) } empty_env = function(env) { obj = ls(envir = env, all.names = TRUE) if(length(obj)) rm(list = obj, envir = env) } get.all.sector.index = function() { .SECTOR.DATA = get(".SECTOR.DATA", envir = .CIRCOS.ENV) if(is.null(.SECTOR.DATA)) { return(character(0)) } else { return(as.vector(.SECTOR.DATA$factor)) } } get.all.track.index = function() { .CELL.DATA = get(".CELL.DATA", envir = .CIRCOS.ENV) if(is.null(.CELL.DATA)) { return(integer(0)) } else if(all(sapply(.CELL.DATA, length) == 0)) { return(integer(0)) } else { return(seq_len(max(sapply(.CELL.DATA[ which(sapply(.CELL.DATA, length) > 0) ], function(x) length(x))))) } } get.sector.data = function(sector.index = get.current.sector.index()) { sector.index = as.character(sector.index) .SECTOR.DATA = get(".SECTOR.DATA", envir = .CIRCOS.ENV) sector.data = as.vector(as.matrix(.SECTOR.DATA[.SECTOR.DATA[[1]] == sector.index, -1])) names(sector.data) = colnames(.SECTOR.DATA)[-1] return(sector.data) } get.current.track.index = function() { .CURRENT.TRACK.INDEX = get(".CURRENT.TRACK.INDEX", envir = .CIRCOS.ENV) return(.CURRENT.TRACK.INDEX) } set.current.track.index = function(x) { .CURRENT.TRACK.INDEX = x assign(".CURRENT.TRACK.INDEX", .CURRENT.TRACK.INDEX, envir = .CIRCOS.ENV) return(invisible(NULL)) } get.current.sector.index = function() { .CURRENT.SECTOR.INDEX = get(".CURRENT.SECTOR.INDEX", envir = .CIRCOS.ENV) return(.CURRENT.SECTOR.INDEX) } set.current.sector.index = function(x) { .CURRENT.SECTOR.INDEX = get(".CURRENT.SECTOR.INDEX", envir = .CIRCOS.ENV) if(!x %in% get.all.sector.index()) { stop_wrap(paste0("Cannot find ", x, " in all available sector names.\n")) } .CURRENT.SECTOR.INDEX = x assign(".CURRENT.SECTOR.INDEX", .CURRENT.SECTOR.INDEX, envir = .CIRCOS.ENV) return(invisible(NULL)) } set.current.cell = function(sector.index, track.index) { sector.index = as.character(sector.index) set.current.sector.index(sector.index) set.current.track.index(track.index) } get.cell.data = function(sector.index = get.current.sector.index(), track.index = get.current.track.index()) { sector.index = as.character(sector.index) .CELL.DATA = get(".CELL.DATA", envir = .CIRCOS.ENV) .CELL.DATA[[sector.index]][[track.index]] } set.cell.data = function(sector.index = get.current.sector.index(), track.index = get.current.track.index(), ...) { sector.index = as.character(sector.index) .CELL.DATA = get(".CELL.DATA", envir = .CIRCOS.ENV) .CELL.DATA[[sector.index]][[track.index]] = list(...) assign(".CELL.DATA", .CELL.DATA, envir = .CIRCOS.ENV) return(invisible(NULL)) } has.cell = function(sector.index, track.index) { sector.index = as.character(sector.index) .CELL.DATA = get(".CELL.DATA", envir = .CIRCOS.ENV) if(sector.index %in% names(.CELL.DATA) && track.index <= length(.CELL.DATA[[sector.index]]) && !is.null(.CELL.DATA[[sector.index]][[track.index]])) { return(TRUE) } else { return(FALSE) } } circos.info = function(sector.index = NULL, track.index = NULL, plot = FALSE) { sectors = get.all.sector.index() tracks = get.all.track.index() if(plot) { for(i in seq_along(sectors)) { for(j in seq_along(tracks)) { cell.xlim = get.cell.meta.data("cell.xlim", sector.index = sectors[i], track.index = j) cell.ylim = get.cell.meta.data("cell.ylim", sector.index = sectors[i], track.index = j) circos.text(mean(cell.xlim), mean(cell.ylim), labels = paste(sectors[i], j, sep = ":"), sector.index = sectors[i], track.index = j, facing = "downward") } } } else { if(is.null(sector.index) && is.null(track.index)) { if(length(sectors)) { cat("All your sectors:\n") print(sectors) } else { cat("No sector has been created\n") } cat("\n") if(length(tracks)) { cat("All your tracks:\n") print(tracks) } else { cat("No track has been created\n") } cat("\n") } else { if(is.null(track.index)) { track.index = tracks } else if(is.null(sector.index)) { sector.index = sectors } for(i in seq_along(sector.index)) { for(j in seq_along(track.index)) { cat("sector index: '", sector.index[i], "'\n", sep = "") cat("track index: ", track.index[j], "\n", sep = "") xlim = get.cell.meta.data('xlim', sector.index[i], track.index[j]) ylim = get.cell.meta.data('ylim', sector.index[i], track.index[j]) cell.xlim = get.cell.meta.data("cell.xlim", sector.index[i], track.index[j]) cell.ylim = get.cell.meta.data("cell.ylim", sector.index[i], track.index[j]) xplot = get.cell.meta.data("xplot", sector.index[i], track.index[j]) yplot = get.cell.meta.data("yplot", sector.index[i], track.index[j]) cell.width = get.cell.meta.data("cell.width", sector.index[i], track.index[j]) cell.height = get.cell.meta.data("cell.height", sector.index[i], track.index[j]) track.margin = get.cell.meta.data("track.margin", sector.index[i], track.index[j]) cell.padding = get.cell.meta.data("cell.padding", sector.index[i], track.index[j]) cat("xlim: [", xlim[1], ", ", xlim[2], "]\n", sep = "") cat("ylim: [", ylim[1], ", ", ylim[2], "]\n", sep = "") cat("cell.xlim: [", cell.xlim[1], ", ", cell.xlim[2], "]\n", sep = "") cat("cell.ylim: [", cell.ylim[1], ", ", cell.ylim[2], "]\n", sep = "") cat("xplot (degree): [", xplot[1], ", ", xplot[2], "]\n", sep = "") cat("yplot (radius): [", yplot[1], ", ", yplot[2], "]\n", sep = "") cat("cell.width (degree): ", cell.width, "\n", sep = "") cat("cell.height (radius): ", cell.height, "\n", sep = "") cat("track.margin: c(", track.margin[1], ", ", track.margin[2], ")\n", sep = "") cat("cell.padding: c(", cell.padding[1], ", ", cell.padding[2], ", ", cell.padding[3], ", ", cell.padding[4], ")\n", sep = "") cat("\n") } } } if(length(get.current.sector.index())) cat("Your current sector.index is ", get.current.sector.index(), "\n", sep = "") if(get.current.track.index() > 0) cat("Your current track.index is ", get.current.track.index(), "\n", sep = "") } } show.index = function() { circos.info(plot = TRUE) warning_wrap("`show.index` is deprecated, please use `circos.info` instead.") } get.cell.meta.data = function(name, sector.index = get.current.sector.index(), track.index = get.current.track.index()) { sector.index = as.character(sector.index) if(length(sector.index) == 0) { stop_wrap("It seems the circular plot has not been initialized.") } if(length(track.index) == 0) { stop_wrap("It seems the track has not been created.") } if(length(sector.index) != 1) { stop_wrap("Length of `sector.index` should only be 1.") } if(length(track.index) != 1) { stop_wrap("Length of `track.index` should only be 1.") } if(track.index == 0) { stop_wrap("It seems the track has not been created.") } if(!any(sector.index %in% get.all.sector.index())) { stop_wrap("Cannot find sector: ", sector.index, ".") } if(!any(track.index %in% get.all.track.index())) { stop_wrap("Cannot find track: ", track.index, ".") } current.sector.data = get.sector.data(sector.index) current.cell.data = get.cell.data(sector.index, track.index) cell.padding = current.cell.data$cell.padding if(length(name) != 1) { stop_wrap("``name`` should only have length of 1.") } if(name == "xlim") { return(current.cell.data$xlim) } else if(name == "ylim") { return(current.cell.data$ylim) } else if(name == "xrange") { xlim = current.cell.data$xlim return(xlim[2] - xlim[1]) } else if(name == "yrange") { ylim = current.cell.data$ylim return(ylim[2] - ylim[1]) } else if(name == "xcenter") { xlim = current.cell.data$xlim return((xlim[2] + xlim[1])/2) } else if(name == "ycenter") { ylim = current.cell.data$ylim return((ylim[2] + ylim[1])/2) } else if(name == "cell.xlim") { return(current.cell.data$cell.xlim) } else if(name == "cell.ylim") { return(current.cell.data$cell.ylim) } else if(name == "sector.numeric.index") { return(which(get.all.sector.index() == sector.index)) } else if(name == "sector.index") { return(sector.index) } else if(name == "track.index") { return(track.index) } else if(name == "xplot") { x = current.sector.data[c("start.degree", "end.degree")] names(x) = NULL x = x %% 360 return(x) } else if(name == "yplot") { return(c(current.cell.data$track.start - current.cell.data$track.height, current.cell.data$track.start)) } else if(name == "cell.width") { x = current.sector.data[c("start.degree", "end.degree")] return((x[1] - x[2]) %% 360) } else if(name == "cell.height") { y = c(current.cell.data$track.start - current.cell.data$track.height, current.cell.data$track.start) return(y[2] - y[1]) } else if(name == "track.margin") { return(current.cell.data$track.margin) } else if(name == "cell.padding") { return(current.cell.data$cell.padding) } else if(name == "cell.start.degree") { x = current.sector.data["start.degree"] names(x) = NULL x = x %% 360 return(x) } else if(name == "cell.end.degree") { x = current.sector.data["end.degree"] names(x) = NULL x = x %% 360 return(x) } else if(name == "cell.bottom.radius") { return(current.cell.data$track.start - current.cell.data$track.height) } else if(name == "cell.top.radius") { return(current.cell.data$track.start) } else if(name == "bg.col") { return(current.cell.data$bg.col) } else if(name == "bg.border") { return(current.cell.data$bg.border) } else if(name == "bg.lty") { return(current.cell.data$bg.lty) } else if(name == "bg.lwd") { return(current.cell.data$bg.lwd) } else if(name == "track.height") { return(current.cell.data$track.height) } else { env = circos.par("__tempenv__") if(!is.null(env$track.meta.data)) { track.index = as.character(track.index) if(!is.null(env$track.meta.data[[track.index]])) { if(name %in% names(env$track.meta.data[[track.index]])) { return(env$track.meta.data[[track.index]][[name]]) } } } if(!is.null(env$sector.meta.data)) { if(!is.null(env$sector.meta.data[[sector.index]])) { if(name %in% names(env$sector.meta.data[[sector.index]])) { return(env$sector.meta.data[[sector.index]][[name]]) } } } } return(NULL) } add.track.meta.data = function(name, value, track.index = get.current.track.index()) { env = circos.par("__tempenv__") if(is.null(env$track.meta.data)) env$track.meta.data = list() track.index = as.character(track.index) if(is.null(env$track.meta.data[[track.index]])) env$track.meta.data[[track.index]] = list() env$track.meta.data[[track.index]][[name]] = value } add.sector.meta.data = function(name, value, sector.index = get.current.sector.index()) { sector.index = as.character(sector.index) env = circos.par("__tempenv__") if(is.null(env$sector.meta.data)) env$sector.meta.data = list() if(is.null(env$sector.meta.data[[sector.index]])) env$sector.meta.data[[sector.index]] = list() env$sector.meta.data[[sector.index]][[name]] = value } CELL_META = "don't use me directly" class(CELL_META) = "CELL_META" names.CELL_META = function(x) { sector.index = get.current.sector.index() track.index = get.current.track.index() nm = c("xlim", "ylim", "xrange", "yrange", "xcenter", "ycenter", "cell.xlim", "cell.ylim", "sector.numeric.index", "sector.index", "track.index", "xplot", "yplot", "cell.width", "cell.height", "track.margin", "cell.padding", "cell.start.degree", "cell.end.degree", "cell.bottom.radius", "cell.top.radius", "bg.col", "bg.border", "bg.lty", "bg.lwd", "track.height") env = circos.par("__tempenv__") if(track.index > 0) { if(!is.null(env$track.meta.data)) { track.index = as.character(track.index) if(!is.null(env$track.meta.data[[track.index]])) { nm = c(nm, names(env$track.meta.data[[track.index]])) } } } if(!is.null(sector.index)) { if(!is.null(env$sector.meta.data)) { if(!is.null(env$sector.meta.data[[sector.index]])) { nm = c(nm, names(env$sector.meta.data[[sector.index]])) } } } return(nm) } "$.CELL_META" = function(x, name) { get.cell.meta.data(name) } print.CELL_META = function(x, ...) { cat(paste(strwrap("Please use in a form of `CELL_META$name` where `name` should be supported in `get.cell.meta.data()`. Type `names(CELL_META)` for supported names.\n"), collapse = "\n"), "\n") }
pdb_make_ipm <- function(proto_ipm_list, addl_args = list()) { .check_make_ipm_args(proto_ipm_list, addl_args) made_calls <- .make_ipm_calls(proto_ipm_list, addl_args) out <- lapply(made_calls, eval) class(out) <- c("pdb_ipm", "list") return(out) }
ml_prefixspan <- function(x, seq_col = "sequence", min_support = 0.1, max_pattern_length = 10, max_local_proj_db_size = 32000000, uid = random_string("prefixspan_"), ...) { check_dots_used() UseMethod("ml_prefixspan") } ml_prefixspan.spark_connection <- function(x, seq_col = "sequence", min_support = 0.1, max_pattern_length = 10, max_local_proj_db_size = 32000000, uid = random_string("prefixspan_"), ...) { .args <- list( seq_col = seq_col, min_support = min_support, max_pattern_length = max_pattern_length, max_local_proj_db_size = max_local_proj_db_size ) %>% c(rlang::dots_list(...)) %>% validator_ml_prefixspan() uid <- cast_string(uid) jobj <- invoke_new(x, "org.apache.spark.ml.fpm.PrefixSpan", uid) %>% invoke( "%>%", list("setSequenceCol", .args[["seq_col"]]), list("setMinSupport", .args[["min_support"]]), list("setMaxPatternLength", .args[["max_pattern_length"]]), list("setMaxLocalProjDBSize", .args[["max_local_proj_db_size"]]) ) new_ml_prefixspan_model(jobj) } validator_ml_prefixspan <- function(.args) { .args[["seq_col"]] <- cast_string(.args[["seq_col"]]) .args[["min_support"]] <- cast_scalar_double(.args[["min_support"]]) .args[["max_pattern_length"]] <- cast_integer(.args[["max_pattern_length"]]) .args[["max_local_proj_db_size"]] <- cast_integer(.args[["max_local_proj_db_size"]]) .args } new_ml_prefixspan_model <- function(jobj) { new_ml_transformer( jobj, frequent_sequential_patterns = function(x) { invoke(jobj, "findFrequentSequentialPatterns", spark_dataframe(x)) %>% sdf_register() }, class = "ml_prefixspan_model" ) } ml_freq_seq_patterns <- function(model) { model$frequent_sequential_patterns }
colf_nls <- function(formula, data, start = NULL, trace = FALSE, control = NULL, na.action = c('na.omit', 'na.fail', 'na.exclude'), lower = -Inf, upper = Inf, ...) { na.action <- match.arg(na.action) data <- get(na.action)(data) model_ingredients <- construct_formula(formula, data) if (is.null(start)) { start <- as.list(rep(1, length(model_ingredients$x_coef_names))) names(start) <- model_ingredients$x_coef_names } else { start <- as.list(start) names(start) <- model_ingredients$x_coef_names } nls_mod <- nls(model_ingredients$model_formula, data = model_ingredients$model_data, start = start, trace = trace, control = control, lower = lower, upper = upper, algorithm = 'port', ...) nls_mod$formula <- formula nls_mod$model_data <- data class(nls_mod) <- c('colf_nls', 'nls') nls_mod }
SLE <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(country = "Sierra Leone") x2 <- ourworldindata.org(id = "SLE") x <- full_join(x1, x2, by = "date") } return(x) }
CAScenters<-function(CAS, y=NULL) { averageCAS<-function(x) { avccf = x[[1]] if(length(x)>1) { for(i in 2:length(x)) { avccf = avccf + x[[i]] } avccf = avccf/length(x) } return(avccf) } sumCAS<-function(x) { sccf = x[[1]] if(length(x)>1) { for(i in 2:length(x)) { sccf = sccf + x[[i]] } } return(sccf) } if(!is.null(y)) { if(is.vector(y) || is.factor(y)) { CC = lapply(split(CAS, as.factor(y)), FUN = averageCAS) } else if(inherits(y,"vegclust")) { if(y$method %in% c("KMdd","FCMdd","HNCdd","NCdd","PCMdd")) { mi = c(y$mobileCenters, y$fixedCenters) CC = CAS[mi] } else { memb = y$memb CC = vector("list", ncol(memb)) if(nrow(memb)!=length(CAS)) stop("The number of plots in CAS has to be equal to the classified elements in y") for(cl in 1:ncol(memb)) { CASmemb = CAS s = sum(memb[,cl]) for(i in 1:nrow(memb)) CASmemb[[i]] = CASmemb[[i]]*memb[i,cl] CC[[cl]]<-sumCAS(CASmemb)/s names(CC)[cl]<-colnames(memb)[cl] } } } } else { CC = list(meanCAS=averageCAS(CAS)) } class(CC)<-c("CAS","list") return(CC) }