code
stringlengths
1
13.8M
CE.ZINB.Init <- function(data, init.locs, eps=0.01, rho=0.05, M=200, h=5, a=0.8, b=0.8, distyp = 1, penalty = "BIC", var.init = 100000, parallel=FALSE){ if(is.data.frame(data) == "FALSE"| is.null(dim(data)[2])) { print("Error in data: dataframe only") } else if(dim(data)[2] != 1) { print("Error in data: single column dataframe only") } else if(missing(init.locs)){ print("Error: Initial locations are not provided!!!") } else { if(distyp == 1 & penalty == "BIC"){ Melite <- M * rho L <- length(data[, 1]) L0 <- 1 k <- length(init.locs) r <- suppressWarnings(try(fitdistr(data[, 1], "negative binomial")[[1]][[1]], silent = T)) if(parallel == TRUE & .Platform$OS.type == "windows"){ cl <- makeCluster(parallel::detectCores(), type = "SOCK") clusterExport(cl, c("ce.4betaZINB.BIC.Init", "betarand", "fun.alpha", "fun.beta", "BICzinb", "llhoodzinb", "loglikzinb", "betaIntEst"), envir = environment()) clusterExport(cl, c("data", "rho", "M", "h", "eps", "Melite", "L", "L0", "a", "init.locs", "r", "var.init"), envir = environment()) registerDoParallel(cl) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.4betaZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) stopCluster(cl) } else if (parallel == TRUE & .Platform$OS.type == "unix"){ registerDoParallel(parallel::detectCores()) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.4betaZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) } else sim <- foreach(k = k, .errorhandling = c('pass')) %do% ce.4betaZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) cpt.loci <- sim[[1]]$loci return(list("No.BPs" = length(cpt.loci) - 2, "BP.Loc" = cpt.loci[2:(length(cpt.loci) - 1)], "BIC" = sim[[1]]$BIC, "ll" = sim[[1]]$LogLike)) } else if(distyp == 2 & penalty == "BIC"){ Melite <- M*rho L <- length(data[, 1]) L0 <- 1 k <- length(init.locs) r <- suppressWarnings(try(fitdistr(data[, 1], "negative binomial")[[1]][[1]], silent = T)) if(parallel == TRUE & .Platform$OS.type == "windows"){ cl <- makeCluster(parallel::detectCores(), type = "SOCK") clusterExport(cl, c("ce.simNormalZINB.BIC.Init", "normrand", "BICzinb", "llhoodzinb", "loglikzinb"), envir = environment()) clusterExport(cl, c("data", "rho", "M", "h", "eps", "Melite", "L", "L0", "a", "b", "init.locs", "r", "var.init"), envir=environment()) registerDoParallel(cl) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.simNormalZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) stopCluster(cl) } else if (parallel == TRUE & .Platform$OS.type == "unix"){ registerDoParallel(parallel::detectCores()) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.simNormalZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) } else { sim <- foreach(k = k, .errorhandling = c('pass')) %do% ce.simNormalZINB.BIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) } cpt.loci <- sim[[1]]$loci return(list("No.BPs" = length(cpt.loci) - 2, "BP.Loc" = cpt.loci[2:(length(cpt.loci) - 1)], "BIC" = sim[[1]]$BIC, "ll" = sim[[1]]$LogLike)) } else if(distyp == 1 & penalty == "AIC"){ Melite <- M*rho L <- length(data[, 1]) L0 <- 1 k <- length(init.locs) r <- suppressWarnings(try(fitdistr(data[, 1], "negative binomial")[[1]][[1]], silent = T)) if(parallel == TRUE & .Platform$OS.type == "windows"){ cl <- makeCluster(parallel::detectCores(), type = "SOCK") clusterExport(cl, c("ce.4betaZINB.AIC.Init", "betarand", "fun.alpha", "fun.beta", "AICzinb", "llhoodzinb", "loglikzinb", "betaIntEst"), envir = environment()) clusterExport(cl, c("data", "rho", "M", "h", "eps", "Melite", "L", "L0", "a", "init.locs", "r", "var.init"), envir = environment()) registerDoParallel(cl) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.4betaZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) stopCluster(cl) } else if (parallel == TRUE & .Platform$OS.type == "unix"){ registerDoParallel(parallel::detectCores()) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.4betaZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) } else sim <- foreach(k = k, .errorhandling = c('pass')) %do% ce.4betaZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, r, var.init) cpt.loci <- sim[[1]]$loci return(list("No.BPs" = length(cpt.loci) - 2, "BP.Loc" = cpt.loci[2:(length(cpt.loci) - 1)], "AIC" = sim[[1]]$AIC, "ll" = sim[[1]]$LogLike)) } else if(distyp == 2 & penalty == "AIC"){ Melite <- M*rho L <- length(data[, 1]) L0 <- 1 k <- length(init.locs) r <- suppressWarnings(try(fitdistr(data[, 1], "negative binomial")[[1]][[1]], silent = T)) if(parallel == TRUE & .Platform$OS.type == "windows"){ cl <- makeCluster(parallel::detectCores(), type = "SOCK") clusterExport(cl, c("ce.simNormalZINB.AIC.Init", "normrand", "AICzinb", "llhoodzinb", "loglikzinb"), envir = environment()) clusterExport(cl, c("data", "rho", "M", "h", "eps", "Melite", "L", "L0", "a", "b", "init.locs", "r", "var.init"), envir=environment()) registerDoParallel(cl) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.simNormalZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) stopCluster(cl) } else if (parallel == TRUE & .Platform$OS.type == "unix"){ registerDoParallel(parallel::detectCores()) sim <- foreach(k = k, .errorhandling = c('pass')) %dopar% ce.simNormalZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) } else { sim <- foreach(k = k, .errorhandling = c('pass')) %do% ce.simNormalZINB.AIC.Init(k, init.locs, data, h, L0, L, M, Melite, eps, a, b, r, var.init) } cpt.loci <- sim[[1]]$loci return(list("No.BPs" = length(cpt.loci) - 2, "BP.Loc" = cpt.loci[2:(length(cpt.loci) - 1)], "AIC" = sim[[1]]$AIC, "ll" = sim[[1]]$LogLike)) } } }
extractSiteNames <- function (file) { if (file.info(file)$size == 0) { stop("Your file is empty. Please try again with a different file.") } else { RDatatmp <- n.readLines(file, n = 5, header = FALSE) RDatatmp <- paste(RDatatmp[1:5], collapse = " ") RDatatmp <- stri_split_fixed(RDatatmp, pattern = "Latitude", n = 2)[[1]][1] } }
clean_params <- function(parameters_df, warning = TRUE) { if (min(parameters_df$priors) < 0) stop("Negative alpha arguments for priors are not allowed") if (min(parameters_df$param_value) < 0) stop("Negative arguments for parameters not allowed") for (j in unique(parameters_df$param_set)) { A <- parameters_df$param_set == j check <- sum(parameters_df$param_value[A]) if (!isTRUE(all.equal(check, 1))) { if (warning) message(paste0("Parameters in set ", j, " do not sum to 1. Using normalized parameters")) parameters_df$param_value[A] <- parameters_df$param_value[A]/check } } parameters_df } clean_param_vector <- function(model, parameters) { model$parameters_df$param_value <- as.vector(parameters) x <- clean_params(model$parameters_df, warning = FALSE)$param_value names(x) <- model$parameters_df$param_names x }
expected <- eval(parse(text="structure(c(952L, 3622L, 202L, 406L), .Dim = c(2L, 2L), .Dimnames = list(c(\"subcohort\", \"cohort\"), c(\"1\", \"2\")))")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(952L, 3622L, 202L, 406L), .Dim = c(2L, 2L), .Dimnames = list(c(\"subcohort\", \"cohort\"), c(\"1\", \"2\"))), c(\"subcohort\", \"cohort\"), c(\"1\", \"2\"), FALSE, FALSE, NULL)")); .Internal(prmatrix(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]])); }, o=expected);
ecparam <- function(p, a, b){ p <- gmp::as.bigz(p) a <- gmp::as.bigz(a) b <- gmp::as.bigz(b) new("ECPARAM", p = p, a = a, b = b) } setGeneric("containsPoint", function(curve, x, y) standardGeneric("containsPoint")) setMethod("containsPoint", signature("ECPARAM", "bigz", "bigz"), definition = function(curve, x, y){ term <- (y * y - (x * x * x + curve@a * x + curve@b)) %% curve@p term == 0L }) setMethod("containsPoint", signature("ECPARAM", "integer", "integer"), definition = function(curve, x, y){ x <- gmp::as.bigz(x) y <- gmp::as.bigz(y) term <- (y * y - (x * x * x + curve@a * x + curve@b)) %% curve@p term == 0L }) setMethod("containsPoint", signature("ECPARAM", "character", "character"), definition = function(curve, x, y){ x <- gmp::as.bigz(x) y <- gmp::as.bigz(y) term <- (y * y - (x * x * x + curve@a * x + curve@b)) %% curve@p term == 0L }) ecpoint <- function(ecparam = NULL, x, y, r = NULL){ x <- gmp::as.bigz(x) y <- gmp::as.bigz(y) r <- gmp::as.bigz(r) if (!is.null(ecparam)){ checkpoint <- containsPoint(ecparam, x, y) } else { checkpoint <- TRUE } if (!checkpoint){ stop("Point (x, y) is not on elliptic curve.\n") } new("ECPOINT", ecparam = ecparam, x = x, y = y, r = r) } setGeneric("isNull", function(x) standardGeneric("isNull")) setMethod("isNull", signature = "ECPOINT", function(x){ ans <- length(x@x) == 0L & length(x@y) == 0L ans } ) setGeneric("doubleUp", function(ecp) standardGeneric("doubleUp")) setMethod("doubleUp", signature = "ECPOINT", function(ecp){ if (isNull(ecp)){ return(ecpoint(NULL, NULL, NULL)) } p <- ecp@ecparam@p a <- ecp@ecparam@a l <- ( (3 * ecp@x * ecp@x + a) * inv.bigz(2 * ecp@y, p)) %% p x3 <- (l * l - 2 * ecp@x ) %% p y3 <- (l * (ecp@x - x3) - ecp@y) %% p ans <- ecpoint(ecp@ecparam, x3, y3) ans }) setMethod("+", signature = c("ECPOINT", "ECPOINT"), function(e1, e2){ if (isNull(e2)){ return(e1) } if (isNull(e1)){ return(e2) } if (!identical(e1@ecparam, e2@ecparam)){ stop("EC parameters of operands not identical.\n") } p <- e1@ecparam@p if (e1@x == e2@x){ check <- (e1@y + e2@y) %% p if (check == 0L){ return(ecpoint(NULL, NULL, NULL)) } else { return(doubleUp(e1)) } } l <- ( (e2@y - e1@y) * inv.bigz(e2@x - e1@x, p) ) %% p x3 <- (l * l - e1@x - e2@x) %% p y3 <- (l * (e1@x - x3) - e1@y) %% p ecpoint(e1@ecparam, x3, y3) }) setGeneric("leftmostBit", function(x) standardGeneric("leftmostBit")) setMethod("leftmostBit", signature = "bigz", function(x){ if (x <= 0L){ stop("Negative 'bigz' integer provided.\n") } ans <- as.bigz(1L) while (ans <= x){ ans <- 2L * ans } as.bigz(ans / 2L) }) setGeneric("AND", function(x, y) standardGeneric("AND")) setMethod("AND", signature = c("bigz", "bigz"), function(x, y){ b1 <- as.character(x, b = 2) b1l <- nchar(b1) b2 <- as.character(y, b = 2) b2l <- nchar(b2) n <- min(b1l, b2l) b1num <- rev(as.numeric( (unlist(strsplit(b1, ""))))) b2num <- rev(as.numeric( (unlist(strsplit(b2, ""))))) ans <- rep(0, n) for (i in 1:n){ ans[i] <- ifelse(b1num[i] + b2num[i] > 1, 1, 0) } ans <- rev(ans) ans <- paste("0b", paste0(ans, collapse = ""), sep = "") as.bigz(ans) }) setMethod("*", signature = c("ECPOINT", "bigz"), function(e1, e2){ ecp <- e1 e <- e2 if (isNull(ecp)){ return(ecp) } if (length(ecp@r) > 0){ e <- e %% ecp@r } if ( e == 0L){ return(ecpoint(NULL, NULL, NULL)) } if (e < 0L){ stop("Negative 'bigz' integer.\n") } e3 <- 3L * e negpoint <- ecpoint(ecp@ecparam, ecp@x, -ecp@y, ecp@r) i <- as.bigz(leftmostBit(e3) / 2L) ans <- ecp while (i > 1){ ans <- doubleUp(ans) if ( (AND(e3, i) != 0L) && (AND(e, i) == 0L) ){ ans <- ans + ecp } if ( (AND(e3, i) == 0L) && (AND(e, i) != 0L) ){ ans <- ans + negpoint } i <- as.bigz(i / 2) } ans }) setMethod("*", signature = c("bigz", "ECPOINT"), function(e1, e2){ e2 * e1 })
`%notin%` <- Negate(`%in%`) simu_cov=function(ssObj, covObj, driftHR, HR, nsim, seed, path){ if (missing(ssObj)) stop("Please provide ssObj.") if (missing(covObj)) { message("No covObj is provided.") covObj = NULL } if (missing(HR)){ HR = 1 message("HR values (HR) not provided. Default value 1 is used.") } if (missing(driftHR)){ driftHR = 1 message("driftHR values (driftHR) not provided. Default value 1 is used.") } if (missing(nsim)) { message("Number of simulation is not provided. Default value 5 is used") nsim = 5 } dt0 <- ssObj ssC <- sum(dt0[,'ext'] ==0 & dt0[,'trt'] ==0) ssE <- sum(dt0[,'ext'] ==0 & dt0[,'trt'] ==1) ssExt <- sum(dt0[,'ext'] ==1) message(paste0("The sample size for internal control, internal treatment, and external control arms are ", ssC, ", ", ssE, ", and ", ssExt,", respectively.")) if (missing(seed)){ message(paste0("Set seed to ",.Random.seed[1])) seed = .Random.seed[1] } else set.seed(seed) seed_list <- array(seq(seed, length(driftHR) * length(HR) * nsim + seed, by = 1), dim = c(nsim, length(HR), length(driftHR))) flog.debug(cat("[simu_cov] seed_list:", seed_list, "\n")) res_list <- sapply(1:length(driftHR), function(k){ dr <- driftHR[k] sapply(1:length(HR), function(j) { hr <- HR[j] nsim_res <- lapply(seq(1, nsim, by = 1), function(i){ seed_i = seed_list[i, j, k] message("------------------- j, "of HR =", hr, ", k, "of driftHR = ", dr, ", seed =", seed_i) samp = set_n(ssC = ssC, ssE = ssE, ssExt = ssExt) samp_cov = samp if (!is.null(covObj)) { samp_cov = add_cov(dt = samp, covObj = covObj, seed = seed_i) } flog.debug(cat("[simu_cov] seed_i:", seed_i, "\n")) cbind("driftHR" = dr, "HR" = hr, samp_cov) }) }) }) if (missing(path)) message("Simulated covariates are not saved.") else { save(res_list, file = path) message("Simulated covariates are saved as ", path) } res_list }
"bacteria" bacteria <- data.frame( count = c(680, 720, 775, 810,875, 2000, 2900, 3000, 5000,8000, 10000, 12000, 15000, 20000, 30000, 40000, 41000, 41000, 42000, 47000, 47000, 80500), percentTime = c(0.12, 0.4, 0.7,0.75, 1, 12.5, 26, 27, 51, 73, 83.5, 84.5, 88.5, 91.5, 95.5, 98.3, 98.5, 98.75, 99, 99.25, 99.6, 99.85 ) )
library("enpls") library("ggplot2") data("logd1k") x <- logd1k$x y <- logd1k$y head(x)[, 1:5] head(y) set.seed(42) fit <- enspls.fit(x, y, ratio = 0.7, reptimes = 20, maxcomp = 3) y.pred <- predict(fit, newx = x) df <- data.frame(y, y.pred) ggplot(df, aes_string(x = "y", y = "y.pred")) + geom_abline(slope = 1, intercept = 0, colour = "darkgrey") + geom_point(size = 3, shape = 1, alpha = 0.8) + coord_fixed(ratio = 1) + xlab("Observed Response") + ylab("Predicted Response") cv.fit <- cv.enspls(x, y, nfolds = 5, ratio = 0.7, reptimes = 10, maxcomp = 3, verbose = FALSE ) cv.fit plot(cv.fit) fs <- enspls.fs(x, y, ratio = 0.7, reptimes = 20, maxcomp = 3) print(fs, nvar = 10) plot(fs, nvar = 10) plot(fs, type = "boxplot", nvar = 10) od <- enspls.od(x, y, ratio = 0.8, reptimes = 20, maxcomp = 3) plot(od, prob = 0.05) plot(od, criterion = "sd", sdtimes = 2) x <- x[, -c(17, 52, 59)] x.tr <- x[1:500, ] y.tr <- y[1:500] x.te <- list( "test.1" = x[501:700, ], "test.2" = x[701:800, ] ) y.te <- list( "test.1" = y[501:700], "test.2" = y[701:800] ) ad <- enspls.ad(x.tr, y.tr, x.te, y.te, maxcomp = 3, space = "variable", method = "mc", ratio = 0.8, reptimes = 50 ) plot(ad)
plotsignal <- function(x, ind= NULL, popA=NULL, popB=NULL, xlab=NULL, ylab=NULL, ylim=NULL, main=NULL){ ctmp <- class(x) if (is.null(ctmp)) stop("object has no class") if (ctmp != "adsig") stop("object is not of class adsig") if(is.null(ind)) stop("must provide name of individual to plot") if(sum(match(x$individuals,ind), na.rm=TRUE) != 1) stop("individual not recognised") if(sum(!is.na(match(x$individuals,popA))) != length(popA)) stop("individual in PopA not recognised") if(sum(!is.na(match(x$individuals,popB))) != length(popB)) stop("individual in PopB not recognised") if(is.null(ylab)) ylab <- "signal" if(is.null(main)){ main <- paste("ID:", x$individuals[ind], ", Window size:" ,x$window.size,sep=" ")} tempP <- t(x$signals) if(is.null(x$gendist)){ loc <- 1:dim(tempP)[2] if(is.null(xlab)) xlab <- "SNP number"}else{ loc <- x$gendist if(is.null(xlab)) xlab <- "genetic distance" } if(!is.null(popA)){ Amin <- apply(tempP[popA,],c(2),FUN=min) Amax <- apply(tempP[popA,],c(2),FUN=max) } if(!is.null(popB)){ Bmin <- apply(tempP[popB,],c(2),FUN=min) Bmax <- apply(tempP[popB,],c(2),FUN=max)} if(is.null(ylim)){ ylim <- range(tempP, na.rm=TRUE)} plot(loc,tempP[ind,], xlab=xlab, ylab=ylab,main=main, ylim=ylim,type="l",cex.main=1);abline(h=c(-1,0,1),lty=3,col=3); abline(h=mean(tempP[ind,],),col=2) if(!is.null(popB)){ polygon(c(loc,rev(loc)), c((Bmin), rev(Bmax)), col = "lightblue", border = NA)} if(!is.null(popA)){ polygon(c(loc,rev(loc)), c((Amax), rev(Amin)), col = "lightgreen", border = NA)} lines(loc,tempP[ind,],lwd=1,col=1) }
expected <- eval(parse(text="c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)")); test(id=0, code={ argv <- eval(parse(text="list(c(2.00256647265648e-308, 2.22284878464869e-308, 2.22507363599982e-308, 2.2250738585072e-308, 2.22507408101459e-308, 2.22729893236571e-308, 2.44758124435792e-308, 1.61792382137608e+308, 1.79589544172745e+308, 1.797692955093e+308, 1.79769313486232e+308), 1)")); do.call(`>=`, argv); }, o=expected);
ForestFloorExport <- function(arbOut) { .Deprecated("Export") UseMethod("ForestFloorExport") } "ForestFloorExport.Rborist" <- function(arbOut) { return (tryCatch(.Call("Export", arbOut), error = function(e) {stop(e)})) }
ReportID <- NULL StatusReport <- NULL ws_data <- NULL SearchedAlso <- NULL SearchedWith <- NULL . <- NULL yadirGetWordStatReport <- function( Phrases, GeoID = 0, Login = getOption("ryandexdirect.user"), Token = NULL, AgencyAccount = getOption("ryandexdirect.agency_account"), TokenPath = yadirTokenPath()) { start_time <- Sys.time() Token <- tech_auth(login = Login, token = Token, AgencyAccount = AgencyAccount, TokenPath = TokenPath) Phrases <- yadirToList(Phrases) GeoID <- yadirToList(GeoID) message('.Send report') send_query <- list(method = "CreateNewWordstatReport", param = list(Phrases = Phrases, GeoID = GeoID), locale = "ru", token = Token) %>% toJSON(auto_unbox = TRUE) ans <- POST("https://api.direct.yandex.ru/v4/json/", body = send_query ) rep_id = content(ans, 'parsed') if ( ! is.null( rep_id$error_str ) ) { message(rep_id$error_detail) stop(rep_id$error_str) } rep_status <- 'New' while ( rep_status != 'Done' ) { get_status <- list(method = "GetWordstatReportList", locale = "ru", token = Token) %>% toJSON(auto_unbox = TRUE) ans <- POST("https://api.direct.yandex.ru/v4/json/", body = get_status ) rep_status <- content(ans, 'parsed') %>% tibble( report = .$data ) %>% unnest_wider(report) %>% filter(ReportID == rep_id) %>% select(StatusReport) %>% unlist() Sys.sleep(1) message(".Report status: ", rep_status) } message('.Get report') get_query <- list(method = "GetWordstatReport", param = unlist(rep_id), locale = "ru", token = Token) %>% toJSON(auto_unbox = TRUE) raw_data <- POST("https://api.direct.yandex.ru/v4/json/", body = get_query ) message('.Parse report') SearchedAlso <- content(raw_data, 'parsed') %>% tibble(ws_data = .$data) %>% unnest_wider(ws_data) %>% unnest_longer(GeoID) %>% select(-SearchedWith, -".") %>% unnest_longer(SearchedAlso) %>% hoist(SearchedAlso, Phrase = c("Phrase"), Shows = c("Shows")) SearchedWith <- content(raw_data, 'parsed') %>% tibble(ws_data = .$data) %>% unnest_wider(ws_data) %>% unnest_longer(GeoID) %>% select(-SearchedAlso, -".") %>% unnest_longer(SearchedWith) %>% hoist(SearchedWith, Phrase = c("Phrase"), Shows = c("Shows")) report <- list(SearchedWith = SearchedWith, SearchedAlso = SearchedAlso) message('.Delete report') get_query <- list(method = "GetWordstatReport", param = unlist(rep_id), locale = "ru", token = Token) %>% toJSON(auto_unbox = TRUE) raw_data <- POST("https://api.direct.yandex.ru/v4/json/", body = get_query ) message("Success!") stop_time <- Sys.time() message(paste0("Duration: ", round(difftime(stop_time, start_time , units ="secs"),0), " sec.")) message("Request ID: ", ans$headers$requestid) message("WordStat Report ID: ", rep_id) message("Report SearchedAlso has ", nrow(SearchedAlso), " rows") message("Report SearchedWith has ", nrow(SearchedWith), " rows") message("For get report data x[['ReportName']]") return(report) }
trait.stat <- function(bcnt.otu, coefs) { if (is.factor(coefs$TRAITVAL)) { temp <- levels(coefs$TRAITVAL) } else { if (is.character(coefs$TRAITVAL)) { temp <- unique(coefs$TRAITVAL) } } traitval.u <- character(0) repeat{ w <- regexpr("[A-Za-z]+", temp) if (sum(w!=-1) == 0) break traitval.u <- c(traitval.u,substring(temp, w, w+attributes(w)$match.length- 1)) temp <- substring(temp, w+attributes(w)$match.length+1, nchar(temp)) } traitval.u[traitval.u == ""] <- NA traitval.u <- sort(unique(traitval.u)) if (!is.factor(bcnt.otu[,1])) { bcnt.otu[,1] <- factor(bcnt.otu[,1]) } bcnt.t <- merge(bcnt.otu, coefs, by.x = "OTU", by.y="TAXON", all.x = T) matout <- matrix(NA, ncol = 3*length(traitval.u), nrow = length(levels(bcnt.otu[,1]))) if (is.factor(coefs$TRAITVAL)) { all.traits <- levels(bcnt.t$TRAITVAL)[bcnt.t$TRAITVAL] } else { if (is.character(coefs$TRAITVAL)) { all.traits <- bcnt.t$TRAITVAL } } fsite <- names(bcnt.otu)[1] fabund <- names(bcnt.otu)[3] ftaxon <- names(bcnt.otu)[2] for (i in 1:length(traitval.u)) { incvec <- regexpr(traitval.u[i], all.traits) != -1 tr.rich <- tapply(bcnt.t$OTU[incvec], bcnt.t[incvec,fsite], function(x) length(unique(x))) tr.rich[is.na(tr.rich)] <- 0 matout[,(i-1)*3+1] <- tr.rich trich <- tapply(bcnt.otu[, ftaxon], bcnt.otu[,fsite], function(x) length(unique(x))) matout[,(i-1)*3+2] <- tr.rich/trich totabund <- tapply(bcnt.otu[,fabund], bcnt.otu[,fsite], sum) tr.abund <- tapply(bcnt.t[incvec,fabund], bcnt.t[incvec,fsite], sum) tr.abund[is.na(tr.abund)] <- 0 matout[, (i-1)*3+3] <- tr.abund/totabund } names0 <- paste(rep(traitval.u, times = rep(3, times = length(traitval.u))), rep(c(".RICH", ".PTAX", ".PABN"), times = length(traitval.u)), sep = "") dfout <- data.frame(id = levels(bcnt.otu[,1]), matout) names0 <- c(fsite, names0) names(dfout) <- names0 return(dfout) }
prl_ewa <- hBayesDM_model( task_name = "prl", model_name = "ewa", model_type = "", data_columns = c("subjID", "choice", "outcome"), parameters = list( "phi" = c(0, 0.5, 1), "rho" = c(0, 0.1, 1), "beta" = c(0, 1, 10) ), regressors = list( "ev_c" = 2, "ev_nc" = 2, "ew_c" = 2, "ew_nc" = 2 ), postpreds = c("y_pred"), preprocess_func = prl_preprocess_func)
makeDF <- function(rawdata, colSelect=NULL, showHidden, colNameOpt) { decode <- fromJSON(rawdata, simplifyVector=FALSE, simplifyDataFrame=FALSE) if(length(decode$columnModel)==0){ stop('No columns exist in the result set. Be sure you are using the column name for colNameOpt="fieldname" and the column label for colNameOpt="caption" in the colSelect vector. See the documentation for more details.') } colModelNames = c() colModelLabels = c() colModelRNames = c() for(i in 1:length(decode$columnModel)){ if(!is.null(decode$columnModel[[i]]$dataIndex)){ colModelNames = c(colModelNames, decode$columnModel[[i]]$dataIndex) colModelRNames = c(colModelRNames, .getRNameFromName(decode$columnModel[[i]]$dataIndex, existing=colModelRNames)) } if(!is.null(decode$columnModel[[i]]$header)){ colModelLabels = c(colModelLabels, decode$columnModel[[i]]$header) } } colSelectVector <- NULL if(!is.null(colSelect)){ colSelectVector <- strsplit(colSelect, ",")[[1]] } if(!is.null(colSelectVector) & length(colSelectVector)>0){ for(i in 1:length(colSelectVector)){ if(colSelectVector[[i]] != "*" & !(colSelectVector[[i]] %in% colModelNames) & !(colSelectVector[[i]] %in% colModelLabels) & !(colSelectVector[[i]] %in% colModelRNames)){ stop(paste('The column "',colSelectVector[[i]],'" specified in the colSelect variable does not exist in the result set. Be sure you are using the column name for colNameOpt="fieldname" and the column label for colNameOpt="caption". See the documentation for more details.',sep='')) } } } cnames <- NULL hindex <- NULL hide <- NULL for(j in 1:length(decode$columnModel)) { if (colNameOpt == "caption") { cname <- decode$columnModel[[j]]$header } else if (colNameOpt == "fieldname") { cname <- decode$columnModel[[j]]$dataIndex } else if (colNameOpt == "rname" ) { cname <- .getRNameFromName(decode$columnModel[[j]]$dataIndex, existing=cnames) } else { stop("Invalid colNameOpt option. Valid values are caption, fieldname, and rname.") } cnames <- c(cnames, cname) hindex <- c(hindex, decode$columnModel[[j]]$dataIndex) colHidden <- decode$columnModel[[j]]$hidden if(!is.null(colHidden)) { if(colHidden & !is.null(colSelectVector)) { colHidden <- !(decode$columnModel[[j]]$header %in% colSelectVector | decode$columnModel[[j]]$dataIndex %in% colSelectVector) } } hide <- c(hide, colHidden) } refdf <- data.frame(cnames,hindex,hide) if(length(decode$rows)<1){ tohide <- length(which(refdf$hide==TRUE)) totalcol <- length(refdf$cnames) if(showHidden==FALSE){ emptydf <- as.data.frame(rep(list(num=double(0)), each=(totalcol-tohide))) colnames(emptydf) <- refdf$cnames[refdf$hide==FALSE] warning("Empty data frame was returned. Query may be too restrictive.", call.=FALSE) return(emptydf) } else { emptydf <- as.data.frame(rep(list(num=double(0)), each=(totalcol))) colnames(emptydf) <- refdf$cnames warning("Empty data frame was returned. Query may be too restrictive.", call.=FALSE) } return(emptydf) } if(length(decode$rows)>0) { hold.dat <- NULL tmprow <- filterrow(decode$rows[[1]]) hold.dat<-listToMatrix(decode$rows, names(tmprow)) hold.dat <- as.data.frame(hold.dat,stringsAsFactors=FALSE) names(hold.dat) <- names(tmprow) } oindex <- NULL for(k in 1:length(cnames)){oindex <- rbind(oindex, which(names(hold.dat)==refdf$hindex[k]))} refdf$oindex <- oindex newdat <- as.data.frame(hold.dat[,refdf$oindex],stringsAsFactors=FALSE) refdf$type <- NULL for(p in 1:dim(refdf)[1]) { ind <- which(refdf$hindex==decode$metaData$fields[[p]]$name) refdf$type[ind] <- decode$metaData$fields[[p]]$type } if (showHidden==TRUE || is.null(decode$metaData$id)) {} else { hide.ind <- which(refdf$hide==TRUE) if(length(hide.ind)>0 ) { if(length(hide.ind) == length(newdat)) { stop("No visible columns selected. Use the showHidden=TRUE to see these columns.") } else { newdat <- newdat[,-hide.ind] refdf <- refdf[-hide.ind,] cnames <- cnames[-hide.ind] } } } if(is.null(dim(newdat))==FALSE) { for(j in 1:ncol(newdat)) { mod <- refdf$type[j] try( if(mod=="date") { newdat[,j] <- .parseDate(newdat[,j])} else if(mod=="string"){ suppressWarnings(mode(newdat[,j]) <- "character")} else if(mod=="int"){ suppressWarnings(mode(newdat[,j]) <- "integer")} else if(mod=="boolean"){suppressWarnings(mode(newdat[,j]) <- "logical")} else if(mod=="float"){suppressWarnings(mode(newdat[,j]) <- "numeric")} else {print("MetaData field type not recognized.")} , silent=TRUE) } newdat <- as.data.frame(newdat, stringsAsFactors=FALSE); colnames(newdat)<-cnames } if(is.null(dim(newdat))==TRUE & length(newdat)>1) { mod <- refdf$type try( if(mod=="date"){ newdat <- .parseDate(newdat)}else if(mod=="string"){suppressWarnings(mode(newdat) <- "character")} else if(mod=="int"){ suppressWarnings(mode(newdat) <- "integer")} else if(mod=="boolean"){suppressWarnings(mode(newdat) <- "logical")} else if(mod=="float"){suppressWarnings(mode(newdat) <- "numeric")} else {print("MetaData field type not recognized.")} , silent=TRUE) newdat <- as.data.frame(newdat, stringsAsFactors=FALSE); colnames(newdat)<-cnames[1] } return(newdat) } filterrow<-function(row) { filtered <- NULL for (x in 1:length(row)) { valname <- names(row[x]) if ((nchar(valname)>11) && (substr(valname,1,11) == as.character("_labkeyurl_"))) { next } if (is.null(row[x][[valname]])) { row[x][[valname]]<-NA } filtered <- c(filtered, row[x]) } return(filtered) } .getRNameFromName <- function(lkname, existing=NULL) { rname <- gsub("::", "_", lkname) rname <- tolower(chartr(" /", "__", rname)) if (length(existing)>0) { for (i in 1:99) { if(length(existing[rname == existing]) ==0) {break;} else {rname<- c(paste0(rname, i))} } } return (rname) } .parseDate <- function(s) { s <- as.character(s); d <- tryCatch(as.POSIXct(s),error = function(e) NA); t <- format(d, "%H-%M-%S") if (all(t == "00-00-00", na.rm = TRUE)) { d <- as.Date(d, tz = attr (d, which = "tzone")); } return(d); } convertFactorsToStrings <- function(df) { factors <- sapply(df, is.factor) df[factors] <- lapply(df[factors], as.character) return(df); }
f.final.loglike <- function(data, pred, info, type = "EM"){ .prob <- pred/sum(pred) .pos <- f.pos.match(data = data, info = info) .prob <- .prob[.pos] if(type == "full"){ .probsum <- f.groupsum(.prob, data$orig.lines) .probnorm <- .prob/.probsum .loglike <- sum(.probnorm * log(.prob)) } if(type == "EM"){ .prob <- tapply(.prob, data$orig.lines, sum) .loglike <- sum(log(.prob)) } return(.loglike) }
context("comb_SA") test_that("Forward wrong input to EIG1", { expect_error(comb_SA(1)) expect_error(comb_SA("abs")) expect_error(comb_SA(list(a=1, b=2))) expect_error(comb_SA(NULL)) expect_error(comb_SA(NA)) expect_error(comb_SA(Inf)) expect_error(comb_SA(-Inf)) }) test_that("Check for correct class type and accuracy, when only train set is used", { set.seed(5) obs <- rnorm(100) preds <- matrix(rnorm(1000, 1), 100, 10) train_o<-obs[1:80] train_p<-preds[1:80,] data<-foreccomb(train_o, train_p) result<-comb_SA(data) expect_is(result, "foreccomb_res") expect_length(result, 6) expect_equal(as.vector(result$Accuracy_Train), c(-1.002645, 1.434520, 1.190891, 150.254342, 361.450750, 0.125499, 1.034232), tolerance = 1e-5, check.attributes = FALSE) }) test_that( "Check for correct class type and accuracy, when Forecast_Test is provided but not Actual_Test", { set.seed(5) obs <- rnorm(100) preds <- matrix(rnorm(1000, 1), 100, 10) train_o<-obs[1:80] train_p<-preds[1:80,] test_p<-preds[81:100,] data<-foreccomb(train_o, train_p, newpreds = test_p) result<-comb_SA(data) expect_is(result, "foreccomb_res") expect_length(result, 7) expect_equal(as.vector(result$Accuracy_Train), c(-1.002645, 1.434520, 1.190891, 150.254342, 361.450750, 0.125499, 1.034232), tolerance = 1e-5, check.attributes = FALSE) }) test_that( "Check for correct class type and accuracy, when test set is used", { set.seed(5) obs <- rnorm(100) preds <- matrix(rnorm(1000, 1), 100, 10) train_o<-obs[1:80] train_p<-preds[1:80,] test_o<-obs[81:100] test_p<-preds[81:100,] data<-foreccomb(train_o, train_p, test_o, test_p) result<-comb_SA(data) expect_is(result, "foreccomb_res") expect_length(result, 8) expect_equal(as.vector(result$Accuracy_Test), c(-0.919075, 1.354865, 1.093815, 614.620313, 647.850542), tolerance = 1e-5, check.attributes = FALSE) }) test_that( "Check for correct combination, when test set is used with the predict function (simplified)", { set.seed(5) obs <- rnorm(100) preds <- matrix(rnorm(1000, 1), 100, 10) train_o<-obs[1:80] train_p<-preds[1:80,] test_p<-preds[81:100,] data<-foreccomb(train_o, train_p) result<-comb_SA(data) data2<-foreccomb(train_o, train_p, newpreds=test_p) result2<-comb_SA(data2) preds <- predict(result, test_p, simplify = TRUE) expect_equal(as.vector(preds)[1:5], result2$Forecasts_Test[1:5], tolerance = 1e-5, check.attributes = FALSE) }) test_that( "Check for correct combination, when test set is used with the predict function (extend object)", { set.seed(5) obs <- rnorm(100) preds <- matrix(rnorm(1000, 1), 100, 10) train_o<-obs[1:80] train_p<-preds[1:80,] test_p<-preds[81:100,] data<-foreccomb(train_o, train_p) result<-comb_SA(data) data2<-foreccomb(train_o, train_p, newpreds=test_p) result2<-comb_SA(data2) preds <- predict(result, test_p, simplify = FALSE) expect_equal(as.vector(preds$Forecasts_Test)[1:5], result2$Forecasts_Test[1:5], tolerance = 1e-5, check.attributes = FALSE) })
simVARmodel <- function (numT, model, burnin = 0) { varCoef <- model$Coef noiseCov <- model$Sigma dof <- model$dof p <- length(varCoef$A) K <- dim(varCoef$A[[1]])[1] if (is.null(noiseCov)) { noiseCov <- diag(1, K) } else { if ( length(noiseCov) == 1 ) { noiseCov <- diag(noiseCov, K) } } if (is.infinite(dof)) { retTS <- MASS::mvrnorm(p + burnin + numT, rep(0, K), noiseCov) } else { retTS <- mvtnorm::rmvt(p + burnin + numT, df = dof, delta = rep(0, K), sigma = noiseCov) } for (j in (p+1):(p+burnin+numT)) { retTS[j, ] = retTS[j, ] + t(varCoef$c) for (k in 1:p) { retTS[j, ] = retTS[j, ] + retTS[j - k, ] %*% t(varCoef$A[[k]]) } } colnames(retTS) <- paste("y", 1:K, sep = "") return( retTS[(p + burnin + 1):(p + burnin + numT), , drop = FALSE] ) }
plot.csFSSgr <- function (x, plotclust = TRUE, plotscale = TRUE, sollabels=FALSE, ...) { if (plotscale == TRUE) { if (sollabels==FALSE) plot(x$epscale[, 1], x$epscale[, 2], ...) else { plot(x$epscale[, 1], x$epscale[, 2], type="n", ...) text(x$epscale[, 1], x$epscale[, 2], labels=as.character(x$epclust$labels)) } } if (plotclust == TRUE) { plot(x$epclust, ...) } }
context("catalog_apply generic") ctg <- random_2files_250points opt_chunk_size(ctg) <- 151 opt_progress(ctg) <- FALSE test_that("catalog_apply makes strict non-overlaping chunks", { test <- function(cluster) { las <- readLAS(cluster) if (is.empty(las)) return(NULL) return(nrow(las@data)) } req <- catalog_apply(ctg, test) s1 <- do.call(sum, req) s2 <- sum(ctg@data$Number.of.point.records) expect_equal(length(req), 2L) expect_equal(s1, s2) skip_on_cran() test <- function(cluster) { las <- readLAS(cluster) if (is.empty(las)) return(NULL) return(sum(las@data$ReturnNumber == 1)) } req <- catalog_apply(ctg, test) s1 <- do.call(sum, req) s2 <- sum(ctg@data$Number.of.1st.return) expect_equal(length(req), 2L) expect_equal(s1, s2) }) test_that("catalog_apply fixes chunk alignment", { test <- function(cluster, res) { las <- readLAS(cluster) if (is.empty(las)) return(NULL) return(npoints(las)) } res = 8 R0 <- list(381, 119) R1 <- catalog_apply(ctg, test, res = res) option <- list(raster_alignment = res) expect_message(R2 <- catalog_apply(ctg, test, res = res, .options = option), "Chunk size changed to 152") expect_equal(R0, R2) expect_true(!identical(R0, R1)) }) test_that("catalog_apply fixes chunk alignment even by file", { test <- function(cluster, res, align) { las <- readLAS(cluster) if (is.empty(las)) return(NULL) r = grid_metrics(las, ~max(Z), res, align) return(r) } res = 8 sta = c(8,8) opt_chunk_size(ctg) <- 0 las = readLAS(ctg) R0 = grid_metrics(las, ~max(Z), res = res, start = sta) R1 <- catalog_sapply(ctg, test, res = res, align = sta) option <- list(raster_alignment = list(res = res, start = sta)) R2 <- catalog_sapply(ctg, test, res = res, align = sta, .options = option) expect_equal(R0, R2) expect_true(!identical(R0[], R1[])) }) test_that("catalog_apply generates errors if function does not return NULL for empty chunks", { test <- function(cluster) { las <- readLAS(cluster) return(0) } expect_error(catalog_apply(ctg, test), "not return NULL for empty chunks") }) test_that("catalog_apply use alternative directories", { skip_on_cran() test <- function(cluster) { las <- readLAS(cluster) if (is.empty(las)) return(NULL) return(0) } realdir <- paste0(dirname(ctg$filename[1]), "/") falsedir <- "/home/user/data/" ctg@data$filename <- paste0(falsedir,basename(ctg$filename)) expect_error(catalog_apply(ctg, test)) ctg@input_options$alt_dir = c(falsedir,realdir) expect_error(catalog_apply(ctg, test), NA) }) test_that("catalog_apply return a partial ouptut and generates logs", { test <- function(cluster) { if (raster::extent(cluster)@ymin > 80) stop("Test error") return(data.frame(X = 1:3)) } opt_chunk_size(ctg) <- 0 opt_wall_to_wall(ctg) <- FALSE option <- list(automerge = TRUE) expect_message(req1 <- catalog_apply(ctg, test), "chunk2.rds") expect_message(req2 <- catalog_apply(ctg, test, .options = option), "Test error") expect_is(req1, "list") expect_equal(length(req1), 1L) expect_is(req2, "data.frame") expect_equal(nrow(req2), 3L) }) test_that("catalog_apply can bypass errors", { test <- function(cluster) { if (raster::extent(cluster)@ymin > 80) stop("Test error") return(data.frame(X = 1:3)) } opt_chunk_size(ctg) <- 0 opt_wall_to_wall(ctg) <- FALSE opt_stop_early(ctg) <- FALSE expect_message(catalog_apply(ctg, test), NA) }) test_that("User get a warning/error when using ORIGINALFILENAME", { expect_message({opt_output_files(ctg) <- "{*}"}, "makes sense only when processing by file") expect_message({opt_output_files(ctg) <- "{ID}"}, NA) }) test_that("User get throw error if function does not return NULL for empty chun", { test <- function(cluster) { las <- readLAS(cluster) return(nrow(las@data)) } test2 <- function(cluster) { stop("dummy error", call. = FALSE) } expect_error(catalog_apply(ctg, test), "User's function does not return NULL") expect_error(catalog_apply(ctg, test2), "dummy error") })
acf2incr <- function(acf) { N <- length(acf)-1 if(N == 1) { iacf <- 2*(acf[1]-acf[2]) } else { iacf <- 2*acf[1:N] - acf[1:N+1] - acf[c(2, 1:(N-1))] } iacf }
smape <- function(data, ...) { UseMethod("smape") } smape <- new_numeric_metric( smape, direction = "minimize" ) smape.data.frame <- function(data, truth, estimate, na_rm = TRUE, ...) { metric_summarizer( metric_nm = "smape", metric_fn = smape_vec, data = data, truth = !!enquo(truth), estimate = !!enquo(estimate), na_rm = na_rm ) } smape_vec <- function(truth, estimate, na_rm = TRUE, ...) { smape_impl <- function(truth, estimate) { percent_scale <- 100 numer <- abs(estimate - truth) denom <- (abs(truth) + abs(estimate)) / 2 mean(numer / denom) * percent_scale } metric_vec_template( metric_impl = smape_impl, truth = truth, estimate = estimate, na_rm = na_rm, cls = "numeric" ) }
HKSPOR <- function(X,Y,deg,K,constraint=1,EM=TRUE,TimeTrans_Prop=c(),plotG=TRUE){ if( (length(which(is.na(X))) != 0)){ Y = Y[-which(is.na(X))] X = X[-which(is.na(X))] warning("X contains missing data, these data have been deleted") } if( (length(which(is.na(Y))) != 0)){ X = X[-which(is.na(Y))] Y = Y[-which(is.na(Y))] warning("Y contains missing data, these data have been deleted") } if(length(which(X != X[order(X)])) > 0){ Y = Y[order(X)] X = X[order(X)] warning("X has been ordered") } if(length(X) != length(unique(X))){ duble_value = unique(X[which(duplicated(X)==TRUE)]) for(i in 1:length(duble_value)){ new_y = sum(Y[which(X == duble_value[i])])/length(which(X == duble_value[i])) Y[which(X == duble_value[i])[1]] = new_y Y = Y[-which(X == duble_value[i])[2:length(which(X == duble_value[i]))]] X = X[-which(X == duble_value[i])[2:length(which(X == duble_value[i]))]] warning("Duplicate data of X have been delated. Y becames the mean of these data") } } if(length(X) < K*(deg+2) + K){ warning(paste("X must contain at least",K*(deg+2)+K,"observations to use this degree and this number of regimes")) deg = floor((length(X)-(3*K))/K) if(deg <= 0){ deg = 1 K = floor(length(X)/(deg+3)) warning(paste("The degree was reduced to 1 and the number of regimes to",K)) } warning(paste("The degree was reduced to", deg)) } if(length(X) < 3*K + K ){ stop(paste("X must contain at least", 3*K + K, "observations for a degree equal to 1 and a number", K, "of regime")) } if(K == 1){ nameMat = c() for(i in 1:(deg+1)){ if((deg-i+1) == 0){ nameMat = c(nameMat,"1") }else{ nameMat = c(nameMat,paste("X^",(deg-i+1),sep="")) } } mat_param_i <- matrix(0,1,(deg+1),dimnames = list(c(),nameMat)) sigma2_i <- matrix(0,1,1) VT_opt <- c() obs_table <- data.frame() for(i in 1:deg){ obs_table <- as.data.frame(t(rbind.data.frame(t(obs_table),X^i))) } lmR <- lm(Y ~ ., data = obs_table) mat_param_i[1,] <- rev(lmR$coefficients) sigma2_i[,1] <- sum((lmR$residuals)^2)/(length(Y)-(deg+1)) sortie <- cbind.data.frame(data.frame("TimeT" = c(X[1])),mat_param_i,"sigma2" = t(sigma2_i),row.names=c("1")) }else{ if(length(X) >= ((deg+2)*K)){ if(length(TimeTrans_Prop) == (K-1)){ VT_opt <- TimeTrans_Prop }else{ grid_TT <- .TimeT_grid_K_SPOR(X,deg,K) T_estimation <- .TimeT_estimation_K_SPOR(X,Y,deg,grid_TT,1,K,constraint,EM) VT_opt <- T_estimation$resFi[2:length(T_estimation$resFi)] } res_optim <- .Optimization_K_SPOR(X,Y,deg,VT_opt[order(VT_opt)],EM,constraint) mat_param <- res_optim[[1]] sigma2 <- res_optim[[2]] sortie <- cbind.data.frame(data.frame("TimeT" = c(X[1],VT_opt[order(VT_opt)])),mat_param,"sigma2" = t(sigma2),row.names=as.factor(c(1:(length(VT_opt)+1)))) }else{ warning(paste("For K =", K, "X must have almost a size equal to",(deg+2)*K , sep=" ")) sortie <- c() } } if((plotG == TRUE) && (length(sortie)!=0)){ nameMat = c() for(i in 1:(deg+1)){ if((deg-i+1) == 0){ nameMat = c(nameMat,"1") }else{ nameMat = c(nameMat,paste("X^",(deg-i+1),sep="")) } } plot(X,Y,pch=20,cex.main = 3, cex.lab = 2,cex.axis = 2) if(length(sortie$TimeT) == 1){ pred_y = 0 for(l in 1 :length(nameMat)){ pred_y = pred_y + sortie[1,which(names(sortie)==nameMat[l])]*seq(X[1],X[length(X)],length.out = min(10,length(X)))^(deg-l+1) } lines(seq(X[1],X[length(X)],length.out = min(10,length(X))),pred_y, lwd=3.5,lty=3) }else{ abline(v=c(sortie$TimeT[-1]),lwd=3.5,lty=3) Tt = sortie$TimeT[-1] for(i in 1 : length(sortie$TimeT)){ if(i == 1){ pred_y = 0 for(l in 1 :length(nameMat)){ pred_y = pred_y + sortie[i,which(names(sortie)==nameMat[l])]*seq(X[1],Tt[i],length.out = min(10,length(X[which(X <= Tt[i])])))^(deg-l+1) } lines(seq(X[1],Tt[i],length.out = min(10,length(X[which(X <= Tt[i])]))), pred_y, lwd=3.5,lty=3) }else if(i == length(sortie$TimeT)){ pred_y = 0 for(l in 1 :length(nameMat)){ pred_y = pred_y + sortie[i,which(names(sortie)==nameMat[l])]*seq(Tt[i-1],X[length(X)],length.out = min(10,length(X[which(X >= Tt[i-1])])))^(deg-l+1) } lines(seq(Tt[i-1],X[length(X)],length.out = min(10,length(X[which(X >= Tt[i-1])]))),pred_y, lwd=3.5,lty=3) }else{ pred_y = 0 for(l in 1 :length(nameMat)){ pred_y = pred_y + sortie[i,which(names(sortie)==nameMat[l])]*seq(Tt[i-1],Tt[i],length.out = min(10,length(X[which( (X >= Tt[i-1]) & (X <= Tt[i]))])))^(deg-l+1) } lines(seq(Tt[i-1],Tt[i],length.out = min(10,length(X[which( (X >= Tt[i-1]) & (X <= Tt[i]))]))),pred_y, lwd=3.5,lty=3) } } } } return(sortie) }
ec.EG1 <- function(det1,det2,ymat,npl,befpn,ndet,drop1=NA,drop2=NA){ n<-npl[1];p<-npl[2];nlag<-npl[3] begtrim <- befpn[1]; endtrim <- befpn[2] nforecast<-befpn[3]; npred<-befpn[4] twoqp1 <-ncol(det1); qp1<-twoqp1/2; q <-qp1-1 ntot <-nrow(det1); twop <-2*p; pp1<-p+1 boodet2<-anyNA(det2) longdata <- as.matrix(ymat); if(dim(longdata)[1]!=n){cat("wrong number of lines in ymat")} ndet1<-ndet[1]; ndet2<-ndet[2]; mynames<-colnames(longdata[,pp1:twop]) ylev<-longdata[,pp1:twop] yEG <- ylev[,1,drop=FALSE] if(ndet1==1){ivec <- (1:qp1)} if(ndet1==2){ivec <- (1:(2*qp1))} if(anyNA(drop1)==F){ivec <-ivec[-drop1]} if(ndet1==0){xEG <- as.matrix(ylev[,-1,drop=FALSE]) ivec<-NA}else{ xEG <- cbind(ylev[,-1,drop=FALSE],det1[1:n,ivec])} init <- max(begtrim,nlag,2) estsample <- (init+1):(n-endtrim) yEGest <- yEG[estsample] xEGest <- xEG[estsample,] outEG <- mls(yEGest,xEGest) afEG <- cbind(yEGest,outEG$fit) vEG1step <- as.matrix(outEG$coeffs) colnames(afEG)[2] <- paste0("fit EG1stage") colnames(vEG1step) <- paste0("EG1st eq. ",colnames(yEG),sep="") ibeta<-1:(p-1); beta <- matrix(c(1,-vEG1step[ibeta])) longafEG <- cbind(yEG,xEG%*%vEG1step) colnames(longafEG)[2] <- paste0("f+f EG1stage") if(anyNA(ivec)==T){betad<-NA}else{ betad<-matrix(0,(twoqp1),1); betad[ivec]<--vEG1step[-ibeta] rownames(betad)<-colnames(det1)} ecmlong <- as.matrix(yEG-xEG%*%vEG1step) colnames(ecmlong)<-"ecm_1"; Dy <- as.matrix(longdata[estsample,1:p]) eqnames <- paste("eq",colnames(Dy),sep=". ") colnames(Dy) <- eqnames rwsigma <- (colMeans(Dy^2))^.5 rwabsmean <- colMeans(abs(Dy)) xreg <- as.matrix(ecmlong[estsample]) colnames(xreg)<-"ecm_1" if(nlag>1){xreg<-cbind(xreg,longdata[estsample,(twop+1):((nlag+1)*p)])} iposini<- (p*(nlag-1))+1; if(ndet2==0){ivec2 <- NA; iseldet12<-iposini}else{ if(ndet2==1){ivec2 <- (1:qp1)} if(ndet2==2){ivec2 <- (1:(2*qp1))} if(anyNA(drop2)==F){ivec2 <-ivec2[-drop2]} xreg<-cbind(xreg,det1[estsample,ivec2]) iseldet12<-iposini+ivec2 colnames(xreg)[((nlag-1)*p+1+ivec2)]<-colnames(det1)[ivec2] } if(boodet2==F){xreg<-cbind(xreg,det2[estsample,]) det2col <-ncol(det2)} outEC <- mls(Dy,xreg) acoef <- t(outEC$coeffs) wald <- Wald.mls(outEC) DafEG2<-cbind(Dy,outEC$fit) if(nlag>1){mPhi <- acoef[,2:iposini] }else{mPhi<-matrix(0,p,p)} alpha <- acoef[,1,drop=FALSE] zeta<-matrix(0,p,(twoqp1)) colnames(zeta)<-colnames(det1) rownames(zeta)<-rownames(acoef) xi<-zeta; if(anyNA(ivec2)==F){zeta[,ivec2]<-acoef[,iseldet12]} if(ndet1==0&&ndet2!=0){xi<-zeta} if(ndet1!=0&&ndet2==0){xi<-alpha%*%t(betad)} if(ndet1!=0&&ndet2!=0){xi<-alpha%*%t(betad)+zeta} if(boodet2==T){nu<-NA}else{ nu<-acoef[,((iseldet12[length(iseldet12)]+1):ncol(acoef))]} out <-list(); out$ndet <- ndet; out$det1names<-colnames(det1) out$det2names<-colnames(det2); out$drop1<-drop1 out$drop2 <- drop2; out$estsample <- estsample out$npl<-npl; out$befpn<-befpn out$beta <- beta; out$betad <- betad out$vEG1step <- vEG1step out$afEG <- afEG; out$longafEG <- longafEG out$ecm <- ecmlong out$alpha <- alpha; out$mPhi <- mPhi; out$mPi <- alpha %*% t(beta) out$acoef <- acoef; out$acoef_se <- t(outEC$semat) out$acoef_t <- t(outEC$tmat) out$acoef_pval <- t(outEC$pmat) out$res <- outEC$residuals;out$DafEG2 <- DafEG2 out$Omega <- outEC$Omega out$nu <-nu; out$zeta<-zeta; out$xi<-xi out$wald<-wald; out$rwsigma <- rwsigma out$rwabsmean <- rwabsmean out$EG1 <- outEG; out$EG2 <- outEC return(out) }
js <- '{"type":"Feature","properties":{"id":1.0},"geometry":null}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_POINT") js2 <- sf_geojson(sf, atomise = T) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[1, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"Point","coordinates":[0.0,0.0]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_POINT") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"MultiPoint","coordinates":[[0.0,0.0],[1.0,1.0]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_MULTIPOINT") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"LineString","coordinates":[[0.0,0.0],[1.0,1.0]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_LINESTRING") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"MultiLineString","coordinates":[[[0.0,0.0],[1.0,1.0]]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_MULTILINESTRING") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":2.0},"geometry":null}, {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"Polygon","coordinates":[[[0.0,0.0],[1.0,1.0],[2.0,2.0],[0.0,0.0]]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 2) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_GEOMETRY") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[1, 'geometry'] == "POINT EMPTY") expect_true(wkt[3, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"MultiPolygon","coordinates":[[[[0.0,0.0],[1.0,1.0],[2.0,2.0],[0.0,0.0]]]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) expect_true(attr(sf$geometry, "n_empty") == 1) expect_true(attributes(sf$geometry)[['class']][1] == "sfc_MULTIPOLYGON") js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"GeometryCollection","geometries": [ {"type": "Point","coordinates": [100.0,0.0]}, {"type": "LineString","coordinates": [[101.0,0.0],[102.0,1.0]]}]}}, {"type":"Feature","properties":{"id":2.0},"geometry":null}]}' sf <- geojson_sf(js) wkt <- geojson_wkt(js) expect_true(wkt[2, 'geometry'] == "POINT EMPTY") expect_true(attr(sf$geometry, "n_empty") == 1) js2 <- sf_geojson(sf) expect_true(jsonify::validate_json(js2)) expect_true(gsub(" |\\r|\\n|\\t","",js) == js2) js <- '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":1.0},"geometry":{"type":"GeometryCollection","geometries": [{"type": null},{"type": "LineString","coordinates": [[101.0,0.0],[102.0,1.0]]}]}}]}' expect_error(geojson_sf(js), "No 'type' member at object index 0 - invalid GeoJSON") expect_error(geojson_wkt(js), "No 'type' member at object index 0 - invalid GeoJSON") sf <- structure(list(geometry = structure(list(structure(list(structure(c(0, 0), class = c("XY", "POINT", "sfg")), structure(c(1, 2, 3, 4), .Dim = c(2L, 2L), class = c("XY", "LINESTRING", "sfg")), structure(c(NA_real_, NA_real_), class = c("XY", "POINT", "sfg")), structure(list(), class = c("XY", "MULTIPOLYGON", "sfg"))), class = c("XY", "GEOMETRYCOLLECTION", "sfg"))), class = c("sfc_GEOMETRYCOLLECTION", "sfc"), precision = 0, bbox = structure(c(xmin = 0, ymin = 0, xmax = 2, ymax = 4), class = "bbox"), crs = structure(list( epsg = NA_integer_, proj4string = NA_character_), class = "crs"), n_empty = 0L)), row.names = 1L, class = c("sf", "data.frame"), sf_column = "geometry", agr = structure(integer(0), class = "factor", .Label = c("constant", "aggregate", "identity"), .Names = character(0))) js <- sf_geojson(sf) expect_true(jsonify::validate_json(js)) expect_false(grepl("null", js)) js <- '{"type":"Feature","properties":{},"geometry":null}' sf <- geojson_sf( js ) js2 <- sf_geojson( sf, simplify = F ) expect_true(jsonify::validate_json(js2)) js <- '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":null}]}' sf <- geojson_sf( js ) js2 <- sf_geojson( sf, simplify = T ) expect_true(jsonify::validate_json(js2)) js2 <- sf_geojson( sf, simplify = F ) expect_true(js2 == js) expect_true(jsonify::validate_json(js2)) sf <- structure(list(geometry = structure(list(structure(c(NA_real_, NA_real_), class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = NA_real_, ymin = NA_real_, xmax = NA_real_, ymax = NA_real_), crs = structure(list(epsg = NA_integer_, proj4string = NA_character_), class = "crs"), class = "bbox"), crs = structure(list( epsg = NA_integer_, proj4string = NA_character_), class = "crs"), n_empty = 1L)), row.names = 1L, class = c("sf", "data.frame"), sf_column = "geometry", agr = structure(integer(0), class = "factor", .Label = c("constant", "aggregate", "identity"), .Names = character(0))) expect_equal( as.character(sf_geojson( sf )), "null") js <- sf_geojson( sf , simplify = FALSE ) expect_true( jsonify::validate_json( js ) ) expect_true(grepl("null",js))
"pmcode_91113"
print.DS_FB_obj <- function(x, ...){ cat(paste0("\tPosterior Mean = ",round(x$post.vec[2],4), "\n")) cat(paste0("\tPosterior Mode = ",round(x$post.vec[4],4), "\n")) cat(paste0("\tLower Bound Credible Interval = ",round(x$interval[1],4), "\n")) cat(paste0("\tUpper Bound Credible Interval = ",round(x$interval[2],4), "\n")) cat(paste0("Use plot(x) to generate finite Bayes plot\n")) }
marx <- function(y,x,p_max,sig_level,p_C,p_NC){ if (is.null(x)){ x <- "not" } print(match.call()) nargin <- length(as.list(match.call())) -1 if (nargin == 4){ p = 1 } else{ p = 0 } if (p == 1){ selection.lag(y,x,p_max) p_pseudo <- readline(prompt = "Choose lag order for pseudo causal model: ") p_pseudo <- as.numeric(p_pseudo) pseudo <- arx.ls(y,x,p_pseudo) Cov_pseudo <- pseudo[[4]] U_pseudo <- pseudo[[5]] test_cdf_pseudo <- cbind(U_pseudo, stats::pnorm(U_pseudo,0,Cov_pseudo)) kstest_results <- stats::ks.test(test_cdf_pseudo[,1],"pnorm",0,Cov_pseudo) jarquebera <- tseries::jarque.bera.test(U_pseudo) if (kstest_results$p.value < 0.05){ hh_pseudo = 1 } else{ hh_pseudo = 0 } if (jarquebera$p.value < 0.05){ jarque_check = 1 } else{ jarque_check = 0 } if (hh_pseudo == 0){ cat(' ', "\n") cat(' ', "\n") cat('THE KS-TEST FAILS TO REJECT THE NULL OF NORMALLY DISTRIBUTED RESIDUALS OF THE PURELY CAUSAL ARX MODEL', "\n") cat('p-value:') cat(kstest_results$p.value, "\n") cat('WARNING: MIxED ARX MODEL MIGHT NOT BE IDENTIFIABLE!', "\n") cat(' ', "\n") cat(' ', "\n") } else{ cat(' ', "\n") cat(' ', "\n") cat('THE KS-TEST REJECTS THE NULL OF NORMALLY DISTRIBUTED RESIDUALS OF THE PURELY CAUSAL ARX MODEL', "\n") cat('p-value:') cat(kstest_results$p.value, "\n") cat(' ', "\n") cat(' ', "\n") } if (jarque_check == 0){ cat(' ', "\n") cat(' ', "\n") cat('THE JB-TEST FAILS TO REJECT THE NULL OF NORMALLY DISTRIBUTED RESIDUALS OF THE PURELY CAUSAL ARX MODEL', "\n") cat('p-value:') cat(jarquebera$p.value, "\n") cat('WARNING: MIxED ARX MODEL MIGHT NOT BE IDENTIFIABLE!', "\n") cat(' ', "\n") cat(' ', "\n") } else{ cat(' ', "\n") cat(' ', "\n") cat('THE JB-TEST REJECTS THE NULL OF NORMALLY DISTRIBUTED RESIDUALS OF THE PURELY CAUSAL ARX MODEL', "\n") cat('p-value:') cat(jarquebera$p.value, "\n") cat(' ', "\n") cat(' ', "\n") } stats::qqnorm(U_pseudo, main="Normal Probability Plot of Residuals") stats::qqline(U_pseudo) selection.lag.lead_results <- selection.lag.lead(y,x,p_pseudo) p_C <- selection.lag.lead_results[[1]] p_NC <- selection.lag.lead_results[[2]] } marx.t_results <- marx.t(y,x,p_C,p_NC); B_C <- marx.t_results[[1]] B_NC <- marx.t_results[[2]] B_x <- marx.t_results[[3]] IC <- marx.t_results[[4]] sig <- marx.t_results[[5]] df <- marx.t_results[[6]] inference_results <- inference(y,x,B_C,B_NC,B_x,IC,sig,df,sig_level) BC <- inference_results[[1]] BNC <- inference_results[[2]] Bx <- inference_results[[3]] ICC <- inference_results[[4]] std_c <- inference_results[[5]] std_nc <- inference_results[[6]] std_x <- inference_results[[7]] std_ic <- inference_results[[8]] cat(' ', "\n") cat(' ', "\n") cat('Estimated Causal Parameters: ', "\n") print(B_C) cat(' ', "\n") cat('Corresponding Standard Errors: ', "\n") print(std_c) cat(' ', "\n") cat('Corresponding Confidence Intervals: ', "\n") print(BC) cat(' ', "\n") cat(' ', "\n") cat('Estimated Noncausal Parameters: ', "\n") print(B_NC) cat(' ', "\n") cat('Corresponding Standard Errors: ', "\n") print(std_nc) cat(' ', "\n") cat('Corresponding Confidence Intervals: ', "\n") print(BNC) cat(' ', "\n") cat(' ', "\n") cat('Estimated Parameters Exogenous Variables: ', "\n") print(B_x) cat(' ', "\n") cat('Corresponding Standard Errors: ', "\n") print(std_x) cat(' ', "\n") cat('Corresponding Confidence Intervals: ', "\n") print(Bx) cat(' ', "\n") cat(' ', "\n") cat('Estimated Intercept: ', "\n") print(IC) cat(' ', "\n") cat('Corresponding Standard Errors: ', "\n") print(std_ic) cat(' ', "\n") cat('Corresponding Confidence Intervals: ', "\n") print(ICC) cat(' ', "\n") cat(' ', "\n") cat('Estimated Distributional Parameters (df,sig): ', "\n") print(c(df,sig)) cat(' ', "\n") cat(' ', "\n") } regressor.matrix <- function(y,x,p){ if (is.null(x)){ x <- "not" } y <- fBasics::vec(y) n <- length(y) if (p==1){ k <-1 } else{ k <- NCOL(y) } if (p > 0){ Z <- matlab::zeros(n,k*p) for (i in 1:p){ Z[(1+i):n,((i-1)*k+1):(i*k)] <- y[1:(n-i)] } Z <- Z[(1+p):n,] } else{ Z <- matrix(,nrow=n,ncol=0) } if (x == "not" && length(x) == 1){ Z <- Z } if (NCOL(x) == 1 && x != "not"){ Z <- cbind(Z,x[(1+p):n]) } else if (NCOL(x) > 1 && x != "not"){ Z <- cbind(Z,x[(1+p):n,]) } return(matrix = Z) } arx.ls <- function(y,x,p){ if (is.null(x)){ x <- "not" } n <- length(y) - p Y <- y[(p+1):length(y)] int <- rep(1,(length(y)-p)) Z <- regressor.matrix(y,x,p) Z <- cbind(int,Z) df <- nrow(Z) - NCOL(Z) B <- solve(t(Z) %*% Z) %*% (t(Z) %*% Y) if (p > 0){ if (length(x) > 1){ rownames(B) <- c('int', paste('lag', 1:p), paste('exo', 1:NCOL(x))) } else{ rownames(B) <- c('int', paste('lag', 1:p)) } } else{ if (length(x) > 1){ rownames(B) <- c('int', paste('exo', 1:NCOL(x))) } else{ rownames(B) <- 'int' } } FV <- Z %*% B U <- Y - FV sig <- (t(U) %*% U) sig <- as.numeric(sig) Cov <- (1/n)*sig Cov <- as.numeric(Cov) sigma2 <- sum((Y - Z %*% B)^2)/df qz <- qr(Z) vcov <- sigma2*chol2inv(qz$qr) colnames(vcov) <- rownames(vcov) <- colnames(Z) Loglik <- -(n/2)*(1 + log(2*pi)+log(Cov)) if (p == 0){ B_auto <- 0 } else{ B_auto <- B[2:(p+1)] } if (length(x) > 1){ B_x <- B[(p+2):length(B)] } else{ B_x <- 0 } return(list(coefficients = B, coef.auto = B_auto, coef.exo = B_x, mse = Cov, residuals = U, loglikelihood = Loglik, fitted.values = FV, df = df,vcov=vcov)) } marx.t <- function(y,x,p_C,p_NC,params0){ nargin <- length(as.list(match.call())) - 1 if (is.null(x)){ x <- "not" } if (length(x) == 1){ numcol <- 0 } else{ numcol <- NCOL(x) } if(numcol > 1){ x.rev <- matrix(data=NA,nrow=length(x[,1]),ncol=numcol) for (i in 1:numcol){ x.rev[,i] <- rev(x[,i]) } } else{ x.rev <- matrix(data=NA,nrow=length(x),ncol=numcol) x.rev <- rev(x) } if (nargin < 5){ y <- fBasics::vec(y) z <- rev(y) z <- fBasics::vec(z) BC0 <- arx.ls(y,x,p_C)[[2]] Bx0 <- arx.ls(y,x,p_C)[[3]] BNC0 <- arx.ls(z,x.rev,p_NC)[[2]] IC0 <- 0 df0 <- 20 sig0 <- 2 BC0 <- fBasics::vec(BC0) BNC0 <- fBasics::vec(BNC0) Bx0 <- fBasics::vec(Bx0) if (length(x) > 1){ if (p_C > 0 && p_NC > 0){ params0 <- rbind(BC0,BNC0,Bx0,IC0,sig0,df0) } else if (p_NC > 0 && p_C == 0){ params0 <- rbind(BNC0,Bx0,IC0,sig0,df0) } else if (p_C > 0 && p_NC == 0){ params0 <- rbind(BC0,Bx0,IC0,sig0,df0) } else if (p_C == 0 && p_NC == 0){ params0 <- rbind(Bx0,IC0,sig0,df0) } } else{ if (p_C > 0 && p_NC > 0){ params0 <- rbind(BC0,BNC0,IC0,sig0,df0) } else if (p_NC > 0 && p_C == 0){ params0 <- rbind(BNC0,IC0,sig0,df0) } else if (p_C > 0 && p_NC == 0){ params0 <- rbind(BC0,IC0,sig0,df0) } else if (p_C == 0 && p_NC == 0){ params0 <- rbind(IC0,sig0,df0) } } } optimization_results <- stats::optim(params0,ll.max,gr=NULL,y=fBasics::vec(y),p_C=p_C,p_NC=p_NC,x=x,method="BFGS",hessian=TRUE) PARAMS <- optimization_results$par if (length(x) > 1){ numcol <- NCOL(x) if (p_C > 0 && p_NC > 0){ B_C <- PARAMS[1:p_C] B_NC <- PARAMS[(p_C+1):(p_C + p_NC)] B_x <- PARAMS[(p_C + p_NC + 1):(p_C + p_NC + numcol)] IC <- PARAMS[(p_C + p_NC + numcol + 1)] sig <- PARAMS[(p_C + p_NC + numcol + 2)] df <- PARAMS[(p_C + p_NC + numcol + 3)] } else if (p_NC > 0 && p_C == 0){ B_C <- 0 B_NC <- PARAMS[1:p_NC] B_x <- PARAMS[(p_NC + 1):(p_NC + numcol)] IC <- PARAMS[(p_NC + numcol + 1)] sig <- PARAMS[(p_NC + numcol + 2)] df <- PARAMS[(p_NC + numcol + 3)] } else if (p_C > 0 && p_NC == 0){ B_NC <- 0 B_C <- PARAMS[1:p_C] B_x <- PARAMS[(p_C + 1):(p_C + numcol)] IC <- PARAMS[(p_C + numcol + 1)] sig <- PARAMS[(p_C + numcol + 2)] df <- PARAMS[(p_C + numcol + 3)] } else if (p_C == 0 && p_NC == 0){ B_NC <- 0 B_C <- 0 B_x <- PARAMS[(p_C + 3):(p_C + 2 + numcol)] IC <- PARAMS[(p_C + numcol + 3)] sig <- PARAMS[(p_C + numcol + 4)] df <- PARAMS[(p_C + numcol + 5)] } } else{ numcol <- 0 B_x <- 0 if (p_C > 0 && p_NC > 0){ B_C <- PARAMS[1:p_C] B_NC <- PARAMS[(p_C+1):(p_C + p_NC)] IC <- PARAMS[(p_C + p_NC + 1)] sig <- PARAMS[(p_C + p_NC + 2)] df <- PARAMS[(p_C + p_NC + 3)] } else if (p_NC > 0 && p_C == 0){ B_C <- 0 B_NC <- PARAMS[1:p_NC] IC <- PARAMS[(p_NC + 1)] sig <- PARAMS[(p_NC + 2)] df <- PARAMS[(p_NC + 3)] } else if (p_C > 0 && p_NC == 0){ B_NC <- 0 B_C <- PARAMS[1:p_C] IC <- PARAMS[(p_C + 1)] sig <- PARAMS[(p_C + 2)] df <- PARAMS[(p_C + 3)] } else if (p_C == 0 && p_NC == 0){ B_NC <- 0 B_C <- 0 IC <- PARAMS[1] sig <- PARAMS[2] df <- PARAMS[3] } } ZC1 <- y[(p_C+1):length(y)] ZC1 <- fBasics::vec(ZC1) ZC2 <- regressor.matrix(y,"not",p_C) if (p_C == 1){ ZC2 <- fBasics::vec(ZC2) } if (p_C > 0){ V <- ZC1 - ZC2 %*% B_C } else{ V <- ZC1 } U <- rev(V) U <- fBasics::vec(U) ZNC1 <- U[(p_NC + 1):length(U)] ZNC1 <- fBasics::vec(ZNC1) ZNC2 <- regressor.matrix(U,"not",p_NC) if(numcol > 1){ for (i in 1:numcol){ x[,i] <- rev(x[,i]) } } else{ x <- rev(x) } if(length(x) > 1){ if (numcol > 1 ){ x <- x[(p_NC +1):length(U),] } else{ x <- x[(p_NC +1):length(U)] x <- fBasics::vec(x) } } else{ x <- "not" } if (p_NC == 1){ ZNC2 <- fBasics::vec(ZNC2) } if (length(x) > 1){ if (p_NC > 0){ E <- rev(ZNC1 - (ZNC2 %*% B_NC) - IC - (x %*% B_x)) } else{ E <- rev(ZNC1 - IC - (x %*% B_x)) } } else{ if (p_NC > 0){ E <- rev(ZNC1 - (ZNC2 %*% B_NC) - IC) } else{ E <- rev(ZNC1 - IC) } } se <- sqrt(diag(solve(optimization_results$hessian))) se.dist <- se[(length(se)-1):length(se)] se.dist <- rev(se.dist) return(list(coef.c = B_C, coef.nc = B_NC, coef.exo = B_x, coef.int = IC, scale = sig,df = df,residuals = E, se.dist = se.dist)) } inference <- function(y,x,B_C,B_NC,B_x,IC,sig,df,sig_level){ if (is.null(x)){ x <- "not" } p_C = length(B_C) p_NC = length(B_NC) p_x = length(B_x) if (length(B_C) == 1 && B_C == 0){ p_C = 0 } if (length(B_NC) == 1 && B_NC == 0){ p_NC = 0 } obser = length(y) - p_C - p_NC regressor_C <- regressor.matrix(y,"not",p_C) regressand_C <- fBasics::vec(y[(p_C+1):length(y)]) if (p_C == 1){ regressor_C <- fBasics::vec(regressor_C) } regressor_NC <- regressor.matrix(fBasics::vec(rev(y)),"not",p_NC) if (p_NC > 1){ for(i in 1:NCOL(regressor_NC)){ regressor_NC[,i] <- fBasics::vec(rev(regressor_NC[,i])) } } if (p_NC == 1){ regressor_NC <- fBasics::vec(rev(fBasics::vec(regressor_NC))) } regressand_NC <- fBasics::vec(y[1:(length(y)-p_NC)]) if (p_C > 0){ if (p_NC > 0){ U <- regressand_NC - regressor_NC %*% B_NC } else{ U <- regressand_NC } U_regressor_C <- regressor.matrix(U,"not",p_C) Gam_C <- (t(U_regressor_C) %*% U_regressor_C)/obser Cov_C <- (df+3)/(df+1)*sig^2*solve(Gam_C) std_c <- matrix(data=NA,nrow=length(Cov_C[,1]), ncol=1) BC <- matrix(data=NA,nrow=length(Cov_C[,1]), ncol=2) for(i in 1:length(Cov_C[,1])){ std_c[i] = sqrt(Cov_C[i,i]/obser) BC[i,] = c((B_C[i] - stats::qnorm(1-(sig_level/2))*std_c[i]),(B_C[i] + stats::qnorm(1-(sig_level/2))*std_c[i])) } } else if (p_C == 0){ BC = 0 std_c = 0 } if (p_NC > 0){ if (p_C > 0){ V <- regressand_C - regressor_C %*% B_C } else{ V <- regressand_C } V_regressor_NC <- regressor.matrix(fBasics::vec(rev(V)),"not",p_NC) if (p_NC > 1){ for(i in 1:NCOL(V_regressor_NC)){ V_regressor_NC[,i] <- fBasics::vec(rev(V_regressor_NC[,i])) } } if (p_NC == 1){ V_regressor_NC <- fBasics::vec(rev(fBasics::vec(V_regressor_NC))) } Gam_NC <- (1/obser)* (t(V_regressor_NC) %*% V_regressor_NC) Cov_NC <- (df+3)/(df+1)*sig^2*solve(Gam_NC) std_nc <- matrix(data=NA,nrow=length(Cov_NC[,1]), ncol=1) BNC <- matrix(data=NA,nrow=length(Cov_NC[,1]), ncol=2) for(i in 1:length(Cov_NC[,1])){ std_nc[i] = sqrt(Cov_NC[i,i]/obser) BNC[i,] = c((B_NC[i] - stats::qnorm(1-(sig_level/2))*std_nc[i]),(B_NC[i] + stats::qnorm(1-(sig_level/2))*std_nc[i])) } } else if (p_NC == 0){ BNC = 0 std_nc = 0 } Cov_IC <- (df+3)/(df+1)*sig^2 std_ic <- sqrt(Cov_IC/obser) BIC <- c((IC - stats::qnorm(1-(sig_level/2))*std_ic),(IC + stats::qnorm(1-(sig_level/2))*std_ic)) if (length(x) > 1){ Gam_x <- (1/obser) * (t(x) %*% x) Cov_x <- (df+3)/(df+1)*sig^2*solve(Gam_x) std_x <- matrix(data=NA,nrow=length(Cov_x[,1]), ncol=1) Bx <- matrix(data=NA,nrow=length(Cov_x[,1]), ncol=2) for(i in 1:length(Cov_x[,1])){ std_x[i] = sqrt(Cov_x[i,i]/obser) Bx[i,] = c((B_x[i] - stats::qnorm(1-(sig_level/2))*std_x[i]),(B_x[i] + stats::qnorm(1-(sig_level/2))*std_x[i])) } } else{ Bx <- 0 std_x <- 0 } return(list(CI.c = BC, CI.nc = BNC, CI.exo = Bx, CI.int = BIC, se.c = std_c, se.nc = std_nc, se.exo = std_x, se.int = std_ic)) } ll.max <- function(params,y,x,p_C,p_NC){ if (is.null(x)){ x <- "not" } y <- fBasics::vec(y) if (length(x) > 1){ colnum <- NCOL(x) if (p_C > 0 && p_NC > 0){ BC1 <- params[1:p_C] BNC1 <- params[(p_C+1):(p_C + p_NC)] Bx1 <- params[(p_C+ p_NC + 1):(p_C + p_NC + colnum)] IC1 <- params[(p_C + p_NC + colnum + 1)] sig1 <- params[(p_C + p_NC + colnum + 2)] df1 <- params[(p_C + p_NC + colnum + 3)] } else if (p_NC > 0 && p_C == 0){ BC1 <- 0 BNC1 <- params[1:p_NC] Bx1 <- params[(p_NC+1):(p_NC + colnum)] IC1 <- params[(p_NC + colnum + 1)] sig1 <- params[(p_NC + colnum + 2)] df1 <- params[(p_NC + colnum + 3)] } else if (p_C > 0 && p_NC == 0){ BNC1 <- 0 BC1 <- params[1:p_C] Bx1 <- params[(p_C + 1): (p_C + colnum)] IC1 <- params[(p_C + colnum + 1)] sig1 <- params[(p_C + colnum + 2)] df1 <- params[(p_C + colnum + 3)] } else if (p_C == 0 && p_NC == 0){ BNC1 <- 0 BC1 <- 0 Bx1 <- params[(1:colnum)] IC1 <- params[(colnum + 1)] sig1 <- params[(colnum + 2)] df1 <- params[(colnum + 3)] } } else{ colnum <- 0 if (p_C > 0 && p_NC > 0){ BC1 <- params[1:p_C] BNC1 <- params[(p_C+1):(p_C + p_NC)] IC1 <- params[(p_C + p_NC + 1)] sig1 <- params[(p_C + p_NC + 2)] df1 <- params[(p_C + p_NC + 3)] } else if (p_NC > 0 && p_C == 0){ BC1 <- 0 BNC1 <- params[1:p_NC] IC1 <- params[(p_NC + 1)] sig1 <- params[(p_NC + 2)] df1 <- params[(p_NC + 3)] } else if (p_C > 0 && p_NC == 0){ BNC1 <- 0 BC1 <- params[1:p_C] IC1 <- params[(p_C + 1)] sig1 <- params[(p_C + 2)] df1 <- params[(p_C + 3)] } else if (p_C == 0 && p_NC == 0){ BNC1 <- 0 BC1 <- 0 IC1 <- params[1] sig1 <- params[2] df1 <- params[3] } } ZC1 <- y[(p_C+1):length(y)] ZC1 <- fBasics::vec(ZC1) ZC2 <- regressor.matrix(y,"not",p_C) if (p_C == 1){ ZC2 <- fBasics::vec(ZC2) } if (p_C > 0){ V <- ZC1 - (ZC2 %*% BC1) } else{ V <- ZC1 } U <- rev(V) U <- fBasics::vec(U) ZNC1 <- U[(p_NC + 1):length(U)] ZNC1 <- fBasics::vec(ZNC1) ZNC2 <- regressor.matrix(U,"not",p_NC) if(colnum > 1){ for (i in 1:colnum){ x[,i] <- rev(x[,i]) } } else{ x <- rev(x) } if (length(x) > 1){ if (colnum > 1){ x <- x[(p_NC +1):length(U),] } else{ x <- x[(p_NC + 1):length(U)] x <- fBasics::vec(x) } } else{ x = "not" } if (p_NC == 1){ ZNC2 <- fBasics::vec(ZNC2) } if (length(x) > 1){ if (p_NC > 0){ E <- rev(ZNC1 - (ZNC2 %*% BNC1) - IC1 - (x %*% Bx1)) } else{ E <- rev(ZNC1 - IC1 - (x %*% Bx1)) } } else{ if (p_NC > 0){ E <- rev(ZNC1 - (ZNC2 %*% BNC1) - IC1) } else{ E <- rev(ZNC1 - IC1) } } n <- length(E) loglik_eval <- -(n*lgamma((df1+1)/2) - n*log(sqrt(df1*pi*sig1^2)) - n*lgamma(df1/2) - ((df1+1)/2)*log(1+(E/sig1)^2/df1) %*% matlab::ones(n,1)) return(neg.loglikelihood = loglik_eval) } selection.lag.lead <- function(y,x,p_pseudo){ if (is.null(x)){ x <- "not" } P_C <- seq(length=(p_pseudo+1), from=0, by=1) P_C <- fBasics::vec(P_C) P_NC <- rev(P_C) P_NC <- fBasics::vec(P_NC) n <- length(y) - p_pseudo loglik <- c() for (i in 1:(p_pseudo+1)){ marx.t_results <- marx.t(y,x,P_C[i],P_NC[i]); sig <- marx.t_results[[5]] df <- marx.t_results[[6]] E <- marx.t_results[[7]] loglik[i] <- (n*lgamma((df+1)/2) - n*log(sqrt(df*pi*sig^2)) - n*lgamma(df/2) - ((df+1)/2)*log(1+(E/sig)^2/df) %*% matlab::ones(n,1)) } maxloglik <- which.max(loglik) P = cbind(P_C,P_NC) P = fBasics::vec(P[maxloglik,]) p_C <- P[1] p_NC <- P[2] return(list(p.C = p_C, p.NC = p_NC,loglikelihood = rev(loglik))) } selection.lag <- function(y,x,p_max){ if (is.null(x)){ x <- "not" } bic_results <- bic(y,x,p_max) aic_results <- aic(y,x,p_max) hq_results <- hq(y,x,p_max) bic_vec <- bic_results[[2]] colnames(bic_vec) <- paste('p =', 0:p_max) aic_vec <- aic_results[[2]] colnames(aic_vec) <- paste('p =', 0:p_max) hq_vec <- hq_results[[2]] colnames(hq_vec) <- paste('p =', 0:p_max) cat('Order Selection Criteria Pseudo Causal Model:', "\n") cat(' ', "\n") cat('BAYESIAN INFORMATION CRITERION', "\n") print(bic_vec) cat(' ', "\n") cat('Minimum value attained at p = ') cat(which.min(bic_vec) -1) cat(' ', "\n") cat(' ', "\n") cat('AKAIKE INFORMATION CRITERION', "\n") print(aic_vec) cat(' ', "\n") cat('Minimum value attained at p = ') cat(which.min(aic_vec) - 1) cat(' ', "\n") cat(' ', "\n") cat('HANNAN-QUINN INFORMATION CRITERION', "\n") print(hq_vec) cat(' ', "\n") cat('Minimum value attained at p = ') cat(which.min(hq_vec) - 1) cat(' ', "\n") cat(' ', "\n") return(list(bic = bic_vec, aic = aic_vec, hq = hq_vec)) } bic <- function(y,x,p_max){ if (is.null(x)){ x <- "not" } y <- fBasics::vec(y) if (length(x) > 1){ numcol <- NCOL(x) } else{ numcol = 0 } crit <- matrix(data=NA, nrow=(p_max+1), ncol=1) for (p in 0:p_max){ arx.ls_results <- arx.ls(fBasics::vec(y),x,p) n <- length(arx.ls_results[[5]]) Cov <- arx.ls_results[[6]] crit[(p+1)] <- -2*Cov/n + ((log(n))/n)*(p+1+numcol) } p_bic <- which.min(crit) - 1 crit <- t(crit) colnames(crit) <- paste('p =', 0:p_max) return(list(p = p_bic, values= crit)) } aic <- function(y,x,p_max){ if (is.null(x)){ x <- "not" } y <- fBasics::vec(y) if (length(x) > 1){ numcol <- NCOL(x) } else{ numcol = 0 } crit <- matrix(data=NA, nrow=(p_max+1), ncol=1) for (p in 0:p_max){ arx.ls_results <- arx.ls(fBasics::vec(y),x,p) n <- length(arx.ls_results[[5]]) Cov <- arx.ls_results[[6]] crit[(p+1)] <- -2*Cov/n + (2/n)*(p+1+numcol) } p_aic <- which.min(crit) - 1 crit <- t(crit) colnames(crit) <- paste('p =', 0:p_max) return(list(p = p_aic,values = crit)) } hq <- function(y,x,p_max){ if (is.null(x)){ x <- "not" } y <- fBasics::vec(y) if (length(x) > 1){ numcol <- NCOL(x) } else{ numcol = 0 } crit <- matrix(data=NA, nrow=(p_max+1), ncol=1) for (p in 0:p_max){ arx.ls_results <- arx.ls(fBasics::vec(y),x,p) n <- length(arx.ls_results[[5]]) Cov <- arx.ls_results[[6]] crit[(p+1)] <- -2*Cov/n + ((2*log(log(n)))/n)*(p+1+numcol) } p_hq <- which.min(crit) - 1 crit <- t(crit) colnames(crit) <- paste('p =', 0:p_max) return(list(p = p_hq, values = crit)) } sim.marx <- function(dist.eps, dist.x, obs, c_par, nc_par, exo_par){ if (is.null(dist.x)){ exo_par = 0 dist.x = 0 } if (length(dist.x) == 1){ exo_par = 0 } M <- 5*obs + 300 M.star <- 500 if (dist.eps[1] == 't'){ eps <- as.numeric(dist.eps[3])*(stats::rt((3*(obs+200)), df = as.numeric(dist.eps[2]), ncp = 0)) } else if (dist.eps[1] == 'cauchy'){ eps <- stats::rcauchy((3*(obs+200)), location= as.numeric(dist.eps[2]), scale=as.numeric(dist.eps[3])) } else if (dist.eps[1] == 'normal') { eps <- stats::rnorm((3*(obs+200)), mean = as.numeric(dist.eps[2]), sd=as.numeric(dist.eps[3])) } else if (dist.eps[1] == 'stable') { eps <- stabledist::rstable((3*(obs+200)), alpha = as.numeric(dist.eps[2]), beta=as.numeric(dist.eps[3]), gamma=as.numeric(dist.eps[4]), delta=as.numeric(dist.eps[5])) } if (dist.x[1] == 't'){ x <- as.numeric(dist.x[3])*(stats::rt((3*(M+200)), df = as.numeric(dist.x[2]), ncp = 0)) } else if (dist.x[1] == 'cauchy'){ x <- stats::rcauchy((3*(M+200)), location= as.numeric(dist.x[2]), scale=as.numeric(dist.x[3])) } else if (dist.x[1] == 'normal') { x <- stats::rnorm((3*(M+200)), mean = as.numeric(dist.x[2]), sd=as.numeric(dist.x[3])) } else if (dist.x[1] == 'stable') { x <- stabledist::rstable((3*(M+200)), alpha = as.numeric(dist.x[2]), beta=as.numeric(dist.x[3]), gamma=as.numeric(dist.x[4]), delta=as.numeric(dist.x[5])) } eps <- eps[(2*(obs+200)):(3*(obs+200))] r <- length(c_par) s <- length(nc_par) if (length(dist.x) != 1){ BC <- c(c_par, rep(0,M.star - length(c_par))) Phi.matrix <- matrix(data=0, nrow=M.star, ncol=M.star) Psi <- c() Psi[1] <- 1 for (i in 1:M.star){ for (j in 1:i){ Phi.matrix[i,j] = Psi[i-j+1]*BC[j] } Psi[(i+1)] <- sum(Phi.matrix[i,]) } MA_rep <- matrix(data=NA, nrow=(obs+200), ncol=M.star) for (i in 1:(obs+200)){ for (j in 1:M.star){ MA_rep[i,j] <- Psi[j]*x[M-(j-1)-(i-1)] } } exo_var <- c() exo_var <- MA_rep[,1] MA_rep <- rowSums(MA_rep) } else{ MA_rep <- matrix(data=0, nrow=(obs+200),ncol=M.star) exo_var <- c() } u <- matrix(data=NA, nrow=(obs+100+s), ncol=1) U.mat <- u[(201+obs):(200+obs+s)] <- rep(1,s) for (i in (obs+200):1){ if (length(nc_par) == 1){ AR <- nc_par * U.mat } else{ AR <- sum(t(nc_par*U.mat)) } if (i == (obs+200)){AR <- 0} u[i] <- AR + eps[i] if (s == 1){ U.mat <- u[i] } else{ U.mat <- c(u[i], t(U.mat[1:(length(U.mat)-1)])) U.mat <- t(U.mat) } } y <- matrix(data=0, nrow=(obs+r+200), ncol=1) Y <- y[1:r] <- rep(0,r) for (i in 1:(obs+200)){ if (r == 1){ AR2 <- c_par * Y } else{ AR2 <- sum(t(c_par*Y)) } if (i == 1){AR2 <- 0} y[i+r] <- AR2 + u[i] + exo_par * MA_rep[i+r] if (r == 1){ Y <- y[i+r] } else{ Y <- c(y[i+r], t(Y[1:(length(Y)-1)])) Y <- t(Y) } } u <- u[1:obs] y <- y[(101+r):(obs+100+r)] exo_var <- exo_var[(101+r):(obs+100+r)] return(list(y = y, x = exo_var)) } companion.form <- function(pol){ r <- length(pol) b <- cbind(diag((r-1)),rep(0,(r-1))) C <- rbind(t(pol),b) return(C) } compute.MA <- function(pol,M){ r <- length(pol) str <- c(rep(0,(r-1)),1) psi <- c(1) for (j in 1:M){ psi[j+1] <- t(pol) %*% rev(str) if (r > 1){ str <- c(str[2:length(str)],psi[j+1]) } else{ str <- psi[j+1] } } return(psi) } forecast.marx <- function(y,X,p_C,p_NC,X.for,h,M,N){ set.seed(9999) if (missing(X) == TRUE){ X = NULL } if (missing(N) == TRUE){ N = 10000 } object <- mixed(y,X,p_C,p_NC) obs <- length(y) if (missing(X.for) == TRUE && missing(M) == TRUE){ X.for = NULL M = 50 } else if(missing(X.for) == TRUE && missing(M) == FALSE){ X.for = NULL M = M } else if(missing(X.for) == FALSE && missing(M) == TRUE){ if (NCOL(X.for) == 1){ if(is.null(X.for) == TRUE){ M = 50 } else{ M = length(X.for) } } else{ M = length(X.for[,1]) } } else if(missing(X.for) == FALSE && missing(M) == FALSE){ if (NCOL(X.for) == 1){ if(is.null(X.for) == TRUE){ M = M } else{ M = min(length(X.for), M) } } else{ M = min(length(X.for[,1]),M) } } coef.caus <- c() if (object$order[1] == 0){ r = 1 coef.caus <- object$coefficients[(r+1)] } else{ r = object$order[1] coef.caus <- object$coefficients[2:(r+1)] } coef.noncaus <- c() if (object$order[2] == 0){ s = 1 coef.noncaus <- object$coefficients[(r+1+s)] } else{ s = object$order[2] coef.noncaus <- object$coefficients[(r+2):(r+1+s)] } coef.exo <- c() if (object$order[3] == 0){ q = 1 coef.exo <- object$coefficients[(r+1+s+q)] } else{ q = object$order[3] coef.exo <- object$coefficients[(r+1+s+1):(r+s+1+q)] } hve <- c() hve2 <- matrix(data=0, nrow=N,ncol=h) for (iter in 1:N){ eps.sim <- object$coefficients["scale",]*stats::rt(M,object$coefficients["df",]) z2 <- c() for (i in 1:M){ if(is.null(X.for) == TRUE){ z2[i] <- eps.sim[i] } else{ if(NCOL(X.for) > 1){ z2[i] <- eps.sim[i] + coef.exo %*% t(X.for[i,]) } else{ z2[i] <- eps.sim[i] + coef.exo * X.for[i] } } } phi <- c(1,coef.caus) u <- c() for (i in (r+1):obs){ u[i] <- phi %*% y[i:(i-r)] } w <- c(u[(obs-s+1):obs],z2) C <- matrix(data=0, nrow=(M+s), ncol=(M+s)) C[1,] <- compute.MA(coef.noncaus,(M+s-1)) if (s > 1){ for (i in 2:s){ C[i,] <- c(0, C[(i-1),1:(length(C[(i-1),])-1)]) } } for (i in (s+1):(M+s)){ C[i,] <- c(rep(0,(i-1)),1,rep(0,(M+s-i))) } D = solve(C) e <- D %*% w h1 <- c() for (i in 1:s){ h1[i] <- metRology::dt.scaled(e[i], df=object$coefficients["df",], sd=object$coefficients["scale",]) } hve[iter] = prod(h1) for (j in 1:h){ mov.av <- C[1,1:(M-j+1)] %*% z2[j:M] hve2[iter,j] <- mov.av * hve[iter] } } y.star <- y[(obs-r+1):obs] y.for <- c() exp <- c() for (j in 1:h){ exp[j] = ((1/N)*sum(hve2[,j]))/((1/N)*sum(hve)) if(length(coef.caus) == 1){ y.for[j] <- object$coefficients[1]/(1-sum(coef.noncaus)) + coef.caus * y.star + exp[j] } else{ y.for[j] <- object$coefficients[1]/(1-sum(coef.noncaus)) + t(coef.caus) %*% y.star + exp[j] } y.star <- c(y.for[j], y.star[1:(length(y.star)-1)]) } return(y.for) } mixed.combine <- function(y,x,p_C,p_NC){ q <- NCOL(x) if (is.null(x) == TRUE){ x <- "not" q <- 0 } sig_level = 0.05 est <- marx.t(y,x,p_C,p_NC) residuals <- est$residuals fitted.values <- y[(1+p_C):(length(y)-p_NC)] - residuals inf <- inference(y,x,est$coef.c,est$coef.nc,est$coef.exo,est$coef.int,est$scale,est$df,sig_level) coefficients <- c(est$coef.int,est$coef.c,est$coef.nc,est$coef.exo, est$df, est$scale) coefficients <- fBasics::vec(coefficients) if(length(x) > 1){ if (p_C > 0 && p_NC > 0){ rownames(coefficients) <- c('int', paste('lag', 1:p_C), paste('lead', 1:p_NC), paste('exo', 1:NCOL(x)), 'df', 'scale') } else if (p_C > 0 && p_NC == 0){ rownames(coefficients) <- c('int', paste('lag', 1:p_C), 'lead', paste('exo', 1:NCOL(x)), 'df', 'scale') } else if (p_C == 0 && p_NC > 0){ rownames(coefficients) <- c('int', 'lag', paste('lead', 1:p_NC), paste('exo', 1:NCOL(x)), 'df', 'scale') } else if (p_C == 0 && p_NC == 0){ rownames(coefficients) <- c('int', 'lag', 'lead', paste('exo', 1:NCOL(x)), 'df', 'scale') } } else{ if (p_C > 0 && p_NC > 0){ rownames(coefficients) <- c('int', paste('lag', 1:p_C), paste('lead', 1:p_NC), 'exo', 'df', 'scale') } else if (p_C > 0 && p_NC == 0){ rownames(coefficients) <- c('int', paste('lag', 1:p_C), 'lead', 'exo', 'df', 'scale') } else if (p_C == 0 && p_NC > 0){ rownames(coefficients) <- c('int', 'lag', paste('lead', 1:p_NC), 'exo', 'df', 'scale') } else if (p_C == 0 && p_NC == 0){ rownames(coefficients) <- c('int', 'lag', 'lead', 'exo', 'df', 'scale') } } se <- c(inf$se.int, inf$se.c, inf$se.nc, inf$se.exo, est$se.dist[1], est$se.dist[2]) if (length(x) > 1){ degree <- NROW(est$residuals) - (p_C + p_NC + NCOL(x) + 1) } else{ degree <- NROW(est$residuals) - (p_C + p_NC + 1) } return(list(coefficients = coefficients, se = se, df.residual = degree, residuals= residuals, fitted.values = fitted.values, order=c(p_C,p_NC,q))) } pseudo <- function(y,x,p){ UseMethod("pseudo")} pseudo.default <- function(y,x,p){ if (is.null(x)){ x <- "not" } est <- arx.ls(y,x,p) est$call <- match.call(); class(est) <- "pseudo" est } print.pseudo <- function(x,...){ cat("Call:\n") print(x$call) cat("\n Coefficients:\n") print(x$coefficients) } summary.pseudo <- function(object,...){ se <- sqrt(diag(object$vcov)) tval <- stats::coef(object) / se TAB <- cbind(Estimate = stats::coef(object), StdErr = se, t.value = tval, p.value = 2*stats::pt(-abs(tval),df=object$df)) colnames(TAB) <- c("Estimate", "Std.Err", "t value", "p value") res <- list(call=object$call, coefficients = TAB) class(res) <- "summary.pseudo" res } pseudo <- function(y,x,p){ UseMethod("pseudo")} pseudo.default <- function(y,x,p){ if (is.null(x)){ x <- "not" } est <- arx.ls(y,x,p) est$call <- match.call(); class(est) <- "pseudo" est } print.pseudo <- function(x,...){ cat("Call:\n") print(x$call) cat("\n Coefficients:\n") print(x$coefficients) } summary.pseudo <- function(object,...){ se <- sqrt(diag(object$vcov)) tval <- stats::coef(object) / se TAB <- cbind(Estimate = stats::coef(object), StdErr = se, t.value = tval, p.value = 2*stats::pt(-abs(tval),df=object$df)) colnames(TAB) <- c("Estimate", "Std.Err", "t value", "p value") res <- list(call=object$call, coefficients = TAB) class(res) <- "summary.pseudo" res } mixed <- function(y,x,p_C,p_NC){ UseMethod("mixed")} mixed.default <- function(y,x,p_C,p_NC){ est <- mixed.combine(y,x,p_C,p_NC); est$call <- match.call(); class(est) <- "mixed" est } print.mixed <- function(x,...){ cat("Call:\n") print(x$call) cat("\n Coefficients:\n") print(x$coefficients) } summary.mixed <- function(object,...){ tval <- stats::coef(object) / object$se TAB <- cbind(Estimate = stats::coef(object), StdErr = object$se, t.value = tval, p.value = 2*stats::pt(-abs(tval),df=object$df.residual)) colnames(TAB) <- c("Estimate", "Std.Err", "t value", "p value") res <- list(call=object$call, coefficients = TAB) class(res) <- "summary.mixed" res } mixed <- function(y,x,p_C,p_NC){ UseMethod("mixed")} mixed.default <- function(y,x,p_C,p_NC){ est <- mixed.combine(y,x,p_C,p_NC); est$call <- match.call(); class(est) <- "mixed" est } print.mixed <- function(x,...){ cat("Call:\n") print(x$call) cat("\n Coefficients:\n") print(x$coefficients) } summary.mixed <- function(object,...){ tval <- stats::coef(object) / object$se TAB <- cbind(Estimate = stats::coef(object), StdErr = object$se, t.value = tval, p.value = 2*stats::pt(-abs(tval),df=object$df.residual)) colnames(TAB) <- c("Estimate", "Std.Err", "t value", "p value") res <- list(call=object$call, coefficients = TAB) class(res) <- "summary.mixed" res }
if (interactive()) savehistory(); library("aroma.affymetrix"); chipType <- "Mapping250K_Nsp"; cdf <- AffymetrixCdfFile$byChipType(chipType); ugc <- AromaUnitGcContentFile$allocateFromCdf(cdf, tags="na28,h=500kb,HB20090602"); print(ugc); csv <- AffymetrixNetAffxCsvFile$byChipType(chipType, tags=".na28"); colClasses <- c("^(probeSetID|%GC)$"="character"); data <- readDataFrame(csv, colClasses=colClasses); units <- indexOf(cdf, names=data$probeSetID); stopifnot(all(is.finite(units))); values <- as.double(data[["%GC"]]); ugc[units,1] <- values; srcFileTags <- list(); srcFiles <- c(list(cdf), list(csv)); for (kk in seq_along(srcFiles)) { srcFile <- srcFiles[[kk]]; tags <- list( filename=getFilename(srcFile), filesize=getFileSize(srcFile), checksum=getChecksum(srcFile) ); srcFileTags[[kk]] <- tags; } print(srcFileTags); footer <- readFooter(ugc); footer$createdOn <- format(Sys.time(), "%Y%m%d %H:%M:%S", usetz=TRUE); footer$createdBy = list( fullname = "Henrik Bengtsson", email = sprintf("%s@%s", "henrik.bengtsson", "aroma-project.org") ); names(srcFileTags) <- sprintf("srcFile%d", seq_along(srcFileTags)); footer$srcFiles <- srcFileTags; footer$gcBinWidth <- as.integer(500e3); writeFooter(ugc, footer); print(ugc); print(summary(ugc)); print(range(ugc[,1], na.rm=TRUE));
export.qm <- function(qmobject, file, style = c("R", "PQMethod")) { style <- match.arg(style) if (style=="R") capture.output(print(qmobject, length=max(qmobject$brief$nstat, qmobject$brief$nqsorts)), file=file) else if (style=="PQMethod") { pqmethod.output <- function(qmobject) { cat(qmobject$brief$info, sep="\n") cat("\n") pqout <- as.list(rep(NA, 15)) cat("\n\nCorrelation Matrix Between Sorts", sep="\n") print(round(cor(qmobject[[2]]), digits=4)) cat("\n\nUnrotated Factor Matrix", sep="\n") print(principal(qmobject[[2]], nfactors=8, rotate="none")$loadings, cutoff=0) cat("\n\nCumulative Communalities Matrix", sep="\n") comm <- data.frame(matrix(as.numeric(NA), ncol=8, nrow=length(qmobject[[2]]))) for (i in 1:8) { comm[[i]] <- principal(qmobject[[2]], nfactors=i, rotate="none")$communality } print(round(comm, digits=4)) cat("\n\nFactor Matrix and Defining Sorts", sep="\n") fmx <- list(round(qmobject$loa, digits=4), qmobject$flagged) names(fmx) <- c("Q-sort factor loadings", "Flagged Q-sorts") print(fmx) cat("\n\nFree Distribution Data Results -- not calculated", sep="\n") cat("\n\nFactor Scores (z-scores)", sep="\n") print(round(qmobject$zsc, digits=2)) cat("\n\nCorrelations Between Factor Scores", sep="\n") print(round(qmobject$f_char[[2]], digits=4)) cat("\n\nFactor Scores ", sep="\n") nfactors <- ncol(qmobject$zsc_n) fsco <- as.list(1:nfactors) zsc.df <- as.data.frame(qmobject$zsc) for (i in 1:nfactors) { names(fsco)[i] <- paste0("-- For Factor ", i) fsco[[i]] <- round(zsc.df[order(zsc.df[i], decreasing=T), c(i, i)][1], digits=3) } print(fsco) cat("\n\nDescending Array of Differences Between Factors ", sep="\n") comparisons <- combn(nfactors, 2, simplify=F) daf <- as.list(1:length(comparisons)) for (i in 1:length(comparisons)) { names(daf)[i] <- paste(comparisons[[i]], collapse=" and ", sep="") zsc <- zsc.df[comparisons[[i]]] dif <- qmobject[[8]][c(names(qmobject[[8]])[grep(paste(paste(comparisons[[i]][1], comparisons[[i]][2], sep=".*"), paste(comparisons[[i]][2], comparisons[[i]][1], sep=".*"), sep="|"),names(qmobject[[8]]))],"dist.and.cons")] dad <- cbind(zsc, dif) daf[[i]] <- format(dad[order(dad[3], decreasing = T), ], digits=2) } print(daf) cat("\n\nFactor Q-Sort Values for Each Statement", sep="\n") print(qmobject$zsc_n) cat("\n\nFactor Q-Sort Values for Statements sorted by Consensus vs. Disagreement (Variance across Factor Z-Scores)", sep="\n") zsc.ord <- order(apply(zsc.df, 1, var)) print(qmobject$zsc_n[zsc.ord,]) cat("\n\nFactor Characteristics", sep="\n") fch <- t(qmobject$f_char[[1]]) rownames(fch) <- c( "Average reliability coefficient", "Number of loading Q-sorts", "Eigenvalues", "Percentage of explained variance", "Composite reliability", "Standard error of factor scores") print(round(fch, digits=2)) cat("\n\nStandard Errors for Differences in Factor Z-Scores", sep="\n") print(qmobject$f_char[[3]]) cat("\n\nDistinguishing Statements ", sep="\n") dc <- qmobject$qdc dsf <- as.list(1:nfactors) for (i in 1:nfactors) { names(dsf)[i] <- paste0("for Factor ", i) d <- grep(paste0("f",i, "|all"), dc$dist.and.cons) dsf[[i]] <- cbind(round(zsc.df[d, ], digits=2),dc[d, c(1,1+(2*(1:length(comparisons))))]) } print(dsf) cat("\n\nConsensus Statements -- Those That Do Not Distinguish Between ANY Pair of Factors.", sep="\n") dcon <- which(dc$dist.and.cons == "Consensus") print(cbind(round(qmobject$zsc[dcon, ], digits=2),dc[dcon, c(1,1+(2*(1:length(comparisons))))])) } capture.output(pqmethod.output(qmobject), file=file) } }
dbSendQuery_MariaDBConnection_character <- function(conn, statement, params = NULL, ...) { dbSend(conn, statement, params, is_statement = FALSE) } setMethod("dbSendQuery", c("MariaDBConnection", "character"), dbSendQuery_MariaDBConnection_character)
find.intersect <- function(d, r1, r2) { beta <- (r1^2 + d^2 - r2^2) / (2 * r1 * d); gamma <- (r2^2 + d^2 - r1^2) / (2 * r2 * d); area <- r1^2 * (acos(beta) - 0.5 * sin(2 * acos(beta))) + r2^2 * (acos(gamma) - 0.5 * sin(2 * acos(gamma))); return(area); }
print.biprobit <- function(x,...) { printCoefmat(x$coef,...) return(invisible(x)) }
of_country_codes <- function(foptions = list()) { url <- "http://openfisheries.org/api/landings/countries.json" countries_call <- GET(url, foptions) stop_for_status(countries_call) countries<- content(countries_call) countries <- data.frame(rbindlist(countries), stringsAsFactors = FALSE) return(countries) } country_codes <- function() { .Deprecated(new = "of_country_codes", package = "rfisheries", msg = "This function is deprecated, and will be removed in a future version. See ?of_country_codes") }
GroupNumeric <- function(x, n = NULL, groupNames = NULL, orderedFactor = FALSE, style = "quantile", ...){ nNames <- length(groupNames) if (nNames > 0){ if (is.null(n)){ n <- nNames } else { if (n != nNames){ stop("Length of groupNames is not equal to n") } } } else { if (is.null(n)){ stop("Either n or groupNames must be specified") } } y <- classInt::classIntervals(x, n, style = style, ...) cutoffs <- y$brks nGrps <- length(cutoffs) - 1 if ((nNames > 0) & (nGrps != n)){ errMsg <- paste("Internal classInt call with style = ", style, "returned", nGrps, "groups instead of", n, "\n To see the resulting groups, rerun without groupNames") stop(errMsg) } z <- cut(x, breaks = cutoffs, labels = groupNames, include.lowest = TRUE, ordered_result = orderedFactor) return(z) }
remove_nonstandard_aa <- function(df) { seq_aa <- df[,2] seq_name <- df[,1] standard_aa_indices <-grepl('^[ARNDCEQGHILKMFPSTWYV]+$', seq_aa) df[standard_aa_indices,] }
"MCtest.fixed" <- function(x,statistic,resample,Nmax=3619,extreme="geq",conf.level=.99,seed=1234325){ N<-Nmax set.seed(seed) t0<-statistic(x) ti<-rep(NA,N) for (i in 1:N){ ti[i]<-statistic(resample(x)) } if (extreme=="leq") S<-length((1:N)[ti<=t0]) else if (extreme=="geq") S<-length((1:N)[ti>=t0]) p.value<-(S+1)/(N+1) p.alpha<-1-conf.level if (S==0){ ci.lower<-0 } else { ci.lower<- qbeta(p.alpha/2,S,N-S+1) } if (S==N){ ci.upper<-1 } else{ ci.upper<-qbeta(1-p.alpha/2,S+1,N-S) } pvalue.ci<-c(ci.lower,ci.upper) attr(pvalue.ci,"conf.level")<-conf.level out<-list(Ti=ti,type="fixed",parms=c(Nmax=N),T0=t0,p.value=p.value,p.value.ci=pvalue.ci) class(out)<-"MCtest" out }
listdtr <- function(y, a, x, stage.x, seed = NULL, kfolds = 5L, fold = NULL, maxlen = 10L, zeta.choices = NULL, eta.choices = NULL) { if (!is.matrix(y)) { y <- as.matrix(y) } if (!is.data.frame(a)) { a <- as.data.frame(a) } if (!is.matrix(x)) { x <- as.matrix(x) } if (is.null(colnames(x))) { colnames(x) <- paste0("x", seq_len(ncol(x))) } stopifnot(nrow(y) == nrow(a) && nrow(y) == nrow(x)) n <- nrow(y) stopifnot(ncol(y) == ncol(a)) n.stage <- ncol(y) dtr <- vector("list", n.stage) future.y <- double(n) if (is.null(colnames(a))) { colnames(a) <- paste0("a", 1L : n.stage) } a.mm <- lapply(1L : n.stage, function(j) model.matrix(as.formula(sprintf("~ -1 + %s", colnames(a)[j])), a)) stage.a.mm <- rep.int(1L : n.stage, sapply(a.mm, ncol)) a.mm <- do.call("cbind", a.mm) if (is.null(fold)) { if (!is.null(seed)) { set.seed(seed) } fold <- rep_len(1L : kfolds, n)[sample.int(n)] } for (i.stage in n.stage : 1L) { current.x <- cbind( x[, which(stage.x <= i.stage), drop = FALSE], a.mm[, which(stage.a.mm < i.stage), drop = FALSE], y[, seq_len(i.stage - 1L), drop = FALSE]) if (ncol(current.x) < 2L) { current.x <- cbind(x = current.x, dummy_ = 0.0) } current.a <- a[, i.stage] current.y <- y[, i.stage] + future.y model <- krr(current.x, current.y, current.a) options <- model$options outcomes <- predict(model, current.x) regrets <- get.regrets(outcomes) obj <- build.rule.cv(current.x, regrets, kfolds, fold, maxlen, zeta.choices, eta.choices) dtr[[i.stage]] <- obj future.y <- outcomes[cbind(1L : n, obj$action)] } class(dtr) <- "listdtr" dtr } predict.listdtr <- function(object, xnew, stage, ...) { stopifnot(stage >= 1L && stage <= length(object)) if (!is.matrix(xnew) || ncol(xnew) < 2L) { xnew <- cbind(x = xnew, dummy_ = 0.0) } action <- apply.rule(object[[stage]], xnew, "label") action } print.listdtr <- function(x, stages = NULL, digits = 3L, ...) { object <- x if (is.null(stages)) { stages <- seq_along(object) } for (i.stage in stages) { cat(sprintf("===== Stage %d =====\n", i.stage)) show.rule(object[[i.stage]], digits) } invisible(object) } plot.listdtr <- function(x, stages = NULL, digits = 3L, ...) { object <- x if (is.null(stages)) { stages <- seq_along(object) } figures <- lapply(stages, function(i.stage) draw.rule(object[[i.stage]], digits)) if (length(stages) <= 1L) { print(figures[[1L]] + ggtitle("Stage 1")) } else { grid.newpage() pushViewport(viewport(layout = grid.layout(1L, length(stages)))) for (i in seq_len(length(stages))) { print(figures[[i]] + ggtitle(sprintf("Stage %d", stages[i])), vp = viewport(layout.pos.row = 1L, layout.pos.col = i)) } } invisible(object) }
construct_download_url <- function(url, format='csv', sheetid = NULL){ key <- stringr::str_extract(url, '[[:alnum:]_-]{30,}') if(is.null(sheetid) & stringr::str_detect(url, 'gid=[[:digit:]]+')){ sheetid <- as.numeric(stringr::str_extract(stringr::str_extract(url,'gid=[[:digit:]]+'),'[[:digit:]]+')) } address <- paste0('https://docs.google.com/spreadsheets/export?id=',key,'&format=',format) if(!is.null(sheetid)){ address <- paste0(address, '&gid=', sheetid) } return(address) }
context("Test ALA data profiles") test_that("show_all_profiles returns profiles", { skip_on_cran() profiles <- show_all_profiles() expect_s3_class(profiles, "data.frame") expect_equal(ncol(profiles), 4) }) test_that("search_profile_attributes checks input", { expect_error(search_profile_attributes(10)) expect_error(search_profile_attributes("invalid")) }) test_that("search_profile_attributes returns dataframe", { skip_on_cran() atts <- search_profile_attributes(92) expect_equal(ncol(atts), 2) expect_s3_class(atts, "data.frame") atts <- search_profile_attributes("ALA") expect_equal(ncol(atts), 2) expect_s3_class(atts, "data.frame") atts <- search_profile_attributes("ALA General") expect_equal(ncol(atts), 2) expect_s3_class(atts, "data.frame") })
gof.hergm <- function(object, sample_size = 1000, ...) { network <- object$network d <- network directed <- is.directed(d) n <- d$gal$n indicator <- object$indicator if (object$method == "bayes") { sample_size <- nrow(indicator) } else { object$sample_size <- sample_size } verbose <- object$verbose observed.components <- silent(component.dist(d)) observed.component.number <- length(observed.components$csize) observed.max.component.size <- max(observed.components$csize) observed.distances <- geodist(d) observed.distances <- observed.distances$gdist observed.frequencies_distances <- table(observed.distances) number <- length(observed.frequencies_distances) - 1 - (sum(observed.distances == Inf) > 0) observed.distance.label <- rownames(observed.frequencies_distances)[2:(number+1)] observed.distance <- observed.frequencies_distances[2:(number+1)] observed.edges <- summary(d ~ edges) if (directed == TRUE) { observed.degree <- summary(d ~ odegree(1:n-1)) observed.star <- summary(d ~ ostar(2)) observed.triangle <- summary(d ~ ttriple) } else { observed.degree <- summary(d ~ degree(1:n-1)) observed.star <- summary(d ~ kstar(2)) observed.triangle <- summary(d ~ triangle) } object.hergm <- simulate.hergm(object, verbose=verbose, sample_size = sample_size) output <- summary_sample_network(edgelists=object.hergm$edgelist, sample_size=sample_size, directed=directed, n) oldpar <- par(no.readonly = TRUE) on.exit(par(oldpar)) par(mfrow = c(2, 3)) hist(output$max.component.size, 50, prob = T, xlim = c(0, max(abs(output$max.component.size))), main = "", xlab = "size of largest component", ylab = "", cex.lab=1.25) abline(v = observed.max.component.size, col="red") boxplot(output$distance[,1:(n-2)], main = "", xlab = "geodesic distances", ylab = "", cex.lab=1.25) points(x = c(observed.distance[1:(n-2)]), col = "red", type = "b") if (directed == TRUE) xlab <- "out-degrees" else xlab <- "degrees" boxplot(output$degree[,1:(n-1)], ylim = c(0,n-1), main = "", xlab = xlab, ylab = "", cex.lab=1.25) points(x = c(observed.degree), col = "red", type = "b") hist(output$edges, 50, prob = T, main = "", xlab = "number of edges", ylab = "", cex.lab=1.25) abline(v = observed.edges, col="red") if (directed == TRUE) xlab <- "number of 2-out-stars" else xlab <- "number of 2-stars" hist(output$star, 50, prob = T, main = "", xlab = xlab, ylab = "", cex.lab=1.25) abline(v = observed.star, col="red") if (directed == TRUE) xlab <- "number of transitive triples" else xlab <- "number of triangles" hist(output$triangle, 50, prob = T, main = "", xlab = xlab, ylab = "", cex.lab=1.25) abline(v = observed.triangle, col="red") output }
rasterize_terrain = function(las, res = 1, algorithm = tin(), use_class = c(2L,9L), shape = "convex", ...) { UseMethod("rasterize_terrain", las) } rasterize_terrain.LAS = function(las, res = 1, algorithm = tin(), use_class = c(2L,9L), shape = "convex", ...) { if (is_a_number(res)) assert_all_are_non_negative(res) else if (!raster_is_supported(res)) stop("'res' must be a number or a raster.", call. = FALSE) assert_is_algorithm(algorithm) assert_is_algorithm_spi(algorithm) if (is.character(shape)) shape <- match.arg(shape, c("convex", "concave", "bbox")) else if (!is(shape, "sfc_POLYGON") & !is(shape, "sfc_MULTIPOLYGON")) stop("Argument 'shape' must be a string or a sfc", call. = FALSE) if (!"Classification" %in% names(las)) stop("LAS object does not contain 'Classification' attribute", call. = FALSE) if (any(as.integer(use_class) != use_class)) stop("'use_class' is not a vector of integers'", call. = FALSE) use_class <- as.integer(use_class) dots <- list(...) Wdegenerated <- isTRUE(dots$Wdegenerated) keep_lowest <- isTRUE(dots$keep_lowest) force_crs <- isTRUE(dots$force_crs) pkg <- if (is.null(dots$pkg)) getOption("lidR.raster.default") else dots$pkg . <- Z <- Zref <- X <- Y <- Classification <- NULL ground <- las@data[Classification %in% c(use_class), .(X,Y,Z)] if (nrow(ground) == 0) stop("No ground points found. Impossible to compute a DTM.", call. = FALSE) ground <- check_degenerated_points(ground, Wdegenerated) layout <- if (!is_a_number(res)) raster_template(res) else raster_layout(las, res, format = "template") layout <- raster_materialize(layout, values = 0, pkg = "stars") sf::st_crs(layout) <- st_crs(las) if (is.character(shape) && shape %in% c("convex", "concave")) { if (shape == "concave") hull <- st_concave_hull(las, concavity = 10, length_threshold = 100) else hull <- st_convex_hull(las) shape <- sf::st_buffer(hull, dist = raster_res(layout)[1]) } if (is(shape, "sfc")) layout <- layout[shape] grid <- raster_as_dataframe(layout, xy = TRUE, na.rm = TRUE) lidR.context <- "rasterize_terrain" ground <- LAS(ground, las@header, crs = st_crs(las), check = FALSE, index = las@index) Zg <- algorithm(ground, grid) Zg[is.nan(Zg)] <- NA_real_ isna <- is.na(Zg) nnas <- sum(isna) if (nnas > 0) { nn <- knnidw(1, rmax = .Machine$double.xmax) sub_grid <- data.frame(X = grid$X[isna], Y = grid$Y[isna]) znn <- nn(ground, sub_grid) Zg[isna] <- znn warning(glue::glue("Interpolation of {nnas} points failed because they are too far from ground points. Nearest neighbour was used but interpolation is weak for those points"), call. = FALSE) } fast_quantization(Zg, las[["Z scale factor"]], las[["Z offset"]]) cells <- get_group(layout, grid) layout <- raster_layout(las, res) layout <- raster_materialize(layout, pkg = pkg) layout <- raster_set_values(layout, Zg, cells = cells) if (keep_lowest) { res <- raster_res(layout)[1] lasg <- filter_poi(las, Classification %in% c(use_class)) rmin <- template_metrics(lasg, ~list(Z = min(Z)), layout) Z1 <- raster_values(layout) Z2 <- raster_values(rmin) Zg <- pmin(Z1, Z2, na.rm = TRUE) layout <- raster_set_values(layout, Zg) } raster_names(layout) <- "Z" return(layout) } rasterize_terrain.LAScluster = function(las, res = 1, algorithm = tin(), use_class = c(2L,9L), shape = "convex", ...) { x <- readLAS(las) if (is.empty(x)) return(NULL) if (is_raster(res)) res <- raster_crop(res, st_adjust_bbox(x, raster_res(res))) dtm <- rasterize_terrain(x, res, algorithm, use_class = use_class, shape = shape, ...) dtm <- raster_crop(dtm, st_bbox(las)) return(dtm) } rasterize_terrain.LAScatalog = function(las, res = 1, algorithm = tin(), use_class = c(2L,9L), shape = "convex", ...) { assert_is_algorithm(algorithm) assert_is_algorithm_spi(algorithm) if (is_a_number(res)) assert_all_are_non_negative(res) else if (!raster_is_supported(res)) stop("'res' must be a number or a raster.", call. = FALSE) if (!is_a_number(res)) las <- catalog_intersect(las, res) opt_select(las) <- "xyzc" opt_filter(las) <- paste("-keep_class", paste(use_class, collapse = " "), opt_filter(las)) alignment <- raster_alignment(res) if (opt_chunk_size(las) > 0 && opt_chunk_size(las) < 2*alignment$res) stop("The chunk size is too small. Process aborted.", call. = FALSE) options <- list(need_buffer = TRUE, drop_null = TRUE, raster_alignment = alignment, automerge = TRUE) output <- catalog_apply(las, rasterize_terrain, res = res, algorithm = algorithm, shape = shape, use_class = use_class, ..., .options = options) return(output) }
library(tabshiftr) library(testthat) library(checkmate) context("clusters") test_that("regular vertical clusters of otherwise tidy data", { input <- tabs2shift$clusters_vertical schema <- setCluster(id = "territories", left = 1, top = c(3, 9)) %>% setIDVar(name = "territories", columns = 1, rows = c(3, 9)) %>% setIDVar(name = "year", columns = 2) %>% setIDVar(name = "commodities", columns = 5) %>% setObsVar(name = "harvested", columns = 6) %>% setObsVar(name = "production", columns = 7) .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2) }) test_that("regular vertical clusters with a listed observed variable", { input <- tabs2shift$listed_column_wide schema <- setCluster(id = "territories", left = 1, top = c(2, 7)) %>% setIDVar(name = "territories", columns = 1) %>% setIDVar(name = "year", columns = 2) %>% setIDVar(name = "commodities", columns = c(6, 7), rows = 1) %>% setObsVar(name = "harvested", columns = c(6, 7), key = 4, value = "harvested") %>% setObsVar(name = "production", columns = c(6, 7), key = 4, value = "production") .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2) }) test_that("regular vertical clusters with a listed observed variable and an implicit variable", { input <- tabs2shift$listed_column_wide schema <- setCluster(id = "territories", left = 1, top = c(2, 7)) %>% setIDVar(name = "region", value = "group 1") %>% setIDVar(name = "territories", columns = 1) %>% setIDVar(name = "year", columns = 2) %>% setIDVar(name = "commodities", columns = c(6, 7), rows = 1) %>% setObsVar(name = "harvested", columns = c(6, 7), key = 4, value = "harvested") %>% setObsVar(name = "production", columns = c(6, 7), key = 4, value = "production") .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2, groups = TRUE) schema <- setCluster(id = "territories", left = 1, top = c(2, 7)) %>% setIDVar(name = "region", value = "group 1") %>% setIDVar(name = "territories", columns = 1, rows = 1, relative = T) %>% setIDVar(name = "year", columns = 2) %>% setIDVar(name = "commodities", columns = c(6, 7), rows = 1) %>% setObsVar(name = "harvested", columns = c(6, 7), key = 4, value = "harvested") %>% setObsVar(name = "production", columns = c(6, 7), key = 4, value = "production") .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2, groups = TRUE) schema <- setCluster(id = "territories", left = 1, top = c(2, 7)) %>% setFilter(rows = c(1, 4, 5, 9, 10)) %>% setIDVar(name = "territories", value = "unit 1") %>% setIDVar(name = "year", columns = 2) %>% setIDVar(name = "commodities", columns = c(6, 7), rows = 1) %>% setObsVar(name = "harvested", columns = c(6, 7), key = 4, value = "harvested") %>% setObsVar(name = "production", columns = c(6, 7), key = 4, value = "production") out <- reorganise(input = input, schema = schema) expect_equal(out$territories, c("unit 1", "unit 1", "unit 1", "unit 1")) expect_equal(out$year, c("year 2", "year 2", "year 2", "year 2")) expect_equal(out$commodities, c("maize", "maize", "soybean", "soybean")) expect_equal(out$harvested, c(1221, 2221, 1211, 2211)) expect_equal(out$production, c(1222, 2222, 1212, 2212)) }) test_that("regular horizontal clusters of otherwise tidy data", { input <- tabs2shift$clusters_horizontal schema <- setCluster(id = "territories", left = c(1, 6), top = 2) %>% setIDVar(name = "territories", columns = c(1, 6), rows = 2) %>% setIDVar(name = "year", columns = c(2, 7)) %>% setIDVar(name = "commodities", columns = c(1, 6)) %>% setObsVar(name = "harvested", columns = c(3, 8)) %>% setObsVar(name = "production", columns = c(4, 9)) .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2) }) test_that("clusters that are aggregated per observed variable", { input <- tabs2shift$clusters_observed schema <- setCluster(id = "observed", left = 1, top = c(2, 12)) %>% setIDVar(name = "territories", columns = 2) %>% setIDVar(name = "year", columns = 3) %>% setIDVar(name = "commodities", columns = 5) %>% setObsVar(name = "harvested", columns = 7, key = "cluster", value = 1) %>% setObsVar(name = "production", columns = 7, key = "cluster", value = 2) .expect_valid_table(x = reorganise(input = input, schema = schema), units = 2) }) test_that("clusters that are nested into groups", { input <- tabs2shift$clusters_nested schema <- setCluster(id = "territories", group = "region", member = c(1, 1, 2), left = 1, top = c(3, 8, 15)) %>% setIDVar(name = "region", columns = 1, rows = c(2, 14)) %>% setIDVar(name = "territories", columns = 1, rows = c(3, 8, 15)) %>% setIDVar(name = "year", columns = 7) %>% setIDVar(name = "commodities", columns = 2) %>% setObsVar(name = "harvested", columns = 5) %>% setObsVar(name = "production", columns = 6) .expect_valid_table(x = reorganise(input = input, schema = schema), units = 3, groups = TRUE) })
"ar_stl_wards"
NULL kinesisvideomedia_get_media <- function(StreamName = NULL, StreamARN = NULL, StartSelector) { op <- new_operation( name = "GetMedia", http_method = "POST", http_path = "/getMedia", paginator = list() ) input <- .kinesisvideomedia$get_media_input(StreamName = StreamName, StreamARN = StreamARN, StartSelector = StartSelector) output <- .kinesisvideomedia$get_media_output() config <- get_config() svc <- .kinesisvideomedia$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .kinesisvideomedia$operations$get_media <- kinesisvideomedia_get_media
check.value <- function(value,type) { if(type!="boolean" && type!="string" && type!="integer" && type!="str_int" && type!="vector") { return() } if(is.vector(value)) { if(type=="vector" && !is.list(value)) { return(TRUE) } else if(length(value)!=1) { return(FALSE) }else if (type=="boolean" && is.logical(value)) { return(TRUE) }else if((type=="string" || type=="str_int") && is.character(value)) { return(TRUE) }else if((type=="integer" || type=="str_int") && is.numeric(value) && as.integer(value)==value) { return(TRUE) }else{ return(FALSE) } }else if(type=="vector" && is.factor(value)) { return(TRUE) }else if(is.null(value)) { return(TRUE) }else{ return(FALSE) } }
.Random.seed <- c(403L, 10L, -1419741262L, 331087533L, -819546521L, -496630386L, -1809354136L, 700411499L, -1535916023L, -445270376L, 1177334214L, 1823269153L, 1621275059L, -676344542L, -668178668L, -79143017L, -69091443L, -230079836L, 628608138L, -2014977291L, 325797199L, -536292778L, 39678208L, 1458619459L, 534202337L, -2044418224L, 1932499374L, 1120114521L, -981721749L, -1444559654L, 1973865884L, -11832929L, 1694290933L, -1569946996L, -1442740382L, -1064077507L, 301387703L, -1517167522L, -1757900392L, 1587705083L, -778977127L, -1142443736L, -1982052394L, 636019793L, 1870761731L, 1623819922L, -789674972L, 924142311L, -1220436163L, 1729994676L, 1312818202L, -1610621083L, 656278015L, -1201517434L, -804630512L, -954690893L, -139652783L, 1064497408L, -1523534882L, 455172137L, 1759442907L, 1106863338L, 1389281932L, 606625231L, -412610171L, 1152494140L, 1656475410L, 788313101L, 563412807L, -1529397970L, 589184136L, -743626357L, 74035561L, -736773320L, 365520358L, 1693827457L, -1456646893L, -1436609854L, -265732748L, 1602862455L, -2036087187L, -126056188L, -1895474134L, -708152939L, 1014244911L, -1463712970L, 370195296L, 561594787L, 1011516097L, -45213008L, -1335257650L, 1075398969L, -2007112373L, -1571541254L, 1056464892L, 1389584447L, -1409738475L, -658726356L, 1479405314L, 1267940317L, -206833961L, -1874968130L, -312335368L, 426219483L, 1263790649L, 1238248328L, 1506302774L, 65489265L, -406232157L, 29962994L, 2141803076L, -23364345L, 353240285L, -1957695020L, 942232826L, -409957307L, -258270049L, -1495302618L, -1935770960L, 945710931L, -1129749903L, 1388785568L, -191985858L, -380563895L, 809134843L, -681567542L, -770339796L, 910152751L, -1307247387L, 1272542620L, 1427240946L, 117662317L, -2107103321L, 114760142L, -645353688L, 1581131051L, 53020489L, -896349096L, -144754426L, 475907297L, 595158131L, 1477374178L, 946329684L, -2012611241L, 1189121357L, -1595584284L, 1766739146L, 286499125L, -274552945L, 5469334L, 773635136L, -1328747261L, 1675518241L, -1046975984L, 200405486L, -1152653927L, 584843819L, 364573466L, -2068559396L, -994279457L, 378865589L, 1019093324L, -1042552926L, 1505464061L, 1047076855L, 1007118622L, 444421080L, -971786949L, 953815769L, 570527336L, -1382641770L, 2093808401L, -106605373L, -1041539886L, -607532700L, 2018389159L, 44438013L, -1965540364L, 669021402L, 723047973L, -1433367745L, 1434020038L, 1790862672L, 554978675L, 221468561L, 63007168L, -1461359714L, 1560991081L, 682413467L, 1537478826L, 216182476L, -619737201L, 1098488773L, 2040446844L, 1116848082L, -270053555L, -1848857081L, 72183278L, 899504328L, 1319704523L, 453091881L, -304242568L, -1638646362L, -1835472959L, 1051122771L, -2146323710L, -685107660L, -1377823817L, -258010195L, -1729799996L, -1883824918L, -1513893035L, -1808628497L, 1642334966L, -301287904L, -416371741L, -2052005759L, 383852272L, 1394036110L, -283057415L, 1303060619L, -1845221190L, -1052632132L, 292397311L, -2004155307L, -2084827284L, -2057297982L, 768915485L, 12257431L, -928538260L, -377676876L, -1283788270L, 1925150688L, -760604212L, -1444063008L, -925395934L, 1208744744L, 230402572L, -1517235396L, 131180530L, 187458288L, -1205507516L, 142366296L, -1695074502L, 133314544L, 1476332220L, 1897932052L, 2126408898L, 156961888L, 1319001468L, -1041195056L, 1135905058L, 1124298408L, 125640588L, -959707972L, -70798542L, 43210304L, 211989684L, 2108148808L, 330075578L, 84982288L, -1669231380L, 691450196L, 1364400914L, 967165344L, -126668084L, -576992672L, -1797806142L, 1360290600L, -823180884L, -1656081092L, 295256946L, -244366032L, -1813782748L, -1806883528L, -631798054L, -1375774832L, 1570972412L, 1513274260L, 1296155714L, 806489344L, -1015152580L, 1383222608L, -1374112606L, -1817412792L, -584143092L, -699633956L, 378865490L, -1233238400L, 888139860L, -702397464L, -462869766L, -1372058288L, 117200684L, -1078326412L, 1298170770L, 1529629280L, 989106060L, 363403104L, 168999906L, 1871088552L, 1234185420L, -1197618692L, -648294478L, 472079856L, -2118861372L, -36048552L, -1901558406L, 1744297392L, -1045986372L, 1369401428L, 1388404674L, 700028960L, 548204732L, -938534320L, 1317705698L, 507518568L, -1293705652L, -810342148L, -1102598158L, 147760384L, 1254595444L, -750217208L, -629888582L, 1353338320L, 1197970412L, -1049121900L, -1577071662L, 2024140640L, -1540048564L, -1165614816L, 56471426L, -1569337624L, 1400748268L, -1359184324L, -556670094L, -1355069840L, 730606628L, 1614995256L, 642515098L, 2015053520L, 668640444L, 1464388244L, -1099343230L, 1359564992L, -132553412L, -1391687536L, -1494843870L, -1177323000L, -1966287604L, 2065949340L, 864605714L, 147501440L, -187063788L, -1322861016L, -1521139398L, -1493591088L, 983912044L, -993494220L, -977718638L, -362216096L, -269224628L, -1175133216L, 1424301986L, 386178984L, -1867780212L, -1054098756L, 1005788018L, -1352826640L, 1903594564L, 1765043544L, 1357303866L, 1789068144L, 1917588540L, -801068268L, -1957655102L, -1794831136L, 786200444L, 104109776L, 1257298594L, 233051176L, 1610809612L, 451611580L, 1753040178L, -1234602048L, -209312204L, 1867426760L, 956064954L, -1026717808L, -227956244L, -2103208876L, 337517202L, -1258968288L, 171549132L, 1720703968L, 1901762242L, -575465944L, -229331284L, -1902459204L, -318914062L, 1951406384L, -16463708L, -2109228360L, 1057120090L, 283704720L, 253390204L, -282488556L, -94261950L, -84086016L, 803941308L, -786246832L, 320447778L, -744249016L, -1969058804L, -2048213924L, 1557996754L, -1275780096L, 1480337236L, 248502760L, 371801082L, -1016821040L, 503219500L, 1004592372L, -862018670L, -1346392992L, 235026700L, -1342334240L, 1442194786L, 565458600L, -308412852L, 1895732092L, 44572466L, 1107714672L, -1494314684L, 1750697944L, -302463878L, 672737840L, -2035274052L, 1986842452L, -1395016126L, -102137952L, -1942348612L, 2048430544L, -1681972894L, -1364170776L, 1593473996L, 1591713532L, 1025213426L, 1379243136L, -1535221516L, -694390648L, -1865912006L, 1256067920L, -1200136084L, -1473831788L, 164963666L, 1123923570L, -1173638464L, 744937257L, 222451099L, 1900900972L, -1839536518L, 1957975983L, 389214905L, -1157030706L, -705481188L, -384299635L, 1169202167L, 1148329728L, 1479144798L, 1394564651L, 1327386925L, -1013764710L, 1545534296L, -1386544447L, 988947827L, -922208620L, -260160734L, -1758654921L, 2011831041L, -236953082L, -2055978940L, 969462133L, 1595847903L, -1810528200L, 292605974L, -72073181L, 415752165L, 1041639938L, 25196656L, -1545449959L, 1677234187L, 1320798972L, -123479254L, 1976536415L, 108463337L, 2037912574L, -1973604372L, -868418755L, -505350393L, 197062384L, -27505010L, 2105428155L, -553648995L, -806473654L, 1750684264L, -788439471L, 2144412995L, 719524932L, 933926642L, 1516314311L, -284941167L, 1001249302L, -672036748L, -1209595L, -1895456433L, -1758829752L, -218606874L, 1542112275L, -1583236235L, -577807534L, -34485344L, -1541398903L, 1523083963L, -1714925300L, 643804314L, -1291832817L, 748639833L, -109810962L, -1428692612L, 1369674221L, 347037335L, 789444960L, -1430291138L, 1761979915L, 1220795021L, 1626068922L, 574399992L, -226459231L, 1620059987L, -851548556L, -1854396414L, -1278127465L, 1463385185L, 165533862L, -385202012L, 736198997L, 1821843967L, -1080010600L, -1576745546L, 1004252739L, 158028677L, -1830045662L, -1672070384L, 541857465L, 2029546347L, 1939751516L, -82206838L, -1307488385L, -1533173047L, -876065954L, -359305204L, 1808900061L, -286872857L, -1026194672L, 264493614L, -1544716069L, 1133067709L, -1590932694L, 2140816328L, 1302085873L, 1302445667L, 1461291620L, -65443438L, 1411024487L, -616888783L, 762788726L, 1261785236L, -1312907611L, 1958218671L, 1481861224L, -981681082L, 1023179251L, -1684011691L, -1342681294L, -1460911360L, 1958619113L, -1342408101L, 966567084L, -1003750726L, -190353297L, 1516211705L, 1838127246L, -990613156L, -1081407027L, -1030951625L, -378454080L, 918075550L, -1987682965L, 1988822253L, -1219840678L, -1348159976L, 1315496833L, -1207322317L, -639068332L, 559182178L, -1879574025L, 459651649L, -1290318138L, 195743748L, -186073163L, -1334120289L, 141339896L, 1231049942L, -1807743645L, -2086489819L, 703325890L, -627301456L, -766083111L, -1817331381L, -1613742148L, 1223628778L, -1313095649L, -615594327L, 1712036414L, -617939611L)
print.LM <- function(x, ...){ a <- x[[1]] b <- x[[2]] cat('Sign test result: \n No. of positive values: ',a,' \n No. of negative values: ',b, "\n" ) }
rpqueue <- function() { newq <- new.env(parent = emptyenv()) newq$lhat <- rstack() newq$l <- rstack() newq$r <- rstack() class(newq) <- "rpqueue" return(newq) }
test_that("brightness_pillars works", { d <- 2:4 aaa <- array(seq_len(prod(d)), dim = d) expect_equal( ijtiff::ijtiff_img(brightness_pillars(aaa)), ijtiff::ijtiff_img(apply_on_pillars(aaa, brightness_vec)) ) }) test_that("pillar-stats works", { d <- 2:4 aaa <- array(seq_len(prod(d)), dim = d) expect_equal( ijtiff::ijtiff_img(mean_pillars(aaa)), ijtiff::ijtiff_img(apply_on_pillars(aaa, mean)) ) expect_equal( ijtiff::ijtiff_img(median_pillars(aaa)), ijtiff::ijtiff_img(apply_on_pillars(aaa, median)) ) expect_equal( ijtiff::ijtiff_img(var_pillars(aaa)), ijtiff::ijtiff_img(apply_on_pillars(aaa, var)) ) d <- 2:5 aaaa <- array(sample.int(prod(d)), dim = d) skip_if_not_installed("abind") ans <- purrr::map(seq_len(dim(aaaa)[3]), ~ mean_pillars(aaaa[, , ., ])) %>% purrr::reduce(~ abind::abind(.x, .y, along = 3)) %>% structure(dimnames = NULL) expect_equal( ijtiff::ijtiff_img(mean_pillars(aaaa)), ijtiff::ijtiff_img(ans) ) ans <- purrr::map(seq_len(dim(aaaa)[3]), ~ median_pillars(aaaa[, , ., ])) %>% purrr::reduce(~ abind::abind(.x, .y, along = 3)) %>% structure(dimnames = NULL) expect_equal( ijtiff::ijtiff_img(median_pillars(aaaa)), ijtiff::ijtiff_img(ans) ) ans <- purrr::map(seq_len(dim(aaaa)[3]), ~ var_pillars(aaaa[, , ., ])) %>% purrr::reduce(~ abind::abind(.x, .y, along = 3)) %>% structure(dimnames = NULL) expect_equal( ijtiff::ijtiff_img(var_pillars(aaaa)), ijtiff::ijtiff_img(ans) ) ans <- purrr::map( seq_len(dim(aaaa)[3]), ~ brightness_pillars(aaaa[, , ., ]) ) %>% purrr::reduce(~ abind::abind(.x, .y, along = 3)) %>% structure(dimnames = NULL) expect_equal( ijtiff::ijtiff_img(brightness_pillars(aaaa)), ijtiff::ijtiff_img(ans) ) })
test_that("matsindf_apply() fails with an unexpected argument", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_error(matsindf_apply(.dat = "a string", FUN = example_fun, a = 2, b = 2), ".dat must be a data frame or a list in matsindf_apply, was character") }) test_that("matsindf_apply() works as expected for single values", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_equal(example_fun(a = 2, b = 2), list(c = 4, d = 0)) expect_equal(matsindf_apply(FUN = example_fun, a = 2, b = 2), list(c = 4, d = 0)) }) test_that("matsindf_apply() works as expected for single matrices", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("r1", "r2"), c("c1", "c2"))) b <- a expected_list <- list(c = a + b, d = a - b) expect_equal(example_fun(a, b), expected_list) expect_equal(matsindf_apply(FUN = example_fun, a = a, b = b), expected_list) }) test_that("matsindf_apply() works as expected for lists of single values", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_equal(example_fun(a = list(2, 2), b = list(2, 2)), list(c = list(4, 4), d = list(0, 0))) expect_equal(matsindf_apply(FUN = example_fun, a = list(2, 2, 2), b = list(2, 2, 2)), data.frame(c = I(list(4, 4, 4)), d = I(list(0, 0, 0)), stringsAsFactors = FALSE), ignore_attr = TRUE) expect_equal(matsindf_apply(FUN = example_fun, a = list(2, 2), b = list(1, 2)), data.frame(c = I(list(3, 4)), d = I(list(1, 0)), stringsAsFactors = FALSE), ignore_attr = TRUE) }) test_that("matsindf_apply() works as expected for lists of matrices", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("r1", "r2"), c("c1", "c2"))) b <- a c <- a + b d <- a - b a <- list(a, a) b <- list(b, b) DF_expected <- data.frame(c = I(list(c, c)), d = I(list(d, d)), stringsAsFactors = FALSE) attr(DF_expected$c, which = "class") <- NULL attr(DF_expected$d, which = "class") <- NULL expect_equal(matsindf_apply(FUN = example_fun, a = a, b = b), DF_expected) }) test_that("matsindf_apply() works as expected using .DF with single numbers", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } DF <- tibble::tibble(a = c(4, 4, 5), b = c(4, 4, 4)) expect_equal(matsindf_apply(DF, FUN = example_fun, a = "a", b = "b"), tibble::tibble(a = c(4, 4, 5), b = c(4, 4, 4), c = c(8, 8, 9), d = c(0, 0, 1))) }) test_that("matsindf_apply() works as expected using .DF with matrices", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("r1", "r2"), c("c1", "c2"))) b <- a c <- a + b d <- a - b DF <- data.frame(a = I(list(a, a)), b = I(list(b,b)), stringsAsFactors = FALSE) result <- matsindf_apply(DF, FUN = example_fun, a = "a", b = "b") expected <- dplyr::bind_cols(DF, data.frame(c = I(list(c, c)), d = I(list(d, d)), stringsAsFactors = FALSE)) expect_equal(result, expected, ignore_attr = TRUE) result <- DF %>% matsindf_apply(FUN = example_fun, a = "a", b = "b") expect_equal(result, expected, ignore_attr = TRUE) }) test_that("matsindf_apply() fails as expected when not all same type for ...", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_error(matsindf_apply(FUN = example_fun, a = "a", b = 2), 'argument "a" is missing, with no default') }) test_that("matsindf_apply() fails as expected when wrong type of data is sent in ...", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_error(matsindf_apply(FUN = example_fun, a = list("a"), b = list(2)), "non-numeric argument to binary operator") }) test_that("matsindf_apply() fails gracefully when some of ... are NULL", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_error(matsindf_apply(FUN = example_fun, a = 1, b = 2, c = NULL), "unused argument") }) test_that("matsindf_apply() fails as expected when .DF argument is missing from a data frame", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_error(matsindf_apply(FUN = example_fun, a = "a", b = "b"), ".dat was missing and all arguments were strings") }) test_that("matsindf_apply() fails as expected when .DF argument is not a data frame or a list", { expect_error(matsindf_apply(.DF = "string", FUN = example_fun, a = "a", b = "b"), ".dat was missing and all arguments were strings") }) test_that("matsindf_apply_types() works as expected", { expect_equal(matsindf_apply_types(a = 1, b = 2), list(dots_present = TRUE, all_dots_num = TRUE, all_dots_mats = FALSE, all_dots_list = FALSE, all_dots_vect = FALSE, all_dots_char = FALSE)) expect_equal(matsindf_apply_types(a = matrix(c(1, 2)), b = matrix(c(2, 3)), c = matrix(c(3, 4))), list(dots_present = TRUE, all_dots_num = FALSE, all_dots_mats = TRUE, all_dots_list = FALSE, all_dots_vect = FALSE, all_dots_char = FALSE)) expect_equal(matsindf_apply_types(a = list(1, 2), b = list(3, 4), c = list(5, 6)), list(dots_present = TRUE, all_dots_num = FALSE, all_dots_mats = FALSE, all_dots_list = TRUE, all_dots_vect = TRUE, all_dots_char = FALSE)) expect_equal(matsindf_apply_types(a = "a", b = "b", c = "c"), list(dots_present = TRUE, all_dots_num = FALSE, all_dots_mats = FALSE, all_dots_list = FALSE, all_dots_vect = FALSE, all_dots_char = TRUE)) expect_equal(matsindf_apply_types(), list(dots_present = FALSE, all_dots_num = FALSE, all_dots_mats = FALSE, all_dots_list = FALSE, all_dots_vect = FALSE, all_dots_char = FALSE)) }) test_that("matsindf_apply() works with a NULL argument", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("r1", "r2"), c("c1", "c2"))) b <- a c <- a + b d <- a - b DF <- data.frame(a = I(list(a, a)), b = I(list(b,b)), stringsAsFactors = FALSE) result <- matsindf_apply(DF, FUN = example_fun, a = "a", b = "b", z = NULL) expected <- dplyr::bind_cols(DF, data.frame(c = I(list(c, c)), d = I(list(d, d)), stringsAsFactors = FALSE)) expect_equal(result, expected, ignore_attr = TRUE) result <- DF %>% matsindf_apply(FUN = example_fun, a = "a", b = "b", z = NULL) expect_equal(result, expected, ignore_attr = TRUE) }) test_that("matsindf_apply() works when .DF is a list", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_equal(matsindf_apply(list(a = 1, b = 2), FUN = example_fun, a = "a", b = "b"), list(a = 1, b = 2, c = 3, d = -1)) }) test_that("matsindf_apply() works when .DF supplies some or all argument names", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_equal(matsindf_apply(list(a = 1, b = 2), FUN = example_fun), list(a = 1, b = 2, c = 3, d = -1)) expect_equal(matsindf_apply(list(a = 1, b = 2), FUN = example_fun, a = "a", b = "b"), list(a = 1, b = 2, c = 3, d = -1)) expect_equal(matsindf_apply(list(a = 1, b = 2, z = 10), FUN = example_fun, a = "z", b = "b"), list(a = 1, b = 2, z = 10, c = 12, d = 8)) expect_warning(res <- matsindf_apply(list(a = 1, b = 2, c = 10), FUN = example_fun, a = "c", b = "b"), "name collision in matsindf_apply: c") expect_equal(res, c(list(a = 1, b = 2, c = 10), list(c = 12, d = 8))) }) test_that("matsindf_apply() works for single numbers in data frame columns", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } DF <- tibble::tibble(a = c(4, 4, 5), b = c(4, 4, 4)) expected <- DF expected$c <- c(8, 8, 9) expected$d <- c(0, 0, 1) expect_equal(matsindf_apply(DF, FUN = example_fun, a = "a", b = "b"), expected) expect_equal(matsindf_apply(DF, FUN = example_fun), expected) }) test_that("override works() for single numbers supplied in a list", { example_fun <- function(a, b){ return(list(c = matsbyname::sum_byname(a, b), d = matsbyname::difference_byname(a, b))) } expect_equal(matsindf_apply(list(a = 2, b = 1), FUN = example_fun, a = 10), list(a = 10, b = 1, c = 11, d = 9)) }) test_that("matsindf_apply() works when an argument is missing", { outer_fun <- function(.DF = NULL, a = "a", b = "b"){ inner_fun <- function(a_num, b_num = NULL){ return(list(c = matsbyname::sum_byname(a_num, b_num), d = matsbyname::difference_byname(a_num, b_num))) } matsindf_apply(.DF, FUN = inner_fun, a_num = a, b_num = b) } expect_equal(outer_fun(a = 2, b = 2), list(c = 4, d = 0)) expect_equal(outer_fun(a = 2), list(c = 2, d = 2)) expect_error(outer_fun(b = 2), 'argument "a_num" is missing, with no default') }) test_that("matsindf_apply() works with functions similar in form to those in `Recca`", { find_matching_rownames <- function(.DF = NULL, prefixes, m = "m", out_colname = "matching_rows") { rowmatch_fun <- function(prefixes_arg, m_arg) { out <- m_arg %>% matsbyname::select_rows_byname(retain_pattern = RCLabels::make_or_pattern(strings = prefixes_arg, pattern_type = "leading")) %>% matsbyname::getrownames_byname() if (!is.list(out)) { out <- list(out) } out %>% magrittr::set_names(out_colname) } matsindf_apply(.DF, FUN = rowmatch_fun, prefixes_arg = prefixes, m_arg = m) } mat <- matrix(c(0, 1, 2, 3, 4, 5), nrow = 3, ncol = 2, byrow = TRUE, dimnames = list(c("ra1", "ra2", "b3"), c("c1", "c2"))) expect_error(find_matching_rownames(prefixes = "ra", m = mat), 'argument "prefixes_arg" is missing, with no default') res2 <- find_matching_rownames(prefixes = list("ra"), m = list(mat)) expect_type(res2, type = "list") expect_s3_class(res2, class = "data.frame") expect_equal(res2[["matching_rows"]][[1]], c("ra1", "ra2")) res3 <- find_matching_rownames(prefixes = list("ra", "ra"), m = list(mat, mat)) expect_type(res3, type = "list") expect_s3_class(res3, class = "data.frame") expect_equal(res3[["matching_rows"]][[1]], c("ra1", "ra2")) expect_equal(res3[["matching_rows"]][[2]], c("ra1", "ra2")) expect_equal(ncol(res3), 1) df <- tibble::tibble(prefixes = list("ra", c("r", "b"), "b"), m = list(mat, mat, mat)) %>% find_matching_rownames(prefixes = "prefixes") expect_equal(df$matching_rows[[1]], c("ra1", "ra2")) expect_equal(df$matching_rows[[2]], c("ra1", "ra2", "b3")) expect_equal(df$matching_rows[[3]], "b3") }) test_that("matsindf_apply() issues a warning when replacing a column", { a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("r1", "r2"), c("c1", "c2"))) b <- 2 * a DF <- data.frame(a = I(list(a, a)), b = I(list(b, b)), stringsAsFactors = FALSE) replace_func <- function(a_mat, b_mat) { a <- matsbyname::difference_byname(a_mat, b_mat) d <- matsbyname::sum_byname(a_mat, b_mat) list(a, d) %>% magrittr::set_names(c(a_name, d_name)) } a_name <- "a" d_name <- "d" expect_warning( suppressMessages( matsindf_apply(DF, FUN = replace_func, a_mat = "a", b_mat = "b") ), "name collision in matsindf_apply: a" ) })
pchc <- function(x, method = "pearson", alpha = 0.05, robust = FALSE, ini.stat = NULL, R = NULL, restart = 10, score = "bic-g", blacklist = NULL, whitelist = NULL) { runtime <- proc.time() if ( robust ) { dm <- dim(x) n <- dm[1] ; p <- dm[2] mod <- robustbase::covMcd( x, alpha = ceiling( 0.5 * (n + p + 1) )/n ) w <- sum( mod$mcd.wt ) d1 <- w / (w - 1)^2 * mod$mah[mod$mcd.wt == 1] d0 <- w / (w + 1) * (w - p) / ( (w - 1) * p ) * mod$mah[mod$mcd.wt == 0] ep1 <- which( d1 > qbeta(0.975, 0.5 * p, 0.5 * (w - p - 1) ) ) ep0 <- which( d0 > qf(0.975, p, w - p) ) poia <- c( which(mod$mcd.wt == 1)[ep1], which(mod$mcd.wt == 0)[ep0] ) x <- x[-poia, ] n <- dim(x)[1] } if ( method == "cat" & !is.matrix(x) ) { for ( i in 1:dim(x)[2] ) x[, i] <- as.numeric(x[, i]) - 1 x <- Rfast::data.frame.to_matrix(x, col.names = colnames(x) ) } if ( method == "pearson" & is.null(ini.stat) & !is.null(R) ) { ini.stat <- 0.5 * log( (1 + R)/( (1 - R) ) ) * sqrt(n - 3) } a <- Rfast::pc.skel(x, method = method, alpha = alpha, stat = ini.stat) nama <- colnames(x) if ( is.null(nama) ) nama <- paste("X", 1:dim(x)[2], sep = "") colnames(x) <- nama vale <- which(a$G == 1) dag <- NULL scoring <- NULL if ( length(vale) > 0 ) { x <- as.data.frame(x) mhvale <- as.data.frame( which(a$G == 0, arr.ind = TRUE) ) mhvale[, 1] <- nama[ mhvale[, 1] ] mhvale[, 2] <- nama[ mhvale[, 2] ] colnames(mhvale) <- c("from", "to") if ( !is.null(blacklist) ) { colnames(blacklist) <- c("from", "to") mhvale <- rbind(mhvale, blacklist) } if ( !is.null(whitelist) ) colnames(whitelist) <- c("from", "to") if ( method == "cat" ) { for ( i in 1:dim(x)[2] ) x[, i] <- as.factor(x[, i]) } dag <- bnlearn::hc(x, blacklist = mhvale, whitelist = whitelist, score = score, restart = restart) scoring <- bnlearn::score(x = dag, data = x, type = score ) } runtime <- proc.time() - runtime colnames(a$G) <- nama ; rownames(a$G) <- nama list(ini = a, dag = dag, scoring = scoring, runtime = runtime[3]) }
RMBCaux=function(Y,K, thetaOld.alpha,thetaOld.mu, thetaOld.sigma,max_iter, niterFixedPoint,tolerance,cutoff=1-1e-3){ n=nrow(Y); valLLK=rep(0,max_iter) errkl=2*tolerance; iter=1 thetaNew.alpha=0*thetaOld.alpha thetaNew.mu=lapply(thetaOld.mu,FUN=function(x){0*x}) thetaNew.sigma=lapply(thetaOld.sigma,FUN=function(x){0*x}) outliersConGr=which(!is_in_gr(Y, cutoff=cutoff,thetaOld.mu,thetaOld.sigma)); while ((errkl>tolerance) & (iter<max_iter)){ OutliersNew=outliersConGr Fji=matrix(0,nrow=K,ncol=n) logFji=matrix(0,nrow=K,ncol=n); alphaji=matrix(0,nrow=K,ncol=n) w=matrix(0,nrow=K,ncol=n); for (j in 1:K){ Fji[j,]=mvtnorm::dmvnorm(x=Y,mean=thetaOld.mu[[j]],sigma=as.matrix(thetaOld.sigma[[j]])); logFji[j,]=mvtnorm::dmvnorm(x=Y,mean=thetaOld.mu[[j]],sigma=as.matrix(thetaOld.sigma[[j]]),log=TRUE); } for (i in 1:n){ for (j in 1:K){ alphaji[j,i]=Fji[j,i]*thetaOld.alpha[j]/sum(Fji[,i]*thetaOld.alpha) } if (sum(Fji[,i])<1e-16){ KKK=min(abs(logFji[,i])) FjiNEW=exp(logFji[,i] + KKK); alphaji[,i]=FjiNEW*thetaOld.alpha/sum(FjiNEW*thetaOld.alpha) } } for (j in 1:K){ for (i in 1:n){ w[j,i]=alphaji[j,i]/sum(alphaji[j,]) } } for (j in 1:K){ thetaNew.alpha[j]=mean(alphaji[j,]) } for (j in 1:K){ muIni=thetaOld.mu[[j]] sigmaIni= thetaOld.sigma[[j]] salW=weightedSestimator(Y,muIni,sigmaIni,max_iterFP=niterFixedPoint, weights=alphaji[j,], fixed_alpha=thetaNew.alpha[j]) thetaNew.mu[[j]]=salW$mu thetaNew.sigma[[j]]=salW$cov } relativeAlphaDiff=abs(thetaOld.alpha/thetaNew.alpha - 1) maxErr=max(relativeAlphaDiff) if(maxErr<(tolerance)){ errkl=sumkl(thetaNew.mu,thetaNew.sigma,thetaOld.mu,thetaOld.sigma) } thetaOld.alpha=thetaNew.alpha; thetaOld.mu=thetaNew.mu thetaOld.sigma= thetaNew.sigma iter=iter+1 outliersConGr=which(!is_in_gr(Y, cutoff=cutoff,theta.mu=thetaNew.mu,theta.sigma=thetaNew.sigma)); nonoutliersConGr=which(is_in_gr(Y, cutoff=cutoff,theta.mu=thetaNew.mu,theta.sigma=thetaNew.sigma)); } salqs=quad_disc(Y = Y,theta.alpha = thetaNew.alpha, theta.mu = thetaNew.mu,theta.sigma = thetaNew.sigma) clusterRMBC=apply(salqs,1,function(x) which(x==max(x))[1]) list(theta.mu=thetaNew.mu,theta.sigma=thetaNew.sigma, theta.alpha= thetaNew.alpha, outliers=outliersConGr,nonoutliers=nonoutliersConGr, cluster=clusterRMBC,iter=iter-1) }
library(dplyr) al <- matrix(c( "A", "AT", "AT", "A", "A", "AT", "A", "AT", "A", "AT", "D", "I", "A", "AT", "I", "D", "AT", "A", "D", "I", "AT", "A", "I", "D", "D", "I", "AT", "A", "D", "I", "A", "AT", "I", "D", "AT", "A", "I", "D", "A", "AT", "I", "D", "AT", "AT", "I", "D", "D", "I" ), nrow=4) %>% t recode_indels_22(al[,1], al[,2], al[,3], al[,4]) %>% cbind(al, .) recode_indels_21(al[,1], al[,2], al[,3]) %>% cbind(al, .) recode_indels_12(al[,1], al[,3], al[,4]) %>% cbind(al, .) a <- extract_instruments(2) b <- extract_outcome_data(a$SNP, 7) ab <- harmonise_data(a,b) mr(ab, method_list="mr_ivw") a1 <- a b1 <- b a1$effect_allele.exposure[1] <- "GAAAA" b1$other_allele.outcome[23] <- "GAAAA" ab1 <- harmonise_data(a1,b1) mr(ab1, method_list="mr_ivw") a1 <- a b1 <- b a1$effect_allele.exposure[1] <- "GAAAA" b1$other_allele.outcome[23] <- "I" b1$effect_allele.outcome[23] <- "D" ab1 <- harmonise_data(a1,b1) mr(ab1, method_list="mr_ivw") a1 <- a b1 <- b b1$other_allele.outcome <- NA ab1 <- harmonise_data(a1,b1) mr(ab1, method_list="mr_ivw") a1 <- a b1 <- b a1$effect_allele.exposure[1] <- "GAAAA" b1$other_allele.outcome[23] <- "I" b1$effect_allele.outcome[23] <- "D" b1$other_allele.outcome <- NA ab1 <- harmonise_data(a1,b1) mr(ab1, method_list="mr_ivw") a1 <- a b1 <- b a1$effect_allele.exposure[1] <- "GAAAA" b1$other_allele.outcome[23] <- "I" b1$effect_allele.outcome[23] <- "D" b1$other_allele.outcome <- NA ab1 <- harmonise_data(a1,b1) mr(ab1, method_list="mr_ivw") x <- data.frame( SNP=c("a","b", "c", "d", "e", "f"), beta=1, se=1, effect_allele=c("D", "ACTG", "A", "G", "C", "TD"), other_allele=c("I", "F", "T", "C", "G", "A"), stringsAsFactors=FALSE ) format_data(x)
MBSGSSS = function(Y, X, group_size, pi0 = 0.5, pi1 = 0.5, a1 = 1, a2 = 1, c1 = 1, c2 = 1, pi_prior = TRUE, niter = 10000,burnin = 5000,d=3,num_update = 100, niter.update =100) { n = dim(Y)[1] q = dim(Y)[2] p = dim(X)[2] if(p<n){ model <- lm(Y~X) k <- mean(apply(model$residuals,2,var))}else{ var.res <- NULL for(l in 1:q){ mydata <- data.frame(y=Y[,l],X) min.model <- lm(y~-1,data=mydata) formula.model <- formula(lm(y~0+.,data=mydata)) model <- stepAIC(min.model,direction='forward',scope=formula.model,steps=n-1,trace=FALSE) var.res <- c(var.res,var(residuals(model))) } k <- mean(var.res) } Q = k*diag(q) ngroup = length(group_size) Sigma <- diag(q) l = rep(0, ngroup) b = vector(mode='list', length=ngroup) beta = vector(mode='list', length=ngroup) for(i in 1:ngroup){ beta[[i]]=matrix(1,ncol=q,nrow=group_size[i]) b[[i]]=matrix(1,ncol=q,nrow=group_size[i])} Z = rep(0, ngroup) m = dim(X)[2] b_prob = rep(0.5, ngroup) tau = rep(1, m) tau_prob = rep(0.5, m) s2 = 1 fit_for_t =MBSGSSS_EM_t(k,Y, X, group_size=group_size,num_update = num_update, niter=niter.update) t = tail(fit_for_t$t_path, 1) YtY = crossprod(Y, Y) XtY = crossprod(X, Y) XtX = crossprod(X, X) XktY = vector(mode='list', length=ngroup) XktXk = vector(mode='list', length=ngroup) XktXmk = vector(mode='list', length=ngroup) begin_idx = 1 for(i in 1:ngroup) { end_idx = begin_idx + group_size[i] - 1 Xk = X[,begin_idx:end_idx] XktY[[i]] = crossprod(Xk, Y) XktXk[[i]] = crossprod(Xk, Xk) XktXmk[[i]] = crossprod(Xk, X[,-(begin_idx:end_idx)]) begin_idx = end_idx + 1 } YtXi <- vector(mode='list', length=m) XmitXi = array(0, dim=c(m,m-1)) XitXi = rep(0, m) for(j in 1:m) { YtXi[[j]] = crossprod(Y, X[,j]) XmitXi[j,] = crossprod(X[,-j], X[,j]) XitXi[j] = crossprod(X[,j], X[,j]) } coef = vector("list", length=q) for(jj in 1:q){ coef[[jj]] <- array(0, dim=c(p, niter-burnin)) } bprob = array(-1, dim=c(ngroup, niter-burnin)) tauprob = array(-1, dim=c(m, niter-burnin)) for (iter in 1:niter) { Z = rep(0, ngroup) n_nzg = 0 n_nzt = 0 unif_samples = runif(m) idx = 1 Sigma_inv <- solve(Sigma) Beta <- do.call(rbind, beta) matb <- do.call(rbind, b) for(g in 1:ngroup) { for (j in 1:group_size[g]) { M = Sigma_inv%*%(YtXi[[idx]]-t(Beta[-idx,])%*%matrix(XmitXi[idx,],ncol=1,nrow=m-1))%*%matrix(matb[idx,],nrow=1,ncol=q) bsquare <- t(matrix(matb[idx,],ncol=q,nrow=1))%*%matrix(matb[idx,],ncol=q,nrow=1) vgj_square = 1/(sum(diag(XitXi[idx]*Sigma_inv%*%bsquare))+1/s2) ugj = sum(diag(M))*vgj_square tau_prob[idx] = pi1/( pi1 + 2 * (1-pi1) * ((s2)^(-0.5))*(vgj_square)^(0.5)* exp(pnorm(ugj/sqrt(vgj_square),log.p=TRUE) + ugj^2/(2*vgj_square))) if(unif_samples[idx] < tau_prob[idx]) { tau[idx] = 0 } else { tau[idx] = rtruncnorm(1, mean=ugj, sd=sqrt(vgj_square), a=0) n_nzt = n_nzt + 1 } idx = idx + 1 } } begin_idx = 1 unif_samples_group = runif(ngroup) for(g in 1:ngroup) { end_idx = begin_idx + group_size[g] - 1 Vg = diag(tau[begin_idx:end_idx]) Sig = solve(crossprod(Vg, XktXk[[g]]) %*% Vg + diag(group_size[g])) dev = (Vg %*% (XktY[[g]] - XktXmk[[g]] %*% Beta[-c(begin_idx:end_idx),])) num <- 0.5*sum(diag(solve(Sigma)%*%crossprod(dev,Sig)%*%dev)) exp.num <- exp(num) if(exp.num == Inf) exp.num <- 1.797693e+307 b_prob[g] = pi0 / ( pi0 + (1-pi0) * det(Sig)^(q/2) * exp.num) if(unif_samples_group[g] < b_prob[g]){ matb[begin_idx:end_idx,] = 0 b[[g]] = matrix(0,ncol=q,nrow=group_size[g]) Z[g] = 0} else { matb[begin_idx:end_idx,] = matrix(rmnorm(1, mean=c(Sig%*%dev), varcov=kronecker(Sigma,Sig)),ncol=q,nrow=group_size[g],byrow = FALSE) b[[g]] = matb[begin_idx:end_idx,] Z[g] = 1 n_nzg = n_nzg + 1 } Beta[begin_idx:end_idx,] = Vg %*% matb[begin_idx:end_idx,] beta[[g]] <- Beta[begin_idx:end_idx,] begin_idx = end_idx + 1 } if(iter > burnin){ for(jj in 1:q){ coef[[jj]][,iter-burnin] <- Beta[,jj] } bprob[,iter-burnin] = b_prob tauprob[,iter-burnin] = tau_prob } ddf <- d + n +sum(group_size*Z) res <- Y-X%*%Beta S <- t(res)%*%res+t(matb)%*%matb + Q Sigma <- riwish(ddf, S) if(pi_prior == TRUE) { pi0 = rbeta(1, ngroup - n_nzg + a1, n_nzg + a2) pi1 = rbeta(1, m - n_nzt + c1, n_nzt + c2) } s2 = rinvgamma(1, shape = 1 + n_nzt/2, scale = t + sum(tau)/2) } pos_mean = matrix(unlist(lapply(coef, FUN=function(x) apply(x, 1, mean))),ncol=q,nrow=p,byrow=FALSE) pos_median = matrix(unlist(lapply(coef, FUN=function(x) apply(x, 1, median))),ncol=q,nrow=p,byrow=FALSE) list(pos_mean = pos_mean, pos_median = pos_median, coef = coef) }
validate_state <- function(state, .msg=interactive()) { if (is.null(state)) return(NULL) state <- tolower(str_trim(state)) if (grepl("^[[:digit:]]+$", state)) { state <- sprintf("%02d", as.numeric(state)) if (state %in% fips_state_table$fips) { return(state) } else { state_sub <- substr(state, 1, 2) if (state_sub %in% fips_state_table$fips) { message(sprintf("Using first two digits of %s - '%s' (%s) - for FIPS code.", state, state_sub, fips_state_table[fips_state_table$fips == state_sub, "name"]), call.=FALSE) return(state_sub) } else { stop(sprintf("'%s' is not a valid FIPS code or state name/abbreviation", state), call.=FALSE) } } } else if (grepl("^[[:alpha:]]+", state)) { if (nchar(state) == 2 && state %in% fips_state_table$abb) { if (.msg) message(sprintf("Using FIPS code '%s' for state '%s'", fips_state_table[fips_state_table$abb == state, "fips"], toupper(state))) return(fips_state_table[fips_state_table$abb == state, "fips"]) } else if (nchar(state) > 2 && state %in% fips_state_table$name) { if (.msg) message(sprintf("Using FIPS code '%s' for state '%s'", fips_state_table[fips_state_table$name == state, "fips"], simpleCapSO(state))) return(fips_state_table[fips_state_table$name == state, "fips"]) } else { stop(sprintf("'%s' is not a valid FIPS code or state name/abbreviation", state), call.=FALSE) } } else { stop(sprintf("'%s' is not a valid FIPS code or state name/abbreviation", state), call.=FALSE) } } validate_county <- function(state, county, .msg = interactive()) { if (is.null(state) || is.null(county)) return(NULL) state <- validate_state(state) county_table <- fips_codes[fips_codes$state_code == state, ] if (grepl("^[[:digit:]]+$", county)) { county <- sprintf("%03d", as.numeric(county)) if (county %in% county_table$county_code) { return(county) } else { warning(sprintf("'%s' is not a current FIPS code for counties in %s", county, county_table$state_name[1]), call. = FALSE) return(county) } } else if ((grepl("^[[:alpha:]]+", county))) { county_index <- grepl(sprintf("^%s", county), county_table$county, ignore.case = TRUE) matching_counties <- county_table$county[county_index] if (length(matching_counties) == 0) { stop(sprintf("'%s' is not a valid name for counties in %s", county, county_table$state_name[1]), call. = FALSE) } else if (length(matching_counties) == 1) { if (.msg) message(sprintf("Using FIPS code '%s' for '%s'", county_table[county_table$county == matching_counties, "county_code"], matching_counties)) return(county_table[county_table$county == matching_counties, "county_code"]) } else if (length(matching_counties) > 1) { ctys <- format_vec(matching_counties) stop("Your county string matches ", ctys, " Please refine your selection.", call. = FALSE) } } } format_vec <- function(vec) { out <- paste0(vec, ', ') l <- length(out) out[l - 1] <- paste0(out[l - 1], 'and ') out[l] <- gsub(', ', '.', out[l]) return(paste0(out, collapse = '')) } simpleCapSO <- function(x) { s <- strsplit(x, " ")[[1]] paste0(toupper(substring(s, 1,1)), substring(s, 2), collapse=" ") } print_api_call <- function(url) { url <- gsub("&key.*", "", url) message(paste("Census API call:", utils::URLdecode(url))) }
icd9_sub_chapters <- list( `Intestinal Infectious Diseases` = c(start = "001", end = "009"), Tuberculosis = c(start = "010", end = "018"), `Zoonotic Bacterial Diseases` = c( start = "020", end = "027" ), `Other Bacterial Diseases` = c(start = "030", end = "041"), `Human Immunodeficiency Virus (Hiv) Infection` = c( start = "042", end = "042" ), `Poliomyelitis And Other Non-Arthropod-Borne Viral Diseases And Prion Diseases Of Central Nervous System` = c( start = "045", end = "049" ), `Viral Diseases Generally Accompanied By Exanthem` = c( start = "050", end = "059" ), `Arthropod-Borne Viral Diseases` = c( start = "060", end = "066" ), `Other Diseases Due To Viruses And Chlamydiae` = c( start = "070", end = "079" ), `Rickettsioses And Other Arthropod-Borne Diseases` = c( start = "080", end = "088" ), `Syphilis And Other Venereal Diseases` = c( start = "090", end = "099" ), `Other Spirochetal Diseases` = c( start = "100", end = "104" ), Mycoses = c(start = "110", end = "118"), Helminthiases = c( start = "120", end = "129" ), `Other Infectious And Parasitic Diseases` = c( start = "130", end = "136" ), `Late Effects Of Infectious And Parasitic Diseases` = c( start = "137", end = "139" ), `Malignant Neoplasm Of Lip, Oral Cavity, And Pharynx` = c( start = "140", end = "149" ), `Malignant Neoplasm Of Digestive Organs And Peritoneum` = c( start = "150", end = "159" ), `Malignant Neoplasm Of Respiratory And Intrathoracic Organs` = c( start = "160", end = "165" ), `Malignant Neoplasm Of Bone, Connective Tissue, Skin, And Breast` = c( start = "170", end = "176" ), `Malignant Neoplasm Of Genitourinary Organs` = c( start = "179", end = "189" ), `Malignant Neoplasm Of Other And Unspecified Sites` = c( start = "190", end = "199" ), `Malignant Neoplasm Of Lymphatic And Hematopoietic Tissue` = c( start = "200", end = "208" ), `Neuroendocrine Tumors` = c(start = "209", end = "209"), `Benign Neoplasms` = c(start = "210", end = "229"), `Carcinoma In Situ` = c( start = "230", end = "234" ), `Neoplasms Of Uncertain Behavior` = c( start = "235", end = "238" ), `Neoplasms Of Unspecified Nature` = c( start = "239", end = "239" ), `Disorders Of Thyroid Gland` = c( start = "240", end = "246" ), `Diseases Of Other Endocrine Glands` = c( start = "249", end = "259" ), `Nutritional Deficiencies` = c(start = "260", end = "269"), `Other Metabolic And Immunity Disorders` = c( start = "270", end = "279" ), `Diseases Of The Blood And Blood-Forming Organs` = c(start = "280", end = "289"), `Organic Psychotic Conditions` = c( start = "290", end = "294" ), `Other Psychoses` = c(start = "295", end = "299"), `Neurotic Disorders, Personality Disorders, And Other Nonpsychotic Mental Disorders` = c( start = "300", end = "316" ), `Intellectual Disabilities` = c( start = "317", end = "319" ), `Inflammatory Diseases Of The Central Nervous System` = c( start = "320", end = "326" ), `Organic Sleep Disorders` = c(start = "327", end = "327"), `Hereditary And Degenerative Diseases Of The Central Nervous System` = c( start = "330", end = "337" ), Pain = c(start = "338", end = "338"), `Other Headache Syndromes` = c( start = "339", end = "339" ), `Other Disorders Of The Central Nervous System` = c( start = "340", end = "349" ), `Disorders Of The Peripheral Nervous System` = c( start = "350", end = "359" ), `Disorders Of The Eye And Adnexa` = c( start = "360", end = "379" ), `Diseases Of The Ear And Mastoid Process` = c( start = "380", end = "389" ), `Acute Rheumatic Fever` = c(start = "390", end = "392"), `Chronic Rheumatic Heart Disease` = c(start = "393", end = "398"), `Hypertensive Disease` = c(start = "401", end = "405"), `Ischemic Heart Disease` = c( start = "410", end = "414" ), `Diseases Of Pulmonary Circulation` = c( start = "415", end = "417" ), `Other Forms Of Heart Disease` = c( start = "420", end = "429" ), `Cerebrovascular Disease` = c(start = "430", end = "438"), `Diseases Of Arteries, Arterioles, And Capillaries` = c( start = "440", end = "449" ), `Diseases Of Veins And Lymphatics, And Other Diseases Of Circulatory System` = c( start = "451", end = "459" ), `Acute Respiratory Infections` = c( start = "460", end = "466" ), `Other Diseases Of The Upper Respiratory Tract` = c( start = "470", end = "478" ), `Pneumonia And Influenza` = c(start = "480", end = "488"), `Chronic Obstructive Pulmonary Disease And Allied Conditions` = c( start = "490", end = "496" ), `Pneumoconioses And Other Lung Diseases Due To External Agents` = c( start = "500", end = "508" ), `Other Diseases Of Respiratory System` = c( start = "510", end = "519" ), `Diseases Of Oral Cavity, Salivary Glands, And Jaws` = c( start = "520", end = "529" ), `Diseases Of Esophagus, Stomach, And Duodenum` = c( start = "530", end = "539" ), Appendicitis = c(start = "540", end = "543"), `Hernia Of Abdominal Cavity` = c( start = "550", end = "553" ), `Noninfectious Enteritis And Colitis` = c( start = "555", end = "558" ), `Other Diseases Of Intestines And Peritoneum` = c( start = "560", end = "569" ), `Other Diseases Of Digestive System` = c( start = "570", end = "579" ), `Nephritis, Nephrotic Syndrome, And Nephrosis` = c( start = "580", end = "589" ), `Other Diseases Of Urinary System` = c( start = "590", end = "599" ), `Diseases Of Male Genital Organs` = c( start = "600", end = "608" ), `Disorders Of Breast` = c(start = "610", end = "612"), `Inflammatory Disease Of Female Pelvic Organs` = c( start = "614", end = "616" ), `Other Disorders Of Female Genital Tract` = c( start = "617", end = "629" ), `Ectopic And Molar Pregnancy` = c( start = "630", end = "633" ), `Other Pregnancy With Abortive Outcome` = c( start = "634", end = "639" ), `Complications Mainly Related To Pregnancy` = c( start = "640", end = "649" ), `Normal Delivery, And Other Indications For Care In Pregnancy, Labor, And Delivery` = c( start = "650", end = "659" ), `Complications Occurring Mainly In The Course Of Labor And Delivery` = c( start = "660", end = "669" ), `Complications Of The Puerperium` = c( start = "670", end = "677" ), `Other Maternal And Fetal Complications` = c( start = "678", end = "679" ), `Infections Of Skin And Subcutaneous Tissue` = c( start = "680", end = "686" ), `Other Inflammatory Conditions Of Skin And Subcutaneous Tissue` = c( start = "690", end = "698" ), `Other Diseases Of Skin And Subcutaneous Tissue` = c( start = "700", end = "709" ), `Arthropathies And Related Disorders` = c( start = "710", end = "719" ), Dorsopathies = c(start = "720", end = "724"), `Rheumatism, Excluding The Back` = c( start = "725", end = "729" ), `Osteopathies, Chondropathies, And Acquired Musculoskeletal Deformities` = c( start = "730", end = "739" ), `Congenital Anomalies` = c(start = "740", end = "759"), `Maternal Causes Of Perinatal Morbidity And Mortality` = c( start = "760", end = "763" ), `Other Conditions Originating In The Perinatal Period` = c( start = "764", end = "779" ), Symptoms = c(start = "780", end = "789"), `Nonspecific Abnormal Findings` = c( start = "790", end = "796" ), `Ill-Defined And Unknown Causes Of Morbidity And Mortality` = c( start = "797", end = "799" ), `Fracture Of Skull` = c( start = "800", end = "804" ), `Fracture Of Neck And Trunk` = c( start = "805", end = "809" ), `Fracture Of Upper Limb` = c(start = "810", end = "819"), `Fracture Of Lower Limb` = c(start = "820", end = "829"), Dislocation = c(start = "830", end = "839"), `Sprains And Strains Of Joints And Adjacent Muscles` = c( start = "840", end = "848" ), `Intracranial Injury, Excluding Those With Skull Fracture` = c( start = "850", end = "854" ), `Internal Injury Of Thorax, Abdomen, And Pelvis` = c( start = "860", end = "869" ), `Open Wound Of Head, Neck, And Trunk` = c( start = "870", end = "879" ), `Open Wound Of Upper Limb` = c( start = "880", end = "887" ), `Open Wound Of Lower Limb` = c( start = "890", end = "897" ), `Injury To Blood Vessels` = c( start = "900", end = "904" ), `Late Effects Of Injuries, Poisonings, Toxic Effects, And Other External Causes` = c( start = "905", end = "909" ), `Superficial Injury` = c(start = "910", end = "919"), `Contusion With Intact Skin Surface` = c( start = "920", end = "924" ), `Crushing Injury` = c(start = "925", end = "929"), `Effects Of Foreign Body Entering Through Orifice` = c( start = "930", end = "939" ), Burns = c(start = "940", end = "949"), `Injury To Nerves And Spinal Cord` = c( start = "950", end = "957" ), `Certain Traumatic Complications And Unspecified Injuries` = c( start = "958", end = "959" ), `Poisoning By Drugs, Medicinal And Biological Substances` = c( start = "960", end = "979" ), `Toxic Effects Of Substances Chiefly Nonmedicinal As To Source` = c( start = "980", end = "989" ), `Other And Unspecified Effects Of External Causes` = c( start = "990", end = "995" ), `Complications Of Surgical And Medical Care, Not Elsewhere Classified` = c( start = "996", end = "999" ), `Persons With Potential Healthhazards Related To Communicable Diseases` = c( start = "V01", end = "V06" ), `Persons With Need For Isolation, Other Potential Health Hazards And Prophylactic Measures` = c( start = "V07", end = "V09" ), `Persons With Potential Health Hazards Related To Personal And Family History` = c( start = "V10", end = "V19" ), `Persons Encountering Health Services In Circumstances Related To Reproduction And Development` = c( start = "V20", end = "V29" ), `Liveborn Infants According To Type Of Birth` = c( start = "V30", end = "V39" ), `Persons With A Condition Influencing Their Health Status` = c( start = "V40", end = "V49" ), `Persons Encountering Health Services For Specific Procedures And Aftercare` = c( start = "V50", end = "V59" ), `Persons Encountering Health Services In Other Circumstances` = c( start = "V60", end = "V69" ), `Persons Without Reported Diagnosis Encountered During Examination And Investigation Of Individuals And Populations` = c( start = "V70", end = "V82" ), Genetics = c(start = "V83", end = "V84"), `Body Mass Index` = c( start = "V85", end = "V85" ), `Estrogen Receptor Status` = c( start = "V86", end = "V86" ), `Other Specified Personal Exposures And History Presenting Hazards To Health` = c( start = "V87", end = "V87" ), `Acquired Absence Of Other Organs And Tissue` = c( start = "V88", end = "V88" ), `Other Suspected Conditions Not Found` = c( start = "V89", end = "V89" ), `Retained Foreign Body` = c( start = "V90", end = "V90" ), `Multiple Gestation Placenta Status` = c( start = "V91", end = "V91" ), `External Cause Status` = c( start = "E000", end = "E000" ), Activity = c(start = "E001", end = "E030"), `Railway Accidents` = c(start = "E800", end = "E807"), `Motor Vehicle Traffic Accidents` = c( start = "E810", end = "E819" ), `Motor Vehicle Nontraffic Accidents` = c( start = "E820", end = "E825" ), `Other Road Vehicle Accidents` = c( start = "E826", end = "E829" ), `Water Transport Accidents` = c( start = "E830", end = "E838" ), `Air And Space Transport Accidents` = c( start = "E840", end = "E845" ), `Vehicle Accidents Not Elsewhere Classifiable` = c( start = "E846", end = "E848" ), `Place Of Occurrence` = c( start = "E849", end = "E849" ), `Accidental Poisoning By Drugs, Medicinal Substances, And Biologicals` = c( start = "E850", end = "E858" ), `Accidental Poisoning By Other Solid And Liquid Substances, Gases, And Vapors` = c( start = "E860", end = "E869" ), `Misadventures To Patients During Surgical And Medical Care` = c( start = "E870", end = "E876" ), `Surgical And Medical Procedures As The Cause Of Abnormal Reaction Of Patient Or Later Complication,Without Mention Of Misadventure At The Time Of Procedure` = c( start = "E878", end = "E879" ), `Accidental Falls` = c(start = "E880", end = "E888"), `Accidents Caused By Fire And Flames` = c( start = "E890", end = "E899" ), `Accidents Due To Natural And Environmental Factors` = c( start = "E900", end = "E909" ), `Accidents Caused By Submersion, Suffocation, And Foreign Bodies` = c( start = "E910", end = "E915" ), `Other Accidents` = c(start = "E916", end = "E928"), `Late Effects Of Accidental Injury` = c( start = "E929", end = "E929" ), `Drugs, Medicinal And Biological Substances Causing Adverse Effects In Therapeutic Use` = c( start = "E930", end = "E949" ), `Suicide And Self-Inflicted Injury` = c( start = "E950", end = "E959" ), `Homicide And Injury Purposely Inflicted By Other Persons` = c( start = "E960", end = "E969" ), `Legal Intervention` = c(start = "E970", end = "E978"), Terrorism = c(start = "E979", end = "E979"), `Injury Undetermined Whether Accidentally Or Purposely Inflicted` = c( start = "E980", end = "E989" ), `Injury Resulting From Operations Of War` = c( start = "E990", end = "E999" ) )
water_vp_sat <- function(temperature, over.ice = FALSE, method = "tetens", check.range = TRUE) { method <- tolower(method) if (length(method) > 1L) { if (length(unique(method)) > 1L) { stop("Only one method can be used per function call.") } else { method <- method[1L] } } if (length(over.ice) == 1L && length(temperature > 1)) { over.ice <- rep_len(over.ice, length(temperature)) } if (any(temperature > 0 & over.ice)) { warning("At temperature > 0 C, ice surface will be wet.") } if (method == "magnus") { if (check.range && any(!is.na(temperature) & (temperature < -80 | temperature > 50))) { warning("Out of bounds temperature value(s) set to NA, range: -80 C to +50 C.") temperature <- ifelse(temperature < -80, NA_real_, temperature) } z <- ifelse(over.ice, 611.21 * exp(22.587 * temperature / (273.86 + temperature)), 610.94 * exp(17.625 * temperature / (243.04 + temperature))) } else if (method == "tetens") { if (check.range && any(!is.na(temperature) & (temperature < -40))) { warning("Out of bounds temperature value(s) set to NA, range: -40 C to +50 C.") temperature <- ifelse(temperature < -40, NA_real_, temperature) } z <- ifelse(over.ice, 610.78 * exp(21.875 * temperature / (265.5 + temperature)), 610.78 * exp(17.269 * temperature / (237.3 + temperature))) } else if (method == "wexler") { if (check.range && any(!is.na(temperature) & (temperature < -100 | temperature > 110))) { warning("Out of bounds temperature value(s) set to NA, range: -100 C to +100 C") temperature <- ifelse(temperature < -100 | temperature > 110, NA_real_, temperature) } temperature.K <- temperature + 273.15 wexler.ice <- function(temperature.K) { g <- c(-5.8666426e3, 2.232870244e1, 1.39387003e-2, -3.4262402e-5, 2.7040955e-8, 6.7063522e-1) exp(sum(temperature.K^((0:4) - 1) * g[1:5]) + g[6] * log(temperature.K)) } wexler.water <- function(temperature.K) { g <- c(-2.8365744e3, -6.028076559e3, 1.954263612e1, -2.737830188e-2, 1.6261698e-5, 7.0229056e-10, -1.8680009e-13, 2.7150305) exp(sum(temperature.K^((0:6) - 2) * g[1:7]) + g[8] * log(temperature.K)) } z <- ifelse(over.ice, sapply(temperature.K, wexler.ice), sapply(temperature.K, wexler.water)) } else if (method == "goff.gratch") { if (check.range && any(temperature < -50)) { warning("Out of bounds temperature value(s) set to NA, range: -50 C to +100 C") temperature <- ifelse(temperature < -50, NA_real_, temperature) } temperature.K <- temperature + 273.15 z <- ifelse(over.ice, 10^(-9.09718 * (273.16 / temperature.K - 1) - 3.56654 * log10(273.16 / temperature.K) + 0.876793 * (1 - temperature.K / 273.16) + log10(6.1173) ), 10^(-7.90298 * (373.16 / temperature.K - 1) + 5.02808 * log10(373.16 / temperature.K) - 1.3816e-7 * (10^(11.344 * (1 - temperature.K / 373.16)) - 1) + 8.1328e-3 * (10^(-3.49149 * (373.16 / temperature.K - 1)) - 1) + log10(1013.25))) z <- z * 1e2 } else { warning("Method '", method, "' unavailable; use 'magnus', 'tetens', 'wexler' or 'goff.gratch'.") z <- rep(NA_real_, length(temperature)) } z } water_dp <- function(water.vp, over.ice = FALSE, method = "tetens", check.range = TRUE) { method <- tolower(method) if (length(method) > 1L) { if (length(unique(method)) > 1L) { stop("Only one method can be used per function call.") } else { method <- method[1L] } } if (length(over.ice) == 1L && length(water.vp > 1)) { over.ice <- rep_len(over.ice, length(water.vp)) } if (any(water.vp <= 0)) { warning("Dew point is not defined for vapour pressure <= 0 Pa.") water.vp <- ifelse(water.vp <= 0, NA_real_, water.vp) } if (method == "magnus") { z <- ifelse(over.ice, 273.86 * log(water.vp / 611.21) / (22.587 - log(water.vp / 611.21)), 243.04 * log(water.vp / 610.94) / (17.625 - log(water.vp / 610.94))) if (check.range && any((!is.na(z)) & z < -80 | z > 50)) { warning("Out of bounds temperature value(s) set to NA, range: -80 C to +50 C.") z <- ifelse((!is.na(z)) & z < -80 | z > 50, NA_real_, z) } } else if (method == "tetens") { z <- ifelse(over.ice, 265.5 * log(water.vp / 610.78) / (21.875 - log(water.vp / 610.78)), 237.3 * log(water.vp / 610.78) / (17.269 - log(water.vp / 610.78))) if (check.range && any((!is.na(z)) & z < -30)) { warning("Out of bounds temperature value(s) set to NA, range: -30 C to +50 C.") z <- ifelse((!is.na(z)) & z < -30 | z > 50, NA_real_, z) } } else if (method == "wexler") { wexler.inv.ice <- function(water.vp) { c <- c(2.1257969e2, -1.0264612e1, 1.4354796e-1) d <- c(1, -8.2871619e-2, 2.3540411e-3, -2.4363951e-5) sum(c * log(water.vp)^(0:2)) / sum(d * log(water.vp)^(0:3)) } wexler.inv.water <- function(water.vp) { c <- c(2.0798233e2, -2.0156028e1, 4.6778925e-1, -9.2288067e-6) d <- c(1, -1.3319669e-1, 5.6577518e-3, -7.5172865e-5) sum(c * log(water.vp)^(0:3)) / sum(d * log(water.vp)^(0:3)) } z <- ifelse(over.ice, sapply(water.vp, wexler.inv.ice) - 273.15, sapply(water.vp, wexler.inv.water) - 273.15) if (check.range && any((!is.na(z)) & z < -100 | z > 100)) { warning("Out of bounds temperature value(s) set to NA, -100 C to + 100 C.") z <- ifelse((!is.na(z)) & z < -100 | z > 100, NA_real_, z) } } else { warning("Method '", method, "' unavailable; use 'magnus', 'tetens' or 'wexler'.") z <- rep(NA_real_, length(water.vp)) } method <- tolower(method) if (any(z > 0) && over.ice) { warning("At dew point temperature > 0 C, ice surface will be wet.") } z } water_fp <- function(water.vp, over.ice = TRUE, method = "tetens", check.range = TRUE) { water_dp(water.vp = water.vp, over.ice = over.ice, method = method, check.range = check.range) } water_vp2mvc <- function(water.vp, temperature) { 2.166 * water.vp / (temperature + 273.16) } water_mvc2vp <- function(water.mvc, temperature) { (temperature + 273.16) / 2.166 * water.mvc } water_vp2RH <- function(water.vp, temperature, over.ice = FALSE, method = "tetens", pc = TRUE, check.range = TRUE) { z <- water.vp / water_vp_sat(temperature, over.ice = over.ice, method = method, check.range = check.range) if (pc) { z * 100 } else { z } } water_RH2vp <- function(relative.humidity, temperature, over.ice = FALSE, method = "tetens", pc = TRUE, check.range = TRUE) { if (pc) { relative.humidity <- relative.humidity * 1e-2 } relative.humidity * water_vp_sat(temperature, over.ice = over.ice, method = method, check.range = check.range) } water_vp_sat_slope <- function(temperature, over.ice = FALSE, method = "tetens", check.range = TRUE, temperature.step = 0.1) { vp_sat1 <- water_vp_sat(temperature + temperature.step / 2, over.ice = over.ice, method = method, check.range = check.range) vp_sat2 <- water_vp_sat(temperature - temperature.step / 2, over.ice = over.ice, method = method, check.range = check.range) (vp_sat1 - vp_sat2) / temperature.step } psychrometric_constant <- function(atmospheric.pressure = 101325) { lambda <- 2.45 C.p <- 1.013e-3 epsilon <- 0.622 (C.p * atmospheric.pressure) / (epsilon * lambda) }
print.errprof <- function(x, ...){ nms <- names(x) attributes(x) <- NULL names(x) <- nms print(x) }
weighted_posteriors <- function(..., prior_odds = NULL, missing = 0, verbose = TRUE) { UseMethod("weighted_posteriors") } weighted_posteriors.data.frame <- function(..., prior_odds = NULL, missing = 0, verbose = TRUE) { Mods <- list(...) mnames <- sapply(match.call(expand.dots = FALSE)$`...`, .safe_deparse) iterations <- min(sapply(Mods, nrow)) if (!is.null(prior_odds)) { prior_odds <- c(1, prior_odds) } else { warning("'prior_odds = NULL'; Using uniform priors odds.\n", "For weighted data frame, 'prior_odds' should be specified as a numeric vector.", call. = FALSE ) prior_odds <- rep(1, length(Mods)) } Probs <- prior_odds / sum(prior_odds) weighted_samps <- round(iterations * Probs) res <- .weighted_posteriors(Mods, weighted_samps, missing) attr(res, "weights") <- data.frame(Model = mnames, weights = weighted_samps) return(res) } weighted_posteriors.stanreg <- function(..., prior_odds = NULL, missing = 0, verbose = TRUE, effects = c("fixed", "random", "all"), component = c("conditional", "zi", "zero_inflated", "all"), parameters = NULL) { Mods <- list(...) effects <- match.arg(effects) component <- match.arg(component) BFMods <- bayesfactor_models(..., denominator = 1, verbose = verbose) model_tab <- .get_model_table(BFMods, priorOdds = prior_odds) postProbs <- model_tab$postProbs iterations <- min(sapply(Mods, .total_samps)) weighted_samps <- round(iterations * postProbs) params <- lapply(Mods, insight::get_parameters, effects = effects, component = component, parameters = parameters ) res <- .weighted_posteriors(params, weighted_samps, missing) attr(res, "weights") <- data.frame(Model = BFMods$Model, weights = weighted_samps) return(res) } weighted_posteriors.brmsfit <- weighted_posteriors.stanreg weighted_posteriors.blavaan <- weighted_posteriors.stanreg weighted_posteriors.BFBayesFactor <- function(..., prior_odds = NULL, missing = 0, verbose = TRUE, iterations = 4000) { Mods <- c(...) BFMods <- bayesfactor_models(Mods, verbose = verbose) model_tab <- .get_model_table(BFMods, priorOdds = prior_odds, add_effects_table = FALSE) postProbs <- model_tab$postProbs weighted_samps <- round(iterations * postProbs) intercept_only <- which(BFMods$Model == "1") params <- vector(mode = "list", length = nrow(BFMods)) for (m in seq_along(params)) { if (length(intercept_only) && m == intercept_only) { params[[m]] <- data.frame( mu = rep(NA, iterations), sig2 = rep(NA, iterations), g = rep(NA, iterations) ) } else if (m == 1) { params[[m]] <- BayesFactor::posterior(1 / Mods[1], iterations = iterations, progress = FALSE) } else { params[[m]] <- BayesFactor::posterior( Mods[m - 1], iterations = iterations, progress = FALSE ) } } params <- lapply(params, data.frame) res <- .weighted_posteriors(params, weighted_samps, missing) attr(res, "weights") <- data.frame(Model = BFMods$Model, weights = weighted_samps) return(res) } .weighted_posteriors <- function(params, weighted_samps, missing) { par_names <- unique(unlist(sapply(params, colnames), recursive = TRUE)) params <- params[weighted_samps != 0] weighted_samps <- weighted_samps[weighted_samps != 0] for (m in seq_along(weighted_samps)) { temp_params <- params[[m]] i <- sample(nrow(temp_params), size = weighted_samps[m]) temp_params <- temp_params[i, , drop = FALSE] missing_pars <- setdiff(par_names, colnames(temp_params)) temp_params[, missing_pars] <- missing params[[m]] <- temp_params } do.call("rbind", params) } .total_samps <- function(mod) { x <- insight::find_algorithm(mod) if (is.null(x$iterations)) x$iterations <- x$sample x$chains * (x$iterations - x$warmup) }
str_extract_non_nums_no_ambigs <- function(string, num_pattern) { stringi::stri_split_regex(string, num_pattern, omit_empty = TRUE) } str_extract_non_numerics <- function(string, decimals = FALSE, leading_decimals = decimals, negs = FALSE, sci = FALSE, commas = FALSE) { checkmate::assert_character(string) checkmate::assert_flag(decimals) checkmate::assert_flag(leading_decimals) checkmate::assert_flag(negs) checkmate::assert_flag(sci) checkmate::assert_flag(commas) if (is_l0_char(string)) { return(list()) } num_pattern <- num_regex( decimals = decimals, leading_decimals = leading_decimals, negs = negs, sci = sci, commas = commas ) ambig_pattern <- ambig_num_regex( decimals = decimals, leading_decimals = leading_decimals, sci = sci, commas = commas ) ambigs <- num_ambigs(string, decimals = decimals, leading_decimals = leading_decimals, sci = sci, commas = commas ) out <- vector(mode = "list", length = length(string)) if (any(ambigs)) { ambig_warn(string, ambigs, ambig_regex = ambig_pattern) out[ambigs] <- NA_character_ not_ambigs <- !ambigs out[not_ambigs] <- str_extract_non_nums_no_ambigs( string[not_ambigs], num_pattern ) } else { out[] <- str_extract_non_nums_no_ambigs(string, num_pattern) } out } str_nth_non_numeric_no_ambigs <- function(string, num_pattern, n) { if (length(string) == 0) { return(character()) } if (length(n) == 1 && n >= 0) { out <- stringi::stri_split_regex(string, num_pattern, n = n + 1, omit_empty = TRUE, simplify = TRUE )[, n] out %T>% { .[!str_length(.)] <- NA_character_ } } else { stringi::stri_split_regex(string, num_pattern, omit_empty = TRUE) %>% chr_lst_nth_elems(n) } } str_nth_non_numeric <- function(string, n, decimals = FALSE, leading_decimals = decimals, negs = FALSE, sci = FALSE, commas = FALSE) { if (is_l0_char(string)) { return(character()) } verify_string_n(string, n) checkmate::assert_flag(decimals) checkmate::assert_flag(leading_decimals) checkmate::assert_flag(negs) checkmate::assert_flag(sci) checkmate::assert_flag(commas) num_pattern <- num_regex( decimals = decimals, leading_decimals = leading_decimals, negs = negs, sci = sci, commas = commas ) ambig_pattern <- ambig_num_regex( decimals = decimals, leading_decimals = leading_decimals, sci = sci, commas = commas ) ambigs <- num_ambigs(string, decimals = decimals, leading_decimals = leading_decimals, sci = sci, commas = commas ) out <- character(length(string)) if (any(ambigs)) { ambig_warn(string, ambigs, ambig_pattern) out[ambigs] <- NA_character_ not_ambigs <- !ambigs out[not_ambigs] <- str_nth_non_numeric_no_ambigs( string[not_ambigs], num_pattern, n ) } else { out[] <- str_nth_non_numeric_no_ambigs(string, num_pattern, n) } out } str_first_non_numeric <- function(string, decimals = FALSE, leading_decimals = decimals, negs = FALSE, sci = FALSE, commas = FALSE) { str_nth_non_numeric(string, n = 1, decimals = decimals, leading_decimals = leading_decimals, negs = negs, sci = sci, commas = commas ) } str_last_non_numeric <- function(string, decimals = FALSE, leading_decimals = decimals, negs = FALSE, sci = FALSE, commas = FALSE) { str_nth_non_numeric(string, n = -1, decimals = decimals, leading_decimals = leading_decimals, negs = negs, sci = sci, commas = commas ) }
dendro_data <- function(model, ...) { UseMethod("dendro_data", model) } dendro_data.default <- function(model, ...) { x <- class(model) stop(paste("No dendro_data method defined for class", x)) return(NULL) } is.dendro <- function(x) { inherits(x, "dendro") } as.dendro <- function(segments, labels, leaf_labels = NULL, class) { if (missing(class)) stop("Missing class in as.dendro") x <- list( segments = segments, labels = labels, leaf_labels = leaf_labels, class = class ) class(x) <- "dendro" x } segment <- function(x) { x$segments } label <- function(x) { x$labels } leaf_label <- function(x) { x$leaf_labels }
Give_Sentences_PMC = function(PMCID,term){ check = getURL(paste("https://www.ncbi.nlm.nih.gov/pmc/articles/PMC", PMCID, "/", sep="")) checkxml = htmlTreeParse(check,useInternalNodes = T) check3 = lapply(getNodeSet(checkxml,"//p"),function(x){xmlValue(x)}) test = NULL; for (i in 1:length(check3)) {tempA = SentenceToken(check3[[i]]);tempB = regexpr(term,tempA); tempC = which(attr(tempB,"match.length") == nchar(term)); if ( length(tempC) != 0 ) tempD = tempA[tempC] else tempD = NULL; test = c(test,tempD)}; return(test)}
pgfIpolyaaeppli <- function(s,params) { k<-s[abs(s)>1] if (length(k)>0) warning("At least one element of the vector s are out of interval [-1,1]") if (length(params)<2) stop("At least one value in params is missing") if (length(params)>2) stop("The length of params is 2") theta<-params[1] p<-params[2] if (theta<=0) stop ("Parameter theta must be positive") if ((p>=1)|(p<=0)) stop ("Parameter p belongs to the interval (0,1)") (theta+log(s))/(theta+p*log(s)) }
"smaller.clade.spectrum" <- function(tree) { if (identical(tree,NULL)) { stop("invalid tree","\n") } merge=tree$merge spec <- matrix(0,nrow=nrow(merge),ncol=2) spec[nrow(merge),]=c(2,1) for (node in 2:nrow(merge)) { if (merge[node,1]<0) {lc=1} else {lc=spec[nrow(merge)-merge[node,1]+1, 1]} if (merge[node,2]<0) {rc=1} else {rc=spec[nrow(merge)-merge[node,2]+1, 1]} spec[nrow(merge)-node+1,]=c(rc+lc, min(rc, lc)) } spec }
GQ=0 FccaXYdir <- function(Lx, Lp, LPhi, resp, l1, l2, cv=1) { .Call('flars_FccaXYdir',Lx, Lp, LPhi, resp, l1, l2, cv=1, PACKAGE = 'flars') } FccaXYdir0 <- function(Lx, Lp, LPhi, resp, l1, l2, cv=1) { .Call('flars_FccaXYdir0',Lx, Lp, LPhi, resp, l1, l2, cv=1, PACKAGE = 'flars') } cov.linear=function(hyper,Data,Data.new=NULL){ if(is.null(Data.new)) Data.new=Data hyper=lapply(hyper,exp);n.hyper=length(hyper$linear.a) cov.lin=xixj(Data.new,Data,hyper$linear.a) return(cov.lin) } cov.pow.ex=function(hyper,Data,Data.new=NULL,gamma=1){ if(is.null(gamma)) gamma=1 hyper=lapply(hyper,exp); datadim=dim(Data) v.power=xixj_sta(Data,Data.new,hyper$pow.ex.w,power=gamma) exp.v.power=hyper$pow.ex.v*exp(-v.power/2) } xixj=function(mat,mat.new=NULL,a=NULL){ mat=as.matrix(mat) mdim=dim(mat) if(is.null(mat.new)){ mat.new=mat } if(is.null(a)) a=rep(1,mdim[2]) if(length(a)<mdim[2]) { a1=rep(1,mdim[2]) a1[1:length(a)]=a a=a1;rm(a1) warning('number of "a" is less than the number of columns, use 1 as the missing "a"') } if(length(a)>mdim[2]) { a=a[1:mdim[2]] warning('number of "a" is more than the number of columns, omit the extra "a"') } aa=matrix(rep(a,mdim[1]),ncol=mdim[2],byrow=T) out=(aa*mat)%*%t(mat.new) return(out) } xixj_sta=function(mat,mat.new=NULL,w=NULL,power=NULL){ mat=as.matrix(mat) if(is.null(mat.new)) mat.new=mat mdim=dim(mat);mdim.new=dim(mat.new) cov.=matrix(sapply(1:mdim[1],function(i) matrix(rep(mat[i,],mdim.new[1]),nrow=mdim.new[1],byrow=T)-mat.new),ncol=mdim[1]) if(is.null(power)) power=1 cov.=((cov.)^2)^power; if(is.null(w)) { w=rep(1,mdim[2]) warning('missing "weight", use 1 instead') } if(length(w)==1&mdim[2]>1){ w=rep(w,mdim[2]) warning('only one "weight" found, applied to all columns') } if(length(w)>1&length(w)<mdim[2]){ w1=rep(1,mdim[2]) w1[1:length(w)]=w w=w1;rm(w1) warning('number of "weight" is less than the number of columns, use 1 as the missing "weight"') } if(length(w)>mdim[2]){ w=w[1:mdim[2]] warning('number of "weight" is more than the number of columns, omit the extra "weight"') } wmat=matrix(rep(w,each=dim(cov.)[1]*dim(cov.)[2]/mdim[2]),ncol=dim(cov.)[2],byrow=T) cov.=wmat*cov. cov..=matrix(0,ncol=mdim[1],nrow=mdim.new[1]) if(mdim[2]>1){ for(i in 1:(mdim[2]-1)){ cov..=cov..+cov.[1:mdim.new[1],,drop=F];cov.=cov.[-(1:mdim.new[1]),,drop=F]} cov.=cov..+cov. } return(cov.) } ind_fv_gen=function(effect_sample_size=10,num_fv=3,nsample=80,seed=NULL){ if(is.null(seed)) seed=sample(seq(1,1e4),size=1) set.seed(seed) x=matrix(rnorm(nsample*num_fv*effect_sample_size),ncol=effect_sample_size*num_fv) idx_factor=rep(rep(1:num_fv,each=nsample),effect_sample_size) x=lapply(split(x,idx_factor),function(i) matrix(i,ncol=effect_sample_size)) for(i in 2:num_fv){ a=do.call('cbind',x[1:(i-1)]) b=x[[i]] out=resid(lm(b~a)) x[[i]]=out } return(x) } mat2fd=function(mat,fdList=NULL){ fl=list(time=seq(0,1,len=ncol(mat)),nbasis=min(as.integer(ncol(mat)/5),23),norder=6,bSpline=TRUE,Pen=c(0,0),lambda=1e-4) nbasis=c(fdList$nbasis,fl$nbasis)[1] norder=c(fdList$norder,fl$norder)[1] lambda=c(fdList$lambda,fl$norder)[1] bSpline=c(fdList$bSpline,fl$bSpline)[1] time=list(a=fdList$time,b=fl$time) time=time[[which(unlist(lapply(time,is.null))^2==0)[1]]] if(1-bSpline) fl$Pen=c(c(0,(2*pi/diff(range(time)))^2,0)) Pen=list(a=fdList$Pen,b=fl$Pen) Pen=Pen[[which(unlist(lapply(Pen,is.null))^2==0)[1]]] if(bSpline) basis=create.bspline.basis(range(time),nbasis,norder) if(1-bSpline) basis=create.fourier.basis(range(time),nbasis,diff(range(time))) Par=vec2Lfd(Pen,range(time)) matfd=smooth.basisPar(time,t(mat),basis,Lfdobj=Par,lambda)$fd return(matfd) } add_shape=function(mat,vec){ dim_vec=length(vec) if(nrow(mat)==dim_vec & nrow(mat)!=ncol(mat)) mat=t(mat) mat=apply(mat,1,function(iii) return(iii+vec)) if(nrow(mat)==dim_vec & nrow(mat)!=ncol(mat)) mat=t(mat) return(mat) } f_var_from_f_independent=function(f_independent,weight,intercept=NULL, slope=NULL){ fi=f_independent nf=length(fi) ni=ns=0 if(!is.null(intercept)) ni=length(intercept) if(!is.null(slope)) ns=length(slope) if(is.null(intercept)) intercept=0 if(is.null(slope)) slope=0 z=vector('list',length=nrow(weight)) weight=split(weight,rep(1:nrow(weight),ncol(weight))) for(i in seq_along(z)){ z0=lapply(1:nf,function(k) fi[[k]]*weight[[i]][k]*matrix(slope[[sample(ns,1)]],ncol=ncol(fi[[k]]),nrow=nrow(fi[[k]]),byrow = T)+matrix(intercept[[sample(ni,1)]],ncol=ncol(fi[[k]]),nrow=nrow(fi[[k]]),byrow = T)) z[[i]]=Reduce('+',z0) } return(z) } rmse=function(t,a){ y = sqrt(mean((a-t)^2,na.rm = T)) return(y) } getL=function(dimension,order){ l=matrix(0,nrow=dimension-order,ncol=dimension) for(i in 1:nrow(l)) l[i,i+0:order]=(c(-1,1,0)+(order-1)*c(0,1,-1))[1:(order+1)] return(l) } get2L=function(dimension,DelT){ l=matrix(0,nrow = dimension-2,ncol=dimension) for(i in 1:nrow(l)){ l[i,i+0:2]=2/c((DelT[i]+DelT[i+1])*DelT[i],-DelT[i]*DelT[i+1],(DelT[i]+DelT[i+1])*DelT[i+1]) } return(l) } cp=function(mat1,mat2=NULL){ if(is.data.frame(mat1)) mat1=data.matrix(mat1) if(is.data.frame(mat2)) mat2=data.matrix(mat2) return(crossprod(mat1,mat2)) } tcp=function(mat1,mat2=NULL){ if(is.data.frame(mat1)) mat1=data.matrix(mat1) if(is.data.frame(mat2)) mat2=data.matrix(mat2) return(tcrossprod(mat1,mat2)) } GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } plot_fm=function(f_var,dim=NULL){ nfm=length(f_var) if(is.null(dim)) par(mfrow=c(((nfm/2)%%1!=0)+as.integer(nfm/2),2)) if(!is.null(dim)) par(mfrow=c(dim[1],dim[2])) for(i in 1:nfm){ fv=f_var[[i]] plot(-100,-100,xlim=c(0,ncol(fv)),ylim=range(fv), main=substitute( paste("x"[{x000}],"(t)",sep=''), list(x000=i) ), ylab='',xlab='index') for(ii in 1:nrow(fv)) lines(1:ncol(fv),fv[ii,],col=col1(1.2*nrow(fv))[ii]) } par(mfrow=c(1,1)) } col1 <- colorRampPalette(c(" " ran_fv_gen=function(effect_sample_size=10,num_fv=3,nsample=80,seed=NULL){ if(is.null(seed)) seed=sample(seq(1,1e4),size=1) set.seed(seed) x=matrix(rnorm(nsample*num_fv*effect_sample_size),ncol=effect_sample_size*num_fv) idx_factor=rep(rep(1:num_fv,each=nsample),effect_sample_size) x=lapply(split(x,idx_factor),function(i) matrix(i,ncol=effect_sample_size)) return(x) } data_generation=function(seed,nsamples=80,hyper=NULL,var_type=c('f','m'),cor_type=1:6,uncorr=TRUE,nVar=8){ set.seed(seed) var_type=var_type[1] cor_type=cor_type[1] data.gen=T if(is.null(hyper)) hp <- list('pow.ex.w'=log(50),'linear.a'=log(2),'pow.ex.v'=log(20),'vv'=log(0.5)) if(!is.null(hyper)) hp=hyper if(data.gen){ if(uncorr==T) x=ind_fv_gen(effect_sample_size=10,num_fv=nVar,nsample=nsamples,seed=seed) if(uncorr==F) x=ran_fv_gen(effect_sample_size=10,num_fv=nVar,nsample=nsamples,seed=seed) effect_sample_size=10;num_fv=nVar;nsample=nsamples G=cov.pow.ex(hp,seq(0,1,len=10))+cov.linear(hp,seq(0,1,len=10)) G2=chol(G) x=lapply(x,'%*%',G2) f=lapply(x,function(i){ mat2fd(i,fdList=list(nbasis=2*effect_sample_size,norder=min(effect_sample_size-1,6),lambda=1e-7)) }) ntime=100 fm0=lapply(f,function(i) t(eval.fd(seq(0,1,len=ntime),i))) err_range=diff(apply(sapply(fm0,range),1,mean))/20 fm0=lapply(fm0,function(i) i+eval.fd(seq(0,1,len=ntime),mat2fd(t(rnorm(50,sd=err_range)),list(lambda=1e-3)))[,1]) shape0=list(s1=sin(seq(0,pi,len=ntime)), s2=pnorm(seq(0.6,1.2,len=ntime),mean=.8,sd=0.01)+0.2*exp(seq(-1,2.5,len=ntime)), s3=cos(seq(0,1.5,len=ntime))^2, s4=sin(cos(seq(0,3,len=ntime))), s5=cos(sin(seq(-2,3,len=ntime))), s6=seq(-2,3,len=ntime)^3-cos(seq(-2,3,len=ntime)^2)^3, s7=cos(sqrt(exp(seq(-2,3,len=ntime)))), s8=sin(sqrt(exp(seq(-2,3,len=ntime))))) shape=lapply(shape0,function(i)return(i*err_range*nsample/diff(range(i)))) fm=fm0 for(i in seq_along(fm)) fm[[i]]=add_shape(fm[[i]],shape[[sample(seq_along(shape0),1)]]) b1=princomp(x[[1]], cor=F)$loadings[,1] b1=mat2fd(t(as.matrix(b1)),fdList=list(nbasis=5,norder=4,lambda=0)) bm=eval.fd(seq(0,1,len=ntime),b1) b1const=(max(fm[[1]]%*%bm)-min(fm[[1]]%*%bm)) y01=fm[[1]]%*%bm/b1const y1=y01 b2=princomp(x[[2]], cor=F)$loadings[,1] p=dnorm((rnorm(2*ntime))) idx=sort(sample(1:(2*ntime),10,prob=p/sum(p))) time2=seq(0,1,len=2*ntime)[idx] time2=(time2-(min(time2)))/max(time2) b2=mat2fd(t(as.matrix(b2)),fdList=list(time=time2,nbasis=7,norder=4,lambda=0)) bm=eval.fd(seq(min(time2),max(time2),len=ntime),b2) b2const=(max(fm[[2]]%*%bm)-min(fm[[2]]%*%bm)) y02=fm[[2]]%*%bm/b2const y2=y02 noise=rnorm(nsample,mean=0,sd=0.5) b3=princomp(x[[3]], cor=F)$loadings[,1] b3=mat2fd(t(as.matrix(b3)),fdList=list(nbasis=5,norder=4,lambda=0)) bm=eval.fd(seq(0,1,len=ntime),b3) b3const=(max(fm[[3]]%*%bm)-min(fm[[3]]%*%bm)) y03=fm[[3]]%*%bm/b3const y3=y03 mu=sample(c(0,5,10,20,100),size = 1) noise=mu+noise*0.1 } BetaT=list(b1=b1,b2=b2,b3=b3) bConst=c(b1const=b1const,b2const=b2const,b3const=b3const) if(var_type=='f'){ if(cor_type==1){ fsm=fm y=y1+y2+y3+noise } if(cor_type==2){ fmm=list('vector',8) fmm[c(1:3,5:8)]=fm[c(1:3,5:8)] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=w3=rep(0,8) w1[c(1,4)]=GenWeight(2,2,c(1,2)) w=t(as.matrix(w1)) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4)]=z fsm=fmm y=y1+y2+y3+noise } if(cor_type==3){ fmm=list('vector',8) fmm[c(1:3,7,8)]=fm[c(1:3,7,8)] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=w3=rep(0,8) w1[c(1,4)]=GenWeight(2,2,c(1,2)) w2[c(2,5)]=GenWeight(2,3,c(1,2)) w3[c(3,6)]=GenWeight(2,4,c(1,2)) w=rbind(w1,w2,w3) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4:6)]=z fsm=fmm y=y1+y2+y3+noise } if(cor_type==4){ fmm=list('vector',8) fmm[c(1:3,6:8)]=fm[c(1:3,6:8)] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=rep(0,8) w1[c(1,4)]=c(0.2,0.8) w2[c(1,5)]=c(0.2,0.8) w=rbind(w1,w2) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4,5)]=z fsm=fmm y=y1+y2+y3+noise } beta_xs=NULL } if(var_type=='m'){ xs=x[-8] xsMat=matrix(0,ncol=5,nrow=nsamples) xsMat=apply(xsMat,2,rnorm,n=nsamples) if(uncorr==F){ a=do.call(cbind,xs) b=xsMat[,1] xsMat[,1]=resid(lm(b~a)) for(i in 2:ncol(xsMat)){ a=cbind(do.call('cbind',xs),xsMat[,1:(i-1)]) b=xsMat[,i] out=resid(lm(b~a)) xsMat[,i]=out } } xsMat=scale(xsMat) beta_xs=1/apply(apply(xsMat,2,range),2,diff) beta_xs[4:5]=0 y_xs=xsMat%*%beta_xs xsList=lapply(split(xsMat,rep(1:ncol(xsMat),each=nrow(xsMat))),as.matrix) y=y1+y2+y3+y_xs if(cor_type==1){ fsm=fm fsm=fsm[-8] fsm=c(fsm,xsList) y=y+noise } if(cor_type==2){ fmm=list('vector',8) fmm[c(1:8)]=fm[1:8] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=rep(0,8) w1[c(1,7,5)]=c(0.2,-0.01,0.3) w2[c(1,7,4)]=c(0.2,-0.01,0.3) w=rbind(w1,w2) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4,5)]=z fsm=fmm fsm=fsm[-8] fsm=c(fsm,xsList) y=y+noise } if(cor_type==3){ fsm=fm fsm=fsm[-8] fsm=c(fsm,xsList) fsm[[11]]=0.2*xsList[[1]]+0.8*xsList[[4]] fsm[[12]]=0.2*xsList[[1]]+0.8*xsList[[5]] y=y+noise } if(cor_type==4){ fmm=list('vector',8) fmm[c(1:8)]=fm[1:8] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=rep(0,8) w1[c(1,7,5)]=c(0.2,-0.01,0.3) w2[c(1,7,4)]=c(0.2,-0.01,0.3) w=rbind(w1,w2) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4,5)]=z fsm=fmm fsm=fsm[-8] fsm=c(fsm,xsList) fsm[[11]]=0.2*xsList[[1]]+0.8*xsList[[4]] fsm[[12]]=0.2*xsList[[1]]+0.8*xsList[[5]] y=y+noise } if(cor_type==5){ fmm=list('vector',8) fmm[c(1:8)]=fm[1:8] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=rep(0,8) w1[c(1,7,5)]=c(0.2,-0.01,0.3) w2[c(1,7,4)]=c(0.2,-0.01,0.3) w=rbind(w1,w2) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4,5)]=z fsm=fmm fsm=fsm[-8] fsm=c(fsm,xsList) fsm[[11]]=0.2*xsList[[1]]+0.8*xsList[[4]] fsm[[12]]=0.2*xsList[[1]]+0.8*xsList[[5]] fsm[[6]]=apply(fsm[[6]],2,function(i6) i6+xsList[[1]]) y=y+noise } if(cor_type==6){ fmm=list('vector',8) fmm[c(1:8)]=fm[1:8] GenWeight=function(nx,seed,avoid){ a=rnorm(nx) a[avoid]=rnorm(length(avoid),sd = 1e-1) a=nx*a/sum(abs(a)) return(abs(a)) } w1=w2=rep(0,8) w1[c(1,2,8,4)]=c(0.8,0,1.2,0.5) w=rbind(w1,w2) z=f_var_from_f_independent(f_independent=fm,weight=w,intercept = shape0,slope = shape0) fmm[c(4,5)]=z fsm=fmm fsm=fsm[-8] fsm=c(fsm,xsList) fsm[[11]]=0.2*xsList[[1]]+0.8*xsList[[4]] fsm[[12]]=0.2*xsList[[1]]+0.8*xsList[[5]] fsm[[6]]=apply(fsm[[6]],2,function(i6) i6+0.2*xsList[[1]]) y=y+noise } } BetaT$S=beta_xs return(list(x=fsm,y=y,BetaT=BetaT,bConst=bConst,noise=noise,mu=mu)) } fccaGen=function(xL,yVec,type=c('dir','cor','a','all'),method=c('basis','gq','raw'),GCV=TRUE,control=list()){ if(!is.list(xL)) xL=list(xL) if(is.list(xL)) xL=lapply(xL,as.matrix) nList=length(xL) ndimL=sapply(xL,ncol) idxFD=seq_along(xL)[ndimL>1] if(length(idxFD)==0){ x=sapply(xL,as.matrix) type=type[1] xc=crossprod(x) xy=t(x)%*%yVec Beta=as.matrix(rep(NA,length(yVec))) try(Beta<-solve(xc,xy),T) if(type=='dir' | type=='a'){ return(Beta) } if(type=='cor') return(cor(x%*%Beta,yVec)) if(type=='all'){ return(list('corr'=cor(x%*%Beta,yVec),'a'=Beta,'PureScalar'=1,'TraceHat'=dim(x))) } } method=method[1] gqWeight=NULL pL=phiL=vector('list',length=nList) if(method=='basis'){ con=list(nbasis=18,norder=6,pen1=10^(seq((-20),5,len=41)),pen2=0.01,t=seq(0,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control nbasis=con$nbasis;norder=con$norder;pen1=con$pen1 pen2=con$pen2;t=con$t if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } if(length(nbasis)!=length(norder)){ nbasis=nbasis[1] norder=norder[1] warning('length of nbasis is different from length of norder') } if(length(nbasis)!=nList) nbasis=rep(nbasis[1],nList) if(length(norder)!=nList) norder=rep(norder[1],nList) for(iL in idxFD){ tRange=range(t[[iL]]) nb=nbasis[iL];no=norder[iL] tiL=t[[iL]] spline=create.bspline.basis(tRange,nbasis = nb,norder = no) MS=eval.basis(tiL,spline,0) MS2=eval.basis(tiL,spline,2) pL[[iL]]=crossprod(MS2) phiL[[iL]]=MS/(ncol(xL[[iL]])) } } if(method=='gq'){ con=list(nP=18,pen1=10^(seq((-20),5,len=21)),pen2=0.01,t=seq(-1,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control t=con$t;nP=con$nP;pen1=con$pen1;pen2=con$pen2 if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } if(GQ==0){ .GlobalEnv$modelChronic <- readRDS( file.path(system.file('inst/extdata',package='flars'), 'GQ.rds')) } gqWeight=data.matrix(GQ[GQ$n==nP,c(1,2)]) gqWeight2=data.matrix(GQ[GQ$n==(nP-2),c(1,2)]) xi=as.numeric(gqWeight[,1]) wi=as.matrix(gqWeight[,2]) wi=wi[order(xi)] xi=sort(xi) xi2=as.numeric(gqWeight2[,1]) wi2=as.matrix(gqWeight2[,2]) wi2=wi2[order(xi2)] xi2=sort(xi2) idxL=vector('list',length=length(idxFD)) xL0=xL for(iL in idxFD){ dimFx=dim(xL[[iL]]) ncols=dimFx[2] nrows=dimFx[1] zi=t[[iL]] idx=as.numeric(sapply(xi,function(i) which.min(abs(zi-i)))) idxL[[iL]]=idx xGQ=xL[[iL]][,idx] xL[[iL]]=xGQ pL[[iL]]=t(get2L(ncol(xL[[iL]]),diff(xi)))%*%diag(wi2)%*%get2L(ncol(xL[[iL]]),diff(xi)) phiL[[iL]]=diag(wi) } } if(method=='raw'){ con=list(pen1=10^(seq((-10),-5,len=21)),pen2=0.01,t=seq(0,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control t=con$t;pen1=con$pen1;pen2=con$pen2 if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } for(iL in idxFD){ pL[[iL]]=crossprod(get2L(ncol(xL[[iL]]),diff(t[[iL]]))) phiL[[iL]]=diag(1,ncol(xL[[iL]]))/(ncol(xL[[iL]])) } } if(length(idxFD)<nList){ pL[-idxFD]=lapply(pL[-idxFD],function(i) i=matrix(0)) phiL[-idxFD]=lapply(phiL[-idxFD],function(i) i=matrix(1)) } type=type[1] GCV=1 if(type!='all') B=FccaXYdir(xL,pL,phiL,yVec,pen1,pen2,cv=GCV) if(type=='all'){ B_all=FccaXYdir0(xL,pL,phiL,yVec,pen1,pen2,cv=GCV) B=B_all$betahat B_K=B_all$K B_S=B_all$S B_lam1=B_all$lambda1 B_lam2=B_all$lambda2 GCV_mat=B_all$GCV_mat TrHat=B_all$HatMatTrace } idxB=unlist(sapply(1:nList,function(ii)rep(ii,len=ncol(phiL[[ii]])))) if(method!='gq'){ BL=split(B,idxB) out=unlist(mapply('%*%',phiL,BL,SIMPLIFY = F)) } if(method=='gq'){ BL=split(B,idxB) out=mapply('%*%',phiL,BL,SIMPLIFY = F) outBL=lapply(ndimL,function(i)rep(0,i)) for(iL in idxFD){ outBL[[iL]][idxL[[iL]]]=out[[iL]] } outBL[-idxFD]=BL[-idxFD] out=unlist(outBL) xL=xL0 } if(type=='cor'){ corr=cor(yVec,drop(do.call(cbind,xL)%*%out)) out=abs(corr) return(out) } if(type=='a'){ a=out/(sd(yVec)*abs(cor(yVec,do.call(cbind,xL)%*%out))) out=a return(out) } if(type=='dir'){ return(out) } if(type=='all'){ corr=abs(cor(yVec,do.call(cbind,xL)%*%out)) a=out/(sd(yVec)*corr) return(list('corr'=corr,'a'=a,'K'=B_K,'gq'=gqWeight, 'phiL'=phiL,'S'=B_S,'lam1'=B_lam1,'lam2'=B_lam2, 'GCV_mat'=GCV_mat,'TraceHat'=TrHat)) } } flars=function(x,y,method=c('basis','gq','raw'),max_selection,cv=c('gcv'),normalize=c('trace','rank','norm','raw'),lasso=TRUE,check=1,select=TRUE,VarThreshold=0.1,SignThreshold=0.8,control=list()){ x=lapply(x,scale) xMean=lapply(x,function(i)attr(i,"scaled:center")) xSD=lapply(x,function(i)attr(i,"scaled:scale")) x=lapply(x,function(i){ da=i attr(da,"scaled:center")=NULL attr(da,"scaled:scale")=NULL da }) yMean=mean(y) ySD=sd(y) y=as.numeric(scale(y)) nx=length(x) nsample=nrow(x[[1]]) max_iter=max_selection alpha0=p2_norm0=NULL r=as.matrix(y) cv=cv[1] beta0=rep(0,ncol(do.call('cbind',x))) beta=betaM=NULL gamma0=mapply(function(a,b)as.matrix(rep(0,each=b)),rep(0,length(x)),sapply(x,ncol),SIMPLIFY = F) betaGQ=NULL A=A0=NULL method.=method if(cv=='gcv'){ GCV=T cor1=sapply(x,function(ixL) fccaGen(xL = ixL,yVec=r[,1],type='cor',method=method.,GCV=T,control=control)) } idx1=as.numeric(which.max(cor1)) A0=c(A0,idx1);A=as.numeric(na.omit(A0[A0>0])) iter=1 varSplit=NULL MaxIter=min(max_iter,length(x)) p0=NULL dfIter=NULL corIter=NULL SignCheckF0=NULL Checked=F cat('iter ') while(iter <=MaxIter){ cat(iter,' ') GCV0=1 gamma_all=fccaGen(x[A],r[,iter,drop=F],type='all',method=method.,GCV=GCV0,control=control) gamma=split(gamma_all$a,unlist(mapply(rep,1:length(x[A]),each=sapply(x[A],ncol)))) gamma2=gamma0 gamma2[A]=gamma gamma2=as.matrix(unlist(gamma2)) S0=gamma_all$S S0_norm=1 p2=do.call('cbind',x)%*%gamma2*S0_norm p2_norm=1/sd(p2) p2=p2*p2_norm if(cv=='gcv'){ GCV=T cor2=sapply(x[-A],function(ixL) fccaGen(xL = ixL,yVec=r[,iter],type='all',method=method.,GCV=T,control=control),simplify = F) } S=lapply(cor2,function(i)i$S) SidxNull=sapply(S,is.null) if(sum(unlist(SidxNull))!=0) S[SidxNull]=lapply(x[-A][SidxNull],function(i)tcrossprod(i)/drop(crossprod(i))) normalize=normalize[1] S_norm=sapply(S,function(i){ if(normalize=='trace'){ if(!is.null(i)) return(1/sum(diag(i))) } if(normalize=='rank'){ if(!is.null(i)) return(1/rankMatrix(i)) } if(normalize=='norm'){ if(!is.null(i)) return(1/(sqrt(sum(diag(crossprod(i))))) ) } if(normalize=='raw'){ if(!is.null(i)) return(1) } }) pBar=tcrossprod(p2)/drop(crossprod(p2)) pk_norm=1 if(normalize=='trace') pk_norm=1/sum(diag(pBar)) if(normalize=='rank') pk_norm=1/rankMatrix(pBar) if(normalize=='norm') pk_norm=1/(sqrt(sum(diag(cp(pBar))))) if(normalize=='raw') pk_norm==1 SBar=mapply('*',S,S_norm,SIMPLIFY = F) pBar=pBar*pk_norm MatAlpha=matrix(0,ncol=2,nrow=length(x)) colnames(MatAlpha)=c('plus','minus') MatAlpha[A,]=1e5 Plus=Minus=rep(NA,length(cor2)) aa=bb=cc=vector('list',length(cor2)) try(aa<-lapply(SBar,function(i){ cp(p2,i-pBar)%*%p2 }),T) try(bb<-lapply(SBar,function(i){ -2*cp(r[,iter],i-pBar)%*%p2 }),T) try(cc<-lapply(SBar,function(i){ cp(r[,iter],i-pBar)%*%r[,iter] }),T) aa=unlist(aa) bb=unlist(bb) cc=unlist(cc) bb2ac=bb^2-4*aa*cc bb2ac[bb2ac<0]=NA try(Plus<-(-bb+sqrt(bb2ac))/(2*aa),T) try(Minus<-(-bb-sqrt(bb2ac))/(2*aa),T) MatAlpha[-A,1]=unlist(Plus) MatAlpha[-A,2]=unlist(Minus) MatAlpha[MatAlpha<0]=NA alpha0=c(alpha0,as.vector(MatAlpha)[which.min(as.vector(MatAlpha))]) ols=0 if(alpha0[iter]==1e5){ idx2=NA m0=lm(r[,iter]~0+p2) alpha0[iter]=m0$coefficients ols=1 } if(alpha0[iter]!=1e5 & ols==0){ idx2=c(which(MatAlpha[,1]==alpha0[iter]),which(MatAlpha[,2]==alpha0[iter])) } A0=c(A0,idx2) A=as.numeric(na.omit(A0[A0>0])) beta=cbind(beta,as.vector(gamma2)*alpha0[iter]*p2_norm) p2_norm0=c(p2_norm0,p2_norm) p0=cbind(p0,p2) if(rmse(r[,iter],do.call(cbind,x)%*%beta[,iter,drop=F])>rmse(r[,iter],-do.call(cbind,x)%*%beta[,iter,drop=F])){ alpha0[iter]=alpha0[iter] beta[,iter]=-beta[,iter] } if(iter==1) betaM=cbind(betaM,beta[,iter]) if(iter>1) betaM=cbind(betaM,betaM[,iter-1]+beta[,iter]) Checked==F if(lasso==T){ if(check==1){ betaL=split(betaM[,iter],unlist(mapply(rep,seq_along(x),each=sapply(x,ncol)))) xSplit=mapply('%*%',x,betaL) tmpVar=apply(xSplit,2,var) varSplit=cbind(varSplit,tmpVar) VarIdx=as.logical(apply(varSplit,1,function(i){ tail(i,1)<max(i[max(1,tail(which(i==0),1)):(length(i)-1)]) & tail(i,n = 1)>0 & tail(i,n = 1)<VarThreshold })) if(length(which(VarIdx==TRUE))>0){ Checked=T RmIdx=which.min(tmpVar[VarIdx]) RmIdx=which(VarIdx==TRUE)[RmIdx] RmIdxBeta=sum(sapply(betaL[1:RmIdx],length))-rev(seq_along(betaL[[RmIdx]]))+1 betaM[RmIdxBeta,iter]=0 A0[which(A0==RmIdx)]=A0[which(A0==RmIdx)]*(-1)-iter*0.0001 A=as.numeric(na.omit(A0[A0>0])) } } if(check==2){ betaL=split(betaM[,iter],unlist(mapply(rep,seq_along(x),each=sapply(x,ncol)))) if(iter>2){ SignCheckF=mapply(crossprod,lapply(betaL,sign),lapply(betaL0,sign))/sapply(betaL,function(iBetaL) length(iBetaL[iBetaL!=0])) SignCheckF0=cbind(SignCheckF0,as.numeric(SignCheckF)) SignCheckIdx=which(SignCheckF<=SignThreshold & SignCheckF!=0) if(length(SignCheckIdx)>0){ SignCheckIdx=SignCheckIdx[which.min(SignCheckF[SignCheckIdx])] A0[which(A0==SignCheckIdx)]=A0[which(A0==SignCheckIdx)]*(-1)-iter*0.0001 A=as.numeric(na.omit(A0[A0>0])) BetaIdxL=split(1:nrow(betaM),unlist(mapply(rep,seq_along(x),each=sapply(x,ncol)))) RmIdxBeta=unlist(BetaIdxL[SignCheckIdx]) betaM[RmIdxBeta,iter]=0 } } betaL0=betaL } } r=cbind(r,y-do.call(cbind,x)%*%betaM[,iter,drop=F]) if(Checked & !select){ r[,ncol(r)]=r[,1] } if(is.null(gamma_all$S)){ gamma_all$S=tcrossprod(do.call(cbind,x[A])) } dfIter=c(dfIter,list(diag(1,nsample)-gamma_all$S)) iter=iter+1 corIter=c(corIter,cor(r[,iter],p2)) p3=p2 } betaM0=betaM Mu=Beta=NULL for(colI in 1:ncol(betaM0)){ bb=betaM0[,colI,drop=F] b1=unlist(xMean) b2=bb/unlist(xSD) y1=yMean y2=ySD Mu=c(Mu,y1-y2*sum(b1*b2)) Beta=cbind(Beta,y2*b2) } betaOLSdir=fccaGen(x,y,type='all') Sigma2Bar=var(y-do.call(cbind,x)%*%betaOLSdir$a) dfIterS=vector('list',length(dfIter)) dfIterS[[1]]=dfIter[[1]] for(iDF in 2:length(dfIter)){ dfIterS[[iDF]]=dfIter[[iDF]]%*%dfIterS[[iDF-1]] } dfIterS=lapply(dfIterS,function(iDFS) diag(1,nsample)-iDFS) dfIterS=sapply(dfIterS,function(iDFS) sum(diag(iDFS))) RSS=apply(do.call(cbind,x)%*%betaM0,2,function(cpI) sqrt(crossprod(y-cpI))) dfIterS=dfIterS[seq_along(RSS)] R2=1-RSS^2/crossprod(scale(y)) R2Adj=1-(1-R2)*(nsample-1)/(nsample-dfIterS-1) Cp=RSS/Sigma2Bar-nsample+2*dfIterS CpTrue=NULL aicTrue=NULL aic=2*RSS/(2*Sigma2Bar)+2*nsample*(log(sqrt(Sigma2Bar))+log(2*pi))+dfIterS bicTrue=NULL bic=2*RSS/(2*Sigma2Bar)+2*nsample*(log(sqrt(Sigma2Bar))+log(2*pi))+dfIterS*log(nsample) StopStat=list(RSS=RSS,R2=R2,R2Adj=R2Adj,Cp=Cp,aic=aic,bic=bic,corIter=corIter) CD=abs(StopStat$corIter[-length(StopStat$corIter)]*alpha0[-1]) out=list(Mu=Mu, Beta=Beta, alpha=alpha0, p2_norm=p2_norm0[1:(iter-1)], AllIndex=A0, index=A, CD=CD, method=method, resid=r, RowMeans=xMean, RowSds=xSD, yMean=yMean, ySD=ySD, p0=p0, cor1=cor1, lasso=lasso, df=dfIterS, Sigma2Bar=Sigma2Bar, StopStat=StopStat, varSplit=varSplit, SignCheckF=SignCheckF0 ) class(out)='flars' return(out) } predict.flars=function(object,newdata,...){ if (!inherits(object, "flars")) stop("Not a legitimate 'flars' object") xL=newdata if(!is.list(xL)) xL=list(xL) if(is.list(xL)) xL=lapply(xL,as.matrix) nList=length(xL) ndimL=sapply(xL,ncol) idxFD=seq_along(xL)[ndimL>1] if(length(idxFD)==0){ x=sapply(xL,as.matrix) mu=object$Mu Beta=object$Beta yhattmp=matrix(rep(mu,each=nrow(x)),nrow=nrow(x),byrow = F)+x%*%Beta } if(length(idxFD)>0){ mu=object$Mu Beta=object$Beta yhattmp=matrix(rep(mu,each=nrow(xL[[1]])),nrow=nrow(xL[[1]]),byrow = F)+do.call(cbind,xL)%*%Beta } return(yhattmp) } flars_TrainTest=function(seed=1,nsamples=120,nTrain=80,var_type=c('f','m'),VarThreshold0=0.1,SignThreshold0=0.8,cor_type=1:5,lasso=TRUE,check=1,uncorr=T,nVar=8,Discrete_Norm_ID=1:12,NoRaw_max=12,raw_max=9,hyper=NULL,RealX=NULL,RealY=NULL,dataL=NULL,nCor=0,control=list()){ selection=Discrete_Norm_ID var_type=var_type[1] cor_type=cor_type[1] if(is.null(dataL) & is.null(RealX) & is.null(RealY)){ dataL=data_generation(seed = seed,nsamples = nsamples,hyper = hyper,var_type =var_type,cor_type = cor_type,uncorr = uncorr,nVar = nVar) } fsm=dataL$x y=dataL$y TrainIdx=seq(nTrain) TestIdx=seq(nsamples)[-TrainIdx] fsmTrain=lapply(fsm,function(fsmI) fsmI[TrainIdx,,drop=F]) fsmTest=lapply(fsm,function(fsmI) fsmI[TestIdx,,drop=F]) yTrain=y[TrainIdx] yTest=y[TestIdx] noise=dataL$noise if(!is.null(RealX) & !is.null(RealY)){ fsm=RealX y=RealY } out=vector('list',length = 12) if(nCor<=1){ iSam='seed' if(1%in%selection){ test_Basis_Norm=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[1],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[2],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Basis_Norm mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Basis_Norm$yhat=cbind(yTest,yhattmp) out[[1]]=test_Basis_Norm cat(iSam,'.1',' ',sep = '') } if(2%in%selection){ test_Basis_Rank=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[1],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[4],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Basis_Rank mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Basis_Rank$yhat=cbind(yTest,yhattmp) out[[2]]=test_Basis_Rank cat(iSam,'.2',' ',sep = '') } if(3%in%selection){ test_Basis_Trace=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[1],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[1],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Basis_Trace mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Basis_Trace$yhat=cbind(yTest,yhattmp) out[[3]]=test_Basis_Trace cat(iSam,'.3',' ',sep = '') } if(4%in%selection){ test_Basis_Raw=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[1],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[3],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Basis_Raw mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Basis_Raw$yhat=cbind(yTest,yhattmp) out[[4]]=test_Basis_Raw cat(iSam,'.4',' ',sep = '') } if(5%in%selection){ test_GQ_Norm=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[2],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[2],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_GQ_Norm mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_GQ_Norm$yhat=cbind(yTest,yhattmp) out[[5]]=test_GQ_Norm cat(iSam,'.5',' ',sep = '') } if(6%in%selection){ test_GQ_Rank=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[2],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[4],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_GQ_Rank mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_GQ_Rank$yhat=cbind(yTest,yhattmp) out[[6]]=test_GQ_Rank cat(iSam,'.6',' ',sep = '') } if(7%in%selection){ test_GQ_Trace=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[2],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[1],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_GQ_Trace mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_GQ_Trace$yhat=cbind(yTest,yhattmp) out[[7]]=test_GQ_Trace cat(iSam,'.7',' ',sep = '') } if(8%in%selection){ test_GQ_Raw=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[2],max_selection = NoRaw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[3],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_GQ_Raw mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_GQ_Raw$yhat=cbind(yTest,yhattmp) out[[8]]=test_GQ_Raw cat(iSam,'.8',' ',sep = '') } if(9%in%selection){ test_Raw_Norm=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[3],max_selection = raw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[2],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Raw_Norm mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Raw_Norm$yhat=cbind(yTest,yhattmp) out[[9]]=test_Raw_Norm cat(iSam,'.9',' ',sep = '') } if(10%in%selection){ test_Raw_Rank=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[3],max_selection = raw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[4],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Raw_Rank mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Raw_Rank$yhat=cbind(yTest,yhattmp) out[[10]]=test_Raw_Rank cat(iSam,'.A',' ',sep = '') } if(11%in%selection){ test_Raw_Trace=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[3],max_selection = raw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[1],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Raw_Trace mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Raw_Trace$yhat=cbind(yTest,yhattmp) out[[11]]=test_Raw_Trace cat(iSam,'.B',' ',sep = '') } if(12%in%selection){ test_Raw_Raw=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[3],max_selection = raw_max,lasso=lasso,normalize = c('trace','norm','raw','rank')[3],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) test=test_Raw_Raw mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test_Raw_Raw$yhat=cbind(yTest,yhattmp) out[[12]]=test_Raw_Raw cat(iSam,'.C',' ',sep = '') } } if(nCor>1){ SelectionIdx=cbind(rep(1:3,each=4),rep(1:4,3)) CatIdx=c(1:9,'A','B','C') res=mclapply(selection,function(iSam){ methodIdx=SelectionIdx[iSam,1] normIdx=SelectionIdx[iSam,2] if(methodIdx<3) No_Max=NoRaw_max if(methodIdx==3) No_Max=raw_max test=flars(fsmTrain,yTrain,method = c('basis','gq','raw')[methodIdx],max_selection = No_Max,lasso=lasso,normalize = c('trace','norm','raw','rank')[normIdx],check=check,VarThreshold=VarThreshold0,SignThreshold=SignThreshold0,control=control) mu=test$Mu Beta=test$Beta yhattmp=matrix(rep(mu,each=length(TestIdx)),nrow=length(TestIdx),byrow = F)+do.call(cbind,fsmTest)%*%Beta test$yhat=cbind(yTest,yhattmp) cat('seed.',CatIdx[iSam],sep = '') return(test) },mc.cores = nCor,mc.set.seed=F) out[selection]=res } names(dataL$x)=paste0('x',seq_along(dataL$x)) out$dataL=dataL names(out)=c('out_Basis_Norm','out_Basis_Rank','out_Basis_Trace','out_Basis_Raw','out_GQ_Norm','out_GQ_Rank','out_GQ_Trace','out_GQ_Raw','out_Raw_Norm','out_Raw_Rank','out_Raw_Trace','out_Raw_Raw','dataL') return(out) } fccaXXcv=function(xL1,xL2,method=c('basis','gq','raw'),centre = TRUE,tol=1e-7,Control1=list(),Control2=list(),alpha=10^seq(-6,1,len=10)){ out=rep(0,length(alpha)) for(i in seq_along(alpha)){ Control1$pen1=c(Control1$pen1,alpha[i])[1] Control2$pen1=c(Control2$pen1,alpha[i])[1] Control2$pen2=Control2$pen2=0 cvL1=cvL2=rep(0,nrow(xL1[[1]])) for(j in 1:nrow(xL1[[1]])){ cvL1[j]= cvL2[j] =0 xL1nI=lapply(xL1,function(ii) ii[-j,]) xL2nI=lapply(xL2,function(ii) ii[-j,]) xL1I=lapply(xL1,function(ii) ii[j,,drop=F]) xL2I=lapply(xL2,function(ii) ii[j,,drop=F]) tmp=fccaXX(xL1nI,xL2nI,method=method,centre = centre,control1=Control1,tol = tol,control2=Control2) tmp try(cvL1[j]<-Reduce('+',mapply('%*%',xL1I,lapply(tmp$coef1,function(ii) ii[,1,drop=F] ))),T) try(cvL2[j]<-Reduce('+',mapply('%*%',xL2I,lapply(tmp$coef2,function(ii) ii[,1,drop=F] ))),T) if(sum(c(cvL1[j], cvL2[j])%in%0)>0) break } if(length(cvL1)!=nrow(xL1[[1]])) out[i]=NA if(length(cvL1)==nrow(xL1[[1]])) out[i]=suppressWarnings(cor(cvL1,cvL2)) Control1$pen1=Control2$pen1=NULL } idx_na=which(is.na(out)) outcome=list(cor=out[-idx_na],alpha=alpha[-idx_na]) return(outcome) } fccaPre=function(xL,centre=TRUE,method=c('basis','gq','raw'),control=list()){ if(!is.list(xL)) xL=list(xL) if(is.list(xL)) xL=lapply(xL,as.matrix) nList=length(xL) ndimL=sapply(xL,ncol) idxFD=seq_along(xL)[ndimL>1] if(centre){ xL=lapply(xL,scale) xMean=lapply(xL,function(i)attr(i,"scaled:center")) xSD=lapply(xL,function(i)attr(i,"scaled:scale")) xL=lapply(xL,function(i){ da=i attr(da,"scaled:center")=NULL attr(da,"scaled:scale")=NULL da }) } method=method[1] gqWeight=NULL pL=phiL=vector('list',length=nList) if(method=='basis'){ con=list(nbasis=35,norder=6,pen1=10^(seq((-20),5,len=41)),pen2=0.01,t=seq(0,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control nbasis=con$nbasis;norder=con$norder;pen1=con$pen1 pen2=con$pen2;t=con$t if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } if(length(nbasis)!=length(norder)){ nbasis=nbasis[1] norder=norder[1] warning('length of nbasis is different from length of norder') } if(length(nbasis)!=nList) nbasis=rep(nbasis[1],nList) if(length(norder)!=nList) norder=rep(norder[1],nList) for(iL in idxFD){ tRange=range(t[[iL]]) nb=nbasis[iL];no=norder[iL] tiL=t[[iL]] spline=create.bspline.basis(tRange,nbasis = nb,norder = no) MS=eval.basis(tiL,spline,0) MS2=eval.basis(tiL,spline,2) pL[[iL]]=crossprod(MS2) phiL[[iL]]=MS/(ncol(xL[[iL]])) } } if(method=='gq'){ con=list(nP=18,pen1=10^(seq((-20),5,len=21)),pen2=0.01,t=seq(-1,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control t=con$t;nP=con$nP;pen1=con$pen1;pen2=con$pen2 if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } if(GQ==0){ .GlobalEnv$modelChronic <- readRDS( file.path(system.file('inst/extdata',package='flars'), 'GQ.rds')) } gqWeight=data.matrix(GQ[GQ$n==nP,c(1,2)]) gqWeight2=data.matrix(GQ[GQ$n==(nP-2),c(1,2)]) xi=as.numeric(gqWeight[,1]) wi=as.matrix(gqWeight[,2]) wi2=as.matrix(gqWeight2[,2]) for(iL in idxFD){ dimFx=dim(xL[[iL]]) ncols=dimFx[2] nrows=dimFx[1] zi=t[[iL]] idx=as.numeric(sapply(xi,function(i) which.min(abs(zi-i)))) xGQ=t(apply(xL[[iL]][,sort(idx)],1,function(i)i*(wi[order(idx)]))) xL[[iL]]=xGQ pL[[iL]]=t(get2L(ncol(xL[[iL]]),diff(sort(xi))))%*%diag(wi2[,1])%*%get2L(ncol(xL[[iL]]),diff(sort(xi))) phiL[[iL]]=diag(wi[,1]) } } if(method=='raw'){ con=list(pen1=10^(seq((-10),-5,len=21)),pen2=0.01,t=seq(-1,1,len=max(sapply(xL,ncol),na.rm = T))) con[(namc <- names(control))] <- control t=con$t;pen1=con$pen1;pen2=con$pen2 if(!is.list(t)){ tRange=range(t) t=lapply(xL,function(i){ if(ncol(i)==length(t)){ return(t) } if(ncol(i)!=length(t) & ncol(i)>1){ return(seq(tRange[1],tRange[2],len=ncol(i))) } if(ncol(i)==1){ return((tRange[1]+tRange[2])/2) } }) } if(is.list(t)){ if(length(t)!=nList) t=lapply(xL,function(i)return(t[[1]])) } for(iL in idxFD){ pL[[iL]]=crossprod(get2L(ncol(xL[[iL]]),diff(t[[iL]]))) phiL[[iL]]=diag(1,ncol(xL[[iL]]))/(ncol(xL[[iL]])) } } if(length(idxFD)<nList){ pL[-idxFD]=lapply(pL[-idxFD],function(i) i=matrix(0)) phiL[-idxFD]=lapply(phiL[-idxFD],function(i) i=matrix(1)) } W=phiL;W2=pL v=do.call(cbind,mapply('%*%',xL,W,SIMPLIFY = F)) vv=crossprod(v) Pen=matrix(0,ncol=ncol(vv),nrow=nrow(vv)) DimPhL=sapply(phiL,ncol) DimP1=DimPhL[1] DimPhL=DimPhL-DimP1 for(i in seq_along(phiL)){ Pen[1:(DimPhL[i]+DimP1)+DimP1*(i-1)+sum(DimPhL[1:(i-1)]), 1:(DimPhL[i]+DimP1)+DimP1*(i-1)+sum(DimPhL[1:(i-1)])]=pen1[1]*W2[[i]]+pen2[1]*crossprod(W[[i]]) } P=vv+Pen output=list(P=P,Xv=v,W=W,W2=W2) return(output) } fccaXX=function(xL1,xL2,centre=TRUE,method=c('basis','gq','raw'),control1=list(),control2=list(),tol=1e-7){ pre1=fccaPre(xL1,centre=centre,method = method[1],control = control1) pre2=fccaPre(xL2,centre=centre,method = method[1],control = control2) M1=ginv(pre1$P)%*%crossprod(pre1$Xv,pre2$Xv)%*%ginv(pre2$P)%*%crossprod(pre2$Xv,pre1$Xv) M2=ginv(pre2$P)%*%crossprod(pre2$Xv,pre1$Xv)%*%ginv(pre1$P)%*%crossprod(pre1$Xv,pre2$Xv) out1=eigen(M1) out2=eigen(M2) rho=rho1=Re(out1$values) rho2=Re(out2$values) if(rho1[1]-rho2[1]>1e-7) warning("eigenvalues don't match") idx=rho>tol rho=rho[idx] a=Re(out1$vectors)[,idx,drop=F] b=Re(out2$vectors)[,idx,drop=F] if(length(idx)==0){ rho=0 coef1=coef2=1 } if(length(idx)!=0){ aDim=c(0,cumsum(sapply(pre1$W,ncol))) coef1=vector('list',length = length(xL1)) for(i in seq_along(xL1)){ coef1[[i]]=pre1$W[[i]]%*%a[(1+aDim[i]):aDim[i+1],] } bDim=c(0,cumsum(sapply(pre2$W,ncol))) coef2=vector('list',length = length(xL2)) for(i in seq_along(xL2)){ coef2[[i]]=pre2$W[[i]]%*%b[(1+bDim[i]):bDim[i+1],] } } out=list(corr=rho,coef1=coef1,coef2=coef2,corr2=rho2) return(out) }
state_shapepull = function() { temp <- tempfile() temp2 <- tempfile() download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/State+Shapes/US_States_Viz_2020_high_res.zip", temp) unzip(zipfile = temp, exdir = temp2) filename <- list.files(temp2, full.names = TRUE) shp_file <- filename %>% subset(grepl("*.shp$", filename)) dataset <- sf::st_read(shp_file, stringsAsFactors = FALSE) %>% dplyr::mutate(FIPSn = as.character(FIPSn), FIPSn = stringr::str_pad(FIPSn, width = 2, pad = "0")) %>% sf::st_transform(4269) message("NOTE::This shapefile has been simplified to make analysis quicker. For final vizualizations, please use the unsimplified shapefiles available through NCES.") return(dataset) }
test_that("exprs() without arguments creates an empty named list", { expect_identical(exprs(), named_list()) }) test_that("exprs() captures arguments forwarded with `...`", { wrapper <- function(...) exprs(...) expect_identical(wrapper(a = 1, foo = bar), list(a = 1, foo = quote(bar))) }) test_that("exprs() captures empty arguments", { expect_identical(exprs(, , .ignore_empty = "none"), set_names(list(missing_arg(), missing_arg()), c("", ""))) }) test_that("dots are always named", { expect_named(dots_list("foo"), "") expect_named(dots_splice("foo", list("bar")), c("", "")) expect_named(exprs(foo, bar), c("", "")) }) test_that("dots can be spliced", { spliced_dots <- dots_values(!!! list(letters)) expect_identical(spliced_dots, list(splice(list(letters)))) expect_identical(flatten(dots_values(!!! list(letters))), list(letters)) expect_identical(list2(!!! list(letters)), list(letters)) wrapper <- function(...) list2(...) expect_identical(wrapper(!!! list(letters)), list(letters)) }) test_that("interpolation by value does not guard formulas", { expect_identical(dots_values(~1), list(~1)) }) test_that("dots names can be unquoted", { expect_identical(dots_values(!! paste0("foo", "bar") := 10), list(foobar = 10)) }) test_that("can take forced dots with `allowForced = FALSE`", { fn <- function(...) { force(..1) captureDots() } expect_identical(fn(a = letters), pairlist(a = list(expr = letters, env = empty_env()))) }) test_that("captured dots are only named if names were supplied", { fn <- function(...) captureDots() expect_null(names(fn(1, 2))) expect_identical(names(fn(a = 1, 2)), c("a", "")) }) test_that("dots_values() handles forced dots", { fn <- function(...) { force(..1) dots_values(...) } expect_identical(fn("foo"), list("foo")) expect_identical(lapply(1:2, function(...) dots_values(...)), list(list(1L), list(2L))) expect_identical(lapply(1:2, dots_values), list(list(1L), list(2L))) }) test_that("empty arguments trigger meaningful error", { expect_error(list2(1, , 3), "Argument 2 is empty") expect_error(dots_list(1, , 3), "Argument 2 is empty") }) test_that("cleans empty arguments", { expect_identical(dots_list(1, ), named_list(1)) expect_identical(list2(1, ), list(1)) expect_identical(exprs(1, ), named_list(1)) expect_identical(dots_list(, 1, , .ignore_empty = "all"), named_list(1)) }) test_that("doesn't clean named empty argument arguments", { expect_error(dots_list(1, a = ), "Argument 2 is empty") expect_identical(exprs(1, a = ), alist(1, a = )) expect_identical(exprs(1, a = , b = , , .ignore_empty = "all"), alist(1, a = , b = )) }) test_that("capturing dots by value only unquote-splices at top-level", { expect_identical_(dots_list(!!! list(quote(!!! a))), named_list(quote(!!! a))) expect_identical_(dots_list(!!! exprs(!!! 1:3)), named_list(1L, 2L, 3L)) }) test_that("can't unquote when capturing dots by value", { expect_identical(dots_list(!!! list(!!! TRUE)), named_list(FALSE)) }) test_that("can splice NULL value", { expect_identical(dots_list(!!! NULL), named_list()) expect_identical(dots_list(1, !!! NULL, 3), named_list(1, 3)) }) test_that("dots_splice() flattens lists", { expect_identical(dots_splice(list("a", list("b"), "c"), "d", list("e")), named_list("a", list("b"), "c", "d", "e")) expect_identical(dots_splice(list("a"), !!! list("b"), list("c"), "d"), named_list("a", "b", "c", "d")) expect_identical(dots_splice(list("a"), splice(list("b")), list("c"), "d"), named_list("a", "b", "c", "d")) }) test_that("dots_splice() doesn't squash S3 objects", { s <- structure(list(v1 = 1, v2 = 2), class = "foo") expect_identical(dots_splice(s, s), named_list(s, s)) }) test_that("dots_split() splits named and unnamed dots", { dots <- dots_split(1, 2) expect_identical(dots$named, list()) expect_identical(dots$unnamed, list(1, 2)) dots <- dots_split(a = 1, 2) expect_identical(dots$named, list(a = 1)) expect_identical(dots$unnamed, list(2)) dots <- dots_split(a = 1, b = 2) expect_identical(dots$named, list(a = 1, b = 2)) expect_identical(dots$unnamed, list()) }) test_that("dots_split() handles empty dots", { dots <- dots_split() expect_identical(dots$named, list()) expect_identical(dots$unnamed, list()) }) test_that("dots_split() fails if .n_unnamed doesn't match", { expect_error(dots_split(1, 2, .n_unnamed = 1), "Expected 1 unnamed") expect_error(dots_split(1, 2, .n_unnamed = 0:1), "Expected 0 or 1 unnamed") dots <- dots_split(a = 1, 2, .n_unnamed = 1) expect_identical(dots$named, list(a = 1)) expect_identical(dots$unnamed, list(2)) }) test_that("can splice NULL and atomic vectors", { expect_identical(list2(!!!letters), as.list(letters)) expect_identical(list2(!!!NULL), list()) }) test_that("can unquote quosures in LHS", { quo <- quo(foo) expect_identical(list2(!!quo := NULL), list(foo = NULL)) expect_identical(exprs(!!quo := bar), exprs(foo = bar)) }) test_that("can preserve empty arguments", { list3 <- function(...) unname(dots_list(..., .preserve_empty = TRUE)) expect_identical(list3(, ), list(missing_arg())) expect_identical(list3(, , .ignore_empty = "none"), list(missing_arg(), missing_arg())) expect_identical(list3(, , .ignore_empty = "all"), list()) }) test_that("forced symbolic objects are not evaluated", { x <- list(quote(`_foo`)) expect_identical_(lapply(x, list2), list(x)) expect_identical_(list2(!!!x), x) x <- unname(exprs(stop("tilt"))) expect_identical_(lapply(x, list2), list(x)) }) test_that("dots collectors do not warn by default with bare `<-` arguments", { expect_no_warning(list2(a <- 1)) expect_no_warning(dots_list(a <- 1)) expect_no_warning(exprs(a <- 1)) expect_no_warning(quos(a <- 1)) myexprs <- function(...) enexprs(...) myquos <- function(...) enexprs(...) expect_no_warning(myexprs(a <- 1)) expect_no_warning(myquos(a <- 1)) }) test_that("dots collectors can elect to warn with bare `<-` arguments", { expect_warning(dots_list(a <- 1, .check_assign = TRUE), "`<-` as argument") myexprs <- function(...) enexprs(..., .check_assign = TRUE) myquos <- function(...) enexprs(..., .check_assign = TRUE) expect_warning(myexprs(TRUE, a <- 1), "`<-` as argument") expect_warning(myquos(TRUE, a <- 1), "`<-` as argument") }) test_that("dots collectors never warn for <- when option is set", { local_options(rlang_dots_disable_assign_warning = TRUE) expect_no_warning(list2(a <- 1)) myexprs <- function(...) enexprs(..., .check_assign = TRUE) myquos <- function(...) enquos(..., .check_assign = TRUE) expect_no_warning(myexprs(a <- 1)) expect_no_warning(myquos(a <- 1)) }) test_that("`.homonyms` is matched exactly", { expect_error(dots_list(.homonyms = "k"), "must be one of") }) test_that("`.homonyms = 'first'` matches first homonym", { list_first <- function(...) { dots_list(..., .homonyms = "first") } out <- list_first(1, 2) expect_identical(out, named_list(1, 2)) out <- list_first(a = 1, b = 2, 3, 4) expect_identical(out, list(a = 1, b = 2, 3, 4)) out <- list_first(a = 1, b = 2, a = 3, a = 4, 5, 6) expect_identical(out, list(a = 1, b = 2, 5, 6)) }) test_that("`.homonyms = 'last'` matches last homonym", { list_last <- function(...) { dots_list(..., .homonyms = "last") } out <- list_last(1, 2) expect_identical(out, named_list(1, 2)) out <- list_last(a = 1, b = 2, 3, 4) expect_identical(out, list(a = 1, b = 2, 3, 4)) out <- list_last(a = 1, b = 2, a = 3, a = 4, 5, 6) expect_identical(out, list(b = 2, a = 4, 5, 6)) }) test_that("`.homonyms` = 'error' fails with homonyms", { list_error <- function(...) { dots_list(..., .homonyms = "error") } expect_identical(list_error(1, 2), named_list(1, 2)) expect_identical(list_error(a = 1, b = 2), list(a = 1, b = 2)) expect_snapshot({ (expect_error(list_error(1, a = 2, a = 3))) (expect_error(list_error(1, a = 2, b = 3, 4, b = 5, b = 6, 7, a = 8))) (expect_error(list_error(1, a = 2, b = 3, 4, b = 5, b = 6, 7, a = 8))) }) }) test_that("`.homonyms` works with spliced arguments", { args <- list(a = 1, b = 2, a = 3, a = 4, 5, 6) expect_identical(dots_list(!!!args, .homonyms = "first"), list(a = 1, b = 2, 5, 6)) myexprs <- function(...) enexprs(..., .homonyms = "last") expect_identical(myexprs(!!!args), list(b = 2, a = 4, 5, 6)) myquos <- function(...) enquos(..., .homonyms = "first") expect_identical(myquos(!!!args), quos_list(a = quo(1), b = quo(2), quo(5), quo(6))) }) test_that("can mix `!!!` and splice boxes", { expect_identical(list2(1L, !!!(2:3), splice(list(4L))), as.list(1:4)) }) test_that("list2() and dots_values() support splice boxes", { expect_identical(list2(1, splice(c("foo", "bar")), 3), list(1, "foo", "bar", 3)) expect_identical(dots_values(1, splice(c("foo", "bar")), 3), list(1, splice(list("foo", "bar")), 3)) }) test_that("dots_values() doesn't splice", { expect_identical_(dots_values(!!!c(1:3)), list(splice(as.list(1:3)))) expect_identical_(dots_values(!!!list("foo", "bar")), list(splice(list("foo", "bar")))) }) test_that("!!! does not evaluate multiple times ( foo <- function() x <<- x + 1 x <- 0 list2(!!!list(foo())) expect_identical(x, 1) x <- 0 exprs(!!!list(foo())) expect_identical(x, 1) x <- 0 quos(!!!list(foo())) expect_identical(x, 1) }) test_that("dots_list() optionally auto-names arguments ( expect_identical( dots_list(.named = TRUE), named(list()) ) expect_identical( dots_list(1, letters, .named = TRUE), list(`1` = 1, letters = letters) ) expect_identical( dots_list(1, foo = letters, .named = TRUE), list(`1` = 1, foo = letters) ) expect_identical( dots_list(!!!list(a = 1:3, 1:3), .named = TRUE), list(a = 1:3, `<int>` = 1:3) ) expect_identical( dots_list(!!!list(1:3, 1:3), .named = TRUE), list(`<int>` = 1:3, `<int>` = 1:3) ) }) test_that("`.ignore_empty` is matched", { expect_snapshot({ (expect_error(dots_list(.ignore_empty = "t"))) foo <- function() dots_list(.ignore_empty = "t") (expect_error(foo())) }) }) test_that("`.named` can be `NULL` (default names) or `FALSE` (minimal names)", { expect_equal( dots_list(.named = FALSE), set_names(list(), "") ) expect_equal( exprs(.named = FALSE), set_names(list(), "") ) expect_equal( dots_list(.named = NULL), list() ) expect_equal( exprs(.named = NULL), list() ) })
do.sir <- function(X, response, ndim=2, h=max(2, round(nrow(X)/5)), preprocess=c("center","scale","cscale","decorrelate","whiten")){ aux.typecheck(X) n = nrow(X) p = ncol(X) response = as.double(response) if ((any(is.infinite(response)))||(!is.vector(response))||(any(is.na(response)))){ stop("* do.sir : 'response' should be a vector containing no NA values.") } ndim = as.integer(ndim) if (!check_ndim(ndim,p)){stop("* do.sir : 'ndim' is a positive integer in [1, h = as.integer(h) if (!is.factor(response)){ if (!check_NumMM(h,2,ceiling(n/2),compact=TRUE)){stop("* do.save : the number of slices should be in [2,n/2].")} } if (missing(preprocess)){ algpreprocess = "center" } else { algpreprocess = match.arg(preprocess) } tmplist = aux.preprocess.hidden(X,type=algpreprocess,algtype="linear") trfinfo = tmplist$info pX = tmplist$pX if (!is.factor(response)){ label = as.integer(sir_makelabel(response, h)) } else { label = as.integer(response) } ulabel = unique(label) nlabel = length(ulabel) class_mean = array(0,c(nlabel,p)) class_count = rep(0,nlabel) for (i in 1:nlabel){ idxclass = which(label==ulabel[i]) class_mean[i,] = as.vector(colMeans(pX[idxclass,]) ) class_count[i] = length(idxclass) } all_mean = as.vector(colMeans(pX)) mat_Sigma = aux_scatter(pX, all_mean)/n mat_Gamma = array(0,c(p,p)) for (i in 1:nlabel){ vecdiff = (as.vector(class_mean[i,])-(all_mean)) mat_Gamma = mat_Gamma + outer(vecdiff,vecdiff)*as.double(class_count[i])/n } costInv = aux.bicgstab(mat_Sigma, mat_Gamma, verbose=FALSE)$x projection = aux.adjprojection(RSpectra::eigs(costInv, ndim)$vectors) projection = matrix(as.double(projection), nrow=p) result = list() result$Y = pX%*%projection result$trfinfo = trfinfo result$projection = projection return(result) } sir_makelabel <- function(responsevec, h){ n = length(responsevec) output = rep(0,n) hn = floor(n/h) startidx = 1 currentlabel = 1 orderlabel = order(responsevec) for (i in 1:(h-1)){ idxorders = orderlabel[startidx:(startidx+hn-1)] output[idxorders] = currentlabel startidx = startidx + hn currentlabel = currentlabel + 1 } idxorders = orderlabel[startidx:n] output[idxorders] = currentlabel return(output) }
ena.set <- function(x) { newset = list() class(newset) <- c("ena.set", class(newset)) x.is.set <- T if("ENAdata" %in% class(x)) { x <- list(enadata = x); x.is.set <- F } code.columns <- apply(x$enadata$adjacency.matrix, 2, paste, collapse = " & ") newset$connection.counts <- x$enadata$adjacency.vectors; colnames(newset$connection.counts) <- code.columns for (i in seq(ncol(newset$connection.counts))) { set(newset$connection.counts, j = i, value = as.ena.co.occurrence(newset$connection.counts[[i]])) } if (grepl(x = x$enadata$model, pattern = "Traj", ignore.case = T)) { newset$meta.data <- data.table::copy(x$enadata$trajectories$units) newset$meta.data[, ENA_UNIT := apply(x$enadata$trajectories$units, 1, paste, collapse = ".")] newset$trajectories <- cbind(newset$meta.data, x$enadata$trajectories$step) for (i in seq(ncol(newset$trajectories))) { set(newset$trajectories, j = i, value = as.ena.metadata(newset$trajectories[[i]])) } } else { newset$meta.data <- x$enadata$metadata } if (!is.null(newset$meta.data) && ncol(newset$meta.data) > 0) { for (i in seq(ncol(newset$meta.data))) { set(newset$meta.data, j = i, value = as.ena.metadata(newset$meta.data[[i]])) } } if (x.is.set) { newset$line.weights <- as.data.table(cbind(x$enadata$metadata, x$line.weights)) to_cols <- names(which(!find_meta_cols(newset$line.weights))) for(col in to_cols) { set(x = newset$line.weights, j = col, value = as.ena.co.occurrence(newset$line.weights[[col]])) } class(newset$line.weights) <- c("ena.line.weights", class(newset$line.weights)) newset$points <- cbind(x$enadata$metadata, x$points.rotated) to_cols <- names(which(!find_meta_cols(newset$points))) for(col in to_cols) { set(x = newset$points, j = col, value = as.ena.dimension(newset$points[[col]])) } newset$points <- as.ena.matrix(newset$points, "ena.points") newset$rotation.matrix <- x$rotation.set$rotation } newset$connection.counts <- cbind(newset$meta.data, newset$connection.counts) class(newset$connection.counts) <- c("ena.connections", class(newset$connection.counts)) newset$model <- list( model.type = x$enadata$model, raw.input = x$enadata$raw, row.connection.counts = x$enadata$accumulated.adjacency.vectors[, unique(names(x$enadata$accumulated.adjacency.vectors)), with = F], unit.labels = x$enadata$unit.names ) cols <- grep("adjacency.code", colnames(newset$model$row.connection.counts)) colnames(newset$model$row.connection.counts)[cols] <- code.columns for(i in cols) { set(newset$model$row.connection.counts, j = i, value = as.ena.co.occurrence(newset$model$row.connection.counts[[i]])) } for (i in which(colnames(newset$model$row.connection.counts) %in% colnames(newset$meta.data)) ) { set(newset$model$row.connection.counts, j = i, value = as.ena.metadata(newset$model$row.connection.counts[[i]])) } for (i in which(colnames(newset$model$row.connection.counts) %in% x$enadata$codes) ) { set(newset$model$row.connection.counts, j = i, value = as.ena.code(newset$model$row.connection.counts[[i]])) } class(newset$model$row.connection.counts) <- c("row.connections", class(newset$model$row.connection.counts)) if (x.is.set) { newset$model$centroids <- x$centroids newset$model$correlations <- x$correlations newset$model$function.call <- x$function.call newset$model$function.params <- x$function.params newset$model$points.for.projection <- cbind(x$enadata$metadata, x$points.normed.centered) newset$model$variance <- x$variance names(newset$model$variance) <- colnames(newset$rotation.matrix) } newset$rotation <- list( adjacency.key = as.data.table(x$enadata$adjacency.matrix), codes = x$enadata$codes ) class(newset$rotation) <- c("ena.rotation.set", class(newset$rotation)) for (i in seq(ncol(newset$rotation$adjacency.key))) { set(newset$rotation$adjacency.key, j = i, value = as.ena.codes(newset$rotation$adjacency.key[[i]])) } if(x.is.set) { newset$rotation$eigenvalues = x$rotation.set$eigenvalues newset$rotation$nodes = x$node.positions newset$rotation$rotation.matrix = x$rotation.set$rotation } newset$`_function.call` <- sys.calls()[[1]] back.frame <- sapply(sys.frames(), function(f) { "window.size.back" %in% ls(envir = f) }) if (any(back.frame)) { call.frame <- sys.frame(which(back.frame)) newset$`_function.params` <- mget(ls(envir = call.frame), envir = call.frame) } else { newset$`_function.params` <- list() } return(newset); }
get.slepians<-function(npoints=900, nwin=5, npi=3) { if(missing(npoints)) npoints=900 if(missing(nwin)) nwin=5 if(missing(npi)) npi=3 tapers = vector(length=nwin*npoints) ary = .C("CALL_slepian", PACKAGE = "RSEIS", as.integer(npoints), as.integer(nwin), as.double(npi), as.double(tapers) ) kout = ary[[4]] mout = matrix( kout, ncol=nwin) invisible(mout) }
library(plotly) nPatients <- 50 nVisits <- 10 d <- data.frame( perc = rnorm(n = nPatients * nVisits, mean = 50, sd = 10), patient = rep(seq(nPatients), each = nVisits), visit = rep(seq(nVisits), nPatients) ) hd <- highlight_key(d, ~patient) p <- plot_ly(hd, x = ~visit, y = ~perc, color = I("black"), text = ~paste("Patient:", patient)) %>% group_by(patient) %>% add_trace(mode = "markers+lines") layout(p, title = "Click on a marker to highlight that patient") p %>% layout(title = "Click and drag to select patient") %>% highlight("plotly_selecting") p %>% layout(title = "Click and drag to select patient", dragmode = "lasso") %>% highlight("plotly_selecting") p %>% highlight(on = "plotly_hover", off = "plotly_doubleclick") %>% layout(dragmode = "zoom") p %>% layout(title = "Shift the key to accumulate selections") %>% highlight("plotly_hover") highlight(p, dynamic = TRUE) colors <- RColorBrewer::brewer.pal(4, "Dark2") highlight(p, color = colors, dynamic = TRUE)
"catdata"
knitr::opts_chunk$set(message=FALSE,warning = FALSE, comment = NA) old.hooks <- fansi::set_knit_hooks(knitr::knit_hooks) library(psycModel) library(dplyr) iris %>% head() iris %>% select(1:3) %>% head(1) iris %>% select(Sepal.Length:Petal.Length) %>% head(1) iris %>% select(c(1, 3:4)) %>% head(1) iris %>% select(Sepal.Length, Petal.Length:Petal.Width) %>% head(1) iris %>% select(1:5, -3) %>% head(1) iris %>% select(Sepal.Length:Species, -Petal.Length) %>% head(1) iris %>% select(everything()) %>% head(1) iris %>% select(c(everything(),-Sepal.Width)) %>% head(1) iris %>% select(starts_with('Sepal')) %>% head(1) iris %>% select(ends_with('Width')) %>% head(1) iris %>% select(contains('Sepal')) %>% head(1) iris %>% select(contains('Width')) %>% head(1) iris %>% select(contains('.')) %>% head(1) iris %>% select(where(is.numeric)) %>% head(1) set.seed(1) test_data = data.frame(y = rnorm(n = 100,mean = 2,sd = 3), x1 = rnorm(n = 100,mean = 1.5, sd = 4), x2 = rnorm(n = 100,mean = 1.7, sd = 4), x3 = rnorm(n = 100,mean = 1.5, sd = 4), x4 = rnorm(n = 100,mean = 2, sd = 4), x5 = rnorm(n = 100,mean = 1.5, sd = 4)) model1 = lm(data = test_data, formula = y ~ x1 + x2 + x3 + x4 + x5) model2 = lm_model(data = test_data, response_variable = y, predictor_variable = c(everything(),-y)) model3 = lm_model(data = test_data, response_variable = y, predictor_variable = everything())
test_that("dai_sync calls out input errors", { skip_on_cran() skip_on_ci() expect_error(dai_sync(file = mtcars), "Invalid file input.") expect_error(dai_sync(file = as.matrix(mtcars)), "Invalid file input.") expect_error(dai_sync(file = TRUE), "Invalid file input.") expect_error(dai_sync(file = 123), "Invalid file input.") expect_error(dai_sync(file = c("foo.pdf", "bar.pdf")), "Invalid file input.") expect_error(dai_sync(file = "foo.txt"), "Unsupported file format. See documentation for details.") expect_error(dai_sync(file = "foo.docx"), "Unsupported file format. See documentation for details.") expect_error(dai_sync(file = "foo.mp4"), "Unsupported file format. See documentation for details.") expect_error(dai_sync(file = "foo"), "Unsupported file format. See documentation for details.") expect_error(dai_sync(file = "foo.pdf"), "Input file not a real pdf. Is the file in your working directory?") expect_error(dai_sync(file = "foo.png", proj_id = 012345), "Invalid proj_id.") expect_error(dai_sync(file = "foo.png", proj_id = c("Project1", "Project2")), "Invalid proj_id.") expect_error(dai_sync(file = "foo.png", proj_id = "abc", proc_id = 123), "Invalid proc_id.") expect_error(dai_sync(file = "foo.png", proj_id = "abc", proc_id = "abc", loc = "USA"), "Invalid location parameter.") }) test_that("dai_sync informs about unsuccessful requests", { skip_on_cran() skip_on_ci() skip_if_offline() file <- testthat::test_path("examples", "image.jpg") response <- dai_sync(file, token = NULL) expect_equal(response[["status_code"]], 401) }) test_that("dai_sync gets text from an example file", { skip_on_cran() skip_on_ci() skip_if_offline() image <- testthat::test_path("examples", "image.jpg") response <- dai_sync(image) expect_equal(response[["status_code"]], 200) parsed <- httr::content(response) expect_type(parsed[["document"]][["text"]], "character") }) test_that("dai_async calls out input errors", { skip_on_cran() skip_on_ci() expect_error(dai_async(files = mtcars), "Invalid files parameter.") expect_error(dai_async(files = as.matrix(mtcars)), "Invalid files parameter.") expect_error(dai_async(files = TRUE), "Invalid files parameter.") expect_error(dai_async(files = 123), "Invalid files parameter.") expect_error(dai_async(files = "foo.png"), "Files contain unsupported file types. Only .pdf, .gif, and .tiff accepted.") expect_error(dai_async(files = "foo.pdf", dest_folder = c("folder1", "folder2")), "Invalid dest_folder parameter.") expect_error(dai_async(files = "foo.pdf", dest_folder = 12345), "Invalid dest_folder parameter.") expect_error(dai_async(files = "foo.pdf", bucket = c("bucket1", "bucket2")), "Invalid bucket parameter.") expect_error(dai_async(files = "foo.pdf", bucket = 12345), "Invalid bucket parameter.") expect_error(dai_async(files = "foo.pdf", bucket = "abc", proj_id = c("project1", "project2")), "Invalid proj_id parameter.") expect_error(dai_async(files = "foo.pdf", bucket = "abc", proj_id = 12345), "Invalid proj_id parameter.") expect_error(dai_async(files = "foo.pdf", bucket = "abc", proj_id = "abc", proc_id = "def", skip_rev = TRUE), "Invalid skip_rev parameter.") expect_error(dai_async(files = "foo.pdf", bucket = "abc", proj_id = "abc", proc_id = "def", loc = "USA"), "Invalid loc parameter.") } ) test_that("dai_async informs about unsuccessful requests", { skip_on_cran() skip_on_ci() skip_if_offline() response <- dai_async("foo.pdf", token = NULL) expect_equal(response[["status_code"]], 401) }) test_that("dai_async sends succesful requests with input in different formats", { skip_on_cran() skip_on_ci() skip_if_offline() response <- dai_async("foo.pdf") expect_equal(response[["status_code"]], 200) response <- dai_async("foo.gif") expect_equal(response[["status_code"]], 200) response <- dai_async("foo.tiff") expect_equal(response[["status_code"]], 200) response <- dai_async("foo.pdf", dest_folder = "folder/") expect_equal(response[["status_code"]], 200) response <- dai_async("foo.pdf", bucket = "gs://bucket") expect_equal(response[["status_code"]], 200) response <- dai_async("foo.pdf", bucket = "bucket/") expect_equal(response[["status_code"]], 200) response <- dai_async(c("foo.pdf", "bar.pdf")) expect_equal(response[["status_code"]], 200) }) test_that("dai_status calls out input errors", { skip_on_cran() skip_on_ci() expect_error(dai_status(123), "Input is not a valid HTTP response.") expect_error(dai_status(mtcars), "Input is not a valid HTTP response.") expect_error(dai_status(as.matrix(mtcars)), "Input is not a valid HTTP response.") expect_error(dai_status("string"), "Input is not a valid HTTP response.") expect_error(dai_status(c("string", "vector")), "Input is not a valid HTTP response.") expect_error(dai_status(list("a", "list")), "Input is not a valid HTTP response.?") wrong <- dai_user() expect_error(dai_status(response = wrong), "Input does not contain a processing job id. Make sure it is from dai_async.") } ) test_that("dai_status calls out input errors", { skip_on_cran() skip_on_ci() resp <- dai_async("foo.pdf") expect_error(dai_status(response = resp, loc = 123), "Invalid location parameter.") expect_error(dai_status(response = resp, loc = "USA"), "Invalid location parameter.") } ) test_that("dai_sync_tab calls out input errors", { skip_on_cran() skip_on_ci() expect_error(dai_sync_tab(file = mtcars), "Invalid file input.") expect_error(dai_sync_tab(file = as.matrix(mtcars)), "Invalid file input.") expect_error(dai_sync_tab(file = TRUE), "Invalid file input.") expect_error(dai_sync_tab(file = 123), "Invalid file input.") expect_error(dai_sync_tab(file = c("foo.png", "bar.png"), "Invalid file input.")) expect_error(dai_sync_tab(file = list("foo.png", "bar.png"), "Invalid file input.")) expect_error(dai_sync_tab(file = "foo.csv"), "Unsupported file format. See documentation for details.") expect_error(dai_sync_tab(file = "bar.doc"), "Unsupported file format. See documentation for details.") expect_error(dai_sync_tab(file = "foobar.txt"), "Unsupported file format. See documentation for details.") expect_error(dai_sync_tab(file = "barfoo.avi"), "Unsupported file format. See documentation for details.") expect_error(dai_sync_tab(file = "fake.pdf"), "Input file not a real pdf. Is the file in your working directory?") expect_error(dai_sync_tab(file = "foo.png", proj_id = mtcars), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = as.matrix(mtcars)), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = TRUE), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = 123), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = c("abc", "def")), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = list("abc", "def")), "Invalid proj_id.") expect_error(dai_sync_tab(file = "foo.png", proj_id = "abc", loc = 123), "Invalid location parameter.") expect_error(dai_sync_tab(file = "foo.png", proj_id = "abc", loc = "USA"), "Invalid location parameter.") }) test_that("dai_sync_tab informs about unsuccessful requests", { skip_on_cran() skip_if_offline() file <- testthat::test_path("examples", "image.jpg") response <- dai_sync_tab(file, proj_id = "abc", token = NULL) expect_equal(response[["status_code"]], 403) }) test_that("dai_sync_tab sends succesful requests with jpgs and pdfs", { skip_on_cran() skip_on_ci() skip_if_offline() file1 <- testthat::test_path("examples", "image.jpg") file2 <- testthat::test_path("examples", "sample.pdf") response <- dai_sync_tab(file1) expect_equal(response[["status_code"]], 200) response <- dai_sync_tab(file2) expect_equal(response[["status_code"]], 200) }) test_that("dai_async_tab calls out input errors", { skip_on_cran() skip_on_ci() expect_error(dai_async_tab(files = mtcars), "Invalid files parameter.") expect_error(dai_async_tab(files = as.matrix(mtcars)), "Invalid files parameter.") expect_error(dai_async_tab(files = TRUE), "Invalid files parameter.") expect_error(dai_async_tab(files = 123), "Invalid files parameter.") expect_error(dai_async_tab(files = "foo.png"), "Input file type not supported.") expect_error(dai_async_tab(files = "foo.pdf", filetype = mtcars, "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = as.matrix(mtcars), "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = TRUE, "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = 123, "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = c("gif", "pdf"), "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = list("gif", "pdf"), "Invalid filetype parameter.")) expect_error(dai_async_tab(files = "foo.pdf", filetype = "gif", "Mismatch between filetype parameter and actual format of files.")) expect_error(dai_async_tab(files = "foo.gif", filetype = "tiff", "Mismatch between filetype parameter and actual format of files.")) expect_error(dai_async_tab(files = "foo.pdf", dest_folder = c("folder1", "folder2")), "Invalid dest_folder parameter.") expect_error(dai_async_tab(files = "foo.pdf", dest_folder = 12345), "Invalid dest_folder parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = c("bucket1", "bucket2")), "Invalid bucket parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = 12345), "Invalid bucket parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = c("project1", "project2")), "Invalid proj_id parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = 12345), "Invalid proj_id parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", loc = 123), "Invalid loc parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", loc = "usa"), "Invalid loc parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", pps = "five"), "Invalid pps parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", pps = 200), "Invalid pps parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", pps = 0), "Invalid pps parameter.") expect_error(dai_async_tab(files = "foo.pdf", bucket = "abc", proj_id = "abc", pps = 10-50), "Invalid pps parameter.") } ) test_that("dai_async_tab sends succesful requests with input in different formats", { skip_on_cran() skip_on_ci() skip_if_offline() response <- dai_async_tab("foo.pdf") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab("foo.gif", filetype = "gif") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab("foo.tiff", filetype = "tiff") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab("foo.pdf", dest_folder = "folder/") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab("foo.pdf", bucket = "gs://bucket") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab("foo.pdf", bucket = "bucket/") expect_equal(response[[1]][["status_code"]], 200) response <- dai_async_tab(c("foo.pdf", "bar.pdf")) expect_equal(response[[1]][["status_code"]], 200) })
tsum.test <- function (mean.x, s.x = NULL, n.x = NULL, mean.y = NULL, s.y = NULL, n.y = NULL, alternative = c("two.sided", "less", "greater"), mu = 0, var.equal = FALSE, conf.level = 0.95, ... ) { alternative <- match.arg(alternative) if (!missing(mu) && (length(mu) != 1 || is.na(mu))) stop("'mu' must be a single number") if (!missing(conf.level) && (length(conf.level) != 1 || !is.finite(conf.level) || conf.level < 0 || conf.level > 1)) stop("'conf.level' must be a single number between 0 and 1") if ( (!is.null(mean.y) || !is.null(s.y) || !is.null(n.y) ) && ( is.null(s.x) || is.null(n.x) ) ) stop("You must enter summarized values for both samples (x and y)") if (!is.null(mean.x) && is.null(mean.y) && is.null(n.x) && is.null(s.x)) stop("You must enter the value for both s.x and n.x") if (is.null(n.x) && !is.null(mean.x) && !is.null(s.x) && is.null(mean.y)) stop("You must enter the value for n.x") if (is.null(s.x) && !is.null(mean.x) && !is.null(n.x) && is.null(mean.y)) stop("You must enter the value for s.x") if (is.null(n.y) && !is.null(mean.x) && !is.null(mean.y) && !is.null(s.y) && !is.null(s.x) && !is.null(n.x)) stop("You must enter the value for n.y") if (is.null(n.y) && is.null(n.x) && !is.null(mean.x) && !is.null(mean.y) && !is.null(s.y) && !is.null(s.x)) stop("You must enter the value for both n.x and n.y") if (is.null(s.x) && is.null(s.y) && !is.null(mean.x) && !is.null(mean.y) && !is.null(n.x) && !is.null(n.y)) stop("You must enter the value for both s.x and s.y") if (!is.null(s.x) && is.null(s.y) && !is.null(mean.x) && !is.null(mean.y) && !is.null(n.x) && !is.null(n.y)) stop("You must enter the value for s.y") if (is.null(n.y) && is.null(s.y) && !is.null(mean.x) && !is.null(mean.y) && !is.null(s.x) && !is.null(n.x)) stop("You must enter the value for both s.y and n.y") if ( (!is.null(mean.y) && !is.null(s.y) && !is.null(n.y)) && (is.null(mean.x) || is.null(s.x) || is.null(n.x)) ) stop("You must enter values for mean.x, s.x, and n.x") if (!is.null(mean.y)) { dname <- "User input summarized values for x and y" yok <- !is.na(mean.y) xok <- !is.na(mean.x) mean.y <- mean.y[yok] } else { dname <- "User input summarized values for x" xok <- !is.na(mean.x) yok <- NULL } mean.x <- mean.x[xok] nx <- n.x mx <- mean.x vx <- s.x^2 if (is.null(mean.y)) { if (nx < 2) stop("not enough 'x' observations") df <- nx - 1 stderr <- sqrt(vx/nx) if (stderr < 10 * .Machine$double.eps * abs(mx)) stop("data are essentially constant") tstat <- (mx - mu)/stderr method <- "One Sample t-test" estimate <- setNames(mx, "mean of x") } else { ny <- n.y if (nx < 1 || (!var.equal && nx < 2)) stop("not enough 'x' observations") if (ny < 1 || (!var.equal && ny < 2)) stop("not enough 'y' observations") if (var.equal && nx + ny < 3) stop("not enough observations") my <- mean.y vy <- s.y^2 method <- paste(if (!var.equal) "Welch", "Two Sample t-test") estimate <- c(mx, my) names(estimate) <- c("mean of x", "mean of y") if (var.equal) { df <- nx + ny - 2 v <- 0 if (nx > 1) v <- v + (nx - 1) * vx if (ny > 1) v <- v + (ny - 1) * vy v <- v/df stderr <- sqrt(v * (1/nx + 1/ny)) } else { stderrx <- sqrt(vx/nx) stderry <- sqrt(vy/ny) stderr <- sqrt(stderrx^2 + stderry^2) df <- stderr^4/(stderrx^4/(nx - 1) + stderry^4/(ny - 1)) } if (stderr < 10 * .Machine$double.eps * max(abs(mx), abs(my))) stop("data are essentially constant") tstat <- (mx - my - mu)/stderr } if (alternative == "less") { pval <- pt(tstat, df) cint <- c(-Inf, tstat + qt(conf.level, df)) } else if (alternative == "greater") { pval <- pt(tstat, df, lower.tail = FALSE) cint <- c(tstat - qt(conf.level, df), Inf) } else { pval <- 2 * pt(-abs(tstat), df) alpha <- 1 - conf.level cint <- qt(1 - alpha/2, df) cint <- tstat + c(-cint, cint) } cint <- mu + cint * stderr names(tstat) <- "t" names(df) <- "df" names(mu) <- if (!is.null(mean.y)){ "difference in means" } else { "mean" } attr(cint, "conf.level") <- conf.level rval <- list(statistic = tstat, parameter = df, p.value = pval, conf.int = cint, estimate = estimate, null.value = mu, alternative = alternative, method = method, data.name = dname) class(rval) <- "htest" return(rval) }
odds.indo2dec <- function (x) { dec <- x dec[] <- NA_real_ dec[which(x <= -1)] <- -1 / x[which(x <= -1)] + 1 dec[which(x >= 1)] <- x[which(x >= 1)] + 1 dec }
jNormalVaR <- function(s,alpha){ mu <- mean(s) vo <- sd(s) object <- mu + vo * jNormInv(alpha) return(-object) }
GVECM_Xt <- function(data,p,type="const",ic="AIC",weight.matrix){ ID<-NULL type=type ic=ic idCol=which(colnames(data) == "ID") timeCol=which(colnames(data)=="Time") dat1=data[,-timeCol] endo.no=ncol(dat1)-1 N=length(unique(dat1[,idCol])) weight.matrix=weight.matrix p=p FLag=p+1 myout= GVECMest(data,p,FLag,lag.max=NULL, ic,type = "const",weight.matrix=weight.matrix) pmatrix=myout$lagmatrix[,2] p=min(pmatrix) cat("\n","Number of lag for eventual Xt is", p, "\n") GO.tmp=NULL G1=NULL G2=NULL RESID=NULL if (p==1) { if (is.list(weight.matrix)) { AVG=matrix(rep(0,N^2),N,N) for (i in 1:length(weight.matrix)){ AVG=AVG+as.matrix(weight.matrix[[i]]) } weight.matrix=AVG/(length(weight.matrix)-1) } else {weight.matrix=as.matrix(weight.matrix)} for (jj in 1:N) { rsd_tmp=resid(myout$gvecm[[jj]]) diff_jj=max(pmatrix)-(pmatrix[jj]) if (diff_jj==0) { rsd_tmp1=rsd_tmp} else {rsd_tmp1=rsd_tmp[-(1:diff_jj),]} RESID=cbind(RESID,rsd_tmp1) endo_lagk0=NULL endo_lagk1=NULL endo_lagk2=NULL for (k in 1:endo.no) { coeff=coef(myout$gvecm[[jj]])[[k]] exo_no=myout$exoLag*endo.no coeff_EXO=coeff[(which(rownames(coeff)=="const")+1):nrow(coeff),] coeff_EXO_LAG0=coeff_EXO[1:endo.no,1] exo_lagi0=NULL;exo_lagk1=NULL for (i in 1:endo.no) { exo_lagi0=rbind(exo_lagi0,coeff_EXO_LAG0[i]*as.matrix(weight.matrix)[,jj]) } endo_lagk0=cbind(endo_lagk0,c(exo_lagi0)) coeff_EXO_LAG=coeff_EXO[-(1:endo.no),1] coeff.ENDO=coeff[1:(pmatrix[jj]*endo.no),1] coeff.ENDO.LAG1=coeff.ENDO[1:endo.no] coeff_EXO_LAG1=coeff_EXO_LAG[1:endo.no] endo_lagi1=NULL for (i in 1:endo.no) { endo_lagi1=rbind(endo_lagi1,coeff_EXO_LAG1[i]*as.matrix(weight.matrix)[,jj]) } tmp.lagi1=matrix(0,endo.no,N) tmp.lagi1[,jj]=coeff.ENDO.LAG1 tmp1=tmp.lagi1+endo_lagi1 endo_lagk1=cbind(endo_lagk1,c(tmp1)) } GO.tmp=cbind(GO.tmp,endo_lagk0) G1=cbind(G1,endo_lagk1) } G0=diag(1,endo.no*N)-GO.tmp invGO=solve(G0) F1=invGO%*%G1 newRESID=t(invGO%*%t(RESID)) varnames=colnames(dat1)[-1] NAME=myout$NAMES dataNT=vnames=NULL for (j in 1:N) { dat=subset(dat1,ID==NAME[j]) vnames=c(vnames,paste(NAME[j],varnames,sep=".")) colnames(dat)=NULL datz=as.matrix(dat[,-1]) dataNT=cbind(dataNT,datz) } colnames(dataNT)=vnames colnames(newRESID)=vnames results <-list(lagmatrix=myout$lagmatrix,G0=G0,G1=G1,F1=F1,RESID=RESID,newRESID=newRESID) } else if (p>=2) { if (is.list(weight.matrix)) { AVG=matrix(rep(0,N^2),N,N) for (i in 1:length(weight.matrix)){ AVG=AVG+as.matrix(weight.matrix[[i]]) } weight.matrix=AVG/(length(weight.matrix)-1) } else {weight.matrix=as.matrix(weight.matrix)} for (jj in 1:N) { rsd_tmp=resid(myout$gvecm[[jj]]) diff_jj=max(pmatrix)-(pmatrix[jj]) if (diff_jj==0) {rsd_tmp1=rsd_tmp } else {rsd_tmp1=rsd_tmp[-(1:diff_jj),]} RESID=cbind(RESID,rsd_tmp1) endo_lagk0=endo_lagk1=endo_lagk2=NULL for (k in 1:endo.no) { coeff=coef(myout$gvecm[[jj]])[[k]] exo_no=myout$exoLag*endo.no coeff_EXO=coeff[(which(rownames(coeff)=="const")+1):nrow(coeff),] coeff_EXO_LAG0=coeff_EXO[1:endo.no,1] exo_lagi0=NULL exo_lagk1=NULL for (i in 1:endo.no) { exo_lagi0=rbind(exo_lagi0,coeff_EXO_LAG0[i]*as.matrix(weight.matrix)[,jj]) } endo_lagk0=cbind(endo_lagk0,c(exo_lagi0)) coeff_EXO_LAG=coeff_EXO[-(1:endo.no),1] coeff.ENDO=coeff[1:(pmatrix[jj]*endo.no),1] coeff.ENDO.LAG1=coeff.ENDO[1:endo.no] coeff_EXO_LAG1=coeff_EXO_LAG[1:endo.no] endo_lagi1=NULL for (i in 1:endo.no) { endo_lagi1=rbind(endo_lagi1,coeff_EXO_LAG1[i]*as.matrix(weight.matrix)[,jj]) } tmp.lagi1=matrix(0,endo.no,N) tmp.lagi1[,jj]=coeff.ENDO.LAG1 tmp1=tmp.lagi1+endo_lagi1 endo_lagk1=cbind(endo_lagk1,c(tmp1)) coeff.ENDO.LAG2=coeff.ENDO[(endo.no+1):(endo.no*p)] coeff_EXO_LAG2=coeff_EXO_LAG[(endo.no+1):(endo.no*p)] endo_lagi2=NULL for (i in 1:endo.no) { endo_lagi2=rbind(endo_lagi2,coeff_EXO_LAG2[i]*as.matrix(weight.matrix)[,jj]) } tmp.lagi2=matrix(0,endo.no,N) tmp.lagi2[,jj]=coeff.ENDO.LAG2 tmp2=tmp.lagi2+endo_lagi2 endo_lagk2=cbind(endo_lagk2,c(tmp2)) } GO.tmp=cbind(GO.tmp,endo_lagk0) G1=cbind(G1,endo_lagk1) G2=cbind(G2,endo_lagk2) } G0=diag(1,endo.no*N)-GO.tmp invGO=solve(G0) F1=invGO%*%G1 F2=invGO%*%G2 newRESID=t(invGO %*% t(RESID)) varnames=colnames(dat1)[-1] NAME=myout$NAMES dataNT=NULL;vnames=NULL for (j in 1:N) { dat=subset(dat1,ID==NAME[j]) vnames=c(vnames,paste(NAME[j],varnames,sep=".")) colnames(dat)=NULL datz=as.matrix(dat[,-1]) dataNT=cbind(dataNT,datz) } colnames(dataNT)=vnames colnames(newRESID)=vnames results <-list(G0=G0,G1=G1,G2=G2, F1=F1,F2=F2,lagmatrix=myout$lagmatrix,RESID=RESID,newRESID=newRESID) } return(results) } .GVARfilter <- function(X, p, Bcoef, exogen = NULL, postpad = c("none", "constant", "zero", "NA")) { X = as.matrix(X) if(any(is.na(X))) stop("\nvarxfilter:-->error: NAs in X.\n") if(ncol(X) < 2) stop("\nvarxfilter:-->error: The matrix 'X' should contain at least two variables.\n") if(is.null(colnames(X))) colnames(X) = paste("X", 1:ncol(X), sep = "") colnames(X) = make.names(colnames(X)) postpad = tolower(postpad[1]) if(any(colnames(Bcoef)=="const")){ constant = TRUE ic = 1 } else{ constant = FALSE ic = 0 } obs = dim(X)[1] K = dim(X)[2] xsample = obs - p Xlags = embed(X, dimension = p + 1)[, -(1:K)] temp1 = NULL for (i in 1:p) { temp = paste(colnames(X), ".l", i, sep = "") temp1 = c(temp1, temp) } colnames(Xlags) = temp1 Xend = X[-c(1:p), ] if(constant){ rhs = cbind( Xlags, rep(1, xsample)) colnames(rhs) <- c(colnames(Xlags), "const") } else{ rhs = Xlags colnames(rhs) <- colnames(Xlags) } if( !(is.null(exogen)) ) { exogen = as.matrix(exogen) if (!identical(nrow(exogen), nrow(X))) { stop("\nvarxfit:-->error: Different row size of X and exogen.\n") } XK = dim(exogen)[2] if (is.null(colnames(exogen))) colnames(exogen) = paste("exo", 1:ncol(exogen), sep = "") colnames(exogen) = make.names(colnames(exogen)) tmp = colnames(rhs) rhs = cbind(rhs, exogen[-c(1:p), ]) colnames(rhs) = c(tmp, colnames(exogen)) } else{ XK = 0 } datamat = as.matrix(rhs) colnames(datamat) = colnames(rhs) xfitted = t( Bcoef %*% t( datamat ) ) xresiduals = tail(X, obs - p) - xfitted if(postpad!="none"){ if(postpad == "constant"){ xfitted = t( Bcoef %*% t( rbind(matrix(c(rep(0, p*K), if(constant) 1 else NULL, if(XK>0) rep(0, XK) else NULL), nrow = p, ncol=dim(Bcoef)[2], byrow = TRUE), datamat ) ) ) xresiduals = X - xfitted } else if(postpad == "zero"){ xfitted = t( Bcoef %*% t( rbind(matrix(rep(0, dim(Bcoef)[2]), nrow = p, ncol=dim(Bcoef)[2], byrow = TRUE), datamat ) ) ) xresiduals = X - xfitted } else if(postpad == "NA"){ xfitted = t( Bcoef %*% t( rbind(matrix(rep(NA, dim(Bcoef)[2]), nrow = p, ncol=dim(Bcoef)[2], byrow = TRUE), datamat ) ) ) xresiduals = X - xfitted } else{ xfitted = t( Bcoef %*% t( datamat ) ) xresiduals = tail(X, obs - p) - xfitted } } ans = list( Bcoef = Bcoef, xfitted = xfitted, xresiduals = xresiduals, lag = p, constant = constant) return( ans ) }
context("Testing rcmvtruncnorm") d <- 5 rho <- 0.9 Sigma <- matrix(0, nrow = d, ncol = d) Sigma <- 0.9^abs(row(Sigma) - col(Sigma)) test_that("The number of samples is a positive integer.", { expect_error( rcmvtruncnorm(n = -2, mean = rep(1, d), sigma = Sigma, lower = rep(-10, d), upper = rep(10, d), dependent.ind = c(2, 3, 5), given.ind = c(1, 4), X.given = c(1, -1) ) ) expect_error( rcmvtruncnorm(n = 0, mean = rep(1, d), sigma = Sigma, lower = rep(-10, d), upper = rep(10, d), dependent.ind = c(2, 3, 5), given.ind = c(1, 4), X.given = c(1, -1) ) ) }) test_that("The burn-in value should be non-negative.", { expect_error( rcmvtruncnorm(2, mean = rep(1, d), sigma = Sigma, lower = rep(-10, d), upper = rep(10, d), dependent.ind = c(2, 3, 5), given.ind = c(1, 4), X.given = c(1, -1), burn = -2L ) ) set.seed(1203) B <- rcmvtruncnorm(1, mean = rep(1, d), sigma = Sigma, lower = rep(-10, d), upper = rep(10, d), dependent.ind = c(2, 3, 5), given.ind = c(1, 4), X.given = c(1, -1), burn = 0L ) expect_equal(round(B[1], 7), 0.1516405) })
AtmosphericEmissivity <- function (airtemp, cloudiness, vp=NULL, opt="linear") { if (opt == "Brutsaert") { if(is.null(vp)){ print("To use Brutsaert's 1975 Clear-Sky Emissivity eqn, enter vapor pressure in kPa") } else return((1.24*((vp*10)/(T+273.2))^(1/7)) * (1 - 0.84 * cloudiness) + 0.84 * cloudiness) } else { return((0.72 + 0.005 * airtemp) * (1 - 0.84 * cloudiness) + 0.84 * cloudiness) } }
scam <- function(formula, family=gaussian(), data=list(), gamma=1, sp=NULL, weights=NULL, offset=NULL, optimizer="bfgs", optim.method=c("Nelder-Mead","fd"), scale=0, knots=NULL, not.exp=FALSE, start=NULL, etastart=NULL, mustart=NULL, control=list(), AR1.rho=0, AR.start=NULL,drop.unused.levels=TRUE) { control <- do.call("scam.control",control) gp <- interpret.gam(formula) cl <- match.call() mf <- match.call(expand.dots=FALSE) mf$formula <- gp$fake.formula mf$family <- mf$control<-mf$scale<-mf$knots<-mf$sp<-mf$min.sp<-mf$H<-mf$select <- mf$drop.intercept <- mf$gamma<-mf$method<-mf$fit<-mf$paraPen<-mf$G<-mf$optimizer <- mf$optim.method <- mf$not.exp <- mf$in.out <- mf$AR1.rho <- mf$AR1.start <- mf$start <- mf$etastart <- mf$mustart <-mf$devtol.fit <- mf$steptol.fit <- mf$del <- mf$...<-NULL mf$drop.unused.levels <- drop.unused.levels mf[[1]] <- quote(stats::model.frame) pmf <- mf mf <- eval(mf, parent.frame()) if (nrow(mf)<2) stop("Not enough (non-NA) data to do anything meaningful") terms <- attr(mf,"terms") vars <- all.vars1(gp$fake.formula[-2]) inp <- parse(text = paste("list(", paste(vars, collapse = ","),")")) if (!is.list(data)&&!is.data.frame(data)) data <- as.data.frame(data) dl <- eval(inp, data, parent.frame()) names(dl) <- vars var.summary <- variable.summary(gp$pf,dl,nrow(mf)) rm(dl) if (is.list(formula)) { environment(formula) <- environment(formula[[1]]) pterms <- list() tlab <- rep("",0) for (i in 1:length(formula)) { pmf$formula <- gp[[i]]$pf pterms[[i]] <- attr(eval(pmf, parent.frame()),"terms") tlabi <- attr(pterms[[i]],"term.labels") if (i>1&&length(tlabi)>0) tlabi <- paste(tlabi,i-1,sep=".") tlab <- c(tlab,tlabi) } attr(pterms,"term.labels") <- tlab } else { pmf$formula <- gp$pf pmf <- eval(pmf, parent.frame()) pterms <- attr(pmf,"terms") } if (is.character(family)) family <- eval(parse(text=family)) if (is.function(family)) family <- family() if (is.null(family$family)) stop("family not recognized") if (family$family[1]=="gaussian" && family$link=="identity") am <- TRUE else am <- FALSE if (AR1.rho!=0&&!is.null(mf$"(AR.start)")) if (!is.logical(mf$"(AR.start)")) stop("AR.start must be logical") if (AR1.rho!=0 && !am) stop("residual autocorrelation, AR1, is currently available only for the Gaussian identity link model.") if (!control$keepData) rm(data) G <- do.call("gam.setup",list(formula=gp,pterms=pterms, data=mf,knots=knots,sp=sp, absorb.cons=TRUE,sparse.cons=0)) G$var.summary <- var.summary G$family <- family if ((is.list(formula)&&(is.null(family$nlp)||family$nlp!=gp$nlp))|| (!is.list(formula)&&!is.null(family$npl)&&(family$npl>1))) stop("incorrect number of linear predictors for family") G$terms<-terms; G$mf<-mf;G$cl<-cl; G$am <- am G$AR1.rho <- AR1.rho; G$AR.start <- AR.start if (is.null(G$offset)) G$offset<-rep(0,G$n) G$min.edf <- G$nsdf if (G$m) for (i in 1:G$m) G$min.edf<-G$min.edf+G$smooth[[i]]$null.space.dim G$formula <- formula G$pred.formula <- gp$pred.formula environment(G$formula)<-environment(formula) if (ncol(G$X)>nrow(G$X)) stop("Model has more coefficients than data") n.terms <- length(G$smooth) n <- nrow(G$X) intercept <- G$intercept G$offset <- as.vector(model.offset(mf)) if (is.null(G$offset)) G$offset <- rep.int(0, n) weights <- G$w fam.name <- G$family[1] if (scale == 0) { if (fam.name == "binomial" || fam.name == "poisson") sig2 <- 1 else sig2 <- -1 } else { sig2 <- scale } if (sig2 > 0) scale.known <- TRUE else scale.known <- FALSE Q <- penalty_pident(G) if (!is.null(sp)) { neg <- FALSE if (length(sp)!= length(G$off)) { warning("Supplied smoothing parameter vector is too short - ignored.") sp <- NULL } else if (sum(is.na(sp))) { warning("NA's in supplied smoothing parameter vector - ignoring.") sp <- NULL } else { good <- sp < 0 if (sum(good) > 0) { warning("Supplied smoothing parameter vector has negative values - ignored.") neg <- TRUE } } if (neg) sp <- NULL } env <- new.env() assign("dbeta.start",rep(0,0),envir=env) assign("sp.last",rep(0,0),envir=env) nvars <- NCOL(G$X) if (!is.null(start)) { if (length(start) != nvars) stop(gettextf("Length of start should equal %d and correspond to initial coefs.",nvars)) else assign("start",start,envir=env) } else{ assign("start",rep(0,0),envir=env) } q.f <- rep(0,n.terms) if (n.terms >0) for (i in 1:n.terms) q.f[i] <- ncol(G$smooth[[i]]$S[[1]]) + 1 G$S <- Q$S G$q.f <- q.f G$q0 <- G$off[1]-1 G$p.ident <- Q$p.ident G$n.terms <- n.terms G$weights <- weights G$sig2 <- sig2 G$scale.known <- scale.known G$not.exp <- not.exp object <- list() if (is.null(sp)) { y <- G$y; family <- G$family nobs <- NROW(y) eval(family$initialize) G$y <- y def.sp <- initial.sp.scam(G, Q,q.f=q.f,n.terms=n.terms,family=family, intercept=intercept,offset=G$offset, env=env, weights=weights, control=control) rho <- log(def.sp+1e-4) if (!is.null(start)) assign("start",start,envir=env) ptm <- proc.time() re <- estimate.scam(G=G,optimizer=optimizer,optim.method=optim.method, rho=rho, gamma=gamma, env=env,control=control) CPU.time <- proc.time()-ptm best <- re object$gcv.ubre <- re$gcv.ubre object$dgcv.ubre <- re$dgcv.ubre best$p.ident <- Q$p.ident best$S <- Q$S object$optimizer <- optimizer object$edf1 <- re$edf1 object$termcode <- re$termcode if (optimizer == "bfgs") { object$check.grad <- re$check.grad object$dgcv.ubre.check <- re$dgcv.ubre.check } } else { best <- scam.fit(G=G, sp=sp,gamma=gamma,env=env, control=control) object$optimizer <- "NA" } best$n.smooth <- object$n.smooth <- n.terms best$formula <- object$formula <- formula best$family <- object$family <- G$family best$smooth <- object$smooth <- G$smooth best$model <- object$model <- G$mf object$R <- best$R if (is.null(object$R)){ rr <- scam.fit(G=G, sp=best$sp, gamma=gamma,env=env, control=control) object$R <- rr$R } object$sp <- best$sp names(object$sp) <- names(G$sp) if (sum(is.na(names(object$sp)))!=0){ if (n.terms >0) for (i in 1:n.terms) names(object$sp)[i] <- object$smooth[[i]]$label } object$conv <- best$conv post <- scam.fit.post(G, object=best) object$edf <- best$edf object$edf1 <- post$edf1 object$trA <- best$trA names(object$edf) <- G$term.names names(object$edf1) <- G$term.names object$aic <- post$aic object$null.deviance <- post$null.dev object$deviance <- post$deviance object$residuals <- post$residuals object$df.residual <- nrow(G$X) - sum(post$edf) object$rank <- post$rank object$var.summary <- G$var.summary object$cmX <- G$cmX object$model<-G$mf object$full.sp <- G$full.sp if (!is.null(object$full.sp)) names(object$full.sp) <- names(G$full.sp) object$na.action <- attr(G$mf,"na.action") object$df.null <- post$df.null object$Ve <- post$Ve object$Vp <- post$Vb object$Ve.t <- post$Ve.t object$Vp.t <- post$Vb.t object$sig2 <- post$sig2 object$coefficients <- best$beta object$coefficients.t <- best$beta.t object$beta <- best$beta object$beta.t <- best$beta.t object$pterms <- G$pterms object$terms <- G$terms object$assign <- G$assign object$contrasts <- G$contrasts object$xlevels <- G$xlevels object$nsdf <- G$nsdf object$y <- G$y if (control$keepData) object$data <- data object$control <- control object$offset <- G$offset object$not.exp <- G$not.exp object$scale.estimated <- !scale.known object$prior.weights <-weights object$weights <- best$w object$fitted.values <- post$mu object$linear.predictors <- post$eta object$call <- cl object$p.ident <- Q$p.ident object$intercept <- G$intercept object$min.edf <- G$min.edf object$gamma <- gamma object$iter <- best$iter if (is.null(sp)) object$CPU.time <- CPU.time else object$CPU.time <- NULL object$AR1.rho <- AR1.rho if (is.null(sp)) { if (optimizer == "bfgs") { object$bfgs.info <- list() object$bfgs.info$conv <- re$conv.bfgs object$bfgs.info$iter <- re$iterations object$bfgs.info$grad <- re$dgcv.ubre object$bfgs.info$score.hist <- re$score.hist } else if (optimizer == "nlm.fd" || optimizer == "nlm") { object$nlm.info <- list() object$nlm.info$conv <- re$conv object$nlm.info$iter <- re$iterations object$nlm.info$grad <- re$dgcv.ubre } else if (optimizer=="optim") { object$optim.info <- list() object$optim.info$conv <- re$conv object$optim.info$iter <- re$iterations object$optim.method <- re$optim.method } else if (optimizer=="efs") { object$efs.info <- list() object$efs.info$conv <- re$conv object$efs.info$iter <- re$iterations object$efs.info$score.hist <- re$score.hist } } if (scale.known) object$method <- "UBRE" else object$method <- "GCV" if (G$nsdf > 0) term.names <- colnames(G$X)[1:G$nsdf] else term.names <- array("", 0) if (n.terms >0) for (i in 1:n.terms) { k <- 1 for (j in G$smooth[[i]]$first.para:G$smooth[[i]]$last.para) { term.names[j] <- paste(G$smooth[[i]]$label, ".", as.character(k), sep = "") k <- k + 1 } } names(object$coefficients) <- term.names names(object$coefficients.t) <- term.names ynames <- if (is.matrix(G$y)) rownames(G$y) else names(G$y) names(object$residuals) <- ynames class(object) <- c("scam","glm","lm") rm(G) dev <- object$deviance if (AR1.rho!=0){ object$std.rsd <- AR.resid(object$residuals,AR1.rho,object$model$"(AR.start)") dev <- sum(object$std.rsd^2) object$deviance <- sum(object$residuals^2) } object$aic <- object$family$aic(object$y,1,object$fitted.values,object$prior.weights,dev) object$aic <- object$aic - 2 * (length(object$y) - sum(sum(object$model[["(AR.start)"]])))*log(1/sqrt(1-AR1.rho^2)) + 2*sum(object$edf) object } scam.control <- function (maxit = 200, maxHalf=30, devtol.fit=1e-7, steptol.fit=1e-7, keepData=FALSE,efs.lspmax=15,efs.tol=.1, nlm=list(),optim=list(),bfgs=list(), trace =FALSE, print.warn=FALSE) { if (!is.numeric(devtol.fit) || devtol.fit <= 0) stop("value of devtol.fit must be > 0") if (!is.numeric(steptol.fit) || devtol.fit <= 0) stop("value of steptol.fit must be > 0") if (!is.numeric(maxit) || maxit <= 0) stop("maximum number of iterations must be > 0") if (!is.numeric(maxHalf) || maxHalf <= 0) stop("maximum number of step halving must be > 0") if (!is.logical(trace)) stop("trace must be logical") if (!is.logical(print.warn)) stop("print.warn must be logical") if (is.null(nlm$ndigit)||nlm$ndigit<2) nlm$ndigit <- max(2,ceiling(-log10(1e-7))) nlm$ndigit <- round(nlm$ndigit) ndigit <- floor(-log10(.Machine$double.eps)) if (nlm$ndigit>ndigit) nlm$ndigit <- ndigit if (is.null(nlm$gradtol)) nlm$gradtol <- 1e-6 nlm$gradtol <- abs(nlm$gradtol) if (is.null(nlm$stepmax)||nlm$stepmax==0) nlm$stepmax <- 2 nlm$stepmax <- abs(nlm$stepmax) if (is.null(nlm$steptol)) nlm$steptol <- 1e-4 nlm$steptol <- abs(nlm$steptol) if (is.null(nlm$iterlim)) nlm$iterlim <- 200 nlm$iterlim <- abs(nlm$iterlim) if (is.null(nlm$check.analyticals)) nlm$check.analyticals <- FALSE nlm$check.analyticals <- as.logical(nlm$check.analyticals) if (is.null(bfgs$check.analytical)) bfgs$check.analytical <- FALSE if (is.null(bfgs$del)) bfgs$del <- 1e-4 if (is.null(bfgs$steptol.bfgs)) bfgs$steptol.bfgs <- 1e-7 if (is.null(bfgs$gradtol.bfgs)) bfgs$gradtol.bfgs <- 1e-06 if (is.null(bfgs$maxNstep)) bfgs$maxNstep <- 5 if (is.null(bfgs$maxHalf)) bfgs$maxHalf <- maxHalf if (is.null(optim$factr)) optim$factr <- 1e7 optim$factr <- abs(optim$factr) if (efs.tol<=0) efs.tol <- .1 list(maxit=maxit, devtol.fit=devtol.fit, steptol.fit=steptol.fit, keepData=as.logical(keepData[1]), nlm=nlm, optim=optim,bfgs=bfgs,efs.lspmax=efs.lspmax,efs.tol=efs.tol,trace = trace, print.warn=print.warn) } initial.sp.scam <- function(G,Q,q.f,n.terms,family,intercept,offset, env= env, weights, control=control) { control$devtol.fit <- 1e-4 control$steptol.fit <- 1e-4 b <- scam.fit(G=G,sp=rep(0.05,length(G$off)), env=env, control=control) H <- crossprod(b$wX1) - b$E n.p <- length(Q$S) def.sp <- array(0,n.p) j <- 1 if (n.terms >0) for (i in 1:n.terms){ for (kk in 1:length(G$smooth[[i]]$S)){ start <- G$off[j] finish <- start + ncol(G$smooth[[i]]$S[[kk]])-1 Hi.norm <- sum(H[start:finish,start:finish]*H[start:finish,start:finish]) Si.norm <- sum(G$smooth[[i]]$S[[kk]]*G$smooth[[i]]$S[[kk]]) def.sp[j] <- (Hi.norm/Si.norm)^0.5 j <- j+1 } } env <- new.env() assign("start",rep(0,0),envir=env) assign("dbeta.start",rep(0,0),envir=env) assign("sp.last",rep(0,0),envir=env) def.sp } penalty_pident <- function(object) { n.terms <- length(object$smooth) q <- ncol(object$X) cons.terms <- rep(0,n.terms) if (n.terms>0) for (i in 1:n.terms){ if (!is.null(object$smooth[[i]]$p.ident)) cons.terms[i] <- 1 } p.ident <- rep(FALSE,q) off.terms <- rep(0,n.terms) off <- object$off if (n.terms ==length(off)) off.terms <- off else { off.terms[1] <- off[1] k <- 1 l <- 1 while (l<length(off)) { if (off[l]!=off[l+1]) { off.terms[k+1] <- off[l+1] k <- k+1; l <- l+1 } else l <- l+1 } } if (n.terms>0) for (i in 1:n.terms){ if (cons.terms[i]==1) p.ident[off.terms[i]:(off.terms[i]+ncol(object$smooth[[i]]$S[[1]])-1)] <- object$smooth[[i]]$p.ident } S <- list() j <- 1 if (n.terms>0) for(i in 1:n.terms){ for (kk in 1:length(object$smooth[[i]]$S)){ S[[j]] <- matrix(0,q,q) S[[j]][off.terms[i]:(off.terms[i]+ncol(object$smooth[[i]]$S[[kk]])-1), off.terms[i]:(off.terms[i]+ncol(object$smooth[[i]]$S[[kk]])-1)] <- object$smooth[[i]]$S[[kk]] j <- j+1 } } object$S <- S object$p.ident <- p.ident object } scam.fit <- function(G,sp, gamma=1, etastart=NULL, mustart=NULL, env=env, null.coef=rep(0,ncol(G$X)), control=scam.control()) { y <- G$y; X <- G$X; S <- G$S; not.exp <- G$not.exp; AR1.rho <- G$AR1.rho attr(X,"dimnames") <- NULL q0 <- G$q0; q.f <- G$q.f p.ident <- G$p.ident; n.terms <- G$n.terms family <- G$family; intercept <- G$intercept; offset <- G$offset; weights <- G$weights; n <- nobs <- NROW(y) q <- ncol(X) dg <- fix.family.link(family) dv <- fix.family.var(family) nvars <- NCOL(X) EMPTY <- nvars == 0 variance <- family$variance linkinv <- family$linkinv if (!is.function(variance) || !is.function(linkinv)) stop("'family' argument seems not to be a valid family object") dev.resids <- family$dev.resids aic <- family$aic mu.eta <- family$mu.eta mu.eta <- family$mu.eta if (AR1.rho!=0) { ld <- 1/sqrt(1-AR1.rho^2) sd <- -AR1.rho*ld row <- c(1,rep(1:nobs,rep(2,nobs))[-c(1,2*nobs)]) weight.r <- c(1,rep(c(sd,ld),nobs-1)) end <- c(1,1:(nobs-1)*2+1) if (!is.null(G$mf$"(AR.start)")) { ii <- which(G$mf$"(AR.start)"==TRUE) if (length(ii)>0) { if (ii[1]==1) ii <- ii[-1] weight.r[ii*2-2] <- 0 weight.r[ii*2-1] <- 1 } } X <- rwMatrix(end,row,weight.r,X) y <- rwMatrix(end,row,weight.r,y) } if (!is.function(variance) || !is.function(linkinv)) stop("illegal `family' argument") valideta <- family$valideta if (is.null(valideta)) valideta <- function(eta) TRUE validmu <- family$validmu if (is.null(validmu)) validmu <- function(mu) TRUE if (is.null(mustart)) { eval(family$initialize) } else { mukeep <- mustart eval(family$initialize) mustart <- mukeep } if (family$family=="gaussian"&&family$link=="identity") strictly.additive <- TRUE else strictly.additive <- FALSE if (EMPTY) { eta <- rep.int(0, nobs) + offset if (!valideta(eta)) stop("Invalid linear predictor values in empty model") mu <- linkinv(eta) if (AR1.rho!=0) { mu <- rwMatrix(end,row,weight.r,mu) } if (!validmu(mu)) stop("Invalid fitted means in empty model") dev <- sum(dev.resids(y, mu, weights)) w <- (weights * mu.eta(eta)^2)/variance(mu) residuals <- (y - mu)/mu.eta(eta) good <- rep(TRUE, length(residuals)) boundary <- conv <- TRUE coef <- numeric(0) iter <- 0 V <- variance(mu) alpha <- dev trA <- 0 GCV <- nobs * alpha/(nobs - gamma * trA)^2 UBRE <- alpha/nobs + 2 * gamma* trA*scale/n - scale scale.est <- alpha/(nobs - trA) aic.model <- aic(y, n, mu, weights, dev) + 2 * trA } else { eta <- if (!is.null(etastart)) etastart else family$linkfun(mustart) mu <- as.numeric(linkinv(eta)) S.t <- matrix(0,q,q) n.pen <- length(S) if (length(sp)!=n.pen) stop (paste("length of sp has to be equal to", n.pen)) if (n.pen>0) for (j in 1:n.pen) S.t <- S.t + sp[j]*S[[j]] er <- eigen(S.t,symmetric=TRUE); er$values[er$values<0] <- 0 rS <- crossprod(sqrt(sqrt(er$values))*t(er$vectors)) iv <- (1:q)[p.ident] beta0 <- get("start",envir=env) dbeta0 <- get("dbeta.start",envir=env) sp.old <- get("sp.last",envir=env) if (length(beta0)==0) { M <- list(X=X,p=rep(0.1,q),C=matrix(0,0,0),sp=sp,y=eta-offset,w=y*0+1) M$Ain <- matrix(0,q,q); diag(M$Ain) <- rep(1,q); M$bin <- rep(-1e+12,q); M$bin[iv] <- 1e-12 M$off <- rep(0,n.pen); M$S <- list() if (n.pen>0) for (j in 1:n.pen) {M$S[[j]] <- matrix(0,q,q); M$S[[j]] <- S[[j]]} beta.t <- pcls(M) beta <- beta.t beta[iv] <- log(beta.t[iv]) } else { beta <- beta0 beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) } eta <- as.numeric(X%*%beta.t + as.numeric(offset)) mu <- linkinv(eta) ii <- 0 while (!(validmu(mu) && valideta(eta))) { ii <- ii + 1 if (ii>20) stop("Can't find valid starting values: please specify some") beta <- beta * .9 + null.coef * .1 beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) eta <- as.numeric(X%*%beta.t + offset) mu <- linkinv(eta) } betaold <- null.coef <- beta betaold.t <- beta betaold.t[iv] <- if (!not.exp) exp(betaold[iv]) else notExp(betaold[iv]) etaold <- as.numeric(X%*%betaold.t + offset) old.pdev <- sum(dev.resids(y,linkinv(etaold),weights)) + sum((rS%*%betaold)^2) pdev.plot <- 0 E <- matrix(0,q,q) Cdiag <- rep(1,q); C1diag <- rep(0,q) boundary <- conv <- FALSE old.warn <- getOption("warn") if (!control$print.warn) curr.warn <- -1 else curr.warn <- old.warn for (iter in 1:control$maxit) { good <- weights > 0 var.val <- variance(mu) varmu <- var.val[good] if (any(is.na(varmu))) stop("NAs in V(mu)") if (any(varmu == 0)) stop("0s in V(mu)") mu.eta.val <- mu.eta(eta) if (any(is.na(mu.eta.val[good]))) stop("NAs in d(mu)/d(eta)") good <- (weights > 0) & (mu.eta.val != 0) if (all(!good)) { conv <- FALSE warning("No observations informative at iteration ", iter) break } if (!not.exp) { Cdiag[iv] <- C1diag[iv] <- beta.t[iv] } else { Cdiag[iv] <- DnotExp(beta[iv]); C1diag[iv] <- D2notExp(beta[iv]) } tX1 <- Cdiag*t(X) g.deriv <- 1/mu.eta(eta) w1 <- weights/(variance(mu)*g.deriv^2) y.mu <- y - mu alpha <- 1+ y.mu*(dv$dvar(mu)/variance(mu)+dg$d2link(mu)/g.deriv) w <- w1*alpha diag(E) <- drop((C1diag*t(X))%*%(w1*g.deriv*y.mu)) abs.w <- abs(w) I.minus <- rep(0,nobs) z1 <- g.deriv*y.mu/alpha iin <- w < 0; I.minus[iin] <- 1;z1[iin] <- -z1[iin] wX11 <- rbind(sqrt(abs.w)[1:nobs]*t(tX1),rS) illcond <- FALSE Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp if (Rrank(R)==ncol(R)) { R.inv <- backsolve(R,diag(ncol(R)))[rp,] tR.inv <- t(R.inv) } else { R <- R[,rp] svd.r <- svd(R) d.inv <- rep(0,q) good1 <- svd.r$d >= max(svd.r$d)*.Machine$double.eps^.5 d.inv[good1] <- 1/svd.r$d[good1] if (sum(!good1)>0) illcond <- TRUE R <- svd.r$d*t(svd.r$v) Q <- qr.qy(Q,rbind(svd.r$u,matrix(0,nobs,q))) tR.inv <- d.inv*t(svd.r$v) R.inv <- t(tR.inv) } QtQRER <- tR.inv%*%(diag(E)*R.inv) if (sum(I.minus)>0) { if (is.qr(Q)) { QtQRER <- QtQRER + 2*crossprod(I.minus*qr.Q(Q)[1:nobs,]) } else { QtQRER <- QtQRER + 2*crossprod(I.minus*Q[1:nobs,]) } } ei <- eigen(QtQRER,symmetric=TRUE) d <- ei$values ok1 <- sum(d>1) > 0 if (ok1 == TRUE) { eta.t <- drop(t(beta)%*%tX1) wX11 <- rbind(sqrt(w1)[1:nobs]*t(tX1),rS) z<-g.deriv*y.mu+eta.t wz<-w1^.5*z wz.aug<-c(wz,rep(0,nrow(rS))) Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp if (Rrank(R)==ncol(R)) { beta <- backsolve(R,qr.qty(Q,wz.aug)[1:q])[rp] } else { R <- R[,rp] s1 <- svd(R) d.inv1 <- rep(0,q) good1 <- s1$d >= max(s1$d)*.Machine$double.eps^.5 d.inv1[good1] <- 1/s1$d[good1] beta <- s1$v%*%((d.inv1*t(s1$u))%*%qr.qty(Q,wz.aug)[1:q]) } } else { Id.inv.r<-1/(1-d)^.5 iin <- (1-d) < .Machine$double.eps Id.inv.r[iin] <- 0 eidrop <- t(Id.inv.r*t(ei$vectors)) wz1<-sqrt(abs.w)*z1 if (is.qr(Q)) { beta <- R.inv%*%(eidrop%*%(t(eidrop)%*%qr.qty(Q,c(wz1,rep(0,nrow(rS))))[1:nrow(eidrop)])) } else { beta <- R.inv%*%(eidrop%*%(t(eidrop)%*%(t(Q[1:nobs,])%*%wz1)[1:nrow(eidrop)])) } beta <- betaold + drop(beta - R.inv%*%(eidrop%*%(t(eidrop)%*%(tR.inv%*%(S.t%*%betaold))))) } beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) if (any(!is.finite(beta))) { conv <- FALSE warning(gettextf("Non-finite coefficients at iteration %d", iter)) break } options(warn = curr.warn) if (any(!is.finite(beta.t))) { conv <- FALSE warning(gettextf("Non-finite exponentiated coefficients at iteration %d", iter)) } eta <- drop(as.numeric(X%*%beta.t + offset)) mu <- linkinv(eta) dev <- sum(dev.resids(y,mu,weights)) penalty <- sum((rS%*%beta)^2) if (control$trace) message(gettextf("Deviance = %s Iterations - %d", dev, iter, domain = "R-scam")) boundary <- FALSE if (!is.finite(dev)) { if (is.null(betaold)) { if (is.null(null.coef)) stop("no valid set of coefficients has been found:please supply starting values", call. = FALSE) betaold <- null.coef } warning("Step size truncated due to divergence", call. = FALSE) ii <- 0 while (!is.finite(dev)) { if (ii > control$maxit) stop("inner loop 1; can't correct step size") ii <- ii + 1 beta <- (beta + c(betaold))/2 beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) eta <- as.numeric(X%*%beta.t + offset) mu <- linkinv(eta) dev <- sum(dev.resids(y, mu, weights)) } boundary <- TRUE penalty <- sum((rS%*%beta)^2) if (control$trace) cat("Step halved: new deviance =", dev, "\n") } if (!(valideta(eta) && validmu(mu))) { warning("Step size truncated: out of bounds", call. = FALSE) ii <- 0 while (!(valideta(eta) && validmu(mu))) { if (ii > control$maxit) stop("inner loop 2; can't correct step size") ii <- ii + 1 beta <- (beta + c(betaold))/2 beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) eta <- as.numeric(X%*%beta.t + offset) mu <- linkinv(eta) } boundary <- TRUE penalty <- sum((rS%*%beta)^2) dev <- sum(dev.resids(y, mu, weights)) if (control$trace) cat("Step halved: new deviance =", dev, "\n") } options(warn = old.warn) pdev <- dev + penalty if (control$trace) message(gettextf("penalized deviance = %s", pdev, domain = "R-scam")) div.thresh <- 10*(.1 +abs(old.pdev))*.Machine$double.eps^.5 if (pdev-old.pdev>div.thresh) { ii <- 0 while (pdev -old.pdev > div.thresh){ if (ii > 100) stop("inner loop 3; can't correct step size") ii <- ii + 1 beta <- (beta + c(betaold))/2 beta.t <- beta beta.t[iv] <- if (!not.exp) exp(beta[iv]) else notExp(beta[iv]) eta <- as.numeric(X%*%beta.t + offset) mu <- linkinv(eta) dev <- sum(dev.resids(y, mu, weights)) pdev <- dev + sum((rS%*%beta)^2) if (control$trace) message(gettextf("Step halved: new penalized deviance = %g", pdev, "\n")) } } Dp.g <- -drop(tX1%*%(w1*g.deriv*(y-mu)))+S.t%*%beta Dp.gnorm <- max(abs(Dp.g)) pdev.plot[iter] <- pdev if (abs(pdev - old.pdev)/(.1 + abs(pdev)) < control$devtol.fit) { if (Dp.gnorm > control$devtol.fit*max(abs(beta+c(betaold)))/2) { old.pdev <- pdev betaold <- beta } else { conv <- TRUE beta <- beta break } } else { old.pdev <- pdev betaold <- beta } } if (!not.exp) { Cdiag[iv] <- C1diag[iv] <- beta.t[iv] } else { Cdiag[iv] <- DnotExp(beta[iv]); C1diag[iv] <- D2notExp(beta[iv]) } X1 <- t(Cdiag*t(X)) g.deriv <- 1/ mu.eta(eta) w1 <- weights/(variance(mu)*g.deriv^2) alpha <- 1+(y-mu)*(dv$dvar(mu)/variance(mu)+dg$d2link(mu)/g.deriv) w <- w1*alpha diag(E) <- drop((C1diag*t(X))%*%(w1*g.deriv*(y-mu))) abs.w <- abs(w) I.minus <- rep(0,nobs) I.minus[w<0] <- 1 wX1 <- sqrt(abs.w)[1:nobs]*X1 wX11 <- rbind(wX1,rS) illcond <- FALSE Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp R.out <- R[,rp] rank <- Rrank(R) if (rank==ncol(R)) { R.inv <- backsolve(R,diag(ncol(R)))[rp,] tR.inv <- t(R.inv) } else { R <- R[,rp] svd.r <- svd(R) d.inv <- rep(0,q) good1 <- svd.r$d >= max(svd.r$d)*.Machine$double.eps^.5 d.inv[good1] <- 1/svd.r$d[good1] if (sum(!good1)>0) illcond <- TRUE R <- svd.r$d*t(svd.r$v) Q <- qr.qy(Q,rbind(svd.r$u,matrix(0,nobs,q))) tR.inv <- d.inv*t(svd.r$v) R.inv <- t(tR.inv) } QtQRER <- tR.inv%*%(diag(E)*R.inv) if (sum(I.minus)>0) { if (is.qr(Q)) { QtQRER <- QtQRER + 2*crossprod(I.minus*qr.Q(Q)[1:nobs,]) } else { QtQRER <- QtQRER + 2*crossprod(I.minus*Q[1:nobs,]) } } ei <- eigen(QtQRER,symmetric=TRUE) d <- ei$values ok1 <- sum(d>1)>0 if (ok1) { wX1<-sqrt(w1)[1:nobs]*X1 wX11<-rbind(wX1,rS) Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp R.out <- R[,rp] rank <- Rrank(R) if (rank==ncol(R)) { P <- backsolve(R,diag(ncol(R)))[rp,] K <- qr.Q(Q)[1:nobs,] } else { R <- R[,rp] s1 <- svd(R) d.inv1 <- rep(0,q) good1 <- s1$d >= max(s1$d)*.Machine$double.eps^.5 d.inv1[good1] <- 1/s1$d[good1] P <- t(d.inv1*t(s1$v)) K <- qr.qy(Q,rbind(s1$u,matrix(0,nobs,q)))[1:nobs,] } } else { Id.inv.r<-1/(1-d)^.5 ii <- (1-d) < .Machine$double.eps Id.inv.r[ii] <- 0 eidrop <- t(Id.inv.r*t(ei$vectors)) P <- R.inv%*%eidrop if (is.qr(Q)) { K <- qr.qy(Q,rbind(eidrop,matrix(0,nobs,q)))[1:nobs,] } else { K <- Q[1:nobs,]%*%eidrop } } Dp.g <- -t(X1)%*%(w1*g.deriv*(y-mu))+S.t%*%beta Dp.gnorm<-max(abs(Dp.g)) I.plus <- rep(1,nobs) I.plus[w<0] <- -1 L <- c(1/alpha) KtILQ1R <- crossprod(L*I.plus*K,wX1) edf <- rowSums(P*t(KtILQ1R)) trA <- sum(edf) wXC1 <- sqrt(abs.w)[1:nobs]*t(C1diag*t(X)) KtILQ1R <- if (!not.exp) KtILQ1R else crossprod(L*I.plus*K,wXC1) KtIQ1R <- if (!not.exp) crossprod(I.plus*K,wX1) else crossprod(I.plus*K,wXC1) C2diag <- rep(0,q) C2diag[iv] <- if (!not.exp) C1diag[iv] else D3notExp(beta[iv]) XC2 <- t(C2diag*t(X)) XC1 <- t(C1diag*t(X)) dlink.mu <- 1/mu.eta(eta); Var<- variance(mu) link <- family$linkfun(mu); d2link.mu <- dg$d2link(mu) dvar.mu <- dv$dvar(mu); d2var.mu <- dv$d2var(mu) d3link.mu <- dg$d3link(mu) z <- g.deriv*(y-mu)+X1%*%beta scale.est <- dev/(nobs-trA) residuals <- rep.int(NA, nobs) residuals <- (y-mu)*g.deriv dbeta.rho <- matrix(0,q,n.pen) if (n.pen>0) for (j in 1:n.pen) { dbeta.rho[,j] <- - sp[j]*P%*%(t(P)%*%(S[[j]]%*%beta)) } aic.model <- aic(y, n, mu, weights, dev) + 2 * sum(edf) if (AR1.rho!=0) { df <- 1 aic.model <- aic.model - 2*(n-df)*log(ld) } assign("start",beta,envir=env) assign("dbeta.start",dbeta.rho,envir=env) assign("sp.last",sp,envir=env) } list(L=L,C1diag=C1diag,E=E,iter=iter, old.beta=betaold, gcv=dev*nobs/(nobs-gamma *trA)^2, sp=sp, mu=mu,X=G$X,y=drop(G$y), X1=X1,beta=beta,beta.t=beta.t,iv=iv,S=S,S.t=S.t,rS=rS, P=P,K=K, C2diag=C2diag, KtILQ1R= KtILQ1R, KtIQ1R=KtIQ1R, dlink.mu=dlink.mu,Var=Var, abs.w=drop(abs.w), link=link,w=as.numeric(w),w1=drop(w1),d2link.mu=d2link.mu,wX1=wX1,I.plus=I.plus, dvar.mu=dvar.mu,d2var.mu=d2var.mu,deviance=dev,scale.est=scale.est, ok1=ok1,alpha=as.numeric(alpha),d3link.mu=d3link.mu,eta=eta,iter=iter, Dp.gnorm=Dp.gnorm, Dp.g=Dp.g,d=d, conv=conv, illcond=illcond,R=R.out, edf=edf,trA=trA, residuals=residuals,z=z,dbeta.rho=dbeta.rho, aic=aic.model,rank=rank) } scam.fit.post<- function(G, object) { y <- G$y; X <- G$X; sig2 <- G$sig2; offset <- G$offset; intercept <- G$intercept; weights <- G$weights; scale.known <- G$scale.known; not.exp <- G$not.exp n <- nobs <- NROW(y) q <- ncol(X) if (G$AR1.rho!=0) { ld <- 1/sqrt(1-G$AR1.rho^2) sd <- -G$AR1.rho*ld row <- c(1,rep(1:nobs,rep(2,nobs))[-c(1,2*nobs)]) weight.r <- c(1,rep(c(sd,ld),nobs-1)) end <- c(1,1:(nobs-1)*2+1) if (!is.null(G$AR.start)) { ii <- which(G$AR.start==TRUE) if (length(ii)>0) { if (ii[1]==1) ii <- ii[-1] weight.r[ii*2-2] <- 0 weight.r[ii*2-1] <- 1 } } X <- rwMatrix(end,row,weight.r,X) y <- rwMatrix(end,row,weight.r,y) } linkinv <- object$family$linkinv dev.resids <- object$family$dev.resids dg <- fix.family.link(object$family) dv <- fix.family.var(object$family) eta <- as.numeric(X%*%object$beta.t + offset) mu <- linkinv(eta) dev <- sum(dev.resids(y,mu,weights)) wtdmu <- if (intercept) sum(weights * G$y)/sum(weights) else linkinv(offset) null.dev <- sum(dev.resids(G$y, wtdmu, weights)) n.ok <- nobs - sum(weights == 0) nulldf <- n.ok - as.integer(intercept) Cdiag <- rep(1,q); C1diag <- rep(0,q) iv <- object$iv if (!not.exp) { Cdiag[iv] <- C1diag[iv] <- object$beta.t[iv] } else { Cdiag[iv] <- DnotExp(object$beta[iv]); C1diag[iv] <- D2notExp(object$beta[iv]) } X1 <- t(Cdiag*t(X)) g.deriv <- 1/object$family$mu.eta(eta) w1 <- weights/(object$family$variance(mu)*g.deriv^2) alpha <- 1+(y-mu)*(dv$dvar(mu)/object$family$variance(mu)+dg$d2link(mu)/g.deriv) w <- w1*alpha E <- matrix(0,q,q) diag(E) <- drop((C1diag*t(X))%*%(w1*g.deriv*(y-mu))) abs.w <- abs(w) I.minus <- rep(0,nobs) I.minus[w<0] <- 1 wX1 <- sqrt(abs.w)[1:nobs]*X1 wX11 <- rbind(wX1,object$rS) illcond <- FALSE Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp R.out <- R[,rp] rank <- Rrank(R) if (rank==ncol(R)) { R.inv <- backsolve(R,diag(ncol(R)))[rp,] tR.inv <- t(R.inv) } else { R <- R[,rp] svd.r <- svd(R) d.inv <- rep(0,q) good <- svd.r$d >= max(svd.r$d)*.Machine$double.eps^.5 d.inv[good] <- 1/svd.r$d[good] if (sum(!good)>0) illcond <- TRUE R <- svd.r$d*t(svd.r$v) Q <- qr.qy(Q,rbind(svd.r$u,matrix(0,nobs,q))) tR.inv <- d.inv*t(svd.r$v) R.inv <- t(tR.inv) } QtQRER <- tR.inv%*%(diag(E)*R.inv) if (sum(I.minus)>0) { if (is.qr(Q)) { QtQRER <- QtQRER + 2*crossprod(I.minus*qr.Q(Q)[1:nobs,]) } else { QtQRER <- QtQRER + 2*crossprod(I.minus*Q[1:nobs,]) } } ei <- eigen(QtQRER,symmetric=TRUE) d <- ei$values ok1 <- sum(d>1)>0 if (ok1) { wX1<-sqrt(w1)[1:nobs]*X1 wX11<-rbind(wX1,object$rS) Q <- qr(wX11,LAPACK=TRUE) R <- qr.R(Q) rp <- 1:ncol(R) rp[Q$pivot] <- rp R.out <- R[,rp] rank <- Rrank(R) if (rank==ncol(R)) { P <- backsolve(R,diag(ncol(R)))[rp,] K <- qr.Q(Q)[1:nobs,] } else { R <- R[,rp] s1 <- svd(R) d.inv1 <- rep(0,q) good1 <- s1$d >= max(s1$d)*.Machine$double.eps^.5 d.inv1[good1] <- 1/s1$d[good1] P <- t(d.inv1*t(s1$v)) K <- qr.qy(Q,rbind(s1$u,matrix(0,nobs,q)))[1:nobs,] } } else { Id.inv.r<-1/(1-d)^.5 ii <- (1-d) < .Machine$double.eps Id.inv.r[ii] <- 0 eidrop <- t(Id.inv.r*t(ei$vectors)) P <- R.inv%*%eidrop if (is.qr(Q)) { K <- qr.qy(Q,rbind(eidrop,matrix(0,nobs,q)))[1:nobs,] } else { K <- Q[1:nobs,]%*%eidrop } } I.plus <- rep(1,nobs) I.plus[w<0] <- -1 L <- c(1/alpha) KtILQ1R <- crossprod(L*I.plus*K,wX1) F <- P%*%(KtILQ1R) edf <- diag(F) edf1 <- 2*edf - rowSums(t(F)*F) trA <- sum(edf) if (!scale.known) sig2 <- dev/(nobs-trA) Vb <- tcrossprod(P) * sig2 Ve <- crossprod(K%*%t(P)) *sig2 df.p <- rep(1,q) df.p[object$iv] <- object$beta.t[object$iv] Vb.t <- t(df.p*t(df.p*Vb)) Ve.t <- t(df.p*t(df.p*Ve)) eta <- as.numeric(G$X%*%object$beta.t + offset) mu <- linkinv(eta) residuals <- rep.int(NA, nobs) g.deriv <- 1/object$family$mu.eta(eta) residuals <- (G$y-mu)*g.deriv aic.model <- object$family$aic(y, n, mu, weights, dev) + 2 * sum(edf) if (G$AR1.rho!=0) { df <- 1 aic.model <- aic.model - 2*(n-df)*log(1/sqrt(1-G$AR1.rho^2)) } list (null.dev=null.dev, df.null=nulldf,Vb=Vb,Vb.t=Vb.t,Ve=Ve,Ve.t=Ve.t,rank=rank, sig2=sig2,edf=edf,edf1=edf1,trA=trA, deviance=dev,residuals=residuals, aic=aic.model, mu=mu, eta=eta) } notExp <- function(x){ f <- x ind <- x > 1 f[ind] <- exp(1)*(x[ind]^2+1)/2 ind <- (x <= 1)&(x > -1) f[ind] <- exp(x[ind]) ind <- (x <= -1) f[ind] <- exp(1)*(x[ind]^2+1)/2; f[ind]<-1/f[ind] f } DnotExp <- function(x) { f <- x ind <- x > 1 f[ind] <- exp(1)*x[ind] ind <- (x <= 1)&(x > -1) f[ind] <- exp(x[ind]) ind <- (x <= -1) f[ind] <- -4*x[ind]/exp(1)/(x[ind]^2+1)^2 f } D2notExp <- function(x) { f <- x ind <- x > 1 f[ind] <- exp(1) ind <- (x <= 1)&(x > -1) f[ind] <- exp(x[ind]) ind <- (x <= -1) f[ind] <- (12*x[ind]^2-4)/exp(1)/(x[ind]^2+1)^3 f } D3notExp <- function(x) { f <- x ind <- x > 1 f[ind] <- 0 ind <- (x <= 1)&(x > -1) f[ind] <- exp(x[ind]) ind <- (x <= -1) f[ind] <- 48*x[ind]*(1-x[ind]^2)/exp(1)/(x[ind]^2+1)^4 f } logLik.scam <- function (object,...) { sc.p <- as.numeric(object$scale.estimated) p <- sum(object$edf) + sc.p val <- p - object$aic/2 np <- length(object$coefficients) + sc.p if (p > np) p <- np attr(val, "df") <- p class(val) <- "logLik" val } formula.scam <- function(x, ...) { x$formula } gam.setup <- function(formula,pterms, data=stop("No data supplied to gam.setup"),knots=NULL,sp=NULL, min.sp=NULL,H=NULL,absorb.cons=TRUE,sparse.cons=0,select=FALSE,idLinksBases=TRUE, scale.penalty=TRUE,paraPen=NULL,gamm.call=FALSE,drop.intercept=FALSE, diagonal.penalty=FALSE,apply.by=TRUE,list.call=FALSE,modCon=0) { if (inherits(formula,"split.gam.formula")) split <- formula else if (inherits(formula,"formula")) split <- interpret.gam(formula) else stop("First argument is no sort of formula!") if (length(split$smooth.spec)==0) { if (split$pfok==0) stop("You've got no model....") m <- 0 } else m <- length(split$smooth.spec) G <- list(m=m,min.sp=min.sp,H=H,pearson.extra=0, dev.extra=0,n.true=-1,pterms=pterms) if (is.null(attr(data,"terms"))) mf <- model.frame(split$pf,data,drop.unused.levels=FALSE) else mf <- data G$intercept <- attr(attr(mf,"terms"),"intercept")>0 if (list.call) { offi <- attr(pterms,"offset") if (!is.null(offi)) { G$offset <- mf[[names(attr(pterms,"dataClasses"))[offi]]] } } else G$offset <- model.offset(mf) if (!is.null(G$offset)) G$offset <- as.numeric(G$offset) if (drop.intercept) attr(pterms,"intercept") <- 1 X <- model.matrix(pterms,mf) if (drop.intercept) { xat <- attributes(X);ind <- xat$assign>0 X <- X[,ind,drop=FALSE] xat$assign <- xat$assign[ind];xat$dimnames[[2]]<-xat$dimnames[[2]][ind]; xat$dim[2] <- xat$dim[2]-1;attributes(X) <- xat G$intercept <- FALSE } rownames(X) <- NULL G$nsdf <- ncol(X) G$contrasts <- attr(X,"contrasts") G$xlevels <- .getXlevels(pterms,mf) G$assign <- attr(X,"assign") PP <- parametricPenalty(pterms,G$assign,paraPen,sp) if (!is.null(PP)) { ind <- 1:length(PP$sp) if (!is.null(sp)) sp <- sp[-ind] if (!is.null(min.sp)) { PP$min.sp <- min.sp[ind] min.sp <- min.sp[-ind] } } G$smooth <- list() G$S <- list() if (gamm.call) { if (m>0) for (i in 1:m) attr(split$smooth.spec[[i]],"gamm") <- TRUE } if (m>0 && idLinksBases) { id.list <- list() for (i in 1:m) if (!is.null(split$smooth.spec[[i]]$id)) { id <- as.character(split$smooth.spec[[i]]$id) if (length(id.list)&&id%in%names(id.list)) { ni <- length(id.list[[id]]$sm.i) id.list[[id]]$sm.i[ni+1] <- i base.i <- id.list[[id]]$sm.i[1] split$smooth.spec[[i]] <- clone.smooth.spec(split$smooth.spec[[base.i]], split$smooth.spec[[i]]) temp.term <- split$smooth.spec[[i]]$term for (j in 1:length(temp.term)) id.list[[id]]$data[[j]] <- cbind(id.list[[id]]$data[[j]], get.var(temp.term[j],data,vecMat=FALSE)) } else { id.list[[id]] <- list(sm.i=i) id.list[[id]]$data <- list() term <- split$smooth.spec[[i]]$term for (j in 1:length(term)) id.list[[id]]$data[[j]] <- get.var(term[j],data,vecMat=FALSE) } } } G$off<-array(0,0) first.para<-G$nsdf+1 sm <- list() newm <- 0 if (m>0) for (i in 1:m) { id <- split$smooth.spec[[i]]$id if (is.null(id)||!idLinksBases) { sml <- smoothCon(split$smooth.spec[[i]],data,knots,absorb.cons,scale.penalty=scale.penalty, null.space.penalty=select,sparse.cons=sparse.cons, diagonal.penalty=diagonal.penalty,apply.by=apply.by,modCon=modCon) } else { names(id.list[[id]]$data) <- split$smooth.spec[[i]]$term sml <- smoothCon(split$smooth.spec[[i]],id.list[[id]]$data,knots, absorb.cons,n=nrow(data),dataX=data,scale.penalty=scale.penalty, null.space.penalty=select,sparse.cons=sparse.cons, diagonal.penalty=diagonal.penalty,apply.by=apply.by,modCon=modCon) } for (j in 1:length(sml)) { newm <- newm + 1 sm[[newm]] <- sml[[j]] } } G$m <- m <- newm if (m>0) { sm <- gam.side(sm,X,tol=.Machine$double.eps^.5) if (!apply.by) for (i in 1:length(sm)) { if (!is.null(sm[[i]]$X0)) { ind <- attr(sm[[i]],"del.index") sm[[i]]$X <- if (is.null(ind)) sm[[i]]$X0 else sm[[i]]$X0[,-ind,drop=FALSE] } } } idx <- list() L <- matrix(0,0,0) lsp.names <- sp.names <- rep("",0) if (m>0) for (i in 1:m) { id <- sm[[i]]$id length.S <- length(sm[[i]]$S) if (is.null(sm[[i]]$L)) Li <- diag(length.S) else Li <- sm[[i]]$L if (length.S > 0) { if (length.S == 1) lspn <- sm[[i]]$label else { Sname <- names(sm[[i]]$S) lspn <- if (is.null(Sname)) paste(sm[[i]]$label,1:length.S,sep="") else paste(sm[[i]]$label,Sname,sep="") } spn <- lspn[1:ncol(Li)] } if (is.null(id)||is.null(idx[[id]])) { if (!is.null(id)) { idx[[id]]$c <- ncol(L)+1 idx[[id]]$nc <- ncol(Li) } L <- rbind(cbind(L,matrix(0,nrow(L),ncol(Li))), cbind(matrix(0,nrow(Li),ncol(L)),Li)) if (length.S > 0) { sp.names <- c(sp.names,spn) lsp.names <- c(lsp.names,lspn) } } else { L0 <- matrix(0,nrow(Li),ncol(L)) if (ncol(Li)>idx[[id]]$nc) { stop("Later terms sharing an `id' can not have more smoothing parameters than the first such term") } L0[,idx[[id]]$c:(idx[[id]]$c+ncol(Li)-1)] <- Li L <- rbind(L,L0) if (length.S > 0) { lsp.names <- c(lsp.names,lspn) } } } Xp <- NULL if (m>0) for (i in 1:m) { n.para<-ncol(sm[[i]]$X) sm[[i]]$first.para<-first.para first.para<-first.para+n.para sm[[i]]$last.para<-first.para-1 Xoff <- attr(sm[[i]]$X,"offset") if (!is.null(Xoff)) { if (is.null(G$offset)) G$offset <- Xoff else G$offset <- G$offset + Xoff } if (is.null(sm[[i]]$Xp)) { if (!is.null(Xp)) Xp <- cbind2(Xp,sm[[i]]$X) } else { if (is.null(Xp)) Xp <- X Xp <- cbind2(Xp,sm[[i]]$Xp);sm[[i]]$Xp <- NULL } X <- cbind2(X,sm[[i]]$X);sm[[i]]$X<-NULL G$smooth[[i]] <- sm[[i]] } if (is.null(Xp)) { G$cmX <- colMeans(X) } else { G$cmX <- colMeans(Xp) qrx <- qr(Xp,LAPACK=TRUE) R <- qr.R(qrx) p <- ncol(R) rank <- Rrank(R) QtX <- qr.qty(qrx,X)[1:rank,] if (rank<p) { R <- R[1:rank,] qrr <- qr(t(R),tol=0) R <- qr.R(qrr) G$P <- forwardsolve(t(R),QtX) } else { G$P <- backsolve(R,QtX) } if (rank<p) { G$P <- qr.qy(qrr,rbind(G$P,matrix(0,p-rank,p))) } G$P[qrx$pivot,] <- G$P } G$X <- X;rm(X) n.p <- ncol(G$X) if (!is.null(sp)) { ok <- TRUE if (length(sp) < ncol(L)) { warning("Supplied smoothing parameter vector is too short - ignored.") ok <- FALSE } if (sum(is.na(sp))) { warning("NA's in supplied smoothing parameter vector - ignoring.") ok <- FALSE } } else ok <- FALSE G$sp <- if (ok) sp[1:ncol(L)] else rep(-1,ncol(L)) names(G$sp) <- sp.names k <- 1 if (m>0) for (i in 1:m) { id <- sm[[i]]$id if (is.null(sm[[i]]$L)) Li <- diag(length(sm[[i]]$S)) else Li <- sm[[i]]$L if (is.null(id)) { spi <- sm[[i]]$sp if (!is.null(spi)) { if (length(spi)!=ncol(Li)) stop("incorrect number of smoothing parameters supplied for a smooth term") G$sp[k:(k+ncol(Li)-1)] <- spi } k <- k + ncol(Li) } else { spi <- sm[[i]]$sp if (is.null(idx[[id]]$sp.done)) { if (!is.null(spi)) { if (length(spi)!=ncol(Li)) stop("incorrect number of smoothing parameters supplied for a smooth term") G$sp[idx[[id]]$c:(idx[[id]]$c+idx[[id]]$nc-1)] <- spi } idx[[id]]$sp.done <- TRUE k <- k + idx[[id]]$nc } } } k <- 1 if (length(idx)) for (i in 1:length(idx)) idx[[i]]$sp.done <- FALSE if (m>0) for (i in 1:m) { id <- sm[[i]]$id if (!is.null(id)) { if (idx[[id]]$nc>0) { G$smooth[[i]]$sp <- G$sp[idx[[id]]$c:(idx[[id]]$c+idx[[id]]$nc-1)] } if (!idx[[id]]$sp.done) { idx[[id]]$sp.done <- TRUE k <- k + idx[[id]]$nc } } else { if (is.null(sm[[i]]$L)) nc <- length(sm[[i]]$S) else nc <- ncol(sm[[i]]$L) if (nc>0) G$smooth[[i]]$sp <- G$sp[k:(k+nc-1)] k <- k + nc } } if (!is.null(min.sp)) { if (length(min.sp)<nrow(L)) stop("length of min.sp is wrong.") min.sp <- min.sp[1:nrow(L)] if (sum(is.na(min.sp))) stop("NA's in min.sp.") if (sum(min.sp<0)) stop("elements of min.sp must be non negative.") } k.sp <- 0 G$rank <- array(0,0) if (m>0) for (i in 1:m) { sm<-G$smooth[[i]] if (length(sm$S)>0) for (j in 1:length(sm$S)) { k.sp <- k.sp+1 G$off[k.sp] <- sm$first.para G$S[[k.sp]] <- sm$S[[j]] G$rank[k.sp]<-sm$rank[j] if (!is.null(min.sp)) { if (is.null(H)) H<-matrix(0,n.p,n.p) H[sm$first.para:sm$last.para,sm$first.para:sm$last.para] <- H[sm$first.para:sm$last.para,sm$first.para:sm$last.para]+min.sp[k.sp]*sm$S[[j]] } } } if (!is.null(PP)) { L <- rbind(cbind(L,matrix(0,nrow(L),ncol(PP$L))), cbind(matrix(0,nrow(PP$L),ncol(L)),PP$L)) G$off <- c(PP$off,G$off) G$S <- c(PP$S,G$S) G$rank <- c(PP$rank,G$rank) G$sp <- c(PP$sp,G$sp) lsp.names <- c(PP$full.sp.names,lsp.names) G$n.paraPen <- length(PP$off) if (!is.null(PP$min.sp)) { if (is.null(H)) H <- matrix(0,n.p,n.p) for (i in 1:length(PP$S)) { ind <- PP$off[i]:(PP$off[i]+ncol(PP$S[[i]])-1) H[ind,ind] <- H[ind,ind] + PP$min.sp[i] * PP$S[[i]] } } } else G$n.paraPen <- 0 fix.ind <- G$sp>=0 if (sum(fix.ind)) { lsp0 <- G$sp[fix.ind] ind <- lsp0==0 ef0 <- indi <- (1:length(ind))[ind] if (length(indi)>0) for (i in 1:length(indi)) { ii <- G$off[i]:(G$off[i]+ncol(G$S[[i]])-1) ef0[i] <- norm(G$X[,ii],type="F")^2/norm(G$S[[i]],type="F")*.Machine$double.eps*.1 } lsp0[!ind] <- log(lsp0[!ind]) lsp0[ind] <- log(ef0) lsp0 <- as.numeric(L[,fix.ind,drop=FALSE]%*%lsp0) L <- L[,!fix.ind,drop=FALSE] G$sp <- G$sp[!fix.ind] } else {lsp0 <- rep(0,nrow(L))} G$H <- H if (ncol(L)==nrow(L)&&!sum(L!=diag(ncol(L)))) L <- NULL G$L <- L;G$lsp0 <- lsp0 names(G$lsp0) <- lsp.names if (absorb.cons==FALSE) { G$C <- matrix(0,0,n.p) if (m>0) { for (i in 1:m) { if (is.null(G$smooth[[i]]$C)) n.con<-0 else n.con<- nrow(G$smooth[[i]]$C) C <- matrix(0,n.con,n.p) C[,G$smooth[[i]]$first.para:G$smooth[[i]]$last.para]<-G$smooth[[i]]$C G$C <- rbind(G$C,C) G$smooth[[i]]$C <- NULL } rm(C) } } G$y <- data[[split$response]] G$n <- nrow(data) if (is.null(data$"(weights)")) G$w <- rep(1,G$n) else G$w <- data$"(weights)" if (G$nsdf > 0) term.names <- colnames(G$X)[1:G$nsdf] else term.names<-array("",0) n.smooth <- length(G$smooth) if (n.smooth) for (i in 1:n.smooth) { k <- 1 jj <- G$smooth[[i]]$first.para:G$smooth[[i]]$last.para if (G$smooth[[i]]$df > 0) for (j in jj) { term.names[j] <- paste(G$smooth[[i]]$label,".",as.character(k),sep="") k <- k+1 } if (!is.null(G$smooth[[i]]$g.index)) { if (is.null(G$g.index)) G$g.index <- rep(FALSE,n.p) G$g.index[jj] <- G$smooth[[i]]$g.index } } G$term.names <- term.names G$pP <- PP G } clone.smooth.spec <- function(specb,spec) { if (specb$dim!=spec$dim) stop("`id' linked smooths must have same number of arguments") if (inherits(specb,c("tensor.smooth.spec","t2.smooth.spec"))) { specb$term <- spec$term specb$label <- spec$label specb$by <- spec$by k <- 1 for (i in 1:length(specb$margin)) { if (is.null(spec$margin)) { for (j in 1:length(specb$margin[[i]]$term)) { specb$margin[[i]]$term[j] <- spec$term[k] k <- k + 1 } specb$margin[[i]]$label <- "" } else { specb$margin[[i]]$term <- spec$margin[[i]]$term specb$margin[[i]]$label <- spec$margin[[i]]$label specb$margin[[i]]$xt <- spec$margin[[i]]$xt } } } else { specb$term <- spec$term specb$label <- spec$label specb$by <- spec$by specb$xt <- spec$xt } specb } all.vars1 <- function(form) { vars <- all.vars(form) vn <- all.names(form) vn <- vn[vn%in%c(vars,"$","[[")] if ("[["%in%vn) stop("can't handle [[ in formula") ii <- which(vn%in%"$") if (length(ii)) { vn1 <- if (ii[1]>1) vn[1:(ii[1]-1)] go <- TRUE k <- 1 while (go) { n <- 2; while(k<length(ii) && ii[k]==ii[k+1]-1) { k <- k + 1;n <- n + 1 } vn1 <- c(vn1,paste(vn[ii[k]+1:n],collapse="$")) if (k==length(ii)) { go <- FALSE ind <- if (ii[k]+n<length(vn)) (ii[k]+n+1):length(vn) else rep(0,0) } else { k <- k + 1 ind <- if (ii[k-1]+n<ii[k]-1) (ii[k-1]+n+1):(ii[k]-1) else rep(0,0) } vn1 <- c(vn1,vn[ind]) } } else vn1 <- vn vn1 } variable.summary <- function(pf,dl,n) { v.n <- length(dl) v.name <- v.name1 <- names(dl) if (v.n) { k <- 0 for (i in 1:v.n) if (length(dl[[i]])>=n) { k <- k+1 v.name[k] <- v.name1[i] } if (k>0) v.name <- v.name[1:k] else v.name <- rep("",k) } p.name <- all.vars(pf[-2]) vs <- list() v.n <- length(v.name) if (v.n>0) for (i in 1:v.n) { if (v.name[i]%in%p.name) para <- TRUE else para <- FALSE if (para&&is.matrix(dl[[v.name[i]]])&&ncol(dl[[v.name[i]]])>1) { x <- matrix(apply(dl[[v.name[i]]],2,quantile,probs=0.5,type=3,na.rm=TRUE),1,ncol(dl[[v.name[i]]])) } else { x <- dl[[v.name[i]]] if (is.character(x)) x <- as.factor(x) if (is.factor(x)) { x <- x[!is.na(x)] lx <- levels(x) freq <- tabulate(x) ii <- min((1:length(lx))[freq==max(freq)]) x <- factor(lx[ii],levels=lx) } else { x <- as.numeric(x) x <- c(min(x,na.rm=TRUE),as.numeric(quantile(x,probs=.5,type=3,na.rm=TRUE)) ,max(x,na.rm=TRUE)) } } vs[[v.name[i]]] <- x } vs } parametricPenalty <- function(pterms,assign,paraPen,sp0) { S <- list() off <- rep(0,0) rank <- rep(0,0) sp <- rep(0,0) full.sp.names <- rep("",0) L <- matrix(0,0,0) k <- 0 tind <- unique(assign) n.t <- length(tind) if (n.t>0) for (j in 1:n.t) if (tind[j]>0) { term.label <- attr(pterms[tind[j]],"term.label") P <- paraPen[[term.label]] if (!is.null(P)) { ind <- (1:length(assign))[assign==tind[j]] Li <- P$L;P$L <- NULL spi <- P$sp;P$sp <- NULL ranki <- P$rank;P$rank <- NULL np <- length(P) if (!is.null(ranki)&&length(ranki)!=np) stop("`rank' has wrong length in `paraPen'") if (np) for (i in 1:np) { k <- k + 1 S[[k]] <- P[[i]] off[k] <- min(ind) if ( ncol(P[[i]])!=nrow(P[[i]])||nrow(P[[i]])!=length(ind)) stop(" a parametric penalty has wrong dimension") if (is.null(ranki)) { ev <- eigen(S[[k]],symmetric=TRUE,only.values=TRUE)$values rank[k] <- sum(ev>max(ev)*.Machine$double.eps*10) } else rank[k] <- ranki[i] } if (np) { if (is.null(Li)) Li <- diag(np) if (nrow(Li)!=np) stop("L has wrong dimension in `paraPen'") L <- rbind(cbind(L,matrix(0,nrow(L),ncol(Li))), cbind(matrix(0,nrow(Li),ncol(L)),Li)) ind <- (length(sp)+1):(length(sp)+ncol(Li)) ind2 <- (length(sp)+1):(length(sp)+nrow(Li)) if (is.null(spi)) { sp[ind] <- -1 } else { if (length(spi)!=ncol(Li)) stop("`sp' dimension wrong in `paraPen'") sp[ind] <- spi } if (length(ind)>1) names(sp)[ind] <- paste(term.label,ind-ind[1]+1,sep="") else names(sp)[ind] <- term.label if (length(ind2)>1) full.sp.names[ind2] <- paste(term.label,ind2-ind2[1]+1,sep="") else full.sp.names[ind2] <- term.label } } } if (k==0) return(NULL) if (!is.null(sp0)) { if (length(sp0)<length(sp)) stop("`sp' too short") sp0 <- sp0[1:length(sp)] sp[sp<0] <- sp0[sp<0] } list(S=S,off=off,sp=sp,L=L,rank=rank,full.sp.names=full.sp.names) } rwMatrix <- function(stop,row,weight,X,trans=FALSE) { if (is.matrix(X)) { n <- nrow(X);p<-ncol(X);ok <- TRUE} else { n<- length(X);p<-1;ok<-FALSE} stop <- stop - 1;row <- row - 1 oo <-.C(C_rwMatrix,as.integer(stop),as.integer(row),as.double(weight),X=as.double(X), as.integer(n),as.integer(p),trans=as.integer(trans),work=as.double(rep(0,n*p))) if (ok) return(matrix(oo$X,n,p)) else return(oo$X) } AR.resid <- function(rsd,rho=0,AR.start=NULL) { if (rho==0) return(rsd) ld <- 1/sqrt(1-rho^2) sd <- -rho*ld N <- length(rsd) ar.row <- c(1,rep(1:N,rep(2,N))[-c(1,2*N)]) ar.weight <- c(1,rep(c(sd,ld),N-1)) ar.stop <- c(1,1:(N-1)*2+1) if (!is.null(AR.start)) { ii <- which(AR.start==TRUE) if (length(ii)>0) { if (ii[1]==1) ii <- ii[-1] ar.weight[ii*2-2] <- 0 ar.weight[ii*2-1] <- 1 } } rwMatrix(ar.stop,ar.row,ar.weight,rsd) } print.scam.version <- function() { library(help=scam)$info[[1]] -> version version <- version[pmatch("Version",version)] um <- strsplit(version," ")[[1]] version <- um[nchar(um)>0][2] hello <- paste("This is scam ",version,".",sep="") packageStartupMessage(hello) } .onAttach <- function(...) { print.scam.version() }
print.lmpermutation_table<-function(x, digits = 4, na.print = "", ...){ cat(attr(x,"heading"), sep = "\n\n") cat(attr(x,"type"), sep = "\n\n") if(is.data.frame(x)){ print(as.matrix(x), digits = digits, na.print = na.print, ...) }else{ print.listof(x, digits = digits, ...) } }
plotpostpairs <- function(mat){ df <- reshape2::melt(mat) a <- ggplot2::aes(.data$Var2, .data$Var1, fill=.data$value) p <- ggplot2::ggplot(df, a) + ggplot2::geom_raster() + ggplot2::scale_x_continuous(expand = c(0, 0)) + ggplot2::scale_y_continuous(expand = c(0, 0)) + ggplot2::theme(panel.grid.minor=ggplot2::element_blank(), panel.grid.major=ggplot2::element_blank()) p } blocktrace <- function(postz, burnin){ df <- reshape2::melt(postz[,burnin]) names(df) <- c("Node", "Iteration", "Block") df$Block <- factor(df$Block) df$Iteration <- df$Iteration + min(burnin) a <- ggplot2::aes(.data$Iteration, .data$Node, fill=.data$Block) p <- ggplot2::ggplot(df, a) + ggplot2::geom_raster() + ggplot2::scale_x_continuous(expand = c(0, 0)) + ggplot2::scale_y_continuous(expand = c(0, 0)) + ggplot2::theme(panel.grid.minor=ggplot2::element_blank(), panel.grid.major=ggplot2::element_blank()) p } numblockstrace <- function(postk, burnin){ ggplot2::ggplot(data=data.frame(Iteration=burnin, K=postk[burnin]), ggplot2::aes(x=.data$Iteration, y=.data$K)) + ggplot2::geom_line() } paramtrace <- function(theta, range, burnin){ if(missing(range)) range <- 1:dim(theta)[2] if(missing(burnin)) burnin <- 1:dim(theta)[3] dimtheta <- dim(theta)[1] thetas <- theta[,range,burnin,drop=FALSE] ps <- list() length(ps) <- dimtheta for(k in 1:dimtheta){ df <- data.frame(burnin, cbind(t(thetas[k,,]))) names(df) <- c("burnin", range-1) mf <- reshape2::melt(df, id="burnin") names(mf) <- c("Iteration", "Theta", "Value") ps[[k]] <- ggplot(mf, aes(x=.data$Iteration, y=.data$Value, col=.data$Theta)) + geom_line() + ggplot2::scale_color_manual(values = c("black", scales::hue_pal()(length(range)-1))) } ps } postpairs <- function(postz){ N <- nrow(postz) P <- matrix(0,N,N) for(i in 2:N) for(j in 1:(i-1)) P[j,i] <- P[i,j] <- mean(postz[i,] == postz[j,]) P } modeblocks <- function(postz) blocks(apply(postz, 1, function(x) which.max(tabulate(x, max(postz))))) eval_plots <- function(output, burnin, theta_index){ if(missing(burnin)) burnin <- 1:output$nsteps nb <- numblockstrace(output$postk, burnin) pp <- postpairs(output$postz[,burnin]) pp_plot <- plotpostpairs(pp) + ggplot2::xlab("Node") + ggplot2::ylab("Node") + ggplot2::scale_fill_continuous(name = "Probability") ind <- order(colSums(pp)) pp_sorted <- plotpostpairs(pp[ind,ind]) + ggplot2::xlab("Node") + ggplot2::ylab("Node") + ggplot2::scale_fill_continuous(name = "Probability") bt <- blocktrace(output$postz, burnin) bt_sorted <- blocktrace(output$postz[ind,], burnin) pt <- paramtrace(output$postt, theta_index, burnin) pt_sorted <- paramtrace(output$postt, theta_index, burnin) list( num_blocks_trace = nb , post_pairs = pp_plot , post_pairs_sorted = pp_sorted , blocks_trace = bt , param_trace = pt , param_trace_sorted = pt_sorted , blocks_trace_sorted = bt_sorted , pp=pp , sortind = ind ) }
test_that("shiny.js version was replaced", { jsFiles <- system.file( file.path("www", "shared", c("shiny.js", "shiny.min.js")), package = "shiny" ) lapply(jsFiles, function(jsFile) { jsFileContent <- paste(suppressWarnings(readLines(jsFile)), collapse = "\n") expect_false(grepl("\\{\\{\\sVERSION\\s\\}\\}", jsFileContent)) }) })
cut.data.frame <- function(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3L, ordered_result = FALSE, cutcol = NULL, ...) { p <- ncol(x) colnum <- which(sapply(x, is.numeric)) if (!is.null(cutcol)) { if (any(!(cutcol %in% 1:p))) stop("cutcol: some column numbers are wrong.") notnum <- setdiff(cutcol, colnum) if (length(notnum) > 0) { warning("Non-numeric columns cannot be divided into intervals.") cutcol <- intersect(cutcol, colnum) } } else { cutcol <- colnum } if (is.list(breaks)){ if ((!is.null(labels))&(!is.list(labels))) stop("If breaks is a list, labels must also be a list.") if ((!is.null(cutcol))&(length(breaks) != length(cutcol))) stop("If breaks is a list, its length must be equal to the number of columns to be changed.") if ((!is.null(labels))&(length(labels) != length(cutcol))) stop("If labels is a list, its length must be equal to the number of columns to be changed.") if (!all(sapply(breaks[cutcol], is.numeric))) { stop("breaks must be either numeric or a list of numeric vector") } nbr <- sapply(breaks, length) if (any(nbr != 1)) { if (any(nbr <= 2)) stop("invalid number of intervals") } } else { if (!is.numeric(breaks)) stop("breaks must be either numeric or a list of numeric vector") if ((!is.null(labels))&(!is.character(labels))) stop("labels: wrong value.") brk <- breaks breaks <- list() for (j in 1:p) breaks[[j]] <- brk if (!is.null(labels)) { lab <- labels labels <- list() for (j in 1:p) labels[[j]] <- lab } } for (j in cutcol) { if (is.numeric(x[, j])) { x[, j] <- cut(x[, j], breaks = breaks[[j]], ordered_result = TRUE) } } return(x) }
pcfcross.inhom <- function(X, i, j, lambdaI=NULL, lambdaJ=NULL, ..., r=NULL, breaks=NULL, kernel="epanechnikov", bw=NULL, stoyan=0.15, correction = c("isotropic", "Ripley", "translate"), sigma=NULL, varcov=NULL) { verifyclass(X, "ppp") stopifnot(is.multitype(X)) if(missing(correction)) correction <- NULL marx <- marks(X) if(missing(i)) i <- levels(marx)[1] if(missing(j)) j <- levels(marx)[2] I <- (marx == i) J <- (marx == j) Iname <- paste("points with mark i =", i) Jname <- paste("points with mark j =", j) g <- pcfmulti.inhom(X, I, J, lambdaI, lambdaJ, ..., r=r,breaks=breaks, kernel=kernel, bw=bw, stoyan=stoyan, correction=correction, sigma=sigma, varcov=varcov, Iname=Iname, Jname=Jname) iname <- make.parseable(paste(i)) jname <- make.parseable(paste(j)) result <- rebadge.fv(g, substitute(g[inhom,i,j](r), list(i=iname,j=jname)), c("g", paste0("list", paren(paste("inhom", i, j, sep=",")))), new.yexp=substitute(g[list(inhom,i,j)](r), list(i=iname,j=jname))) attr(result, "dangerous") <- attr(g, "dangerous") return(result) } pcfdot.inhom <- function(X, i, lambdaI=NULL, lambdadot=NULL, ..., r=NULL, breaks=NULL, kernel="epanechnikov", bw=NULL, stoyan=0.15, correction = c("isotropic", "Ripley", "translate"), sigma=NULL, varcov=NULL) { verifyclass(X, "ppp") stopifnot(is.multitype(X)) if(missing(correction)) correction <- NULL marx <- marks(X) if(missing(i)) i <- levels(marx)[1] I <- (marx == i) J <- rep.int(TRUE, X$n) Iname <- paste("points with mark i =", i) Jname <- paste("points") g <- pcfmulti.inhom(X, I, J, lambdaI, lambdadot, ..., r=r,breaks=breaks, kernel=kernel, bw=bw, stoyan=stoyan, correction=correction, sigma=sigma, varcov=varcov, Iname=Iname, Jname=Jname) iname <- make.parseable(paste(i)) result <- rebadge.fv(g, substitute(g[inhom, i ~ dot](r), list(i=iname)), c("g", paste0("list(inhom,", iname, "~symbol(\"\\267\"))")), new.yexp=substitute(g[list(inhom, i ~ symbol("\267"))](r), list(i=iname))) if(!is.null(dang <- attr(g, "dangerous"))) { dang[dang == "lambdaJ"] <- "lambdadot" dang[dang == "lambdaIJ"] <- "lambdaIdot" attr(result, "dangerous") <- dang } return(result) } pcfmulti.inhom <- function(X, I, J, lambdaI=NULL, lambdaJ=NULL, ..., r=NULL, breaks=NULL, kernel="epanechnikov", bw=NULL, stoyan=0.15, correction=c("translate", "Ripley"), sigma=NULL, varcov=NULL, Iname="points satisfying condition I", Jname="points satisfying condition J") { verifyclass(X, "ppp") win <- X$window areaW <- area(win) npts <- npoints(X) correction.given <- !missing(correction) && !is.null(correction) if(is.null(correction)) correction <- c("translate", "Ripley") correction <- pickoption("correction", correction, c(isotropic="isotropic", Ripley="isotropic", trans="translate", translate="translate", translation="translate", best="best"), multi=TRUE) correction <- implemented.for.K(correction, win$type, correction.given) if(is.null(bw) && kernel=="epanechnikov") { h <- stoyan /sqrt(npts/areaW) hmax <- h bw <- h/sqrt(5) } else if(is.numeric(bw)) { hmax <- 3 * bw } else { hmax <- 2 * stoyan /sqrt(npts/areaW) } if(!is.logical(I) || !is.logical(J)) stop("I and J must be logical vectors") if(length(I) != npts || length(J) != npts) stop(paste("The length of I and J must equal", "the number of points in the pattern")) nI <- sum(I) nJ <- sum(J) if(nI == 0) stop(paste("There are no", Iname)) if(nJ == 0) stop(paste("There are no", Jname)) XI <- X[I] XJ <- X[J] dangerous <- c("lambdaI", "lambdaJ") dangerI <- dangerJ <- TRUE if(is.null(lambdaI)) { dangerI <- FALSE lambdaI <- density(XI, ..., sigma=sigma, varcov=varcov, at="points", leaveoneout=TRUE) } else { if(is.vector(lambdaI)) check.nvector(lambdaI, nI) else if(is.im(lambdaI)) lambdaI <- safelookup(lambdaI, XI) else if(is.function(lambdaI)) lambdaI <- lambdaI(XI$x, XI$y) else stop(paste(sQuote("lambdaI"), "should be a vector, a pixel image, or a function")) } if(is.null(lambdaJ)) { dangerJ <- FALSE lambdaJ <- density(XJ, ..., sigma=sigma, varcov=varcov, at="points", leaveoneout=TRUE) } else { if(is.vector(lambdaJ)) check.nvector(lambdaJ, nJ) else if(is.im(lambdaJ)) lambdaJ <- safelookup(lambdaJ, XJ) else if(is.function(lambdaJ)) lambdaJ <- lambdaJ(XJ$x, XJ$y) else stop(paste(sQuote("lambdaJ"), "should be a vector, a pixel image, or a function")) } danger <- dangerI || dangerJ rmaxdefault <- rmax.rule("K", win, npts/areaW) breaks <- handle.r.b.args(r, breaks, win, rmaxdefault=rmaxdefault) if(!(breaks$even)) stop("r values must be evenly spaced") r <- breaks$r rmax <- breaks$max alim <- c(0, min(rmax, rmaxdefault)) df <- data.frame(r=r, theo=rep.int(1,length(r))) fname <- c("g", "list(inhom,I,J)") out <- fv(df, "r", quote(g[inhom,I,J](r)), "theo", , alim, c("r", makefvlabel(NULL, NULL, fname, "pois")), c("distance argument r", "theoretical Poisson %s"), fname=fname, yexp=quote(g[list(inhom,I,J)](r))) denargs <- resolve.defaults(list(kernel=kernel, bw=bw), list(...), list(n=length(r), from=0, to=rmax)) close <- crosspairs(XI, XJ, rmax+hmax, what="ijd") orig <- seq_len(npts) imap <- orig[I] jmap <- orig[J] iX <- imap[close$i] jX <- jmap[close$j] if(any(I & J)) { ok <- (iX != jX) if(!all(ok)) { close$i <- close$i[ok] close$j <- close$j[ok] close$d <- close$d[ok] } } dclose <- close$d icloseI <- close$i jcloseJ <- close$j weight <- 1/(lambdaI[icloseI] * lambdaJ[jcloseJ]) if(any(correction=="translate")) { edgewt <- edge.Trans(XI[icloseI], XJ[jcloseJ], paired=TRUE) gT <- sewpcf(dclose, edgewt * weight, denargs, areaW)$g out <- bind.fv(out, data.frame(trans=gT), makefvlabel(NULL, "hat", fname, "Trans"), "translation-corrected estimate of %s", "trans") } if(any(correction=="isotropic")) { edgewt <- edge.Ripley(XI[icloseI], matrix(dclose, ncol=1)) gR <- sewpcf(dclose, edgewt * weight, denargs, areaW)$g out <- bind.fv(out, data.frame(iso=gR), makefvlabel(NULL, "hat", fname, "Ripley"), "isotropic-corrected estimate of %s", "iso") } if(is.null(out)) { warning("Nothing computed - no edge corrections chosen") return(NULL) } corrxns <- rev(setdiff(names(out), "r")) formula(out) <- . ~ r fvnames(out, ".") <- corrxns unitname(out) <- unitname(X) if(danger) attr(out, "dangerous") <- dangerous return(out) }
na_kalman <- function(x, model = "StructTS", smooth = TRUE, nit = -1, maxgap = Inf, ...) { data <- x if (!is.null(dim(data)[2]) && dim(data)[2] > 1) { for (i in 1:dim(data)[2]) { if (!anyNA(data[, i])) { next } withCallingHandlers(data[, i] <- na_kalman(data[, i], model, smooth, nit, maxgap,...), warning = function(cond) { warning( paste("imputeTS - warning for column", i, "of the dataset: \n ", cond), call. = FALSE) invokeRestart("muffleWarning")}, error = function(cond2) { warning( paste("imputeTS - warning for column", i, "of the dataset: \n ", cond2), call. = FALSE)} ) } return(data) } else { missindx <- is.na(data) if (!anyNA(data)) { return(x) } if (any(class(data) == "tbl")) { data <- as.vector(as.data.frame(data)[, 1]) } if (sum(!missindx) < 3) { warning("No imputation performed: Input data needs at least 3 non-NA data points for applying na_kalman") return(x) } if (!is.null(dim(data)[2]) && !dim(data)[2] == 1) { warning("No imputation performed: Wrong input type for parameter x") return(x) } if (!is.null(dim(data)[2])) { data <- data[, 1] } if (!is.numeric(data)) { warning("No imputation performed: Input x is not numeric") return(x) } if (!is.logical(smooth)) { stop("No imputation performed: Parameter smooth must be of type logical ( TRUE / FALSE)") } data[1:length(data)] <- as.numeric(data) if (is.character(model) && model == "StructTS" && length(unique(as.vector(data)))==2) { return(na_interpolation(x)) } if (model[1] == "auto.arima") { mod <- forecast::auto.arima(data, ...)$model } else if (model[1] == "StructTS") { if (is.na(data[1])) { data[1] <- data[which.min(is.na(data))] } mod <- stats::StructTS(data, ...)$model0 } else { mod <- model if (length(mod) < 7) { stop("No imputation performed: Parameter model has either to be \"StructTS\"/\"auto.arima\" or a user supplied model in form of a list with at least components T, Z, h , V, a, P, Pn specified") } if (is.null(mod$Z)) { stop("No imputation performed: Something is wrong with the user supplied model. Either choose \"auto.arima\" or \"StructTS\" or supply a state space model with at least components T, Z, h , V, a, P, Pn as specified under Details on help page for KalmanLike") } } if (smooth == TRUE) { kal <- stats::KalmanSmooth(data, mod, nit) erg <- kal$smooth } else { kal <- stats::KalmanRun(data, mod, nit) erg <- kal$states } if (dim(erg)[2] != length(mod$Z)) { stop("No imputation performed: Error with number of components $Z") } karima <- erg[missindx, , drop = FALSE] %*% as.matrix(mod$Z) data[missindx] <- karima if (is.finite(maxgap) && maxgap >= 0) { rlencoding <- rle(is.na(x)) rlencoding$values[rlencoding$lengths <= maxgap] <- FALSE en <- inverse.rle(rlencoding) data[en == TRUE] <- NA } if (!is.null(dim(x)[2])) { x[, 1] <- data return(x) } return(data) } }
df <- data.frame( contract = 1:10, x_attribute = c(0.92, 0.79, 1.00, 0.39, 0.68, 0.55, 0.73, 0.76, 1.00, 0.74), y_attribute = c(0.52, 0.19, 0.62, 1.00, 0.55, 0.52, 0.53, 0.46, 0.61, 0.84) ) psc3 <- df %>% dplyr::mutate(x_SAVF_score = SAVF_score(x_attribute, 0, 1, .653), y_SAVF_score = SAVF_score(y_attribute, 0, 1, .7)) test_that("kraljic_matrix creates a plot", { expect_true(kraljic_matrix(psc3, x_SAVF_score, y_SAVF_score) %>% ggplot2::is.ggplot()) })
NULL neuralNet <- setRefClass( "NeuralNetwork", fields = list(eta = "numeric", layers = "vector") ) neuralNet$methods( initialize = function(input, ...) { layers <<- vector("list", ...length()) for (i in 1:...length()) { l <- ...elt(i) switch (class(l), "PerceptronLayer" = { layers[[i]] <<- perceptronLayer(l$n, input) input <- l$n }, "McCullochPittsLayer" = { layers[[i]] <<- mcCullochPittsLayer(l$n, input) input <- l$n }, stop("argument in ... is not a layer!") ) } }, compute = function(input) { for (layer in layers) { input <- layer$output(input) } input }, train = function (ins, outs, epochs = 1, tax = .01, maxErr = 0) { nLayers <- length(layers) r <- nrow(ins) for (epoch in 1:epochs) { ch <- vector("list", nLayers) ch[[1]] <- vector("list", layers[[1]]$n) for (neu in 1:layers[[1]]$n) { ch[[1]][[neu]] <- list( "ws" = vector("numeric", length(ins[1,])), "b" = vector("numeric", 1) ) } if (nLayers > 1) { for (l in 2:nLayers) { ch[[l]] <- vector("list", layers[[l]]$n) for (ne in 1:layers[[l]]$n) { ch[[l]][[ne]] <- list( "ws" = vector("numeric", layers[[l-1]]$n), "b" = vector("numeric", 1) ) } } } for (i in 1:r) { inputs <- vector("list", nLayers + 1) inputs[[1]] <- ins[i,] for (l in 1:nLayers) { inputs[[l+1]] <- layers[[l]]$output(inputs[[l]]) } cost <- sum(outs[i,] - inputs[[nLayers+1]]) li <- nLayers newErr <- cost for (l in rev(layers)) { err <- newErr newErr <- vector("numeric", length(inputs[[li]])) ni <- 1 for (neu in l$neurons) { d <- neu$ws*inputs[[li]]*err[[ni]]*tax db <- err[[ni]]*tax ch[[li]][[ni]][["ws"]] <- ch[[li]][[ni]][["ws"]] + d ch[[li]][[ni]][["b"]] <- ch[[li]][[ni]][["b"]] + db newErr <- newErr + err[[ni]]*neu$ws ni <- ni + 1 } li <- li - 1 } } li <- 1 for (l in layers) { ni <- 1 for (neu in l$neurons) { wsChange <- ch[[li]][[ni]]$ws/r bChange <- ch[[li]][[ni]]$b/r neu$ws <- neu$ws + unlist(wsChange, use.names = F) neu$bias <- neu$bias - unlist(bChange, use.names = F) ni <- ni + 1 } li <- li + 1 } } }, validationScore = function(ins, outs) { corrects <- 0 for (i in 1:nrow(ins)) { corrects <- corrects + as.integer(compute(ins[i,]) == outs[i,]) } corrects/nrow(ins) } )
NULL format_engr <- function(x, sigdig = NULL, ambig_0_adj = FALSE) { if (!is.data.frame(x)) { warning("Argument must be a data frame.") return(x) } else { x <- as.data.frame(x) } if (is.null(sigdig)) { sigdig <- 4L } else if (any(sigdig < 0)) { warning("Significant digits must be 0 or positive integers.") return(x) } else { sigdig <- as.integer(sigdig) } var_name_list <- rlang::syms(names(x)) double_TF <- purrr::map(x, rlang::is_double) %>% unlist() integer_TF <- purrr::map(x, rlang::is_integer) %>% unlist() ordered_TF <- purrr::map(x, is.ordered) %>% unlist() factor_TF <- purrr::map(x, is.factor) %>% unlist() charac_TF <- purrr::map(x, rlang::is_character) %>% unlist() date_TF <- purrr::map(x, lubridate::is.Date) %>% unlist() yes_double <- double_TF & !ordered_TF & !integer_TF & !factor_TF & !charac_TF & !date_TF yes_integer <- integer_TF & !double_TF & !ordered_TF & !factor_TF & !charac_TF & !date_TF yes_others <- !yes_double & !yes_integer if (!any(yes_double)) { warning("No columns are of type double") return(x) } double_col <- x[, yes_double, drop = FALSE] integer_col <- x[, yes_integer, drop = FALSE] all_other_col <- x[, yes_others, drop = FALSE] m_double_col <- ncol(double_col) if (length(sigdig) == 1) { sigdig <- rep(sigdig, m_double_col) } if (length(sigdig) != m_double_col) { warning(paste( "Incorrect length sigdif vector. Applies only to numeric class 'double'." )) return(x) } numeric_engr <- double_col[, sigdig != 0, drop = FALSE] sigdig_engr <- sigdig[sigdig > 0] m_numeric_engr <- ncol(numeric_engr) numeric_as_is <- double_col[, sigdig == 0, drop = FALSE] numeric_as_is <- dplyr::bind_cols(numeric_as_is, integer_col) m_numeric_as_is <- ncol(numeric_as_is) obs_add <- function(x) { x <- dplyr::mutate(x, observ_index = dplyr::row_number()) } numeric_as_is <- obs_add(numeric_as_is) numeric_engr <- obs_add(numeric_engr) all_other_col <- obs_add(all_other_col) if (m_numeric_engr > 0) { numeric_engr <- format(numeric_engr, scientific = TRUE) %>% tidyr::gather(var, value, 1:m_numeric_engr) %>% dplyr::mutate(observ_index = as.double(observ_index)) %>% mutate(value = ifelse( is.na(value), NA_character_, as.character(value) )) %>% tidyr::separate(value, c("num", "pow"), "e", remove = FALSE, fill = "right" ) %>% mutate(num = str_trim(num, side = "both")) %>% mutate(pow = str_trim(pow, side = "both")) %>% mutate(num = ifelse(!is.na(num), as.numeric(num), NA)) %>% mutate(pow = ifelse(!is.na(pow), as.numeric(pow), NA)) numeric_engr <- numeric_engr %>% dplyr::mutate(dig = rep(sigdig_engr, each = max(observ_index))) numeric_engr <- numeric_engr %>% mutate(div = pow %% 3) %>% mutate(num = num * 10^div) %>% mutate(pow = round(pow - div, 0)) collect <- numeric_engr[FALSE, ] collect$num_str <- character() for (jj in unique(sigdig_engr)) { numeric_string <- numeric_engr %>% filter(dig == jj) %>% mutate(num_str = formatC( signif(num, digits = jj), digits = jj, format = "fg", flag = " )) %>% mutate(num_str = str_replace(num_str, "\\.$", "")) sel <- stringr::str_detect(numeric_string$num_str, "\\.") sel <- !sel & str_detect(numeric_string$num_str, "0$") if (any(sel) & !is.null(ambig_0_adj)) { if (ambig_0_adj) { numeric_string$pow[sel] <- numeric_string$pow[sel] + 3 temp_num <- as.numeric(numeric_string$num_str[sel]) / 1000 numeric_string$num_str[sel] <- formatC( signif(temp_num, digits = jj), digits = jj, format = "fg", flag = " ) } } collect <- rbind(collect, numeric_string) } numeric_engr <- collect numeric_engr <- numeric_engr %>% mutate(output = dplyr::if_else( pow == 0, "$nn$", paste("${nn}\\times 10^{pp}$") )) numeric_engr <- numeric_engr %>% mutate(output = stringr::str_replace(output, "nn", num_str)) %>% mutate(output = stringr::str_replace(output, "pp", as.character(pow))) numeric_engr <- numeric_engr %>% dplyr::select(observ_index, var, output) %>% tidyr::spread(var, output) } if (m_numeric_as_is > 0) { observ_index <- numeric_as_is %>% select(observ_index) num_col <- numeric_as_is %>% select(-observ_index) for (jj in 1:m_numeric_as_is) { num_col[, jj] <- str_c("$", num_col[, jj], "$") } numeric_as_is <- bind_cols(num_col, observ_index) } x <- dplyr::left_join(all_other_col, numeric_as_is, by = "observ_index") x <- dplyr::left_join(x, numeric_engr, by = "observ_index") x <- dplyr::select(x, !!!var_name_list) } "format_engr"
geom_spatial_segment <- function(mapping = NULL, data = NULL, ..., crs = NULL, detail = waiver(), great_circle = TRUE, wrap_dateline = TRUE, arrow = NULL, lineend = "butt", linejoin = "round", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { ggplot2::layer( data = data, mapping = mapping, stat = StatSpatialSegment, geom = ggplot2::GeomPath, position = "identity", show.legend = show.legend, inherit.aes = inherit.aes, params = list( crs = crs, detail = detail, great_circle = great_circle, wrap_dateline = wrap_dateline, arrow = arrow, lineend = lineend, linejoin = linejoin, na.rm = na.rm, ... ) ) } StatSpatialSegment <- ggplot2::ggproto( "StatSpatialSegment", StatSpatialRect, required_aes = c("x", "y", "xend", "yend"), compute_panel = function(self, data, scales, crs, crs_dest, detail = waiver(), great_circle = TRUE, wrap_dateline = TRUE) { if(is.null(crs)) { message("Assuming `crs = 4326` in stat_spatial_segment()") crs <- sf::st_crs(4326) } else { crs <- sf::st_crs(crs) } if (inherits(detail, "waiver")) { if (great_circle) { detail <- 100 } else { detail <- NULL } } if (nrow(data) == 0) { return(data.frame()) } geometry <- spatial_segment_geometry( data, crs, crs_dest, detail, great_circle, wrap_dateline ) geometry_df <- lapply(seq_along(geometry), function(i) { geom <- geometry[[i]] if (inherits(geom, "MULTILINESTRING")) { df <- sf::st_coordinates(geom) colnames(df) <- c("x", "y", "l1", "l2") df <- tibble::as_tibble(df) df$group <- paste(i, df$l1, sep = ".") df$l1 <- NULL df$l2 <- NULL } else if (inherits(geom, "LINESTRING")) { df <- unclass(geom) colnames(df) <- c("x", "y") df <- tibble::as_tibble(df) df$group <- paste0(i, ".1") } else { bad_class <- paste0("`", class(geom), "`", collapse = " / ") stop(glue::glue("Unrecognized geometry in stat_spatial_segment(): {bad_class}")) } df }) geometry_nrow <- vapply(geometry_df, nrow, integer(1)) data_indices <- lapply(seq_len(nrow(data)), function(i) rep(i, geometry_nrow[i])) data$xend <- NULL data$yend <- NULL data <- data[unlist(data_indices), , drop = FALSE] data$group <- NA data[c("x", "y", "group")] <- do.call(rbind, geometry_df) data } ) spatial_segment_geometry <- function(data, crs, crs_dest, detail = NULL, great_circle = TRUE, wrap_dateline = TRUE) { if (great_circle) { if (is.null(detail)) { warning( "Ignoring `detail = NULL` because `great_circle = TRUE` in stat_spatial_segment()", call. = FALSE ) detail <- 100 } data[c("x", "y")] <- xy_transform( data$x, data$y, from = crs, to = 4326 ) data[c("xend", "yend")] <- xy_transform( data$xend, data$yend, from = crs, to = 4326 ) crs <- sf::st_crs(4326) } geometry <- lapply(seq_len(nrow(data)), function(i) { geom <- sf::st_linestring( matrix( c(data$x[i], data$y[i], data$xend[i], data$yend[i]), byrow = TRUE, ncol = 2 ) ) length <- sf::st_length(geom) if (!is.null(detail) && (length > 0)) { if (great_circle) { geom_sfc <- sf::st_sfc(geom, crs = crs) geom_sfc <- lwgeom::st_geod_segmentize( geom_sfc, lwgeom::st_geod_length(geom_sfc) / detail ) if (wrap_dateline) { geom_sfc <- sf::st_wrap_dateline(geom_sfc) } geom <- geom_sfc[[1]] } else { dfMaxLength <- length / detail geom <- sf::st_segmentize(geom, dfMaxLength) } } geom }) geometry <- do.call(sf::st_sfc, c(geometry, list(crs = crs))) sf::st_transform(geometry, crs = crs_dest) }
context("Testing add_grouping") id <- "a" cell_ids <- c("truth", "universally", "acknowledged", "that", "a", "single") cell_info <- tibble( cell_id = cell_ids, info1 = c("man", "in", "possession", "of", "a", "good"), info2 = c("fortune", "must", "be", "in", "want", "of"), info3 = 1:6 ) wrapper1 <- wrap_data(id, cell_ids) %>% add_grouping(cell_info$info1) wrapper2 <- wrap_data(id, cell_ids) %>% add_grouping(unique(cell_info$info1), cell_info$info1) wrapper3 <- wrap_data(id, cell_ids) %>% add_grouping(tibble(cell_id = cell_ids, group_id = cell_info$info1)) wrapper4 <- wrap_data(id, cell_ids) %>% add_prior_information(groups_id = tibble(cell_id = cell_ids, group_id = cell_info$info1)) wrapper5 <- wrap_data(id, cell_ids, cell_info) test_that("Testing add_grouping", { for (wrapper in list(wrapper1, wrapper2, wrapper3)) { expect_true(is_wrapper_with_grouping(wrapper)) expect_true(all(c("grouping", "group_ids") %in% names(wrapper))) expect_true(all(wrapper$group_ids %in% wrapper$grouping)) expect_equal(length(wrapper$grouping), length(wrapper$cell_ids)) expect_equal(names(wrapper$grouping), wrapper$cell_ids) } }) test_that("Testing get_grouping", { for (wrapper in list(wrapper1, wrapper2, wrapper3, wrapper4)) { expect_equal(get_grouping(wrapper), wrapper1$grouping) expect_equal(names(get_grouping(wrapper)), wrapper$cell_ids) } expect_error(get_grouping(wrapper5)) expect_equal(get_grouping(wrapper5, "info1"), wrapper3$grouping) expect_equal(names(get_grouping(wrapper5, "info1")), wrapper5$cell_ids) }) milestone_network <- tibble(from = c("A", "B"), to = c("B", "C"), directed = TRUE, length = 1) progressions <- tibble(cell_id = cell_ids, from = c(rep("A", 3), rep("B", 3)), to = c(rep("B", 3), rep("C", 3)), percentage = c(0, 0.5, 1, 0, 0.5, 1)) trajectory <- wrap_data(id, cell_ids) %>% add_trajectory(milestone_network = milestone_network, progressions = progressions) test_that("Testing group_onto_trajectory_edges", { grouping <- group_onto_trajectory_edges(trajectory) expect_equal(length(grouping), length(cell_ids)) expect_equal(names(grouping), cell_ids) expect_equal(grouping %>% unname(), c("A->B", "A->B", "A->B", "B->C", "B->C", "B->C")) })
calculate_resampling_indices_EKF_interp_joint <- function(env_obj) { if (env_obj$do_trunc_adjust) { trunc_adjustment <- matrix(NA, ncol=env_obj$nstates, nrow=env_obj$npart) } for (s in env_obj$sharks_with_obs) { tmp_mat <- matrix(1, ncol=env_obj$yobs_sharks[ s ] + (env_obj$nstates > 1) + (env_obj$interact==TRUE), nrow=env_obj$npart) colnames(tmp_mat) <- paste("t",1:ncol(tmp_mat)) colnames(tmp_mat)[ 1:env_obj$yobs_sharks[ s ] ] <- paste("y", 1:env_obj$yobs_sharks[ s ], sep="_") if (env_obj$nstates > 1) { colnames(tmp_mat)[ env_obj$yobs_sharks[ s ] + 1] <- "trans" if (env_obj$interact==TRUE) { colnames(tmp_mat)[ env_obj$yobs_sharks[ s ] + 2] <- "interact" } } env_obj$densities_components[[ s ]] <- rep(list(tmp_mat), env_obj$nstates) prev_region <- env_obj$Xpart_history[env_obj$i-1,"region",,s] prev_z <- env_obj$lambda_matrix[,env_obj$i-1,s] if (env_obj$nstates > 1) { for (k in 1:env_obj$nstates) { for (p in 1:env_obj$npart) { env_obj$densities_components[[ s ]][[ k ]][p,"trans"] <- env_obj$transition_mat[[ s ]][[ p ]]$mat[[ prev_region[ p ] ]][ prev_z[ p ],k] } env_obj$densities_components[[ s ]][[ k ]][,"trans"] <- env_obj$densities_components[[ s ]][[ k ]][,"trans"] * env_obj$state_favor[ k ] if (env_obj$interact & k < env_obj$nstates) { env_obj$densities_components[[ s ]][[ k ]][,"interact"] <- env_obj$interact_intensity_draw[,k,env_obj$i,s] } } } for (y in 1:env_obj$yobs_sharks[ s ]) { for (k in 1:env_obj$nstates) { for (p in 1:env_obj$npart) { env_obj$densities_components[[ s ]][[ k ]][p,y] <- pmax(1e-50, mvtnorm::dmvnorm(x=env_obj$ynext[ which(rownames(env_obj$ynext)==s)[ y ],c("X","Y")], mean=env_obj$MuY[[ s ]][,y,k,p], sigma=env_obj$SigY[[ s ]][,,y,k,p])) } env_obj$densities_components[[ s ]][[ k ]] <- keep_finite(env_obj$densities_components[[ s ]][[ k ]]) } if (env_obj$do_trunc_adjust) { for (k in 1:env_obj$nstates) { for (p in 1:env_obj$npart) { trunc_adjustment[p,k] <- fraction_inside(mu=env_obj$MuY[[ s ]][,y,k,p], cmat=env_obj$SigY[[ s ]][,,y,k,p], nsim=500, obj=env_obj) } trunc_adjustment[,k] <- pmax(1e-3, trunc_adjustment[,k]) env_obj$densities_components[[ s ]][[ k ]][,y] <- env_obj$densities_components[[ s ]][[ k ]][,y] / trunc_adjustment[,k] } } } } env_obj$densities_bystate <- lapply(env_obj$densities_components[ env_obj$sharks_with_obs ], function(x) sapply(x, function(y) pmax(1e-50, apply(y, 1, prod)))) env_obj$densities_bystate <- lapply(env_obj$densities_bystate, function(x) matrix(x, nrow=env_obj$npart)) if (env_obj$nstates > 1) { env_obj$densities_bystate <- lapply(env_obj$densities_bystate, function(x) t(apply(x, 1, function(x) pmax(1e-50, x*env_obj$state_favor)))) } names(env_obj$densities_bystate) <- env_obj$sharks_with_obs env_obj$densities <- sapply(env_obj$densities_bystate, function(x) rowSums(x[,drop=FALSE])) colnames(env_obj$densities) <- env_obj$sharks_with_obs na_dens <- apply(env_obj$densities, 1, function(x) any(is.na(x))) if (any(na_dens)) { print(env_obj$densities[ na_dens,]) for (s in env_obj$sharks_with_obs) { for (k in 1:env_obj$nstates) { print(env_obj$densities_components[[ s ]][[ k ]][ na_dens,]) } } } rs <- rowSums(env_obj$densities, na.rm=TRUE) if (any(is.na(env_obj$densities))) { print(env_obj$densities); print(env_obj$densities_components[[ s ]]) } if (all(rs==0)) { rs <- rep(1, env_obj$npart) } eff_size <- eff_ss(p=rowSums(pmax(env_obj$densities, 1e-15, na.rm=TRUE))) env_obj$eff_size_hist[env_obj$i, s] <- eff_size print(paste("Effective size is", round(eff_size, 1))) if (eff_size >= env_obj$npart * env_obj$neff_sample) { swo <- env_obj$sharks_with_obs[ env_obj$shark_final_obs[ env_obj$sharks_with_obs ] == env_obj$i] env_obj$densities <- env_obj$densities[ swo ] } env_obj$sharks_to_resample <- colnames(env_obj$densities) nsharks_resample <- length(env_obj$sharks_to_resample) env_obj$indices <- matrix(1, ncol=nsharks_resample, nrow=env_obj$npart) colnames(env_obj$indices) <- env_obj$sharks_to_resample if (nsharks_resample > 0) { print("resampling...") if (env_obj$nsharks > 1) { print(env_obj$sharks_to_resample) } iter <- 0 if (env_obj$interact) { dens_prob <- apply(env_obj$densities, 1, prod) } if (env_obj$lowvarsample==TRUE) { while(any(apply(env_obj$indices, 2, function(y) length(unique(y))) ==1) & iter < 100) { if (env_obj$interact) { env_obj$indices <- matrix(low_var_sample(wts=dens_prob, M=env_obj$npart), ncol=length(env_obj$sharks_with_obs), nrow=env_obj$npart) } else { env_obj$indices <- apply(env_obj$densities, 2, function(y) low_var_sample(wts=y, M=env_obj$npart)) } iter <- iter + 1 } } else { while(any(apply(env_obj$indices, 2, function(y) length(unique(y))) ==1) & iter < 100) { if (env_obj$interact) { env_obj$indices <- matrix(sample(x=1:env_obj$npart, size=env_obj$npart, prob=dens_prob, replace=TRUE), ncol=length(env_obj$sharks_with_obs), nrow=env_obj$npart) } else { env_obj$indices <- apply(env_obj$densities, 2, function(y) sample(x=1:env_obj$npart, size=env_obj$npart, prob=y, replace=TRUE)) } iter <- iter + 1 } } colnames(env_obj$indices) <- env_obj$sharks_to_resample env_obj$resample_history[env_obj$i, env_obj$sharks_to_resample] <- apply(env_obj$indices, 2, function(x) length(unique(x))/env_obj$npart ) } else{ print("not resampling since effective size is above threshold") } invisible(NULL) }
context("PipeOpSpatialSign") test_that("PipeOpSpatialSign - general functionality", { task = mlr_tasks$get("iris") op = PipeOpSpatialSign$new() expect_pipeop(op) expect_datapreproc_pipeop_class(PipeOpSpatialSign, task = task) result = train_pipeop(op, inputs = list(task)) expect_task(result[[1]]) result = predict_pipeop(op, inputs = list(task)) expect_task(result[[1]]) }) test_that("PipeOpSpatialSign - receive expected result", { task = mlr_tasks$get("iris") op = PipeOpSpatialSign$new(param_vals = list(norm = 2, length = 1L)) result = train_pipeop(op, inputs = list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sqrt(sum(x^2)), 1) }) result = op$predict(list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sqrt(sum(x^2)), 1) }) task = mlr_tasks$get("iris") op = PipeOpSpatialSign$new(param_vals = list(norm = 2, length = 2)) result = train_pipeop(op, inputs = list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sqrt(sum(x^2)), 2) }) result = op$predict(list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sqrt(sum(x^2)), 2) }) task = mlr_tasks$get("iris") op = PipeOpSpatialSign$new(param_vals = list(norm = 1, length = 1L)) result = train_pipeop(op, inputs = list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sum(abs(x)), 1) }) result = op$predict(list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(sum(abs(x)), 1) }) task = mlr_tasks$get("iris") op = PipeOpSpatialSign$new(param_vals = list(norm = Inf, length = 1L)) result = train_pipeop(op, inputs = list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(max(abs(x)), 1) }) result = op$predict(list(task)) t = apply(result[[1]]$data()[, 2:5], MARGIN = 1, function(x) { expect_equal(max(abs(x)), 1) }) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) suppressPackageStartupMessages({ library(ipfr) library(dplyr) }) set.seed(42) mtx <- matrix(data = runif(9), nrow = 3, ncol = 3) row_targets <- c(3, 4, 5) column_targets <- c(5, 4, 3) mtx result <- ipu_matrix(mtx, row_targets, column_targets) result rowSums(result) colSums(result) survey <- tibble( size = c(1, 2, 1, 1), autos = c(0, 2, 2, 1), weight = 1 ) survey targets <- list() targets$size <- tibble( `1` = 75, `2` = 25 ) targets$autos <- tibble( `0` = 25, `1` = 50, `2` = 25 ) targets result <- ipu(survey, targets) names(result) result$weight_tbl result$weight_dist result$primary_comp result <- setup_arizona() hh_seed <- result$hh_seed hh_targets <- result$hh_targets per_seed <- result$per_seed per_targets <- result$per_targets result <- ipu(hh_seed, hh_targets, per_seed, per_targets, max_iterations = 30) result$weight_tbl result$primary_comp result$secondary_comp new_hh_seed <- hh_seed %>% mutate(geo_tract = 1) new_hh_seed <- bind_rows( new_hh_seed, new_hh_seed %>% mutate(geo_tract = 2, id = id + 8) ) new_hh_seed$geo_region <- 1 new_hh_seed new_hh_targets <- hh_targets new_hh_targets$hhtype <- bind_rows(hh_targets$hhtype, hh_targets$hhtype) new_hh_targets$hhtype <- new_hh_targets$hhtype %>% mutate(geo_tract = c(1, 2)) new_hh_targets$hhtype new_per_seed <- bind_rows( per_seed, per_seed %>% mutate(id = id + 8) ) new_per_seed new_per_targets <- per_targets new_per_targets$pertype <- per_targets$pertype %>% mutate_all(list(~. * 2)) %>% mutate(geo_region = 1) new_per_targets$pertype result <- ipu( new_hh_seed, new_hh_targets, new_per_seed, new_per_targets, max_iterations = 30 ) result$primary_comp result$secondary_comp set.seed(42) synthesize(result$weight_tbl, group_by = "geo_tract") %>% head() set.seed(42) result$weight_tbl %>% group_by(geo_tract) %>% synthesize() %>% head()
quickTSPlot <- function(TS, ci = 0.95){ value <- Lag <- ACF <- NULL if(class(TS)[1] %in% c("data.frame", "data.table") ) n <- nrow(TS) else n <- length(TS) dta <- data.frame(time = c(1:n), value = TS) p1 <- ggplot(dta, aes(x = time, y = value)) + geom_line() + theme_light() + labs(x = 'Time', y = 'Value', title = 'Timeseries plot') p2 <- ggplot(dta[dta[, 2] != 0, ], aes(x=value, after_stat(density))) + geom_histogram() + theme_light() + labs(x = 'Nonzero values', y = 'Density', title = 'Empirical density function') acf0 <- acf(TS, plot = FALSE) acf1 <- data.frame(Lag = acf0$lag, ACF = acf0$acf) clim <- qnorm((1 + ci)/2)/sqrt(acf0$n.used) p3 <- ggplot(data = acf1, aes(x = Lag, y = ACF)) + geom_hline(aes(yintercept = clim), linetype = 2) + geom_hline(aes(yintercept = -clim), linetype = 2) + geom_hline(aes(yintercept = 0)) + geom_segment(mapping = aes(xend = Lag, yend = 0)) + labs(title = 'Autocorrelation function') + theme_light() ggdraw() + draw_plot(p1, x = 0, y = .5, width = 1, height = 0.5) + draw_plot(p2, x = 0, y = 0, width = .5, height = .5) + draw_plot(p3, x = .5, y = 0, width = .5, height = .5) }
spatialPIC <- function( L, R, y, xcov, IC, scale.designX, scaled, area, binary, I, C, nn, order, knots, grids, a_eta, b_eta, a_ga, b_ga, a_lamb, b_lamb, beta_iter, phi_iter, beta_cand, beta_sig0, x_user, total, burnin, thin, conf.int, seed){ Ispline<-function(x,order,knots){ k=order+1 m=length(knots) n=m-2+k t=c(rep(1,k)*knots[1], knots[2:(m-1)], rep(1,k)*knots[m]) yy1=array(rep(0,(n+k-1)*length(x)),dim=c(n+k-1, length(x))) for (l in k:n){ yy1[l,]=(x>=t[l] & x<t[l+1])/(t[l+1]-t[l]) } yytem1=yy1 for (ii in 1:order){ yytem2=array(rep(0,(n+k-1-ii)*length(x)),dim=c(n+k-1-ii, length(x))) for (i in (k-ii):n){ yytem2[i,]=(ii+1)*((x-t[i])*yytem1[i,]+(t[i+ii+1]-x)*yytem1[i+1,])/(t[i+ii+1]-t[i])/ii } yytem1=yytem2 } index=rep(0,length(x)) for (i in 1:length(x)){ index[i]=sum(t<=x[i]) } yy=array(rep(0,(n-1)*length(x)),dim=c(n-1,length(x))) if (order==1){ for (i in 2:n){ yy[i-1,]=(i<index-order+1)+(i==index)*(t[i+order+1]-t[i])*yytem2[i,]/(order+1) } }else{ for (j in 1:length(x)){ for (i in 2:n){ if (i<(index[j]-order+1)){ yy[i-1,j]=1 }else if ((i<=index[j]) && (i>=(index[j]-order+1))){ yy[i-1,j]=(t[(i+order+1):(index[j]+order+1)]-t[i:index[j]])%*%yytem2[i:index[j],j]/(order+1) }else{ yy[i-1,j]=0 } } } } return(yy) } Mspline<-function(x,order,knots){ k1=order m=length(knots) n1=m-2+k1 t1=c(rep(1,k1)*knots[1], knots[2:(m-1)], rep(1,k1)*knots[m]) tem1=array(rep(0,(n1+k1-1)*length(x)),dim=c(n1+k1-1, length(x))) for (l in k1:n1){ tem1[l,]=(x>=t1[l] & x<t1[l+1])/(t1[l+1]-t1[l]) } if (order==1){ mbases=tem1 }else{ mbases=tem1 for (ii in 1:(order-1)){ tem=array(rep(0,(n1+k1-1-ii)*length(x)),dim=c(n1+k1-1-ii, length(x))) for (i in (k1-ii):n1){ tem[i,]=(ii+1)*((x-t1[i])*mbases[i,]+(t1[i+ii+1]-x)*mbases[i+1,])/(t1[i+ii+1]-t1[i])/ii } mbases=tem } } return(mbases) } poissrndpositive<-function(lambda){ q=200 t=seq(0,q,1) p=dpois(t,lambda) pp=cumsum(p[2:(q+1)])/(1-p[1]) u=runif(1) while(u>pp[q]){ q=q+1 pp[q]=pp[q-1]+dpois(q,lambda)/(1-p[1]) } ll=sum(u>pp)+1 } set.seed(seed) L=matrix(L,ncol=1) R=matrix(R,ncol=1) y=matrix(y,ncol=1) xcov=as.matrix(xcov) IC=matrix(IC,ncol=1) p=ncol(xcov) if (scale.designX==TRUE){ mean_X<-apply(xcov,2,mean) sd_X<-apply(xcov,2,sd) for (r in 1:p){ if (scaled[r]==1) xcov[,r]<-(xcov[,r]-mean_X[r])/sd_X[r] } } n1=sum(IC==0) n2=sum(IC==1) N=n1+n2 t<-rep(0,N) for (i in 1:N) {t[i]=ifelse(IC[i]==0,L[i],0)} K=length(knots)-2+order kgrids=length(grids) bmsT=Mspline(t[1:n1],order,knots) bisT=Ispline(t[1:n1],order,knots) bisL=Ispline(L[(n1+1):N],order,knots) bisR=Ispline(R[(n1+1):N],order,knots) bisg=Ispline(grids,order,knots) eta=rgamma(1,a_eta,rate=b_eta) lamb=rgamma(1,a_lamb,rate=b_lamb) gamcoef=matrix(rgamma(K, 1, rate=1),ncol=K) phicoef<-matrix(rep(0,I),ncol=1) phicoef2<-matrix(rep(0,N),ncol=1) for (j in 1:N){ phicoef2[j]<-phicoef[area[j]] } beta=matrix(rep(0,p),p,1) beta_original=matrix(rep(0,p),ncol=1) u=array(rep(0,n1*K),dim=c(n1,K)) for (i in 1:n1){ u[i,]=rmultinom(1,1,gamcoef*t(bmsT[,i])) } lambdatT=t(gamcoef%*%bmsT) LambdatT=t(gamcoef%*%bisT) LambdatL=t(gamcoef%*%bisL) LambdatR=t(gamcoef%*%bisR) Lambdatg=t(gamcoef%*%bisg) parbeta=array(rep(0,total*p),dim=c(total,p)) parbeta_original=array(rep(0,total*p),dim=c(total,p)) pareta=array(rep(0,total),dim=c(total,1)) parlamb=array(rep(0,total),dim=c(total,1)) parphi=array(rep(0,total*I),dim=c(total,I)) pargam=array(rep(0,total*K),dim=c(total,K)) parsurv0=array(rep(0,total*kgrids),dim=c(total,kgrids)) parlambdatT=array(rep(0,total*n1),dim=c(total,n1)) parLambdatT=array(rep(0,total*n1),dim=c(total,n1)) parLambdatL=array(rep(0,total*n2),dim=c(total,n2)) parLambdatR=array(rep(0,total*n2),dim=c(total,n2)) pardev=array(rep(0,total),dim=c(total,1)) parfinv_exact=array(rep(0,total*n1),dim=c(total,n1)) parfinv_IC=array(rep(0,total*n2),dim=c(total,n2)) if (is.null(x_user)){parsurv=parsurv0} else { G<-length(x_user)/p parsurv=array(rep(0,total*kgrids*G),dim=c(total,kgrids*G))} iter=1 while (iter<total+1) { z=array(rep(0,n2),dim=c(n2,1)); w=z zz=array(rep(0,n2*K),dim=c(n2,K)); ww=zz for (j in 1:n2){ if (y[n1+j]==0){ templam1=LambdatR[j]*exp(xcov[(n1+j),]%*%beta+phicoef[area[n1+j]]) z[j]=poissrndpositive(templam1) zz[j,]=rmultinom(1,z[j],gamcoef*t(bisR[,j])) } else if (y[n1+j]==1){ templam1=(LambdatR[j]-LambdatL[j])*exp(xcov[(n1+j),]%*%beta+phicoef[area[n1+j]]) w[j]=poissrndpositive(templam1) ww[j,]=rmultinom(1,w[j],gamcoef*t(bisR[,j]-bisL[,j])) } } te1=z*(y[(n1+1):N]==0)+w*(y[(n1+1):N]==1) te2=(LambdatR*(y[(n1+1):N]==0)+LambdatR*(y[(n1+1):N]==1)+LambdatL*(y[(n1+1):N]==2)) te3=LambdatT for (r in 1:p){ if (binary[r]==0){ beta1<-beta2<-beta if (iter<beta_iter) sd_cand<-beta_cand[r] else sd_cand<-sd(parbeta[1:(iter-1),r]) xt<-beta[r] yt<-rnorm(1,xt,sd_cand) beta1[r]<-yt beta2[r]<-xt log_f1<-sum(yt*xcov[1:n1,r]-te3*exp(xcov[1:n1,]%*%beta1+phicoef2[1:n1]))+sum(yt*xcov[(n1+1):N,r]*te1)-sum(exp(xcov[(n1+1):N,]%*%beta1+phicoef2[(n1+1):N])*te2)-0.5*(yt^2)/(beta_sig0^2) log_f2<-sum(xt*xcov[1:n1,r]-te3*exp(xcov[1:n1,]%*%beta2+phicoef2[1:n1]))+sum(xt*xcov[(n1+1):N,r]*te1)-sum(exp(xcov[(n1+1):N,]%*%beta2+phicoef2[(n1+1):N])*te2)-0.5*(xt^2)/(beta_sig0^2) num<-log_f1 den<-log_f2 if (log(runif(1))<(num-den)) beta[r]<-yt else beta[r]<-xt } if (binary[r]==1 & p>1){ te4=sum(xcov[1:n1,r])+sum(xcov[(n1+1):N,r]*te1) te5=sum(te3*exp(as.matrix(xcov[1:n1,-r])%*%as.matrix(beta[-r])+phicoef2[1:n1])*xcov[1:n1,r])+sum(te2*exp(as.matrix(xcov[(n1+1):N,-r])%*%as.matrix(beta[-r])+phicoef2[(n1+1):N])*xcov[(n1+1):N,r]) beta[r]<-log(rgamma(1,a_ga+te4,rate=b_ga+te5)) } if (binary[r]==1 & p==1){ te4=sum(xcov[1:n1,r])+sum(xcov[(n1+1):N,r]*te1) te5=sum(te3*exp(phicoef2[1:n1])*xcov[1:n1,r])+sum(te2*exp(phicoef2[(n1+1):N])*xcov[(n1+1):N,r]) beta[r]<-log(rgamma(1,a_ga+te4,rate=b_ga+te5)) } } if (scale.designX==TRUE){ for (r in 1:p) beta_original[r]<-ifelse(scaled[r]==1,beta[r]/sd_X[r],beta[r]) } if (scale.designX==FALSE) beta_original<-beta for (l in 1:K){ tempa=1+sum(u[,l])+sum(zz[,l]*(y[(n1+1):N]==0)+ww[,l]*(y[(n1+1):N]==1)) tempb=eta+sum(bisT[l,]*exp(xcov[1:n1,]%*%beta+phicoef2[1:n1]))+sum(((bisR[l,])*(y[(n1+1):N]==0)+(bisR[l,])*(y[(n1+1):N]==1) +(bisL[l,])*(y[(n1+1):N]==2))*exp(xcov[(n1+1):N,]%*%beta+phicoef2[(n1+1):N])) gamcoef[l]=rgamma(1,tempa,rate=tempb) } lambdatT=t(gamcoef%*%bmsT) LambdatT=t(gamcoef%*%bisT) LambdatL=t(gamcoef%*%bisL) LambdatR=t(gamcoef%*%bisR) u=array(rep(0,n1*K),dim=c(n1,K)) for (i in 1:n1){ u[i,]=rmultinom(1,1,gamcoef*t(bmsT[,i])) } eta=rgamma(1,a_eta+K, rate=b_eta+sum(gamcoef)) phi1<-array(rep(0,N),dim=c(N,1)) phi2<-array(rep(0,N),dim=c(N,1)) for (i in 1:I){ phi1<-phi2<-phicoef2 if (iter<phi_iter) sd_cand<-sqrt(1/nn[i]) else sd_cand<-sd(parphi[1:(iter-1),i]) xt<-phicoef[i] yt<-rnorm(1,xt,sd_cand) phi1[area==i]<-yt phi2[area==i]<-xt log_f1<-sum(phi1[1:n1])-sum(te3*exp(xcov[1:n1,]%*%beta+phi1[1:n1]))+sum(phi1[(n1+1):N]*te1)-sum((exp(xcov[(n1+1):N,]%*%beta+phi1[(n1+1):N]))*te2)-0.5*nn[i]*lamb*(yt-C[i,]%*%phicoef/nn[i])^2 log_f2<-sum(phi2[1:n1])-sum(te3*exp(xcov[1:n1,]%*%beta+phi2[1:n1]))+sum(phi2[(n1+1):N]*te1)-sum((exp(xcov[(n1+1):N,]%*%beta+phi2[(n1+1):N]))*te2)-0.5*nn[i]*lamb*(xt-C[i,]%*%phicoef/nn[i])^2 num<-log_f1 den<-log_f2 if (log(runif(1))<(num-den)) phicoef[i]<-yt else phicoef[i]<-xt phicoef<-phicoef-mean(phicoef) phicoef2[area==i]<-phicoef[i] } A<-matrix(rep(0,I*I),nrow=I,byrow=TRUE) for (i in 1:I){ for (j in 1:I){ A[i,j]<-(phicoef[i]-phicoef[j])^2*C[i,j]*as.numeric(i < j) } } lamb<-rgamma(1,0.5*(I-1)+a_lamb,rate=0.5*sum(A)+b_lamb) f_iter_exact<-lambdatT*exp(xcov[1:n1,]%*%beta+phicoef2[1:n1])*exp(-LambdatT*exp(xcov[1:n1,]%*%beta+phicoef2[1:n1])) FL<-1-exp(-LambdatL*exp(xcov[(n1+1):N,]%*%beta+phicoef2[(n1+1):N])) FR<-1-exp(-LambdatR*exp(xcov[(n1+1):N,]%*%beta+phicoef2[(n1+1):N])) f_iter_IC<-(FR^(y[(n1+1):N]==0))*((FR-FL)^(y[(n1+1):N]==1))*((1-FL)^(y[(n1+1):N]==2)) finv_iter_exact<-1/f_iter_exact finv_iter_IC<-1/f_iter_IC loglike<-sum(log(f_iter_exact))+sum(log(FR^(y[(n1+1):N]==0))+log((FR-FL)^(y[(n1+1):N]==1))+log((1-FL)^(y[(n1+1):N]==2))) dev<--2*loglike parbeta[iter,]=beta parbeta_original[iter,]=beta_original pareta[iter]=eta parlamb[iter]=lamb parphi[iter,]=phicoef pargam[iter,]=gamcoef ttt=gamcoef%*%bisg if (scale.designX==FALSE) {parsurv0[iter,]<-exp(-ttt)} if (scale.designX==TRUE) {parsurv0[iter,]<-exp(-ttt*exp(-sum((beta*mean_X/sd_X)[scaled==1])))} parlambdatT[iter,]=lambdatT parLambdatT[iter,]=LambdatT parLambdatL[iter,]=LambdatL parLambdatR[iter,]=LambdatR pardev[iter]=dev parfinv_exact[iter,]=finv_iter_exact parfinv_IC[iter,]=finv_iter_IC if (is.null(x_user)){parsurv[iter,]=parsurv0[iter,]} else { A<-matrix(x_user,byrow=TRUE,ncol=p) if (scale.designX==TRUE){ for (r in 1:p){ if (scaled[r]==1) A[,r]<-(A[,r]-mean_X[r])/sd_X[r]} } B<-exp(A%*%beta) for (g in 1:G){ parsurv[iter,((g-1)*kgrids+1):(g*kgrids)]=exp(-ttt*B[g,1])} } iter=iter+1 if (iter%%100==0) print(iter) } wbeta=as.matrix(parbeta_original[seq((burnin+thin),total,by=thin),],ncol=p) wparsurv0=as.matrix(parsurv0[seq((burnin+thin),total,by=thin),],ncol=kgrids) wparsurv=as.matrix(parsurv[seq((burnin+thin),total,by=thin),],ncol=kgrids*G) coef<-apply(wbeta,2,mean) coef_ssd<-apply(wbeta,2,sd) coef_ci<-array(rep(0,p*2),dim=c(p,2)) S0_m<-apply(wparsurv0,2,mean) S_m<- apply(wparsurv,2,mean) colnames(coef_ci)<-c(paste(100*(1-conf.int)/2,"%CI"),paste(100*(0.5+conf.int/2),"%CI")) for (r in 1:p) coef_ci[r,]<-quantile(wbeta[,r],c((1-conf.int)/2,0.5+conf.int/2)) CPO_exact=1/apply(parfinv_exact[seq((burnin+thin),total,by=thin),],2,mean) CPO_IC=1/apply(parfinv_IC[seq((burnin+thin),total,by=thin),],2,mean) NLLK_exact=-sum(log(CPO_exact)) NLLK_IC=-sum(log(CPO_IC)) NLLK=NLLK_exact+NLLK_IC LambdatL_m<-apply(parLambdatL[seq((burnin+thin),total,by=thin),],2,mean) LambdatR_m<-apply(parLambdatR[seq((burnin+thin),total,by=thin),],2,mean) beta_m<-apply(as.matrix(parbeta[seq((burnin+thin),total,by=thin),]),2,mean) phicoef_m<-apply(parphi[seq((burnin+thin),total,by=thin),],2,mean) phicoef2_m<-array(rep(0,N),dim=c(N,1)) for (j in 1:N){ phicoef2_m[j]<-phicoef_m[area[j]] } FL_m<-1-exp(-LambdatL_m*exp(as.matrix(xcov[(n1+1):N,])%*%as.matrix(beta_m)+phicoef2_m[(n1+1):N])) FR_m<-1-exp(-LambdatR_m*exp(as.matrix(xcov[(n1+1):N,])%*%as.matrix(beta_m)+phicoef2_m[(n1+1):N])) loglike_m_IC<-sum(log(FR_m^(y[(n1+1):N]==0))+log((FR_m-FL_m)^(y[(n1+1):N]==1))+log((1-FL_m)^(y[(n1+1):N]==2))) D_thetabar_IC<--2*loglike_m_IC lambdatT_m<-apply(parlambdatT[seq((burnin+thin),total,by=thin),],2,mean) LambdatT_m<-apply(parLambdatT[seq((burnin+thin),total,by=thin),],2,mean) loglike_m_exact<-sum(log(lambdatT_m)+as.matrix(xcov[1:n1,])%*%as.matrix(beta_m)+phicoef2_m[1:n1]-LambdatT_m*exp(as.matrix(xcov[1:n1,])%*%as.matrix(beta_m)+phicoef2_m[1:n1])) D_thetabar_exact<--2*loglike_m_exact D_bar=mean(pardev[seq((burnin+thin),total,by=thin)]) D_thetabar=D_thetabar_IC+D_thetabar_exact DIC=2*D_bar-D_thetabar est<-list( N=nrow(xcov), nameX=colnames(xcov), parbeta=parbeta_original, parsurv0=parsurv0, parsurv=parsurv, parphi=parphi, parlamb=parlamb, coef = coef, coef_ssd = coef_ssd, coef_ci = coef_ci, S0_m = S0_m, S_m = S_m, grids=grids, DIC = DIC, NLLK = NLLK ) est }
treemapClinData <- function(...){ plotCountClinData(..., typePlot = "treemap") }
PLSR1BinFit <- function(Y, X, S=2, tolerance=0.000005, maxiter=100, show=FALSE, penalization=0, cte =TRUE, Algorithm=2, OptimMethod="CG"){ I1=dim(X)[1] J=dim(X)[2] I2=dim(Y)[1] K=dim(Y)[2] I=I2 T=matrix(0, I1, S) U=matrix(0, I1, S) W=matrix(0, J, S) C=matrix(0, K, S) P=matrix(0, J, S) Q=matrix(0, K, S) freq=matrix(1,I,1) w=matrix(0,J,1) if (Algorithm==1){ t0=matrix(1, nrow=I, ncol=1) fit=RidgeBinaryLogistic(Y, t0, penalization=penalization, cte=FALSE) c0=fit$beta[1] for (j in 1:J){ x=as.matrix(X[,j]) fit=RidgeBinaryLogistic(Y, x, cte=TRUE) w[j]=fit$beta[2] } w=w/sqrt(sum(w^2)) t=X %*% w T[,1]=t W[,1]=w p=t(X) %*% t/ sum(t^2) P[,1]=p X1=X-t %*% t(p) for (i in 2:S){ for (j in 1:J){ x=as.matrix(cbind(T[,1:(i-1)],X[,j])) fit=RidgeBinaryLogistic(Y, x, cte=TRUE) w[j]=fit$beta[(i+1)] } w=w/sqrt(sum(w^2)) t=X1 %*% w T[,i]=t W[,i]=w p=t(X) %*% t/ sum(t^2) P[,i]=p X1=X1-t %*% t(p) } fit=RidgeBinaryLogistic(Y, T, penalization=penalization, cte=cte) } if (Algorithm==2){ t0=matrix(1, nrow=I, ncol=1) fit=RidgeBinaryLogistic(Y, t0, penalization=penalization, cte=FALSE) q0=fit$beta[1] for (i in 1:S){ error=1 iter=0 u= Y while ((error>tolerance) & (iter<maxiter)){ iter=iter+1 w=(t(X) %*% u)/sum(u^2) w=w/sqrt(sum(w^2)) t=X %*% w TT=cbind(t0, t) q=fit$beta[2] Q=c(q0, q) CostBinPLS1B(q , Y=Y, U=TT, Q=Q) resbipB <- optimr(q, fn=CostBinPLS1B, gr=grBinPLS1B, method=OptimMethod, Y=Y, U=TT, Q=Q) q=resbipB$par Q=c(c0, q) grBinPLS1A(u, Y=Y, U=TT, Q=Q) parA <- optimr(u, fn=CostBinPLS1A, gr=grBinPLS1A, method=OptimMethod, Y=Y, U=TT, Q=Q) newu=matrix(parA$par, ncol=1) error=sum((u-newu)^2) u=newu if (show) print(c(i, iter, error)) } T[,i]=t U[,i]=u W[,i]=w C[,i]=c Q[,i]=q p=t(X) %*% t/ sum(t^2) P[,i]=p X=X-t %*% t(p) } fit=RidgeBinaryLogistic(Y, T, penalization=penalization, cte=TRUE) } result=list(T=T, W=W, P=P, U=U, C=C, Q=Q, fit=fit) return(result) }