code
stringlengths
1
13.8M
library(OmicKriging) binaryFile <- system.file(package = "OmicKriging", "doc/vignette_data/ig_genotypes.grm.bin") binaryFileBase <- substr(binaryFile,1, nchar(binaryFile) - 4) expressionFile <- system.file(package = "OmicKriging", "doc/vignette_data/ig_gene_subset.txt.gz") phenotypeFile <- system.file(package = "OmicKriging", "doc/vignette_data/ig_pheno.txt") pheno <- read.table(phenotypeFile, header = T) grmMat <- read_GRMBin(binaryFileBase) gxmMat <- make_GXM(expFile = expressionFile) pcMatXM <- make_PCs_irlba(gxmMat, n.top = 10) pcMatGM <- make_PCs_irlba(grmMat, n.top = 10) pcMat <- cbind(pcMatGM, pcMatXM[match(rownames(pcMatGM), rownames(pcMatXM)),]) result <- krigr_cross_validation(pheno.df = pheno, cor.list = list(grmMat, gxmMat), h2.vec = c(0.5, 0.5), covar.mat = pcMat, ncore = 2, nfold = "LOOCV") allCon <- showConnections() socketCon <- as.integer(rownames(allCon)[allCon[, "class"] == "sockconn"]) sapply(socketCon, function(ii) close.connection(getConnection(ii)) )
library(aster) data(radish) options(digits=4) pred <- c(0,1,2) fam <- c(1,3,2) famlist <- fam.default() famlist[[2]] <- fam.negative.binomial(3.1415926526) rout <- try(reaster(resp ~ varb + fit : (Site * Region), list(block = ~ 0 + fit : Block, pop = ~ 0 + fit : Pop), pred, fam, varb, id, root, data = radish, famlist = famlist))
CUSUMfixed <- function(x,d,procedure,bandw,tau=0.15) { if(procedure != "CUSUMfixedb_typeA" & procedure != "CUSUMfixedb_typeB" & procedure != "CUSUMfixedm_typeA" & procedure != "CUSUMfixedm_typeB") stop("You misspecified which procedure to use") if((procedure == "CUSUMfixedb_typeA" | procedure == "CUSUMfixedb_typeB") & !(bandw %in% c(0.05,seq(0.1,1,0.1)))) stop("Use one of the following bandwidths: 0.05,0.1,0.2,0.3,...,0.9,1") if((procedure == "CUSUMfixedm_typeA" | procedure == "CUSUMfixedm_typeB") & !(bandw %in% c(1,2,3,4,10,25,50,100,150,200))) stop("Use one of the following bandwidths: 1,2,3,4,10,25,50,100,150,200") if (any(is.na(x))) stop("x contains missing values") if(tau<=0 | tau>=1) stop("It must hold that 0<tau<1") if (mode(x) %in% ("numeric") == FALSE | is.vector(x) == FALSE) stop("x must be a univariate numeric vector") if(tau!=0.15) warning("Critical values are just implemented for tau=0.15") T <- length(x) m <- bandw*T u_hat <- x-mean(x) cumulated <- cumsum(u_hat) sigma <- c() if(procedure=="CUSUMfixedb_typeA") sigma <- fb_longrun(u_hat,m) if(procedure=="CUSUMfixedb_typeB"){ for(k in ((T*tau):(T*(1-tau)))) {X <- cbind(rep(1,T),c(rep(0,round(k)),rep(1,round(T-k)))) reg <- stats::lm(x~X-1) u_hat2 <- unname(reg$residuals) sigm <- fb_longrun(u_hat2,m) sigma <- c(sigma,sigm)}} if(procedure=="CUSUMfixedm_typeA"){ m <- bandw sigma <- (2*pi/m)*sum(longmemo::per(u_hat)[2:(m+1)])} if(procedure=="CUSUMfixedm_typeB"){ m <- bandw for(k in ((T*tau):(T*(1-tau)))) {First <- c(rep(mean(x[1:k]),round(k)),rep(0,round(T-k))) Second <- c(rep(0,round(k)),rep(mean(x[(k+1):T]),round(T-k))) X_tilde <- x-First-Second sigma <- c(sigma,(2*pi/m)*sum(longmemo::per(X_tilde)[2:(m+1)]))}} crit_values <- CV_shift(d=d,procedure=procedure,param=bandw) testCUSUMfixedb_typeB <- max(abs(cumulated[((T*tau):(T*(1-tau)))]/(sqrt(T*sigma)))) result <- c(crit_values,testCUSUMfixedb_typeB) names(result) <- c("90%","95%","99%","Teststatistic") return(round(result,3)) }
PDEscatter=function(x,y,SampleSize,na.rm=FALSE,PlotIt=TRUE,ParetoRadius,sampleParetoRadius, NrOfContourLines=20,Plotter='native', DrawTopView = TRUE, xlab="X", ylab="Y", main="PDEscatter", xlim, ylim, Legendlab_ggplot="value"){ x=checkFeature(x,'x') y=checkFeature(y,'y') if(identical(x,y)){ stop('PDEscatter: Variable x is identical to variable y. Please check input.') } isnumber=function(x) return(is.numeric(x)&length(x)==1) if(missing(ParetoRadius)){ ParetoRadius =0 } if(!isnumber(ParetoRadius)) stop('PDEscatter: "ParetoRadius" is not a numeric number of length 1. Please change Input.') if(missing(SampleSize)){ SampleSize =-1 } if(missing(sampleParetoRadius)){ sampleParetoRadius=round(sqrt(500000000),-3) } if(!isnumber(SampleSize)) stop('PDEscatter: "SampleSize" is not a numeric number of length 1. Please change Input.') if(!isnumber(sampleParetoRadius)) stop('PDEscatter: "sampleParetoRadius" is not a numeric number of length 1. Please change Input.') if(!isnumber(NrOfContourLines)) stop('PDEscatter: "NrOfContourLines" is not a numeric number of length 1. Please change Input.') if(!is.logical(na.rm)) stop('PDEscatter: "na.rm" is expected to be either TRUE or FALSE') if(!is.logical(PlotIt)){ if(!(PlotIt==-1)) stop('PDEscatter: "PlotIt" is expected to be either TRUE, FALSE or -1.') } if(!is.logical(DrawTopView)) stop('PDEscatter: "DrawTopView" is expected to be either TRUE or FALSE') toRange=function (data, lower, upper) { data <- as.matrix(data) if (lower == upper) { stop("interval width can not be 0!") } if (lower > upper) { temp <- upper upper <- lower lower <- upper } range <- upper - lower n <- dim(data)[1] d <- dim(data)[2] if ((n == 1) & (d > 1)) { data <- t(data) wasRowVector <- 1 } else { wasRowVector <- 0 } nRow <- dim(data)[1] nCol <- dim(data)[2] min <- apply(data, 2, min, na.rm = TRUE) min <- matrix(min, nRow, nCol, byrow = TRUE) max <- apply(data, 2, max, na.rm = TRUE) max <- matrix(max, nRow, nCol, byrow = TRUE) range <- max - min range[range == 0] <- 1 scaleData <- (data - min)/range scaleData <- lower + scaleData * (upper - lower) if (wasRowVector == 1) { scaleData = t(scaleData) } return(scaleData) } if(isTRUE(na.rm)){ noNaNInd <- which(is.finite(x)&is.finite(y)) x = x[noNaNInd] y = y[noNaNInd] } nData <- length(x) if(SampleSize>0){ if (SampleSize<nData) { sampleInd=sample(1:nData,size = SampleSize) x=x[sampleInd] y=y[sampleInd] } } if(missing(xlim)) xlim = c(min(x,na.rm = T), max(x,na.rm = T)) if(missing(ylim)) ylim = c(min(y,na.rm = T), max(y,na.rm = T)) data <- cbind(x,y) percentdata <- toRange(data,0,100) nData <- length(x) if (sampleParetoRadius<nData) { par_sampleInd=sample(1:nData,size = sampleParetoRadius,replace = FALSE) sampleData4radius = percentdata[par_sampleInd,] } else { sampleData4radius = percentdata } if (!requireNamespace('parallelDist',quietly = TRUE)){ message('Subordinate package (parallelDist) is missing. No computations are performed. Please install the package which is defined in "Suggests". Falling back to dist().') DataDists = as.matrix(dist(sampleData4radius, method = 'euclidean', diag =TRUE)) Dists=as.vector(DataDists[upper.tri(DataDists,diag = F)]) }else{ Dists=parallelDist::parDist(sampleData4radius,method = 'euclidean',diag = F,upper = F) Dists=as.vector(Dists) } if(ParetoRadius <= 0){ if(nData<500){ ParetoRadius <- quantile(Dists, 6/100, type = 5, na.rm = TRUE) }else{ ParetoRadius <- c_quantile(Dists[is.finite(Dists)], 6/100) } if(ParetoRadius==0){ if(nData<500){ ParetoRadius <- quantile(Dists, 20/100, type = 5, na.rm = TRUE) }else{ ParetoRadius <- c_quantile(Dists[is.finite(Dists)], 20/100) } if(ParetoRadius==0){ stop(paste0('Estimation of Radius(',ParetoRadius,') for two-dimensional density not possible. Please provide ParetoRadius manually.')) }else{ warning(paste0('Estimation of Radius(',ParetoRadius,') for two-dimensional density may not work properly. You can provide ParetoRadius manually.')) } } } inPSpheres = inPSphere2D(percentdata, ParetoRadius) Matrix3D=cbind(x,y,inPSpheres) if(PlotIt==-1) return(list(X=x,Y=y,Densities=inPSpheres,Matrix3D=Matrix3D,ParetoRadius=ParetoRadius,Handle=NULL)) plt = zplot(x = x,y = y,z = inPSpheres,DrawTopView,NrOfContourLines, TwoDplotter = Plotter, xlim = xlim, ylim = ylim) if(DrawTopView){ switch(Plotter,'ggplot'={ plt <- plt + xlab(xlab) + ylab(ylab) + labs(title=main, fill=Legendlab_ggplot) + theme(panel.background = element_blank()) if(isTRUE(PlotIt)) print(plt) },'native'={ title(main = main, xlab = xlab, ylab = ylab) plt <- 'Native does not have a Handle' if(!isTRUE(PlotIt)) warning('for native plotting cannot be disabled') }, 'plotly'={ requireNamespace('plotly') plt <- plotly::layout(plt,xaxis= list(title=xlab), yaxis= list(title=ylab), title= main) if(isTRUE(PlotIt)) print(plt) }) }else{ switch(Plotter,'ggplot'={ print('Plotly plot is used because ggplot is not implemented for option DrawTopView=FALSE.') requireNamespace('plotly') plt <- plotly::layout(plt,scene=list(xaxis= list(title=xlab), yaxis= list(title=ylab),zaxis= list(title='PDE'), title= main)) if(isTRUE(PlotIt)) print(plt) },'native'={ print('Plotly plot is used because native is not implemented for option DrawTopView=FALSE.') requireNamespace('plotly') plt <- plotly::layout(plt,scene=list(xaxis= list(title=xlab), yaxis= list(title=ylab),zaxis= list(title='PDE'), title= main)) if(isTRUE(PlotIt)) print(plt) }, 'plotly'={ requireNamespace('plotly') plt <- plotly::layout(plt,scene=list(xaxis= list(title=xlab), yaxis= list(title=ylab),zaxis= list(title='PDE'), title= main)) if(isTRUE(PlotIt)) print(plt) }) } return(invisible(list(X=x,Y=y,Densities=inPSpheres,Matrix3D=Matrix3D,ParetoRadius=ParetoRadius,Handle=plt))) }
test_that("Full check of analyse_baSAR function", { skip_on_cran() local_edition(3) set.seed(1) data(ExampleData.BINfileData, envir = environment()) CWOSL.SAR.Data <- subset(CWOSL.SAR.Data, subset = POSITION %in% c(1:3) & LTYPE == "OSL") results <- suppressWarnings(analyse_baSAR( object = CWOSL.SAR.Data, source_doserate = c(0.04, 0.001), signal.integral = c(1:2), background.integral = c(80:100), fit.method = "EXP", method_control = list(inits = list( list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = 1), list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = 2), list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = 3) )), plot = TRUE, verbose = TRUE, n.MCMC = 100, txtProgressBar = TRUE )) expect_s4_class(results, class = "RLum.Results") expect_s3_class(results$summary, "data.frame") expect_s3_class(results$mcmc, "mcmc.list") expect_type(results$models, "list") expect_type(round(sum(results$summary[, c(6:9)]), 2),type = "double") })
install_dev <- function(package, cran_url = getOption("repos")[["CRAN"]], ...) { if (is.null(cran_url) || identical(cran_url, "@CRAN@")) { cran_url <- "https://cloud.r-project.org" } refs <- dev_split_ref(package) url <- build_url(cran_url, "web", "packages", refs[["pkg"]], "DESCRIPTION") f <- tempfile() on.exit(unlink(f)) download(f, url) desc <- read_dcf(f) url_fields <- c(desc$URL, desc$BugReports) if (length(url_fields) == 0) { stop("Could not determine development repository", call. = FALSE) } pkg_urls <- unlist(strsplit(url_fields, "[[:space:]]*,[[:space:]]*")) pkg_urls <- sub("/issues/?$", "", pkg_urls) valid_domains <- c("github[.]com", "gitlab[.]com", "bitbucket[.]org") parts <- re_match(pkg_urls, sprintf("^https?://(?<domain>%s)/(?<username>%s)/(?<repo>%s)(?:/(?<subdir>%s))?", domain = paste0(valid_domains, collapse = "|"), username = "[^/]+", repo = "[^/@ subdir = "[^/@$ ]+" ) )[c("domain", "username", "repo", "subdir")] parts <- unique(stats::na.omit(parts)) if (nrow(parts) != 1) { stop("Could not determine development repository", call. = FALSE) } full_ref <- paste0( paste0(c(parts$username, parts$repo, if (nzchar(parts$subdir)) parts$subdir), collapse = "/"), refs[["ref"]] ) switch(parts$domain, github.com = install_github(full_ref, ...), gitlab.com = install_gitlab(full_ref, ...), bitbucket.org = install_bitbucket(full_ref, ...) ) }
matricear <- function(string, maxdist = 1){ V2 <- c() if(maxdist==1){ V1<-deletion1(string) V1<-as.data.table(V1) V1<-V1[,V2 := string] } else if(maxdist==2){ V1<-deletion2(string) V1<-as.data.table(V1) V1<-V1[,V2 := string] } else if(maxdist==3){ V1<-deletion3(string) V1<-as.data.table(V1) V1<-V1[,V2 := string] } else{stop("Argument 'maxdist' out of range (1:3)")} V1 }
library(desctable) options(DT.options = list( info = F, search = F, dom = "Brtip", fixedColumns = T)) knitr::opts_chunk$set(message = F, warning = F, screenshot.force = F) iris %>% desctable() desctable(mtcars) iris %>% desctable() %>% pander() mtcars %>% desctable() %>% datatable() iris %>% desctable(stats = stats_auto) %>% datatable() mtcars %>% desctable(stats = list("N" = length, "Mean" = mean, "SD" = sd)) %>% datatable() iris %>% desctable(stats = list("N" = length, "%/Mean" = is.factor ~ percent | (is.normal ~ mean), "Median" = is.normal ~ NA | median)) %>% datatable() print(stats_auto) mtlabels <- c(mpg = "Miles/(US) gallon", cyl = "Number of cylinders", disp = "Displacement (cu.in.)", hp = "Gross horsepower", drat = "Rear axle ratio", wt = "Weight (1000 lbs)", qsec = "¼ mile time", vs = "V/S", am = "Transmission", gear = "Number of forward gears", carb = "Number of carburetors") mtcars %>% dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>% desctable(labels = mtlabels) %>% datatable() iris %>% group_by(Species) %>% desctable() -> iris_by_Species iris_by_Species str(iris_by_Species) mtcars %>% group_by(cyl) %>% desctable() %>% pander() iris %>% group_by(Petal.Length > 5) %>% desctable() %>% datatable() mtcars %>% dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>% group_by(vs, am, cyl) %>% desctable() %>% datatable() iris %>% group_by(Species) %>% desctable(tests = tests_auto) %>% datatable() iris %>% group_by(Petal.Length > 5) %>% desctable(tests = list(.auto = tests_auto, Species = ~chisq.test)) %>% datatable() mtcars %>% dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>% group_by(am) %>% desctable(tests = list(.default = ~wilcox.test, mpg = ~t.test)) %>% datatable() mtcars %>% desctable(stats = list("N" = length, "Sum of squares" = function(x) sum(x^2), "Q1" = . %>% quantile(prob = .25), "Q3" = purrr::partial(quantile, probs = .75))) %>% datatable() iris %>% group_by(Species) %>% desctable(tests = list(.auto = tests_auto, Sepal.Width = ~function(f) oneway.test(f, var.equal = F), Petal.Length = ~. %>% oneway.test(var.equal = T), Sepal.Length = ~purrr::partial(oneway.test, var.equal = T))) %>% datatable() library(survival) bladder$surv <- Surv(bladder$stop, bladder$event) bladder %>% group_by(rx) %>% desctable(tests = list(.default = ~wilcox.test, surv = ~. %>% survdiff %>% .$chisq %>% pchisq(1, lower.tail = F) %>% list(p.value = .))) %>% datatable()
test <- c(rep(1, 53), rep(0, 47)) truth <- c(rep(1, 20), rep(0, 33), rep(1, 10), rep(0, 37)) con_mat <- confusion_matrix(test, truth, positive = "1") test_that("Table is as expected", { expect_equivalent(unclass(con_mat$tab), matrix(c(20, 10, 33, 37), ncol = 1)) }) test_that("Sensitivity", { expect_equal(con_mat$stats["Sensitivity", 1], 20 / 30) }) test_that("Specificity", { expect_equal(con_mat$stats["Specificity", 1], 37 / 70) }) test_that("PPV", { expect_equal(con_mat$stats["PPV", 1], 20 / 53) }) test_that("NPV", { expect_equal(con_mat$stats["NPV", 1], 37 / 47) }) test_that("print confusion_matrix", { expect_output(print(con_mat), "Truth:\\ *truth") expect_output(print(con_mat), "Prediction:\\ *test") expect_output(print(con_mat), "Accuracy\\ *0.57") expect_output(print(con_mat), "NPV\\ *0.78") }) test_that("is confusion_matrix", { expect_true(is.confusion_matrix(con_mat)) }) test_that("errors for levels", { x <- sample(c("A", "B", "C"), 100, replace = TRUE) y <- sample(c("A", "B"), 100, replace = TRUE) expect_error(confusion_matrix(x, y)) x <- sample(c("A", "B"), 100, replace = TRUE) x <- factor(x, levels = c("B", "A")) y <- sample(c("A", "B"), 100, replace = TRUE) y <- factor(y, levels = c("B", "A")) expect_equal(attr(confusion_matrix(x, y), "positive") , "B") x <- factor(sample(c("C", "D"), 100, replace = TRUE)) expect_error(confusion_matrix(x, y)) })
test_that("subset RLum.Analysis", { testthat::skip_on_cran() local_edition(3) data("ExampleData.RLum.Analysis") temp <- IRSAR.RF.Data expect_s4_class(subset(temp), "RLum.Analysis") expect_length(subset(temp), length(temp)) expect_identical(subset(temp)[[1]], temp[[1]]) expect_error(subset(temp, LTYPE == "RF"), regexp = "Valid terms are") expect_null(subset(temp, recordType == "xx")) expect_s4_class(subset(temp, recordType == "RF"), class = "RLum.Analysis") expect_s4_class(subset(temp, recordType == "RF")[[1]], class = "RLum.Data.Curve") expect_length(subset(temp, recordType == "RF"), n = length(temp)) expect_s4_class(get_RLum(temp, subset = recordType == "RF"), class = "RLum.Analysis") expect_s4_class(get_RLum(temp, subset = recordType == "RF")[[1]], class = "RLum.Data.Curve") expect_length(get_RLum(temp, subset = recordType == "RF"), n = length(temp)) })
BetaModVar <- R6::R6Class( classname = "BetaModVar", lock_class = TRUE, inherit = ModVar, private = list( ), public = list( initialize = function(description, units, alpha, beta) { D <- BetaDistribution$new(alpha=alpha, beta=beta) super$initialize(description, units, D=D, k=as.integer(1)) return(invisible(self)) }, is_probabilistic = function() { return(TRUE) } ) )
plot.gpcm <- function (x, type = c("ICC", "IIC", "OCCu", "OCCl"), items = NULL, category = NULL, zrange = c(-3.8, 3.8), z = seq(zrange[1], zrange[2], length = 100), annot, labels = NULL, legend = FALSE, cx = "top", cy = NULL, ncol = 1, bty = "n", col = palette(), lty = 1, pch, xlab, ylab, main, sub = NULL, cex = par("cex"), cex.lab = par("cex.lab"), cex.main = par("cex.main"), cex.sub = par("cex.sub"), cex.axis = par("cex.axis"), plot = TRUE, ...) { if (!inherits(x, "gpcm")) stop("Use only with 'gpcm' objects.\n") type <- match.arg(type) betas <- x$coefficients nitems <- length(betas) ncatg <- sapply(betas, length) itms <- if (!is.null(items)) { if (!is.numeric(items) || length(items) > nitems) stop("'items' must be a numeric vector of length at most ", nitems) if (type == "ICC" && any(items < 1 | items > nitems)) stop("'items' must contain numbers between 1 and ", nitems, " denoting the items.\n") if (type == "IIC" && any(items < 0 | items > nitems)) stop("'items' must contain numbers between 0 and ", nitems) items } else 1:nitems ctg <- if (!is.null(category)) { if (length(category) > 1) stop("'category' must be a number indicating the category.\n") if (category < 0 || category > max(ncatg)) stop(paste("'category' must be a number between 1 and ", max(ncatg), ".\n", sep = "")) if (any(ind <- category > ncatg)){ if (sum(ind) > 1) warning("Items ", paste(items[ind], collapse = ", "), " are excluded since they have only ", paste(ncatg[ind], collapse = ", "), " categories, respectively.\n") else warning("Item ", items[ind], " is excluded since they have only ", ncatg[ind], " categories.\n") itms <- itms[!ind] } category } else "all" cpr <- switch(type, "ICC" = lapply(crf.GPCM(betas, z, x$IRT.param), t), "IIC" = infoGPCM(betas, z, x$IRT.param), "OCCl" = lapply(crf.GPCM(betas, z, x$IRT.param), function (x) { pp <- apply(x[-nrow(x), , drop = FALSE], 2, cumsum) if (NCOL(pp) == 1) as.matrix(pp) else t(pp) }), "OCCu" = lapply(crf.GPCM(betas, z, x$IRT.param), function (x) { pp <- apply(x[-nrow(x), , drop = FALSE], 2, cumsum) if (NCOL(pp) == 1) 1 - as.matrix(pp) else 1 - t(pp) }) ) plot.items <- type == "ICC" || (type == "IIC" & (is.null(items) || all(items > 0))) plot.info <- !plot.items if (missing(main)) { Main <- if (type == "ICC") { "Item Response Category Characteristic Curves" } else if (type == "OCCl" || type == "OCCu") { "Item Operation Characteristic Curves" } else { if (plot.items) "Item Information Curves" else "Test Information Function" } mis.ind <- TRUE } else mis.ind <- FALSE if (missing(ylab)) { ylab <- if (type == "ICC" || (type == "OCCl" | type == "OCCu")) "Probability" else "Information" } if (missing(xlab)) { xlab <- "Ability" } if (missing(annot)) { annot <- !legend } col. <- col lty. <- lty if (type == "ICC" || (type == "OCCl" | type == "OCCu")) { if (ctg == "all") { if (plot) { if (length(itms) > 1) { old.par <- par(ask = TRUE) on.exit(par(old.par)) } one.fig <- prod(par("mfcol")) == 1 for (i in seq(along = itms)) { ii <- itms[i] if (mis.ind) { main. <- if (one.fig) paste("- Item:", names(cpr)[ii]) else paste("\nItem:", names(cpr)[ii]) main <- paste(Main, main.) } plot(range(z), c(0, 1), type = "n", xlab = xlab, ylab = ylab, main = main, sub = sub, cex = cex, cex.lab = cex.lab, cex.main = cex.main, cex.axis = cex.axis, cex.sub = cex.sub, ...) p <- cpr[[ii]] pos <- round(seq(10, 90, length = ncol(p))) col <- rep(col., length.out = ncatg[ii]) lty <- rep(lty., length.out = ncatg[ii]) if (!missing(pch)) { pch <- rep(pch, length.out = ncatg[ii]) pch.ind <- round(seq(15, 85, length = 4)) } for (j in 1:ncol(p)) { lines(z, p[, j], lty = lty[j], col = col[j], ...) if (!missing(pch)) points(z[pch.ind], p[pch.ind, j], pch = pch[j], col = col[j], cex = cex, ...) if (annot) text(z[pos[j]], p[pos[j], j], adj = c(0, 1.2), if (missing(labels)) j else labels[j], col = col[j], cex = cex, ...) } if (legend) { ncol. <- if (is.null(ncol)) { if (is.factor(x$X[[ii]]) && any(nchar(levels(x$X[[ii]])) > 11)) 1 else ncatg[ii] %/% 2 } else ncol lab <- if (missing(labels)) { switch(type, "ICC" = if (is.factor(x$X[[i]])) levels(x$X[[ii]]) else 1:ncatg[ii], "OCCu" = paste(if (is.factor(x$X[[ii]])) levels(x$X[[ii]])[-1] else 2:ncatg[ii], "or higher"), "OCCl" = paste(if (is.factor(x$X[[ii]])) levels(x$X[[ii]])[-1] else 2:ncatg[ii], "or lower")) } else labels legend(cx, cy, legend = lab, lty = lty, pch = pch, col = col, bty = bty, ncol = ncol., cex = cex, ...) } } return.value <- list(z = z, pr = cpr[itms]) } else { return(list(z = z, pr = cpr[itms])) } } else { p <- sapply(cpr[itms], function (x, category) x[, category], category = ctg) if (plot) { one.fig <- prod(par("mfcol")) == 1 if (mis.ind) { main. <- if (one.fig) paste("- Category:", ctg) else paste("\nCategory:", ctg) main <- paste(Main, main.) } plot(range(z), c(0, 1), type = "n", xlab = xlab, ylab = ylab, main = main, sub = sub, cex = cex, cex.lab = cex.lab, cex.main = cex.main, cex.axis = cex.axis, cex.sub = cex.sub, ...) pos <- round(seq(10, 90, length = ncol(p))) col <- rep(col., length.out = length(itms)) lty <- rep(lty., length.out = length(itms)) if (!missing(pch)) { pch <- rep(pch, length.out = length(itms)) pch.ind <- round(seq(15, 85, length = 4)) } for (j in 1:ncol(p)) { lines(z, p[, j], lty = lty[j], col = col[j], ...) if (!missing(pch)) lines(z, p[, j], pch = pch[j], col = col[j], cex = cex, ...) if (annot) text(z[pos[j]], p[pos[j], j], adj = c(0, 1.2), if (missing(labels)) colnames(p)[j] else labels[j], col = col[j], cex = cex, ...) } if (legend) { ncol. <- if (is.null(ncol)) { if (any(nchar(colnames(p)) > 11)) 1 else length(items) %/% 2 } else ncol lab <- if (missing(labels)) colnames(p) else labels legend(cx, cy, legend = lab, lty = lty, pch = pch, col = col, bty = bty, ncol = ncol., cex = cex, ...) } return.value <- cbind(z = z, pr = p) } else { return(cbind(z = z, pr = p)) } } } else { p <- cpr[, itms, drop = FALSE] if (plot) { r <- if (plot.items) range(p) else range(rowSums(cpr)) if (mis.ind) { main <- Main } plot(range(z), r, type = "n", xlab = xlab, ylab = ylab, main = main, sub = sub, cex = cex, cex.lab = cex.lab, cex.main = cex.main, cex.axis = cex.axis, cex.sub = cex.sub, ...) if (plot.items) { col <- rep(col., length.out = length(itms)) lty <- rep(lty., length.out = length(itms)) if (!missing(pch)) { pch <- rep(pch, length.out = length(itms)) pch.ind <- round(seq(15, 85, length = 4)) } pos <- round(seq(10, 90, length = ncol(p))) for (i in seq(along = itms)) { lines(z, p[, i], lty = lty[i], col = col[i], ...) if (!missing(pch)) points(z[pch.ind], p[pch.ind, i], pch = pch[i], col = col[i], cex = cex, ...) if (annot) text(z[pos[i]], p[pos[i], i], adj = c(0, 1.2), if (missing(labels)) i else labels[i], col = col[i], cex = cex, ...) } if (legend) { ncol. <- if (is.null(ncol)) ncol. <- if (nitems > 8) 2 else 1 else ncol legend(cx, cy, legend = if (missing(labels)) colnames(cpr)[itms] else labels, lty = lty, pch = pch, col = col, bty = bty, ncol = ncol., cex = cex, ...) } } else { col <- col.[1] lty <- lty.[1] p <- rowSums(cpr) lines(z, p, lty = lty, col = col, ...) if (!missing(pch)) points(z, p, pch = pch, col = col, cex = cex, ...) if (legend) legend(cx, cy, legend = "Information", lty = lty, col = col, pch = pch, bty = bty, ncol = 1, ...) } return.value <- if (plot.items) cbind(z = z, item.info = p) else cbind(z = z, test.info = p) } else { return(if (plot.items) cbind(z = z, item.info = p) else cbind(z = z, test.info = rowSums(cpr))) } } invisible(return.value) }
source("inst/fannie_mae_10pct/00_setup.r") library(disk.frame) library(xgboost) acqall_dev = disk.frame(file.path(outpath, "appl_mdl_data_sampled")) add_var_to_scorecard = disk.frame:::add_var_to_scorecard check_which_is_best <- function(df, target, features, monotone_constraints, format_fns, weight=NULL) { prev_pred = NULL ws = NULL vars_scr = NULL while(length(features) > 0) { res = furrr::future_map(1:length(features), ~add_var_to_scorecard( df, target, features[.x], monotone_constraints = monotone_constraints[.x], prev_pred = prev_pred, format_fn = format_fns[[.x]], weight, save_model_fname = glue::glue("{features[.x]}.xgbm") )) w = which.max(map_dbl(res, ~.x$auc)) ws = c(ws, w) feature_to_fit = features[w] print(glue::glue("choosen: {feature_to_fit}")) var_scr1 = res[[w]] eval(parse(text = glue::glue("vars_scr = c(vars_scr, list({feature_to_fit} = var_scr1))"))) features = features[-w] format_fns = format_fns[-w] monotone_constraints = monotone_constraints[-w] prev_pred = var_scr1$prev_pred } vars_scr } num_vars = c("mi_pct", "orig_amt", "orig_rt", "ocltv", "mi_type", "cscore_c", "oltv", "dti", "orig_trm", "cscore_b", "num_bo", "num_unit", "orig_dte", "frst_dte") num_vars_mon = c(0 , 1 , 1 , 1 , 0 , -1 , 1 , 1 , 1 , -1 , -1 , 0 , 0 , 0) num_var_fmt_fn = c(map(1:10, ~base::I), map(1:2, ~as.numeric), map(1:2, ~function(x) { as.numeric(substr(x, 4, 7)) })) cat_vars = setdiff(names(acqall_dev), num_vars) %>% setdiff( c("loan_id", "default_next_12m", "first_default_date", "mths_to_1st_default", "zip_3", "weight")) pt = proc.time() res_all = check_which_is_best( acqall_dev, "default_next_12m", features = c(num_vars, cat_vars), monotone_constraints = c(num_vars_mon, rep(0, length(cat_vars))), format_fns = c(num_var_fmt_fn, map(1:length(cat_vars), ~base::I)), weight = "weight" ) timetaken(pt) plot(map_dbl(res_all, ~.x$auc)) if(F) { rescat = check_which_is_best( acqall_dev, "default_next_12m", c("seller.name", "oltv", "state", "dti", "mi_type"), c(0 , 1 , 0 , 1 , 0 ), map(1:5, ~base::I) ) system.time(res <- check_which_is_best( acqall1, "default_next_12m", c("ocltv", "cscore_c", "mi_type", "oltv", "dti", "orig_trm", "cscore_b", "num_bo"), c(1 , -1 , 0 , 1 , 1 , 1 , -1 , -1 ), c(map(1:7, ~base::I), list(as.numeric)))) }
mdmb_regression_adjustment_differentiation_parameter <- function(h, par ) { abs_par <- abs(par) hvec <- h * ifelse(abs_par > 1, abs_par, 1) return(hvec) }
me_ <- nm_fun("TEST-range_write") test_that("range_write() works", { skip_if_offline() skip_if_no_token() n <- 3 m <- 5 data <- suppressMessages( tibble::as_tibble( matrix(head(letters, n * m), nrow = n , ncol = m), .name_repair = "unique" ) ) ss <- local_ss(me_(), sheets = list(foo = data)) range_write(ss, data[3:2, ]) props <- sheet_properties(ss) expect_equal(props$grid_rows, n + 1) expect_equal(props$grid_columns, m) df <- read_sheet(ss) expect_identical(df[1, ], df[3, ]) range_write(ss, data, range = "foo!F5") props <- sheet_properties(ss) expect_equal(props$grid_rows, (5 - 1) + n + 1) expect_equal(props$grid_columns, (which(LETTERS == "F") - 1) + m) df <- read_sheet(ss, range = cell_cols(c("F", NA))) expect_equal(df, data) range_write(ss, data[1:3], sheet = "foo", range = "I2:K5") props <- sheet_properties(ss) expect_equal(props$grid_columns, (which(LETTERS == "K"))) df <- read_sheet(ss, range = "I2:K5") expect_equal(df, data[1:3]) }) test_that("we can write a hole-y tibble containing NULLs", { skip_if_offline() skip_if_no_token() dat_write <- tibble::tibble(A = list(NULL, "HI"), B = month.abb[1:2]) ss <- local_ss(me_("write-NULL"), sheets = dat_write) write_sheet(dat_write, ss, sheet = 1) dat_read <- read_sheet(ss) expect_equal(dat_read$A, c(NA, "HI")) expect_equal(dat_read$B, dat_write$B) dat_read <- read_sheet(ss, col_types = "Lc") expect_equal(dat_read$A, dat_write$A) expect_equal(dat_read$B, dat_write$B) }) test_that("prepare_loc() makes the right call re: `start` vs. `range`", { expect_loc <- function(x, loc) { sheets_df <- tibble::tibble(name = "Sheet1", index = 0, id = 123) out <- prepare_loc(as_range_spec(x, sheets_df = sheets_df)) expect_named(out, loc) } expect_loc(NULL, "start") expect_loc("Sheet1", "start") expect_loc("D4", "start") expect_loc("B5:B5", "start") expect_loc(cell_limits(c(5, 2), c(5, 2)), "start") expect_loc("B4:G9", "range") expect_loc("A2:F", "range") expect_loc("A2:5", "range") expect_loc("C:E", "range") expect_loc("5:7", "range") expect_loc(cell_limits(c(2, 4), c(NA, NA)), "range") }) test_that("prepare_dims() works when write_loc is a `start` (a GridCoordinate)", { n <- 3 m <- 5 data <- suppressMessages( tibble::as_tibble( matrix(head(letters, n * m), nrow = n , ncol = m), .name_repair = "unique" ) ) expect_dims <- function(loc, col_names, dims) { expect_equal(prepare_dims(loc, data, col_names = col_names), dims) } loc <- list(start = new("GridCoordinate", sheetId = 123)) expect_dims(loc, col_names = TRUE, list(nrow = n + 1, ncol = m)) expect_dims(loc, col_names = FALSE, list(nrow = n, ncol = m)) loc <- list(start = new("GridCoordinate", sheetId = 123, rowIndex = 2)) expect_dims(loc, col_names = TRUE, list(nrow = 2 + n + 1, ncol = m)) expect_dims(loc, col_names = FALSE, list(nrow = 2 + n, ncol = m)) loc <- list(start = new("GridCoordinate", sheetId = 123, columnIndex = 3)) expect_dims(loc, col_names = TRUE, list(nrow = n + 1, ncol = 3 + m)) expect_dims(loc, col_names = FALSE, list(nrow = n, ncol = 3 + m)) loc <- list( start = new("GridCoordinate", sheetId = 123, rowIndex = 2, columnIndex = 3) ) expect_dims(loc, col_names = TRUE, list(nrow = 2 + n + 1, ncol = 3 + m)) expect_dims(loc, col_names = FALSE, list(nrow = 2 + n, ncol = 3 + m)) }) test_that("prepare_dims() works when write_loc is a `range` (a GridRange)", { n <- 3 m <- 5 data <- suppressMessages( tibble::as_tibble( matrix(head(letters, n * m), nrow = n , ncol = m), .name_repair = "unique" ) ) expect_dims <- function(x, col_names, dims) { sheets_df <- tibble::tibble(name = "Sheet1", index = 0) loc <- prepare_loc(as_range_spec(x, sheets_df = sheets_df)) expect_equal(prepare_dims(loc, data, col_names = col_names), dims) } expect_dims("B4:G9", col_names = TRUE, list(nrow = 9, ncol = which(LETTERS == "G"))) expect_dims("B4:G9", col_names = FALSE, list(nrow = 9, ncol = which(LETTERS == "G"))) expect_dims("B3:D", col_names = TRUE, list(nrow = 2 + n + 1, ncol = which(LETTERS == "D"))) expect_dims("B3:D", col_names = FALSE, list(nrow = 2 + n , ncol = which(LETTERS == "D"))) expect_dims("C3:5", col_names = TRUE, list(nrow = 5, ncol = which(LETTERS == "C") + m - 1)) expect_dims("C3:5", col_names = FALSE, list(nrow = 5, ncol = which(LETTERS == "C") + m - 1)) expect_dims("5:7", col_names = TRUE, list(nrow = 7, ncol = m)) expect_dims("5:7", col_names = FALSE, list(nrow = 7, ncol = m)) expect_dims("B:H", col_names = TRUE, list(nrow = n + 1, ncol = which(LETTERS == "H"))) expect_dims("B:H", col_names = FALSE, list(nrow = n, ncol = which(LETTERS == "H"))) expect_dims( cell_limits(c(2, 4), c(NA, NA)), col_names = TRUE, list(nrow = 2 + n + 1 - 1, ncol = 4 + m - 1) ) expect_dims( cell_limits(c(2, 4), c(NA, NA)), col_names = FALSE, list(nrow = 2 + n - 1, ncol = 4 + m - 1) ) })
match_tree_edges <- function(original_tree, pruned_tree) { n_pruned_tips <- ape::Ntip(phy = pruned_tree) n_pruned_nodes <- ape::Nnode(phy = pruned_tree) if (n_pruned_tips < 3) stop("pruned_tree includes too few (<3) taxa to be used.") if (length(x = setdiff(x = pruned_tree$tip.label, y = original_tree$tip.label)) > 0) stop("pruned_tree cannot include taxa not present in original_tree.") removed_taxa <- setdiff(x = original_tree$tip.label, y = pruned_tree$tip.label) if (length(x = removed_taxa) == 0) { removed_edges <- numeric(0) matching_edges <- as.list(x = 1:nrow(original_tree$edge)) clades <- corresponding_nodes <- c((n_pruned_tips + 1):(n_pruned_tips + n_pruned_nodes), 1:n_pruned_tips) } else { clades <- vector(mode = "character") for (i in (n_pruned_tips + 1):(n_pruned_tips + n_pruned_nodes)) { clades <- c(clades, paste(pruned_tree$tip.label[strap::FindDescendants(n = i, tree = pruned_tree)], collapse = "%%SpLiTtEr%%")) names(clades)[length(x = clades)] <- i } corresponding_nodes <- vector(mode = "numeric") for (i in clades) corresponding_nodes <- c(corresponding_nodes, find_mrca(descendant_names = strsplit(i, "%%SpLiTtEr%%")[[1]], tree = original_tree)) corresponding_nodes <- c(corresponding_nodes, match(pruned_tree$tip.label, original_tree$tip.label)) clades <- c(as.numeric(names(clades)), 1:n_pruned_tips) pruned_edges <- cbind(corresponding_nodes[match(pruned_tree$edge[, 1], clades)], corresponding_nodes[match(pruned_tree$edge[, 2], clades)]) matching_edges <- match(apply(pruned_edges, 1, paste, collapse = "%%"), apply(original_tree$edge, 1, paste, collapse = "%%")) nonmatching_edges <- pruned_edges[is.na(matching_edges), ] if (length(x = nonmatching_edges) > 0) { if (!is.matrix(nonmatching_edges)) nonmatching_edges <- matrix(nonmatching_edges, ncol = 2) for (i in 1:nrow(nonmatching_edges)) { start_node <- nonmatching_edges[i, 1] end_node <- nonmatching_edges[i, 2] edges <- match(end_node, original_tree$edge[, 2]) while (length(x = sort(x = match(original_tree$edge[edges, 1], start_node))) == 0) { end_node <- original_tree$edge[match(end_node, original_tree$edge[, 2]), 1] edges <- c(edges, match(end_node, original_tree$edge[, 2])) } matching_edges[which(x = is.na(matching_edges))[1]] <- paste(rev(edges), collapse = "%%") } matching_edges <- lapply(X = strsplit(matching_edges, "%%"), as.numeric) } else { matching_edges <- as.list(x = matching_edges) } removed_edges <- setdiff(x = 1:nrow(original_tree$edge), y = as.numeric(unlist(x = matching_edges))) } names(matching_edges) <- 1:nrow(pruned_tree$edge) node_matches <- cbind(pruned_node = clades, original_node = corresponding_nodes) list(matching_edges = matching_edges, matching_nodes = node_matches, removed_edges = removed_edges) }
as.data.frame.light.edsurvey.data.frame <- function(x, ...) { res <- x atrs <- names(attributes(x)) atrs <- atrs[!atrs %in% c("names", "row.names", "class")] for(z in atrs) { attr(res, z) <- NULL } class(res) <- "data.frame" res }
plsim.vs.hard = function(...) { args = list(...) if (is(args[[1]],"formula")) UseMethod("plsim.vs.hard",args[[1]]) else UseMethod("plsim.vs.hard") } plsim.vs.hard.formula = function(formula,data,...) { mf = match.call(expand.dots = FALSE) m = match(c("formula","data"), names(mf), nomatch = 0) mf = mf[c(1,m)] mf.xf = mf mf[[1]] = as.name("model.frame") mf.xf[[1]] = as.name("model.frame") chromoly = deal_formula(mf[["formula"]]) if (length(chromoly) != 3) stop("invoked with improper formula, please see plsim.vs.hard documentation for proper use") bronze = lapply(chromoly, paste, collapse = " + ") mf.xf[["formula"]] = as.formula(paste(" ~ ", bronze[[2]]), env = environment(formula)) mf[["formula"]] = as.formula(paste(bronze[[1]]," ~ ", bronze[[3]]), env = environment(formula)) formula.all = terms(as.formula(paste(" ~ ",bronze[[1]]," + ",bronze[[2]], " + ",bronze[[3]]), env = environment(formula))) orig.class = if (missing(data)) sapply(eval(attr(formula.all, "variables"), environment(formula.all)),class) else sapply(eval(attr(formula.all, "variables"), data, environment(formula.all)),class) arguments.mfx = chromoly[[2]] arguments.mf = c(chromoly[[1]],chromoly[[3]]) mf[["formula"]] = terms(mf[["formula"]]) mf.xf[["formula"]] = terms(mf.xf[["formula"]]) if(all(orig.class == "ts")){ arguments = (as.list(attr(formula.all, "variables"))[-1]) attr(mf[["formula"]], "predvars") = bquote(.(as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), arguments)))))[,.(match(arguments.mf,arguments)),drop = FALSE]) attr(mf.xf[["formula"]], "predvars") = bquote(.(as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), arguments)))))[,.(match(arguments.mfx,arguments)),drop = FALSE]) }else if(any(orig.class == "ts")){ arguments = (as.list(attr(formula.all, "variables"))[-1]) arguments.normal = arguments[which(orig.class != "ts")] arguments.timeseries = arguments[which(orig.class == "ts")] ix = sort(c(which(orig.class == "ts"),which(orig.class != "ts")),index.return = TRUE)$ix attr(mf[["formula"]], "predvars") = bquote((.(as.call(c(quote(cbind),as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), arguments.timeseries)))),arguments.normal,check.rows = TRUE)))[,.(ix)])[,.(match(arguments.mf,arguments)),drop = FALSE]) attr(mf.xf[["formula"]], "predvars") = bquote((.(as.call(c(quote(cbind),as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), arguments.timeseries)))),arguments.normal,check.rows = TRUE)))[,.(ix)])[,.(match(arguments.mfx,arguments)),drop = FALSE]) } mf = tryCatch({ eval(mf,parent.frame()) },error = function(e){ NULL }) mf.xf = tryCatch({ eval(mf.xf,parent.frame()) },error = function(e){ NULL }) if(is.null(mf)){ cat( blue$bold("\n Z (") %+% black$bold("z") %+% blue$bold(") should not be NULL.\n") %+% blue$bold(" If Z is null, please utilize linear models, such as ") %+% black$bold("lm() ") %+% blue$bold("function. \n\n") ) return(NULL) } else{ ydat = model.response(mf) } xdat = mf.xf zdat = mf[, chromoly[[3]], drop = FALSE] ydat = data.matrix(ydat) if(!is.null(xdat) & is.null(dim(xdat[,1]))){ xdat = data.matrix(xdat) } else if(!is.null(dim(xdat[,1]))){ xdat = xdat[,1] } if(is.null(dim(zdat[,1]))){ zdat = data.matrix(zdat) } else{ zdat = zdat[,1] } res = plsim.vs.hard(xdat = xdat, zdat = zdat, ydat = ydat, ...) return(res) } plsim.vs.hard.default = function(xdat=NULL,zdat,ydat,h=NULL,zeta_i=NULL,lambdaList=NULL, l1RatioList=NULL,lambda_selector="BIC",threshold=0.05, Method="SCAD",verbose=TRUE,ParmaSelMethod="SimpleValidation",seed=0,...) { n = nrow(y) data = list(x=xdat,y=ydat,z=zdat) x = data$x y = data$y z = data$z if ( is.null( .assertion_for_variables(data)) ) return(NULL) if(is.data.frame(x)) x = data.matrix(x) if(is.data.frame(z)) z = data.matrix(z) if(is.data.frame(y)) y = data.matrix(y) if(is.null(zeta_i)) { if(verbose) zeta_i = plsim.ini(x,z,y,verbose=verbose) } if(Method %in% c('SCAD','LASSO','ElasticNet') ) { class(data) = 'PPLSE' } else if(Method %in% c('AIC','BIC') ) { class(data) = 'StepWise' } else { Method = "SCAD" class(data) = 'PPLSE' } if( !is.null(h) & length(h)==1 ) { res = varSelCore(data,h,zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag=FALSE,ParmaSelMethod,seed) } else if( is.vector(h) & length(h) > 1 ) { hVec = h BIC_best = 1000 res = NULL for(j in 1:length(hVec)) { if(verbose) { cat( blue$bold("\n----------Variable Selection when h=") %+% blue$bold(as.character(hVec[j])) %+% blue$bold("----------\n\n") ) } res_tmp = varSelCore(data,hVec[j],zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag = TRUE,ParmaSelMethod,seed) if(verbose) { cat( "BIC: "%+%blue$bold(as.character(res_tmp$fit_plsimest$BIC))) } if(res_tmp$fit_plsimest$BIC < BIC_best) { res = res_tmp BIC_best = res_tmp$fit_plsimest$BIC } } } else if( is.null(h) ) { hVec = seq(0.1/sqrt(n),2*sqrt(log(n)/n),length=20) BIC_best = 1000 res = NULL for(j in 1:length(hVec)) { if(verbose) { cat( blue$bold("\n----------Variable Selection when h=") %+% blue$bold(as.character(hVec[j])) %+% blue$bold("----------\n\n") ) } res_tmp = varSelCore(data,hVec[j],zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag = TRUE,ParmaSelMethod,seed) if(is.null(res_tmp)) return(NULL) if(verbose) { cat( " BIC: "%+%blue$bold(as.character(res_tmp$fit_plsimest$BIC))) cat("\n") } if(res_tmp$fit_plsimest$BIC < BIC_best) { res = res_tmp BIC_best = res_tmp$fit_plsimest$BIC } } } return(res) } varSelCore=function(data,h,zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag,ParmaSelMethod,seed) { UseMethod("varSelCore") } varSelCore.PPLSE=function(data,h,zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag,ParmaSelMethod,seed,...) { x = data$x z = data$z y = data$y n = nrow(y) if(is.null(x)) { dx = 0 } else { dx = ncol(x) } dz = ncol(z) res = plsim.lam(x,y,z,h,zeta_i,Method,lambdaList,l1RatioList,lambda_selector,verbose,seed) if(is.null(res)) return(NULL) plsim_result = plsim.vs.soft(x,z,y,h,zeta_i,res$lambda_best,l1RatioList,1,Method,verbose,ParmaSelMethod,seed=seed) if(is.null(plsim_result)) return(NULL) alpha = plsim_result$zeta[1:dz] if(!is.null(x)) { beta = plsim_result$zeta[(dz+1):(dz+dx)] } alpha_norm = abs(alpha)/max(abs(alpha)) if(!is.null(x)) { beta_norm = abs(beta)/max(abs(beta)) } alpha_eliminated = which(alpha_norm<threshold) if(!is.null(x)) { beta_eliminated = which(beta_norm<threshold) } res_alpha_sorted = sort.int(alpha_norm,index.return = TRUE,decreasing = TRUE) if(!is.null(x)) { res_beta_sorted = sort.int(beta_norm,index.return = TRUE,decreasing = TRUE) } alpha_varSel = setdiff(res_alpha_sorted$ix,alpha_eliminated) if(!is.null(x)) { beta_varSel = setdiff(res_beta_sorted$ix,beta_eliminated) } if(verbose) { cat( blue$bold("\n Important varaibles in Z are") ,paste(black$bold(alpha_varSel),collapse = ","),sep = ": ") } if(!is.null(x)) { if( length(beta_varSel) > 0 ) { if(verbose) { cat(blue$bold("\n Important varaibles in X are"), paste(black$bold(beta_varSel),collapse = ","),sep = ": ") } } } if(verbose) cat("\n") if(!is.null(x)) { result = list(alpha_varSel=alpha_varSel,beta_varSel=beta_varSel) } else { result = list(alpha_varSel=alpha_varSel) } if(flag) { if(is.null(x)) { x_vs = NULL } else { if(length(beta_varSel) > 1) { x_vs = x[,beta_varSel] } else if(length(beta_varSel) == 1) { x_vs = matrix(x[,beta_varSel]) } else { x_vs = NULL } } if(length(alpha_varSel) > 1) { z_vs = z[,alpha_varSel] } else if( length(alpha_varSel) == 1) { z_vs = matrix(z[,alpha_varSel]) } else { z_vs = NULL } fit_plsimest = plsim.est(x_vs, z_vs, y, ParmaSelMethod = ParmaSelMethod, seed=seed,verbose=verbose) if( !is.null(fit_plsimest)) { fit_plsimest$BIC = .IC(fit_plsimest$mse,sum(fit_plsimest$zeta!=0),n,"BIC") result$fit_plsimest = fit_plsimest } else { fit_plsimest = list(BIC=10000) result$fit_plsimest = fit_plsimest } } return(result) } varSelCore.StepWise=function(data,h,zeta_i,verbose,lambdaList,l1RatioList, lambda_selector,threshold,Method,flag,ParmaSelMethod,seed) { x = data$x z = data$z y = data$y n = nrow(y) if(is.null(x)) { dx = 0 } else { dx = ncol(x) colnames(x) = 1:dx } dz = ncol(z) colnames(z) = 1:dz res = stepWise(data,h,zeta_i,Method,seed,verbose) if(flag) { if(is.null(x)) { x_vs = NULL } else { if(length(res$beta_varSel) > 1) { x_vs = x[,res$beta_varSel] } else { x_vs = matrix(x[,res$beta_varSel]) } } if(length(res$alpha_varSel) > 1) { z_vs = z[,res$alpha_varSel] } else { z_vs = matrix(z[,res$alpha_varSel]) } fit_plsimest = plsim.est(x_vs, z_vs, y,seed=seed) fit_plsimest$BIC = .IC(fit_plsimest$mse,sum(fit_plsimest$zeta!=0),n,"BIC") res$fit_plsimest = fit_plsimest } return(res) } stepWise=function(data,h,zeta_i,Method="BIC",seed,verbose) { x = data$x z = data$z y = data$y n = nrow(y) if(is.null(x)) { dx = 0 } else { dx = ncol(x) } dz = ncol(z) if(!is.null(x)) { colnames(x) = 1:dx } colnames(z) = 1:dz res = plsim.est(x,z,y,h,zeta_i,seed=seed) zeta = res$zeta mse = res$mse df = sum(zeta!=0) IC_all = .IC(mse,df,n,Method) while (TRUE) { res = dropOneVar(x,y,z,h,zeta_i,Method,seed) IC_tmp = res$IC Component = res$Component Idx = res$Idx if(IC_tmp < IC_all) { IC_all = IC_tmp if(Component == "X") { if(ncol(x) == 1) { x = NULL } else if(ncol(x) == 2) { x = matrix(x[,-Idx]) } else { x = x[,-Idx] } zeta_i = zeta_i[-(ncol(z)+Idx)] } else { if(ncol(z) == 2) { z = matrix(z[,-Idx]) } else { z = z[,-Idx] } zeta_i = zeta_i[-Idx] } } else { break } if(!is.null(x)) { if(verbose) { cat('\nSelected X:') cat(paste(colnames(x),collapse = ',')) cat('\n') } } if(verbose) { cat('\nSelected Z:') cat(paste(colnames(z),collapse = ',')) cat('\n\n') } } result = list() if(!is.null(x)) { result$beta_varSel = colnames(x) } result$alpha_varSel = colnames(z) return(result) } dropOneVar=function(x,y,z,h,zeta_i,Method="BIC",seed) { n = nrow(y) dz = ncol(z) if(is.null(x)) { dx = 0 } else { dx = ncol(x) } X_IC_list = c() i = 1 while( i <= dx ) { if(dx == 1) { x_tmp = NULL } if(dx == 2) { x_tmp = matrix(x[,-i]) } else { x_tmp = x[,-i] } zeta_tmp = zeta_i[-(dz+i)] res = plsim.est(x_tmp,z,y,h,zeta_tmp,seed=seed) zeta = res$zeta mse = res$mse df = sum(zeta!=0) X_IC_list[i] = .IC(mse,df,n,Method) i = i + 1 } if(!is.null(x)) { X_IC_min = min(X_IC_list) X_IC_min_Idx = which.min(X_IC_list) } else { X_IC_min = 10000 } Z_IC_list = c() i = 1 while( (i <= dz) & (dz > 1) ) { if(dz == 2) { z_tmp = matrix(z[,-i]) } else { z_tmp = z[,-i] } zeta_tmp = zeta_i[-i] res = plsim.est(x,z_tmp,y,h,zeta_tmp,seed=seed) zeta = res$zeta mse = res$mse df = sum(zeta!=0) Z_IC_list[i] = .IC(mse,df,n,Method) i = i + 1 } Z_IC_min = min(Z_IC_list) Z_IC_min_Idx = which.min(Z_IC_list) result = list() if(X_IC_min < Z_IC_min) { result$IC = X_IC_min result$Component = "X" result$Idx = X_IC_min_Idx } else { result$IC = Z_IC_min result$Component = "Z" result$Idx = Z_IC_min_Idx } class(result) = "pls" return(result) }
core_repos <- function(id, key = NULL, method = "GET", parse = TRUE, ...) { core_parse(core_repos_(id, key, method, ...), parse) } core_repos_ <- function(id, key = NULL, method = "GET", ...) { if (!method %in% c('GET', 'POST')) { stop("'method' must be one of 'GET' or 'POST'", call. = FALSE) } switch( method, `GET` = { if (length(id) > 1) stop("'id' must be of length 1 when 'method=GET'", call. = FALSE) core_GET(path = paste0("repositories/get/", id), key, list(), ...) }, `POST` = core_POST(path = "repositories/get", key, list(), id, ...) ) }
future_by <- function(data, INDICES, FUN, ..., simplify = TRUE, future.envir = parent.frame()) { future.envir <- force(future.envir) UseMethod("future_by") } future_by.default <- function(data, INDICES, FUN, ..., simplify = TRUE, future.envir = parent.frame()) { ndim <- length(dim(data)) .SUBSETTER <- if (ndim == 0L) { function(row) data[row, , drop = TRUE] } else { function(row) data[row, , drop = FALSE] } data <- as.data.frame(data) future_by_internal(data = data, INDICES = INDICES, FUN = FUN, ..., simplify = simplify, .INDICES.NAME = deparse(substitute(INDICES))[1L], .CALL = match.call(), .SUBSETTER = .SUBSETTER, future.envir = future.envir) } future_by.data.frame <- function(data, INDICES, FUN, ..., simplify = TRUE, future.envir = parent.frame()) { future_by_internal(data = data, INDICES = INDICES, FUN = FUN, ..., simplify = simplify, .INDICES.NAME = deparse(substitute(INDICES))[1L], .CALL = match.call(), .SUBSETTER = function(row) data[row, , drop = FALSE], future.envir = future.envir) } future_by_internal <- function(data, INDICES, FUN, ..., simplify = TRUE, .SUBSETTER, .CALL, .INDICES.NAME, future.envir = parent.frame(), future.label = "future_by-%d") { FUN <- if (!is.null(FUN)) match.fun(FUN) stop_if_not(is.function(.SUBSETTER)) if (!is.list(INDICES)) { INDEX <- vector("list", length = 1L) INDEX[[1L]] <- INDICES names(INDEX) <- .INDICES.NAME INDICES <- INDEX INDEX <- NULL } INDICES <- lapply(INDICES, FUN = as.factor) nI <- length(INDICES) if (!nI) stop("'INDICES' is of length zero") nd <- nrow(data) if (!all(lengths(INDICES) == nd)) { stop("All elements of argument 'INDICES' must have same length as 'data'") } namelist <- lapply(INDICES, FUN = levels) extent <- lengths(namelist, use.names = FALSE) cumextent <- cumprod(extent) if (cumextent[nI] > .Machine$integer.max) stop("total number of levels >= 2^31") storage.mode(cumextent) <- "integer" ngroup <- cumextent[nI] group <- as.integer(INDICES[[1L]]) if (nI > 1L) { for (i in 2L:nI) { group <- group + cumextent[i - 1L] * (as.integer(INDICES[[i]]) - 1L) } } cumextent <- NULL levels(group) <- as.character(seq_len(ngroup)) class(group) <- "factor" ans <- split(seq_len(nd), f = group) names(ans) <- NULL index <- as.logical(lengths(ans) > 0L) group <- NULL grouped_data <- lapply(X = ans[index], FUN = .SUBSETTER) ans <- future_lapply(X = grouped_data, FUN = FUN, ..., future.envir = future.envir, future.label = future.label) grouped_data <- NULL ansmat <- array({ if (simplify && all(lengths(ans) == 1L)) { ans <- unlist(ans, recursive = FALSE, use.names = FALSE) if (!is.null(ans) && is.atomic(ans)) vector(typeof(ans)) else NA } else { vector("list", length = prod(extent)) } }, dim = extent, dimnames = namelist) if (length(ans) > 0L) ansmat[index] <- ans ans <- NULL structure(ansmat, call = .CALL, class = "by" ) }
labelstonumbers<-function(phyl,tips) { if (class(phyl) != "phylo") stop("your tree must be class 'phylo.'") newtips<-c() for(j in 1:length(tips)) { for(i in 1:length(phyl$tip.label)) { if(phyl$tip.label[i]==tips[j]) {newtips<-c(newtips,i)} } } newtips }
near.bound<-function(X,Y,bX,bY){ euc<-function(x1,x2,y1,y2)sqrt((x1-x2)^2+(y1-y2)^2) n<-length(X) nb<-length(bX) e<-matrix(ncol=n,nrow=nb) for(i in 1:n){ e[,i]<-euc(X[i],bX,bY,Y[i]) } mn<-apply(e,2,function(x){which(x==min(x))}) xy.bound<-data.frame(near.X.coord=bX[mn],near.Y.coord=bY[mn]) xy.bound }
lim0 <- function( x, f=1/27, curtail=TRUE) { if(length(x)==1) x <- c(0,x) r <- suppressWarnings(range(as.matrix(x), finite=TRUE)) if(!all(is.finite(r))) {warning("x has no finite values, returning plot range 0:1."); r <- 0:1} r2 <- r + c(-f,f) * diff(r) r2[which.min(abs(r2))] <- 0 if(curtail) r2 + c(f,-f) * diff(r2) else r2 }
"qua2ci.cov" <- function(x,f, type=NULL, nsim=1000, interval=c("confidence", "none"), level=0.90, tol=1E-6, asnorm=FALSE, altlmoms=NULL, flip=NULL, dimless=TRUE, usefastlcov=TRUE, nmom=5, getsimlmom=FALSE, verbose=FALSE, ...) { interval <- match.arg(interval) if(is.null(type)) { message("must specify an lmomco distribution abbreviation, returning NA") return(NA) } if(! any(dist.list() == type)) { warning("invalid lmomco distribution abbreviation given, returning NA") return(NA) } if(interval == "none" & length(f) > 1) { warning("function is not vectorized in f for interval 'none', using ", "only the first value") f <- f[1] } if(! check.fs(f)) return(NA) if(! check.fs(level) | level == 1) { warning("level is not in [0,1), returning NA") return(NA) } if(! is.null(altlmoms) & ! dimless) { warning("Altervative L-moments are given, so setting 'dimless=TRUE'") dimless <- TRUE } npar <- dist.list(type=type) if(nmom < npar) { warning("number of parameters distribution 'type' is smaller ", "than 'nmom' resetting 'nmom to' ", npar) nmom <- npar } if(! is.null(flip)) x <- flip - x xlmoms <- lmoms(x, nmom=nmom) if(is.null(altlmoms)) altlmoms <- xlmoms if(verbose) { message(" Lambdas (alternate or of x) "); print(altlmoms$lambdas) } if(! are.lmom.valid(altlmoms)) { warning(" L-moments (either computed on 'x') or from 'altlmoms' ", "are invalid, returning NA") return(NA) } parent <- lmom2par(altlmoms, type=type) if(verbose) { message(" Parent parameters "); print(parent$para) } if(dimless) { newx <- (x - xlmoms$lambdas[1]) / xlmoms$lambdas[2] if(usefastlcov) { lmrcv <- Lmoments::Lmomcov(newx, rmax=nmom) } else { lmrcv <- lmoms.cov(newx, nmom=nmom) } sLM <- NULL fed <- 0 if(nmom >= 2) fed <- c(fed, 1) if(nmom >= 3) fed <- c(fed, altlmoms$ratios[3:nmom]) try(sLM <- MASS::mvrnorm(n=nsim, fed, lmrcv, tol=tol)) if(is.null(sLM)) { message("x=") print(x) message("lmrcv=") print(lmrcv) warning("returning NULL (try increasing the tol-erance)") return(NULL) } MU <- altlmoms$lambdas[1] L2 <- altlmoms$lambdas[2] for(i in 2:nmom) sLM[,i] <- sLM[,i]*L2 sLM[,1] <- sLM[,1]*L2 + MU } else { if(usefastlcov) { lmrcv <- Lmoments::Lmomcov(x, rmax=nmom) } else { lmrcv <- lmoms.cov(x, nmom=nmom) } sLM <- NULL try(sLM <- MASS::mvrnorm(n=nsim, altlmoms$lambdas, lmrcv, tol=tol)) if(is.null(sLM)) { message("x=") print(x) message("lmrcv=") print(lmrcv) warning("returning NULL (try increasing the tol-erance)") return(NULL) } } if(verbose) { message(" Var-covar matrix"); print(lmrcv) message(" Summary of simulated lambdas "); print(summary(sLM)) } if(getsimlmom) return(sLM) ci <- c((1-level)/2, 1-(1-level)/2) n <- length(f) zz <- matrix(nrow=n, ncol=8) for(i in 1:n) { ff <- f[i] quasf <- sapply(1:nsim, function(i) { para <- NULL slams <- sLM[i,] lmr <- vec2lmom(c(slams[1:2], slams[3:nmom]/slams[2])) if(! are.lmom.valid(lmr)) return(NA) para <- lmom2par(lmr, type=type, ...) if(is.null(para)) return(NA) qf <- NULL if(is.null(flip)) { try(qf <- par2qua( ff, para)) ifelse(is.null(qf), return(NA), return(qf)) } else { try(qf <- par2qua(1-ff, para)) ifelse(is.null(qf), return(NA), return(flip - qf)) } }) if(interval == "none") return(quasf) if(any(is.na(quasf))) { num.na <- length(quasf[is.na(quasf)]) warning("at least one of 'quasf' is NA, stripping ", num.na, " NA values (entries) and continuing") quasf <- quasf[! is.na(quasf)] } if(length(quasf) < 3) { warning("critical failure, no quantiles to then estimate the distribution for") return(NULL) } lmr <- lmoms(quasf, nmom=3) mu <- lmr$lambdas[1]; lscale <- lmr$lambdas[2] ifelse(asnorm, z <- qnorm(ci, mean=mu, sd=sd(quasf)), z <- dat2bernqua(ci, quasf)) fit <- ifelse(is.null(flip), par2qua( ff, parent), flip - par2qua(1-ff, parent)) zz[i,] <- c(ff, z[1], fit, z[2], median(quasf), mu, var(quasf), lscale) } colnames(zz) <- c("nonexceed", "lwr", "fit", "upr", "qua_med", "qua_mean", "qua_var", "qua_lam2") zz <- as.data.frame(zz) return(zz) }
LoadApneaWFDB <- function(HRVData, RecordName, RecordPath=".", Tag="APNEA", verbose=NULL) { HRVData = HandleVerboseArgument(HRVData, verbose) VerboseMessage(HRVData$Verbose, paste("Loading apnea episodes for record:", RecordName)) dir=getwd() on.exit(setwd(dir)) VerboseMessage(HRVData$Verbose, paste("Path:", RecordPath)) setwd(RecordPath) if (is.null(HRVData$datetime)) { VerboseMessage(HRVData$Verbose, paste("Reading header info for:", RecordName)) HRVData = LoadHeaderWFDB(HRVData,RecordName,RecordPath) } else { VerboseMessage(HRVData$Verbose, paste("Header info already present for:",RecordName)) } auxHeader = readLines(paste(RecordName,".hea",sep=""),1) splitAuxHeader = strsplit(auxHeader," ") if(length(splitAuxHeader[[1]])>2) samplingFrequency = splitAuxHeader[[1]][3] else samplingFrequency = "250" samplingFrequency = as.numeric(samplingFrequency) VerboseMessage(HRVData$Verbose, paste("Sampling frequency for apnea annotations:", samplingFrequency)) inApnea = FALSE accumulator = 0 initT = c() endT = c() con = file(paste(RecordName,".apn",sep=""),"rb") repeat { value = readBin(con,"integer",n=1,size=1,signed=FALSE)+256*readBin(con,"integer",n=1,size=1,signed=FALSE) code = bitwShiftR(value,10) time = value %% 1024 if(code==0 && time==0) break if (code==8 && !inApnea) { inApnea = TRUE if (accumulator > 30) initT = c(initT,accumulator-30) else initT = c(initT, accumulator) } if (code==1 && inApnea) { inApnea = FALSE endT = c(endT,accumulator-30) } if (code==59) { interval = (readBin(con,"integer",n=1,size=1,signed=FALSE)+readBin(con,"integer",n=1,size=1,signed=FALSE)*256)*65536+(readBin(con,"integer",n=1,size=1,signed=FALSE)+readBin(con,"integer",n=1,size=1,signed=FALSE)*256) accumulator = accumulator + interval/samplingFrequency next } } if (inApnea) { endT = c(endT,accumulator) } close(con) if (length(initT) > 0) { HRVData = AddEpisodes( HRVData, InitTimes = initT, Tags = Tag, Durations = endT-initT, Values = 0 ) } return(HRVData) }
var1 <- function( data, contemporaneous = c("cov","chol","prec","ggm"), beta = "full", omega_zeta = "full", delta_zeta = "full", kappa_zeta = "full", sigma_zeta = "full", lowertri_zeta = "full", mu, beepvar, dayvar, idvar, vars, groups, covs, means, nobs, missing = "listwise", equal = "none", baseline_saturated = TRUE, estimator = "ML", optimizer, storedata = FALSE, covtype = c("choose","ML","UB"), standardize = c("none","z","quantile"), sampleStats, verbose=FALSE ){ contemporaneous <- match.arg(contemporaneous) if (missing(vars)) vars2 <- NULL else vars2 <- vars if (missing(idvar)) idvar <- NULL if (missing(dayvar)) dayvar <- NULL if (missing(beepvar)) beepvar <- NULL if (missing(groups)) groups <- NULL if (!missing(data)){ data <- as.data.frame(data) if (is.null(names(data))){ names(data) <- paste0("V",seq_len(ncol(data))) } } data <- tsData(data, vars = vars2, beepvar = beepvar, dayvar = dayvar, idvar = idvar, groupvar = groups) if (is.null(groups)){ vars <- colnames(data) } else { vars <- colnames(data)[colnames(data)!=groups] } if (missing(sampleStats)){ sampleStats <- samplestats(data = data, vars = vars, groups = groups, covs = covs, means = means, nobs = nobs, missing = ifelse(estimator == "FIML","pairwise",missing), fimldata = estimator == "FIML", storedata = storedata, covtype=covtype, standardize = standardize, verbose=verbose, weightsmatrix = ifelse(!estimator %in% c("WLS","ULS","DWLS"), "none", switch(estimator, "WLS" = "full", "ULS" = "identity", "DWLS" = "diag" ))) } if ( nrow(sampleStats@variables) %% 2 != 0){ stop("Number of variables is not an even number: variance-covariance matrix cannot be a Toeplitz matrix. ") } nNode <- nrow(sampleStats@variables) / 2 model <- generate_psychonetrics(model = "var1",submodel = switch(contemporaneous, "prec" = "gvar", "ggm" = "gvar", "chol" = "var", "cov" = "var" ),types = list(zeta = contemporaneous), sample = sampleStats,computed = FALSE, equal = equal, optimizer = defaultoptimizer(), estimator = estimator, distribution = "Gaussian",verbose=verbose) nGroup <- nrow(model@sample@groups) nVar <- nNode * 2 model@sample@nobs <- nVar * (nVar+1) / 2 * nGroup + nVar * nGroup modMatrices <- list() modMatrices$mu <- matrixsetup_mu(mu,nNode = nVar, nGroup = nGroup, labels = sampleStats@variables$label,equal = "mu" %in% equal, expmeans = model@sample@means, sampletable = sampleStats, name = "mu") shiftCovs <- lapply(sampleStats@covs,spectralshift) exoCovs <- lapply(shiftCovs,function(x)spectralshift(x[1:nNode,1:nNode])) modMatrices$exo_cholesky <- matrixsetup_lowertri("full", name = "exo_cholesky", expcov=exoCovs, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[1:nNode], equal = "exo_cholesky" %in% equal, sampletable = sampleStats) S0est <- lapply(shiftCovs,function(x)spectralshift(x[nNode + (1:nNode),nNode + (1:nNode)])) S1est <- lapply(shiftCovs,function(x)x[nNode + (1:nNode),1:nNode]) S0inv <- lapply(S0est,solve_symmetric) betaEst <- lapply(1:nGroup, function(g) as.matrix(S1est[[g]] %*% S0inv[[g]])) modMatrices$beta <- matrixsetup_beta(beta, name = "beta", nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[nNode + (1:nNode)], equal = "beta" %in% equal, sampletable = sampleStats, start = betaEst, onlyStartSign = FALSE) contCovEst <- lapply(1:nGroup, function(g) spectralshift(S0est[[g]] - S1est[[g]] %*% S0inv[[g]] %*% t(S1est[[g]]))) if (contemporaneous == "cov"){ modMatrices$sigma_zeta <- matrixsetup_sigma(sigma_zeta, name = "sigma_zeta", expcov=contCovEst, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[-(1:nNode)], equal = "sigma_zeta" %in% equal, sampletable = sampleStats) } else if (contemporaneous == "chol"){ modMatrices$lowertri_zeta <- matrixsetup_lowertri(lowertri_zeta, name = "lowertri_zeta", expcov=contCovEst, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[-(1:nNode)], equal = "lowertri_zeta" %in% equal, sampletable = sampleStats) } else if (contemporaneous == "ggm"){ modMatrices$omega_zeta <- matrixsetup_omega(omega_zeta, name = "omega_zeta", expcov=contCovEst, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[-(1:nNode)], equal = "omega_zeta" %in% equal, sampletable = sampleStats, onlyStartSign = FALSE) modMatrices$delta_zeta <- matrixsetup_delta(delta_zeta, name = "delta_zeta", expcov=contCovEst, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[-(1:nNode)], equal = "delta_zeta" %in% equal, sampletable = sampleStats, onlyStartSign = FALSE, omegaStart = modMatrices$omega_zeta$start) } else if (contemporaneous == "prec"){ modMatrices$kappa_zeta <- matrixsetup_kappa(kappa_zeta, name = "kappa_zeta", expcov=contCovEst, nNode = nNode, nGroup = nGroup, labels = sampleStats@variables$label[-(1:nNode)], equal = "kappa_zeta" %in% equal, sampletable = sampleStats) } pars <- do.call(generateAllParameterTables, modMatrices) model@parameters <- pars$partable model@matrices <- pars$mattable model@extramatrices <- list( D = psychonetrics::duplicationMatrix(nNode*2), D2 = psychonetrics::duplicationMatrix(nNode), L = psychonetrics::eliminationMatrix(nNode), Dstar = psychonetrics::duplicationMatrix(nNode,diag = FALSE), In = as(diag(nNode),"dgCMatrix"), In2 = as(diag(nNode),"dgCMatrix"), A = psychonetrics::diagonalizationMatrix(nNode), C = as(lavaan::lav_matrix_commutation(nNode,nNode),"dgCMatrix") ) dummySigma <- matrix(0,nNode*2,nNode*2) smallMat <- matrix(0,nNode,nNode) dummySigma[1:nNode,1:nNode][lower.tri(smallMat,diag=TRUE)] <- seq_len(nNode*(nNode+1)/2) dummySigma[nNode + (1:nNode),nNode + (1:nNode)][lower.tri(smallMat,diag=TRUE)] <- max(dummySigma) + seq_len(nNode*(nNode+1)/2) dummySigma[nNode + (1:nNode),1:nNode] <- max(dummySigma) + seq_len(nNode^2) inds <- dummySigma[lower.tri(dummySigma,diag=TRUE)] model@extramatrices$P <- bdiag(Diagonal(nNode*2),sparseMatrix(j=seq_along(inds),i=order(inds))) model@extramatrices$P <- as(model@extramatrices$P, "dgCMatrix") model@modelmatrices <- formModelMatrices(model) if (baseline_saturated){ basGGM <- diag(nNode*2) basGGM[1:nNode,1:nNode] <- 1 model@baseline_saturated$baseline <- cholesky(data = data, lowertri = basGGM, vars = vars, groups = groups, covs = covs, means = means, nobs = nobs, missing = missing, equal = equal, estimator = estimator, baseline_saturated = FALSE, sampleStats = sampleStats) model@baseline_saturated$saturated <- cholesky(data = data, lowertri = "full", vars = vars, groups = groups, covs = covs, means = means, nobs = nobs, missing = missing, equal = equal, estimator = estimator, baseline_saturated = FALSE, sampleStats = sampleStats) if (estimator != "FIML"){ model@baseline_saturated$saturated@computed <- TRUE model@baseline_saturated$saturated@objective <- psychonetrics_fitfunction(parVector(model@baseline_saturated$saturated),model@baseline_saturated$saturated) } } if (missing(optimizer)){ model <- setoptimizer(model, "default") } else { model <- setoptimizer(model, optimizer) } return(model) }
sdellipse = function (points, stdev = 1.96, density = .01, add = TRUE, show = TRUE, means = NULL, se = FALSE, ...){ if (ncol (points) != 2) stop ('Points input must have exactly two columns.') if (!is.null(means) & nrow(points) > 2) stop ('Covariance matrix must be 2 by 2.') if (!is.null(means) & length(means) > 2) stop ('Exactly two means must be specified.') t = seq (0,2*pi+density,density) x = rbind (cos(t), sin(t)) if (is.null(means)){ sigma = var (points) if (se) sigma = sigma / nrow(points) } if (!is.null(means)){ sigma = points if (is.numeric(se)) sigma = sigma / se } A = eigen(sigma)$vectors %*% (diag(sqrt(eigen(sigma)$values)) * stdev) points = t(colMeans(points) + A%*%x) if (is.null(means)) points = t(colMeans(points) + A%*%x) if (!is.null(means)) points = t(means + A%*%x) if (add == TRUE & show == TRUE) lines (points, ...) if (add == FALSE & show == TRUE) plot (points, type = 'l', ...) invisible (points) }
library(dplyr) test_that("group_slab_data_by works", { df = data.frame( x = 1:8, ymin = 2:9, ymax = 3:10, fill = c("a","a","a","b","b","b","b","a"), alpha = 1 ) ref = data.frame( x = c(1:3, 3.5, 3.5, 3:1, 3.5, 4:7, 7.5, 7.5, 7:4, 3.5, 7.5, 8, 8, 7.5), ymin = c(1:3, 3.5, 3.5, 3:1, 3.5, 4:7, 7.5, 7.5, 7:4, 3.5, 7.5, 8, 8, 7.5) + 1, ymax = c(1:3, 3.5, 3.5, 3:1, 3.5, 4:7, 7.5, 7.5, 7:4, 3.5, 7.5, 8, 8, 7.5) + 2, fill = c(rep("a", 8), rep("b", 12), rep("a", 4)), alpha = 1, group = c(rep(0, 8), rep(1, 12), rep(2,4)), y = c(3:5, 5.5, 4.5, 4:2, 5.5, 6:9, 9.5, 8.5, 8:5, 4.5, 9.5, 10, 9, 8.5) ) grouped_slab_data = arrange(group_slab_data_by(df, side = "both"), group) expect_equal(grouped_slab_data, ref) df$fill = "a" expect_equal(group_slab_data_by(df, side = "topright"), mutate(df, y = ymax)) }) test_that("group_slab works", { skip_if_no_vdiffr() p = tibble( x = seq(-4,4, length.out = 20), d = dnorm(x) ) %>% ggplot(aes(thickness = d)) vdiffr::expect_doppelganger("geom_slab one group", p + geom_slab(aes(x = 1, y = x)) ) vdiffr::expect_doppelganger("geom_slabh one group", p + geom_slab(aes(x = x, y = 1)) ) }) test_that("normalize works", { skip_if_no_vdiffr() p = tribble( ~y, ~id, ~p, ~ dist, ~ mu, ~ sigma, 1, "A", 1, "norm", 0, 1, 1, "B", 1, "norm", 8, 2, 2, "A", 1, "norm", 0, 2, 2, "A", 2, "norm", 0, 2, 1, "B", 2, "norm", 8, 2, ) %>% ggplot(aes(y = y, dist = dist, arg1 = mu, arg2 = sigma, fill = id)) + facet_grid(~p) vdiffr::expect_doppelganger("halfeye with normalize = all", p + stat_dist_halfeye(normalize = "all", n = 20) ) vdiffr::expect_doppelganger("halfeye with normalize = panels", p + stat_dist_halfeye(normalize = "panels", n = 20) ) vdiffr::expect_doppelganger("halfeye with normalize = xy", p + stat_dist_halfeye(normalize = "xy", n = 20) ) vdiffr::expect_doppelganger("halfeye with normalize = groups", p + stat_dist_halfeye(normalize = "groups", n = 20) ) vdiffr::expect_doppelganger("halfeye with normalize = none", p + stat_dist_halfeye(normalize = "none", n = 20) ) }) test_that("alpha channel in fill colors works", { skip_if_no_vdiffr() vdiffr::expect_doppelganger("alpha channel in slab fill", data.frame(x = c(0,1), y = "a", d = c(1,2)) %>% ggplot(aes(x = x, y = y, thickness = d)) + geom_slab(fill = scales::alpha("black", 0.2)) ) }) test_that("side and justification can vary", { skip_if_no_vdiffr() df = tibble( x = rep(1:10, each = 2), y = dnorm(x, c(4.5, 5.5), 2), g = rep(c("a","b"), 10) ) vdiffr::expect_doppelganger("varying side", df %>% ggplot(aes(x = x, y = g, thickness = y, side = ifelse(g == "a", "top", "bottom"), scale = ifelse(g == "a", 0.5, 0.25) )) + geom_slab() ) vdiffr::expect_doppelganger("varying side and just", df %>% ggplot(aes(x = x, y = g, thickness = y, side = ifelse(g == "a", "top", "bottom"), justification = ifelse(g == "a", 1, 0), scale = ifelse(g == "a", 0.5, 0.25) )) + geom_slab() ) expect_error( print( ggplot(df, aes(x = x, y = g, thickness = y, group = g, side = ifelse(x < 5, "top", "bottom") )) + geom_slab(orientation = "horizontal") ), "Slab `side` cannot vary within groups" ) expect_error( print( ggplot(df, aes(x = x, y = g, thickness = y, group = g, justification = ifelse(x < 5, 0, 1) )) + geom_slab(orientation = "horizontal") ), "Slab `justification` cannot vary within groups" ) expect_error( print( ggplot(df, aes(x = x, y = g, thickness = y, group = g, scale = ifelse(x < 5, 0.5, 0.25) )) + geom_slab(orientation = "horizontal") ), "Slab `scale` cannot vary within groups" ) })
FRESA.Model <- function(formula,data,OptType=c("Binary","Residual"),pvalue=0.05,filter.p.value=0.10,loops=32,maxTrainModelSize=20,elimination.bootstrap.steps=100,bootstrap.steps=100,print=FALSE,plots=FALSE,CVfolds=1,repeats=1,nk=0,categorizationType=c("Raw","Categorical","ZCategorical","RawZCategorical","RawTail","RawZTail","Tail","RawRaw"),cateGroups=c(0.1,0.9),raw.dataFrame=NULL,var.description=NULL,testType=c("zIDI","zNRI","Binomial","Wilcox","tStudent","Ftest"),lambda="lambda.1se",equivalent=FALSE,bswimsCycles=20,usrFitFun=NULL) { a = as.numeric(Sys.time()); set.seed(a); categorizationType <- match.arg(categorizationType); cl <- match.call(); cvObject <- NULL; univariate <- NULL; eq=NULL; bagg=NULL; type = "LM"; if (class(formula)=="character") { formula <- formula(formula); } if (class(formula)=="formula") { featureSize = ncol(data)-1; OptType <- match.arg(OptType) varlist <- attr(terms(formula),"variables") dependent <- as.character(varlist[[2]]) timeOutcome = NA; Outcome = NA; type = "LM"; if (length(dependent)==3) { type = "COX" timeOutcome = dependent[2]; Outcome = dependent[3]; dependentout = paste(dependent[1],"(",dependent[2],",",dependent[3],")"); } else { Outcome = dependent[1]; dependentout = Outcome; } setIntersect <- attr(terms(formula),"intercept") if (setIntersect == 0) { covariates = "0"; } else { covariates = "1"; } termslist <- attr(terms(formula),"term.labels"); acovariates <- covariates[1]; if (length(termslist)>0) { for (i in 1:length(termslist)) { covariates <- paste(covariates,"+",termslist[i]); acovariates <- append(acovariates,termslist[i]); } } startOffset = length(termslist); variables <- vector(); descrip <- vector(); pnames <- as.vector(colnames(data)); for (i in 1:length(pnames)) { detected = 0; if (length(termslist)>0) { for (j in 1:length(termslist)) { if (termslist[j] == pnames[i]) detected = 1; } } if (Outcome == pnames[i]) detected = 1; if (!is.na(timeOutcome) ) { if (timeOutcome == pnames[i]) detected = 1; } if (detected == 0) { variables <- append(variables,pnames[i]); if (!is.null(var.description)) { descrip <- append(descrip,var.description[i]); } } } if (!is.null(var.description)) { variables <- cbind(variables,descrip); } else { variables <- cbind(variables,variables); } colnames(variables) <- c("Var","Description"); if (CVfolds>nrow(data)) { cat("Setting to LOO CV\n"); CVfolds=nrow(data); } trainFraction <- 1.0-1.0/CVfolds; trainRepetition <- repeats*CVfolds; fraction = 1.0000; varMax = nrow(variables); baseModel <- paste(dependentout,"~",covariates); cvObject = NULL; reducedModel = NULL; bootstrappedModel = NULL; UpdatedModel = NULL; filter.z.value <- abs(qnorm(filter.p.value)) cutpvalue <- 3.0*filter.p.value if (cutpvalue > 0.45) cutpvalue=0.45; selectionType = match.arg(testType); testType = match.arg(testType); theScores <- names(table(data[,Outcome])) if (((length(theScores)>2)||(min(data[,Outcome])<0))&&(OptType == "Binary")) { OptType = "Residual"; } if (categorizationType=="RawRaw") { rownames(variables) <- variables[,1]; unirank <- uniRankVar(variables,baseModel,Outcome,data,categorizationType="Raw",type,rankingTest="Ztest",cateGroups,raw.dataFrame,description="Description",uniType="Regression",FullAnalysis=FALSE,acovariates=acovariates,timeOutcome=timeOutcome) univariate <- unirank$orderframe; featureSize <- nrow(univariate); unitPvalues <- (1.0-pnorm(univariate$ZUni)); names(unitPvalues) <- univariate$Name; adjPvalues <- p.adjust(unitPvalues,"BH"); variables <- variables[names(adjPvalues[adjPvalues <= 2*filter.p.value]),]; } if (OptType == "Binary") { if (length(dependent)==1) { type = "LOGIT"; } unirank <- uniRankVar(variables,baseModel,Outcome,data,categorizationType,type,rankingTest="zIDI",cateGroups,raw.dataFrame,description="Description",uniType="Binary",FullAnalysis=FALSE,acovariates=acovariates,timeOutcome=timeOutcome); univariate <- unirank$orderframe; featureSize <- nrow(univariate); unitPvalues <- (1.0-pnorm(univariate$ZUni)); names(unitPvalues) <- univariate$Name; adjPvalues <- p.adjust(unitPvalues,"BH"); varMax <- sum(univariate$ZUni >= filter.z.value); if (categorizationType == "Raw") { gadjPvalues <- adjPvalues[adjPvalues < 2*filter.p.value] noncornames <- correlated_Remove(data,names(gadjPvalues),thr=0.99); attr(noncornames,"CorrMatrix") <- NULL; if (length(noncornames) > 1) featureSize <- featureSize*length(noncornames)/length(gadjPvalues); } pvarMax <- sum(adjPvalues < 2*filter.p.value); sizeM <- min(c(pvarMax,varMax)); if (sizeM < 5) sizeM = min(c(5,nrow(univariate))); if (varMax > nrow(univariate)) varMax = nrow(univariate); if (varMax < 5) varMax = min(c(5,nrow(univariate))); redlist <- adjPvalues < cutpvalue; totlist <- min(sum(1*redlist),100); cat("Unadjusted size:",sum(univariate$ZUni >= filter.z.value)," Adjusted Size:",pvarMax," Cut size:",sum(1*redlist),"\n") if (totlist<10) { redlist <- c(1:min(10,nrow(univariate))) totlist <- length(totlist); } cat("\n Z: ",filter.z.value,", Features to test: ",sizeM,",Adjust Size:",featureSize,"\n"); shortUniv <- univariate[redlist,] if (CVfolds>1) { if (categorizationType!="RawRaw") { rownames(variables) <- variables[,1]; } cvObject <- crossValidationFeatureSelection_Bin(sizeM,fraction,c(pvalue,filter.p.value),loops,acovariates,Outcome,timeOutcome,NULL,data,maxTrainModelSize,type,selectionType,startOffset,elimination.bootstrap.steps,trainFraction,trainRepetition,bootstrap.steps,nk,unirank,print=print,plots=plots,lambda=lambda,equivalent=equivalent,bswimsCycles=bswimsCycles,usrFitFun,featureSize=featureSize); firstModel <- cvObject$forwardSelection; UpdatedModel <- cvObject$updateforwardSelection; reducedModel <- cvObject$BSWiMS; bootstrappedModel <- cvObject$FullBSWiMS.bootstrapped; BSWiMS.models <- cvObject$BSWiMS.models; } else { BSWiMS.models <- BSWiMS.model(formula=formula,data=data,type=type,testType=selectionType,pvalue=pvalue,variableList=shortUniv,size=sizeM,loops=loops,elimination.bootstrap.steps=bootstrap.steps,fraction=1.0,maxTrainModelSize=maxTrainModelSize,maxCycles=bswimsCycles,print=print,plots=plots,featureSize=featureSize,NumberofRepeats=repeats); firstModel <- BSWiMS.models$forward.model; UpdatedModel <- BSWiMS.models$update.model; reducedModel <- BSWiMS.models$BSWiMS.model; bootstrappedModel <- reducedModel$bootCV; } } if (OptType == "Residual") { if (testType=="zIDI") { if ((testType=="zIDI")&&(length(theScores)>10)) { warning("Switching to Regresion, More than 10 scores"); testType = "Ftest"; } else { cat("Doing a Ordinal Fit with zIDI Selection\n"); cat("Ordinal Fit will be stored in BSWiMS.models$oridinalModels\n"); cat("Use predict(BSWiMS.models$oridinalModels,testSet) to get the ordinal prediction on a new dataset \n"); } } if (length(dependent)==1) { if ((length(theScores)>2)||(min(data[,Outcome])<0)) { type = "LM"; unirank <- uniRankVar(variables,baseModel,Outcome,data,categorizationType,type,rankingTest="Ztest",cateGroups,raw.dataFrame,description="Description",uniType="Regression",FullAnalysis=FALSE,acovariates=acovariates,timeOutcome=timeOutcome) if ((length(theScores)<=10)&&(testType=="zIDI")) { type = "LOGIT"; } } else { if (type == "LM") type = "LOGIT"; unirank <- uniRankVar(variables,baseModel,Outcome,data,categorizationType,type,rankingTest="Ztest",cateGroups,raw.dataFrame,description="Description",uniType="Binary",FullAnalysis=FALSE,acovariates=acovariates,timeOutcome=timeOutcome) } } else { unirank <- uniRankVar(variables,baseModel,Outcome,data,categorizationType,type,rankingTest="Ztest",cateGroups,raw.dataFrame,description="Description",uniType="Binary",FullAnalysis=FALSE,acovariates=acovariates,timeOutcome=timeOutcome) } univariate <- unirank$orderframe; featureSize <- nrow(univariate); unitPvalues <- (1.0-pnorm(univariate$ZUni)); names(unitPvalues) <- univariate$Name; adjPvalues <- p.adjust(unitPvalues,"BH"); varMax <- sum(univariate$ZUni >= filter.z.value); if (categorizationType == "Raw") { gadjPvalues <- adjPvalues[adjPvalues < 2*filter.p.value] noncornames <- correlated_Remove(data,names(gadjPvalues),thr=0.99); attr(noncornames,"CorrMatrix") <- NULL; if (length(noncornames) > 1) featureSize <- featureSize*length(noncornames)/length(gadjPvalues); } pvarMax <- sum(adjPvalues < 2*filter.p.value); sizeM <- min(c(pvarMax,varMax)); if (sizeM < 5) sizeM = min(c(5,nrow(univariate))); if (varMax > nrow(univariate)) varMax = nrow(univariate); if (varMax < 5) varMax = min(c(5,nrow(univariate))); bootstrappedModel = NULL; redlist <- adjPvalues < cutpvalue; totlist <- min(sum(1*redlist),100); cat("Features to test:",sizeM," Adjusted Size:",featureSize,"\n"); if (totlist<10) { redlist <- c(1:min(10,nrow(univariate))) totlist <- length(totlist); } cat("\n Z: ",filter.z.value," Var Max: ",featureSize,"FitType: ",type," Test Type: ",testType,"\n"); shortUniv <- univariate[redlist,] if (CVfolds>1) { if (categorizationType != "RawRaw") { rownames(variables) <- variables[,1]; } cvObject <- crossValidationFeatureSelection_Res(size=sizeM,fraction=fraction,pvalue=c(pvalue,filter.p.value),loops=loops,covariates=acovariates,Outcome=Outcome,timeOutcome=timeOutcome,variableList=unirank$variableList,data=data,maxTrainModelSize=maxTrainModelSize,type=type,testType=testType,startOffset=startOffset,elimination.bootstrap.steps=elimination.bootstrap.steps,trainFraction=trainFraction,trainRepetition=trainRepetition,setIntersect=setIntersect,unirank=unirank,print=print,plots=plots,lambda=lambda,equivalent=equivalent,bswimsCycles=bswimsCycles,usrFitFun=usrFitFun,featureSize=featureSize); firstModel <- cvObject$forwardSelection; UpdatedModel <- cvObject$updatedforwardModel; reducedModel <- cvObject$BSWiMS; bootstrappedModel <- cvObject$BSWiMS$bootCV; BSWiMS.models <- cvObject$BSWiMS.models; } else { BSWiMS.models <- BSWiMS.model(formula=formula,data=data,type=type,testType=testType,pvalue=pvalue,variableList=shortUniv,size=sizeM,loops=loops,elimination.bootstrap.steps=bootstrap.steps,fraction=1.0,maxTrainModelSize=maxTrainModelSize,maxCycles=bswimsCycles,print=print,plots=plots,featureSize=featureSize,NumberofRepeats=repeats); firstModel <- BSWiMS.models$forward.model; UpdatedModel <- BSWiMS.models$update.model; reducedModel <- BSWiMS.models$BSWiMS.model; bootstrappedModel <- reducedModel$bootCV; } } } else { cat("Expecting a formula object\n"); } if (is.null(reducedModel)) { result <- list(BSWiMS.model = NULL, reducedModel = reducedModel, univariateAnalysis=univariate, forwardModel=firstModel, updatedforwardModel=UpdatedModel, bootstrappedModel=bootstrappedModel, cvObject=cvObject, used.variables=varMax, call=cl); } else { eq <- NULL; bagg <- NULL; if ((length(reducedModel$back.model$coefficients) > 1 ) && equivalent) { collectFormulas <- BSWiMS.models$forward.selection.list; bagg <- baggedModel(collectFormulas,data,type,Outcome,timeOutcome,univariate=univariate,useFreq=loops); shortcan <- bagg$frequencyTable[(bagg$frequencyTable >= (loops*0.05))]; modeltems <- attr(terms(reducedModel$back.model),"term.labels"); eshortlist <- unique(c(names(shortcan),str_replace_all(modeltems,":","\\*"))); eshortlist <- eshortlist[!is.na(eshortlist)]; if (length(eshortlist)>0) { nameslist <- c(all.vars(BSWiMS.models$bagging$bagged.model$formula),as.character(univariate[eshortlist,2])); nameslist <- unique(nameslist[!is.na(nameslist)]); if (categorizationType != "RawRaw") { eqdata <- data[,nameslist]; } else { eqdata <- data; } eq <- reportEquivalentVariables(reducedModel$back.model,pvalue = 0.25*pvalue, data=eqdata, variableList=cbind(eshortlist,eshortlist), Outcome = Outcome, timeOutcome=timeOutcome, type = type,osize=featureSize, method="BH"); } } result <- list(BSWiMS.model = BSWiMS.models$bagging$bagged.model, reducedModel = reducedModel, univariateAnalysis=univariate, forwardModel=firstModel, updatedforwardModel=UpdatedModel, bootstrappedModel=bootstrappedModel, cvObject=cvObject, used.variables=varMax, bagging=bagg, eBSWiMS.model=eq, BSWiMS.models=BSWiMS.models, call=cl ); } return (result); }
load_dataset = function(id, package, keep_rownames = FALSE) { assert_string(id) assert_string(package) assert_flag(keep_rownames) if (!length(find.package(package, quiet = TRUE))) { msg = sprintf("Please install package '%s' for data set '%s'", package, id) stop(errorCondition(msg, packages = package, class = "packageNotFoundError")) } ee = new.env(parent = emptyenv(), hash = FALSE) data(list = id, package = package, envir = ee) data = ee[[id]] if (!keep_rownames && (is.data.frame(data) || is.matrix(data))) { rownames(data) = NULL } data }
gl.utils.fdsim <- function(gl, poppair, obs, sympatric=FALSE, reps=1000, delta=0.02, verbose=NULL) { if (verbose > 0) { cat("Starting gl.utils.fdsim: Using simulation to estimate frequency of false positives\n") } if(!(class(gl)=="genlight")){ cat("Fatal Error: Input data must be a genlight object\n") stop("Execution terminated\n") } if (!(poppair[1] %in% levels(pop(gl)))){ cat("Fatal Error: Population A mislabelled\n") stop("Execution terminated\n") } if (!(poppair[2] %in% levels(pop(gl)))){ cat("Fatal Error: Population B mislabelled\n") stop("Execution terminated\n") } if (length(poppair) == 2) { pair <- gl.keep.pop(gl, poppair, recalc=FALSE, mono.rm = TRUE, verbose=verbose) } else { cat("Fatal Error: Must specify two populations labels from the genlight object, e.g. poppair=c(popA,popB)\n") stop("Execution terminated\n") } if (verbose >= 2) {cat("Comparing ",poppair[1],"and",poppair[2],"\n")} if (verbose >= 3) { cat(" Sample sizes:",table(pop(pair)),"\n") cat(" No. of loci:",nLoc(pair),"\n") cat(" No. of observed fixed differences:",obs,"\n") } rf <- gl.percent.freq(pair, verbose=verbose) rfA <- rf[rf$popn==poppair[1],] rfB <- rf[rf$popn==poppair[2],] if(verbose >= 2){cat(" Calculations based on allopatric populations\n")} if(sympatric){ rfA <- rf rfB <- rf if(verbose >= 2){cat(" Calculations based on sympatric populations\n")} } simA <- array(data=NA,dim=nLoc(pair)) simB <- array(data=NA,dim=nLoc(pair)) fd <- array(data=NA,dim=nLoc(pair)) falsepos <- array(data=NA,dim=reps) if (is.null(obs)) { fdmat <- gl.fixed.diff(pair) obs <- fdmat[2,1] } if (verbose > 1) { cat("Calculating false positive rate with",reps,"replications. Please be patient\n") } for (j in 1:reps){ for (i in 1:nLoc(pair)) { if (is.na(rfA$frequency[i]) || is.na(rfB$frequency[i])) { simA[i]<-NA simB[i]<-NA } else if ((((rfA$frequency[i]/100) < delta) && (1-(rfB$frequency[i]/100)) < delta) || (((rfB$frequency[i]/100) < delta) && (1-(rfA$frequency[i]/100)) < delta)) { simA[i]<-NA simB[i]<-NA } else { szA <- rfA$nobs[i]*2 szB <- rfB$nobs[i]*2 pbA <- rfA$frequency[i]/100 pbB <- rfB$frequency[i]/100 simA[i] <- (rbinom(n=1, size=szA, prob=pbA))/szA simB[i] <- (rbinom(n=1, size=szB, prob=pbB))/szB fd[i] <- ((1-simA[i])**szA)*((simB[i])**szB)+((simA[i])**szA)*((1-simB[i])**szB) } } falsepos[j] <- sum(fd, na.rm=TRUE) } mn <- mean(falsepos) sdev <- sd(falsepos) nprob <- pnorm(obs, mean=mn, sd=sdev, lower.tail=FALSE) if (verbose > 2) { cat("Threshold minor allele frequency for generating a false positive:",delta,"\n") cat("Estimated mean count of false positives:",round(mean(falsepos),1),"\n") cat("Estimated SD of the count of false positives:",round(sd(falsepos),2),"\n") cat("Prob that observed count of",obs,"are false positives:",nprob,"\n") } l <- list(observed=obs,mnexpected=mn,sdexpected=sdev,prob=nprob) if (verbose > 0) { cat("Completed gl.utils.fdsim\n\n") } return(l) }
.format_polynom <- function(p, s = "x") { res <- NULL for(i in seq_along(p)) { d <- i - 1 cc <- p[i] if(cc != 0) { if(d == 0) { res <- format(cc) } else { if(d == 1) { ss <- s } else { ss <- paste0(s, "^", d) } if(cc == 1) { if(length(res) == 0) { res <- c(res, ss) } else { res <- c(res, " + ", ss) } } else if(cc == -1) { res <- c(res, " - ", ss) } else if(cc < 0) { res <- c(res, " - ", -cc, ss) } else { if(is.null(res)) { res <- c(res, cc, ss) } else { res <- c(res, " + ", cc, ss) } } } } } if(is.null(res)) { return("0") } return(paste(res, collapse = "")) } .show.polyMarix <- function(object) { res <- matrix("+", nrow(object) + 1, ncol(object) + 1) res[1, 1] <- " " for(j in seq_len(ncol(object))) { res[1, j + 1] <- paste0("[,", j, "]") } for(i in seq_len(nrow(object))) { res[i + 1, 1] <- paste0("[", i, ",]") for(j in seq_len(ncol(object))) { res[i + 1, j + 1] <- .format_polynom(object[i, j]) } } col_sizes <- apply(res, 2, function(x) { max(sapply(x, nchar)) }) for(i in seq_len(nrow(res))) { s <- NULL for(j in seq_len(ncol(res))) { s <- c(s, format(res[i, j], justify = "right", width = col_sizes[j])) } cat(s, sep = " ") cat("\n") } } .show.polyMarixCharPolynomial <- function (cp) { res <- NULL for(i in seq_len(ncol(cp@coef))) { pc <- cp@coef[1, i] if (pc != 0) { str_p <- .format_polynom(pc) if (sum(c(pc) != 0) == 1) { if (sum(c(pc) > 0) == 1) { str_p <- paste(c("+ ", str_p), collapse = "") } if (!is.null(res)) { res <- c(res, str_p) } else { res <- str_p } } else { if (!is.null(res)) { stopifnot(i != 1) res <- c(res, "+", paste("(", str_p, ")", collapse = "")) } else { if (i == 1) { res <- str_p } else { res <- paste("(", str_p, ")", collapse = "") } } } if (i == 2) { res <- c(res, "l") } else if (i > 2){ res <- c(res, paste(c("l^", i - 1), collapse = "")) } } } cat(paste(res, collapse = " ")) cat("\n") } setMethod("show", signature(object = PM), .show.polyMarix) setMethod("show", signature(object = PMCP), function (object) { .show.polyMarixCharPolynomial(object) })
context("read_rrd") rrd_cpu_0 <- system.file("extdata/cpu-0.rrd", package = "rrd") rrd_content_1 <- system.file("extdata/content-1.rrd", package = "rrd") is_list_of_tibbles <- function(x){ is.list(x) && all( vapply(x, function(x)class(x)[1], FUN.VALUE = character(1), USE.NAMES = FALSE) == "tbl_df" ) } test_that("describe_rrd", { expect_output(describe_rrd(rrd_cpu_0), "An RRD file with 10 RRA arrays and step size 60") capture.output( z <- (describe_rrd(rrd_cpu_0)) ) expect_is(z, "NULL") }) test_that("deprecated functions", { expect_warning(importRRD(rrd_cpu_0), "'importRRD' is deprecated.") z <- suppressWarnings( importRRD(rrd_cpu_0) ) expect_true(is_list_of_tibbles(z)) expect_warning(importRRD(rrd_cpu_0, "MAX", start = Sys.time() - 86400, end = Sys.time(), step = 300L)) z <- suppressWarnings( importRRD(rrd_cpu_0, "MAX", start = Sys.time() - 86400, end = Sys.time(), step = 300L) ) expect_is(z, "tbl") }) test_that("read_rrd rrd_cpu_0", { z <- read_rrd(rrd_cpu_0) expect_true(is_list_of_tibbles(z)) expect_is(z[[1]], "data.frame") expect_equal(length(z), 10) expect_equal( names(z), c("AVERAGE60", "AVERAGE300", "MIN300", "MAX300", "AVERAGE3600", "MIN3600", "MAX3600", "AVERAGE86400", "MIN86400", "MAX86400") ) }) test_that("read_rrd rrd_content_1", { z <- read_rrd(rrd_content_1) expect_true(is_list_of_tibbles(z)) expect_is(z[[1]], "data.frame") expect_equal(length(z), 10) expect_equal( names(z), c("AVERAGE60", "AVERAGE300", "MIN300", "MAX300", "AVERAGE3600", "MIN3600", "MAX3600", "AVERAGE86400", "MIN86400", "MAX86400") ) }) test_that("read_rra from rrd_content_1 using start time", { z <- read_rra(rrd_content_1, "MAX", start = Sys.time() - 86400, end = Sys.time(), step = 300L) expect_is(z, "data.frame") expect_equal(nrow(z), 288) expect_equal(ncol(z), 4) expect_equal( names(z), c("timestamp", "sessions", "procs", "http") ) }) test_that("read_rra from rrd_content_1 using n_rows", { z <- read_rra(rrd_content_1, "MAX", n_steps = 10, end = Sys.time(), step = 300L) expect_is(z, "data.frame") expect_equal(nrow(z), 10) expect_equal(ncol(z), 4) expect_equal( names(z), c("timestamp", "sessions", "procs", "http") ) })
test_that(desc="get_na_counts works as expected", code={ skip_on_oldrel() expect_equal(nrow(get_na_counts(iris,"Species")), 3) expect_error(get_na_counts(airquality, grouping_cols = "Nope"), "All columns to group by should exist in the data set", fixed=TRUE) expect_equal(nrow(get_na_counts(airquality, grouping_cols = "Month")), 5) })
"Drugs_CID"
YRCSkew <- function(row, col, rowinf, rowsup, inst=NULL) { list(predictors = list(substitute(row), substitute(col), substitute(rowinf), substitute(rowsup)), term = function(predLabels, varLabels) { sprintf("%s * %s * (%s - %s) - %s * %s * (%s - %s)", predLabels[3], predLabels[1], predLabels[2], predLabels[1], predLabels[4], predLabels[2], predLabels[1], predLabels[2]) }, call = as.expression(match.call()), common = c(1, 1, 2, 2) ) } class(YRCSkew) <- "nonlin" yrcskew <- function(tab, nd.symm=NA, nd.skew=1, diagonal=FALSE, weighting=c("marginal", "uniform", "none"), se=c("none", "jackknife", "bootstrap"), nreplicates=100, ncpus=getOption("boot.ncpus"), family=poisson, weights=NULL, start=NA, etastart=NULL, tolerance=1e-8, iterMax=15000, trace=FALSE, verbose=TRUE, ...) { weighting <- match.arg(weighting) se <- match.arg(se) tab <- as.table(tab) if(length(dim(tab)) < 2) stop("tab must have (at least) two dimensions") if(nrow(tab) != ncol(tab)) stop("tab must be a square table for asymmetry models") if(!all(rownames(tab) == colnames(tab))) stop("tab must have identical row and column names for symmetric model") if(!is.na(nd.symm) && nd.symm <= 0) stop("nd.symm must be NA or strictly positive") if(is.na(nd.skew)) stop("nd.skew must be strictly positive") if(nd.skew > 1) warning("nd.skew > 1 is untested. You are on your own!") if(!is.na(nd.symm) && nd.symm/2 > min(nrow(tab), ncol(tab)) - 1) stop("Number of dimensions of symmetric association cannot exceed 2 * (min(nrow(tab), ncol(tab)) - 1)") if(length(dim(tab)) > 2) tab <- margin.table(tab, 1:2) tab <- prepareTable(tab, TRUE) vars <- names(dimnames(tab)) if(diagonal && !is.na(nd.symm)) diagstr <- sprintf("+ Diag(%s, %s) ", vars[1], vars[2]) else diagstr <- "" if(is.na(nd.symm)) basef <- sprintf("Freq ~ %s + %s %s+ Symm(%s, %s)", vars[1], vars[2], diagstr, vars[1], vars[2]) else basef <- sprintf("Freq ~ %s + %s %s+ instances(MultHomog(%s, %s), %i)", vars[1], vars[2], diagstr, vars[1], vars[2], nd.symm) contr <- getOption("contrasts") on.exit(options(contrasts=contr)) options(contrasts=c("contr.treatment", "contr.treatment")) if(!is.null(start) && identical(start, NA)) { cat("Running base model to find starting values...\n") args <- list(formula=as.formula(basef), data=tab, weights=weights, family=family, tolerance=1e-3, iterMax=iterMax, verbose=verbose, trace=trace) base <- do.call("gnm", c(args, list(...))) start <- c(parameters(base), rep(NA, nd.skew * (nrow(tab) + 2))) if(is.null(etastart)) etastart <- as.numeric(predict(base)) cat("Running real model...\n") } f <- sprintf("%s + instances(YRCSkew(%s, %s, factor(ifelse(as.numeric(%s) < as.numeric(%s), 1, 0)), factor(ifelse(as.numeric(%s) > as.numeric(%s), 1, 0))), %s)", basef, vars[1], vars[2], vars[1], vars[2], vars[1], vars[2], nd.skew) args <- list(formula=eval(as.formula(f)), data=tab, constrain="YRCSkew\\(.*\\)0$", family=family, weights=weights, start=start, etastart=etastart, tolerance=tolerance, iterMax=iterMax, verbose=verbose, trace=trace) model <- do.call("gnm", c(args, list(...))) if(is.null(model)) return(NULL) class(model) <- c("yrcskew", "rc.symm", "rc", "assocmod", class(model)) model$call.gnm <- model$call model$call <- match.call() if(!is.na(nd.symm)) model$assoc <- assoc.rc.symm(model, weighting=weighting) else model$assoc <- list() model$assoc.yrcskew <- assoc.yrcskew(model, weighting=weighting) if(se %in% c("jackknife", "bootstrap")) { assoc1 <- if(is.na(nd.symm)) assoc.yrcskew else assoc.rc.symm assoc2 <- if(is.na(nd.symm)) NULL else assoc.yrcskew jb <- jackboot(se, ncpus, nreplicates, tab, model, assoc1, assoc2, weighting, NULL, NULL, family, weights, verbose, trace, start, etastart, ...) if(!is.na(nd.symm)) { model$assoc$covtype <- se model$assoc$covmat <- jb$covmat1 model$assoc$adj.covmats <- jb$adj.covmats1 model$assoc$jack.results <- jb$jack.results1 model$assoc$boot.results <- jb$boot.results1 model$assoc.yrcskew$covtype <- se model$assoc.yrcskew$covmat <- jb$covmat2 model$assoc.yrcskew$adj.covmats <- jb$adj.covmats2 model$assoc.yrcskew$jack.results <- jb$jack.results2 model$assoc.yrcskew$boot.results <- jb$boot.results2 } else { model$assoc.yrcskew$covtype <- se model$assoc.yrcskew$covmat <- jb$covmat model$assoc.yrcskew$adj.covmats <- jb$adj.covmats model$assoc.yrcskew$jack.results <- jb$jack.results model$assoc.yrcskew$boot.results <- jb$boot.results } } else { if(!is.na(nd.symm)) { model$assoc$covtype <- se model$assoc$covmat <- numeric(0) model$assoc$adj.covmats <- numeric(0) model$assoc$boot.results <- numeric(0) model$assoc$jack.results <- numeric(0) } model$assoc.yrcskew$covtype <- se model$assoc.yrcskew$covmat <- numeric(0) model$assoc.yrcskew$adj.covmats <- numeric(0) model$assoc.yrcskew$boot.results <- numeric(0) model$assoc.yrcskew$jack.results <- numeric(0) } model } assoc.yrcskew <- function(model, weighting=c("marginal", "uniform", "none"), ...) { if(!inherits(model, "gnm")) stop("model must be a gnm object") tab <- prepareTable(model$data, TRUE) vars <- names(dimnames(tab)) weighting <- match.arg(weighting) if(weighting == "marginal") p <- prop.table(apply(tab, 1, sum, na.rm=TRUE) + apply(tab, 2, sum, na.rm=TRUE)) else if(weighting == "uniform") p <- rep(1/nrow(tab), nrow(tab)) else p <- rep(1, nrow(tab)) sc <- matrix(NA, nrow(tab), 0) nd <- 0 while(TRUE) { musk <- parameters(model)[pickCoef(model, sprintf("YRCSkew\\(.*inst = %i\\)(\\Q%s\\E)", nd+1, paste(rownames(tab), collapse="\\E|\\Q")))] if(length(musk) != nrow(tab)) break nd <- nd + 1 sc <- cbind(sc, musk) } if(nd <= 0) { musk <- parameters(model)[pickCoef(model, sprintf("YRCSkew.*\\)(\\Q%s\\E)$", paste(rownames(tab), collapse="\\E|\\Q")))] if(length(musk) == nrow(tab)) { nd <- 1 sc <- cbind(sc, musk) } else { stop("No skew dimensions found. Are you sure this is a Yamaguchi RC_SK model?") } } skew <- parameters(model)[pickCoef(model, "YRCSkew.*\\)1$")] if(length(skew) != nd) stop("Skew coefficients not found. Are you sure this is a Yamaguchi RC_SK model?") if(length(pickCoef(model, "Diag\\(")) > nrow(tab)) dg <- matrix(pickCoef(model, "Diag\\(", value=TRUE), ncol=nrow(tab)) else if(length(pickCoef(model, "Diag\\(")) > 0) dg <- matrix(pickCoef(model, "Diag\\(", value=TRUE), 1, nrow(tab)) else dg <- numeric(0) sc <- sweep(sc, 2, colSums(sweep(sc, 1, p/sum(p), "*")), "-") lambda <- matrix(0, nrow(tab), ncol(tab)) for(i in 1:nd) { lambda <- lambda + abs(skew[i]) * sc[,i] %o% sc[,i] } lambda0 <- lambda * sqrt(p %o% p) sv <- svd(lambda0) sc[] <- diag(1/sqrt(p)) %*% sv$u[,1:nd] phisk <- sign(skew) * sv$d[1:nd] phisk <- rbind(c(phisk)) dim(sc)[3] <- 1 names(phisk) <- NULL colnames(sc) <- colnames(phisk) <- paste("Dim", 1:nd, sep="") rownames(sc) <- rownames(tab) if(length(dg) > 0) { dg[,order(rownames(tab))] <- dg colnames(dg) <- if(all(rownames(tab) == colnames(tab))) rownames(tab) else paste(rownames(tab), colnames(tab), sep=":") if(nrow(dg) > 1) rownames(dg) <- dimnames(tab)[[3]] else rownames(dg) <- "All levels" } row.weights <- as.matrix(apply(tab, 1, sum, na.rm=TRUE)) col.weights <- as.matrix(apply(tab, 2, sum, na.rm=TRUE)) obj <- list(phi = phisk, row = sc, col = sc, diagonal = dg, weighting = weighting, row.weights = row.weights, col.weights = col.weights, vars = vars) class(obj) <- c("assoc.yrcskew", "assoc.symm", "assoc") obj } assoc <- function(model, weighting, ...) UseMethod("assoc", model)
write.to.home <- NULL systemRun <- function(directory, output, write.to.home){ if (.Platform$OS.type=="unix"){ dir <- paste("cd",directory,sep=" ") system(paste(dir,"open the_audiolyzr_mac_v5/the_audiolyzr_mac_v5.app", sep="; ")) if (!write.to.home) system(paste("cd",output,";","open ..")) } if (.Platform$OS.type=="windows"){ path <- normalizePath(file.path(directory,"the_audiolyzr_win_v5", "the_audiolyzR_win_v5.exe")) shell.exec(path) if (!write.to.home) shell.exec(file.path(output,"..")) } if (!write.to.home) message('To load plots to synthesizer: \n', 'Drag the folder entitled "json_matrix" \n', 'to the "Drop folder here to Audiolyze!" box \n', 'at the bottom of the synthesizer (you may have to scroll down).') message ("Note: Audio plot files written to \n", file.path(output)) }
drawPoliticalMap <- function(cls, dirichletTiles, Lines, Columns, Toroid, add=F, alphaV=0.2){ ccc <- DefaultColorSequence()[cls] if(add==T) { ccc <- alpha(ccc, alphaV) plot(dirichletTiles,fillcol=ccc,close=T, showpoints=T, border=F, add=T) } else{ if(Toroid) plot(1, type="n", ylim=c(Lines*2,1), xlim=c(1,Columns*2)) else plot(1, type="n", ylim=c(Lines,1), xlim=c(1,Columns)) plot(dirichletTiles,fillcol=ccc,close=T, showpoints=T, border=F, add=T) } }
glassopath=function (s, rholist=NULL, thr = 1e-04, maxit = 10000, approx = FALSE , penalize.diagonal = TRUE, w.init = NULL, wi.init = NULL, trace = 1) { n = nrow(s) if(is.null(rholist)){ rholist=seq(max(abs(s))/10,max(abs(s)),length=10) } rholist=sort(rholist) ipen = 1 * (penalize.diagonal) ia = 1 * approx rho=xx=ww=matrix(0,n,n) nrho=length(rholist) beta=what=array(0,c(n,n,nrho)) jerrs=rep(0,nrho) mode(rholist) = "double" mode(nrho) = "integer" mode(rho) = "double" mode(s) = "double" mode(ww) = "double" mode(xx) = "double" mode(n) = "integer" mode(maxit) = "integer" mode(ia) = "integer" mode(trace) = "integer" mode(ipen) = "integer" mode(thr) = "double" mode(beta) = "double" mode(what) = "double" mode(jerrs) = "integer" junk <- .Fortran("glassopath", beta=beta,what=what,jerrs=jerrs,rholist,nrho,n, s, rho, ia, trace, ipen, thr, maxit = maxit, ww = ww, xx = xx, niter = integer(1), del = double(1), ierr = integer(1), PACKAGE="glasso") xx = array(junk$beta, c(n,n,nrho)) what = array(junk$what, c(n,n,nrho)) return(list(w=what, wi = xx, approx = approx, rholist=rholist, errflag = junk$jerrs)) }
l_getNDimStates <- function(widget) { UseMethod("l_getNDimStates", widget) } l_getNDimStates.loon <- function(widget) { statesNames <- loon::l_nDimStateNames(widget) states <- stats::setNames( lapply(statesNames, function(s) { if(length(widget[s]) == 0) return(NULL) widget[s] }), statesNames) remove_null(states, as_list = FALSE) } l_getNDimStates.l_compound <- function(widget) { lapply(widget, function(x) l_getNDimStates(x)) }
setsetequal <- function (x, y) { if (!is.list(x) && !is.list(y)) stop("Arguments must be lists") all(c(setmatch(x, y, 0L) > 0L, setmatch(y, x, 0L) > 0L)) }
predict.mvr <- function(object, newdata, ncomp = 1:object$ncomp, comps, type = c("response", "scores"), na.action = na.pass, ...) { if (missing(newdata) || is.null(newdata)) newX <- model.matrix(object) else if (is.matrix(newdata)) { if (ncol(newdata) != length(object$Xmeans)) stop("'newdata' does not have the correct number of columns") newX <- newdata } else { Terms <- delete.response(terms(object)) m <- model.frame(Terms, newdata, na.action = na.action) if (!is.null(cl <- attr(Terms, "dataClasses"))) .checkMFClasses(cl, m) newX <- delete.intercept(model.matrix(Terms, m)) } nobs <- dim(newX)[1] if (!is.null(object$scale)) newX <- newX / rep(object$scale, each = nobs) type <- match.arg(type) if (type == "response") { if (missing(comps) || is.null(comps)) { if (missing(newdata)) return(fitted(object)[,,ncomp, drop=FALSE]) B <- coef(object, ncomp = ncomp, intercept = TRUE) dPred <- dim(B) dPred[1] <- dim(newX)[1] dnPred <- dimnames(B) dnPred[1] <- if(is.null(dimnames(newX))) list(NULL) else dimnames(newX)[1] pred <- array(dim = dPred, dimnames = dnPred) for (i in seq(along = ncomp)) pred[,,i] <- newX %*% B[-1,,i] + rep(B[1,,i], each = nobs) return(pred) } else { B <- rowSums(coef(object, comps = comps), dims = 2) B0 <- object$Ymeans - object$Xmeans %*% B pred <- newX %*% B + rep(B0, each = nobs) if (missing(newdata) && !is.null(object$na.action)) pred <- napredict(object$na.action, pred) return(pred) } } else { if (missing(comps) || is.null(comps)) comps <- ncomp if (missing(newdata)) { TT <- object$scores[,comps] if (!is.null(object$na.action)) TT <- napredict(object$na.action, TT) } else { if (is.null(object$projection)) stop("`object' has no `projection' component. Maybe it was fitted with `stripped = TRUE'.") TT <- (newX - rep(object$Xmeans, each = nobs)) %*% object$projection[,comps] } return(TT) } }
CDMEAN0 <- function(Train,Test, P, lambda=1e-5, C=NULL){ PTrain<-P[rownames(P)%in%Train,] if (!is.null(C)){ PTrain<-C%*%PTrain} CDmean<-mean(diag(PTrain%*%solve(crossprod(PTrain)+lambda*diag(ncol(PTrain)),t(PTrain)))/diag(tcrossprod(PTrain))) return(CDmean) }
equ6 <- function(temp,rate, augment=F, return_fit=F){ try_test <- try({ R<-8.617343e-5 b <- 1 c <- 1.04 d <- 273.15 e <- 1.04 f <- 273.15 a <- max(rate)/max((((temp+273.15)/298.15)*exp(b/R*(1/298.15-1/(temp+273.15))))/(1+exp(c/R*(1/d-1/(temp+273.15)))+exp(e/R*(1/f-1/(temp+273.15))))) fit = minpack.lm::nlsLM(rate ~ (a*((temp+273.15)/298.15)*exp(b/R*(1/298.15-1/(temp+273.15))))/(1+exp(c/R*(1/d-1/(temp+273.15)))+exp(e/R*(1/f-1/(temp+273.15)))), control = minpack.lm::nls.lm.control(maxiter = 10^20), start = list(a=a,b=b,c=c,d=d,e=e,f=f)) output <- broom::tidy(fit) a <- output$estimate[output$term=="a"] b <- output$estimate[output$term=="b"] c <- output$estimate[output$term=="c"] d <- output$estimate[output$term=="d"] f_equ= function(t){(a*((t+273.15)/298.15)*exp(b/R*(1/298.15-1/(t+273.15))))/(1+exp(c/R*(1/d-1/(t+273.15)))+exp(e/R*(1/f-1/(t+273.15))))} }) output <- temperatureresponse::amend_output(output, fit, f_equ, temp, rate, try_test, augment, return_fit) output$model <- "equ06" print("equ06") return(output) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) incl <- function(x){ path <- paste0("figures/", x) knitr::include_graphics(path) } library("boxr") incl("rstudio-cloud.png") incl("interactive-four-steps.png") incl("interactive-config.png")
next_gBOIN_TB <- function(target, n, y, d, mu_1 = 0.6 * target, mu_2 = 1.4 * target){ ndose <- length(y) if (y[d]/n[d] <=(target+mu_1)/2&& d != ndose) { d = d + 1 } else if (y[d]/n[d] >= (target+mu_2)/2 && d != 1) { d = d - 1 } else { d = d } d }
random_r <- function(K = 100, correlation = 0.5, N = 10, Fisher_Z = FALSE) { if(length(N) != 1) { samples <- sum(N) theGroups <- rep(1:length(N), N) finalN <- N } else { samples <- K * N theGroups <- rep(1:K, each = N) finalN <- N } C <- matrix(c(1, correlation, correlation, 1), nrow = 2, ncol = 2) random_XY <- data.frame(mvrnorm(n = samples, mu = c(0, 0), C), group = theGroups) theCor <- unlist(lapply(split(random_XY, random_XY$group), function(x) return(cor(x[,1], x[,2])))) random_r <- data.frame(r = theCor, var_r = ((1.0 - theCor ^ 2.0) ^ 2.0)/(finalN - 2.0), N = finalN) if(Fisher_Z == TRUE) { random_r <- cbind(random_r, data.frame(Z = 0.5 * log((1.0 + random_r[, 1])/(1.0 - random_r[, 1])), var_Z = 1.0 / (random_r[, 3] - 3))) } return(random_r) }
ltspca <- function(x, q, alpha=0.5, b.choice=NULL,tol=1e-6, N1=3, N2=2, N2bis=10, Npc=10){ determin.start <- function(x, strategy, alpha){ n <- nrow(x) h <- n - floor(n*alpha) Qn.x <- apply(x,2,robustbase::Qn) rm.x <- which(Qn.x != 0) R.x <- apply(x[,rm.x], 2, rank) Med.x <- apply(x[,rm.x],2,median) if(strategy=="spearman"){ Y <- R.x Qn.y <- apply(Y,2,robustbase::Qn) rm.y <- which(Qn.y !=0) U <- sweep(Y[,rm.y], 2, (Qn.x[rm.x][rm.y]/Qn.y[rm.y]) , "*") rm(Y) median.coorwise.U <- apply(U,2,median) Qn.coorwise.U <- apply(U,2,robustbase::Qn) Z <- scale( U ,center= median.coorwise.U, scale= Qn.coorwise.U) obswise.sqnorm <- apply(Z^2, 1, sum) rm(Z) U <- x[which(obswise.sqnorm <= sort(obswise.sqnorm)[h]),] }else if(strategy=="tanh"){ Z <- scale(x[,rm.x] , center= Med.x, scale= Qn.x[rm.x]) Y <- apply(Z, 2, tanh) Qn.y <- apply(Y,2,robustbase::Qn) rm.y <- which(Qn.y !=0) U <- sweep(Y[,rm.y], 2, (Qn.x[rm.x][rm.y]/Qn.y[rm.y]), "*") rm(Y) median.coorwise.U <- apply(U,2,median) Qn.coorwise.U <- apply(U,2,robustbase::Qn) Z <- scale( U , center= median.coorwise.U, scale= Qn.coorwise.U) obswise.sqnorm <- apply(Z^2, 1, sum) rm(Z) U <- x[which(obswise.sqnorm <= sort(obswise.sqnorm)[h]),] }else if(strategy=="normalscore"){ Y <- qnorm( (R.x - (1/3) ) / (n + (1/3) ) ) Qn.y <- apply(Y,2,robustbase::Qn) rm.y <- which(Qn.y !=0) U <- sweep(Y[,rm.y], 2, (Qn.x[rm.x][rm.y]/Qn.y[rm.y]) , "*") rm(Y) median.coorwise.U <- apply(U,2,median) Qn.coorwise.U <- apply(U,2,robustbase::Qn) Z <- scale( U , center= median.coorwise.U, scale= Qn.coorwise.U) obswise.sqnorm <- apply(Z^2, 1, sum) rm(Z) U <- x[which(obswise.sqnorm <= sort(obswise.sqnorm)[h]),] }else if(strategy=="closesubset"){ Z <- scale(x[,rm.x] , center= Med.x, scale= Qn.x[rm.x]) obswise.sqnorm <- apply(Z^2, 1, sum) rm(Z) U <- x[which(obswise.sqnorm <= sort(obswise.sqnorm)[h]),] }else if(strategy=="spatialsign"){ Z <- scale(x[,rm.x] , center= Med.x, scale=FALSE) obswise.norm <- sqrt( apply(Z^2, 1, sum) ) U <- sweep(Z,1,obswise.norm,"/") median.coorwise.U <- apply(U,2,median) Qn.coorwise.U <- apply(U,2,robustbase::Qn) Z <- scale( U , center= median.coorwise.U, scale= Qn.coorwise.U) obswise.sqnorm <- apply(Z^2, 1, sum) rm(Z) U <- x[which(obswise.sqnorm <= sort(obswise.sqnorm)[h]),] } return(U) } x<-as.matrix(x) n<-dim(x)[1] p<-dim(x)[2] h<-n-floor(n*alpha) keep_s <- Inf cand <- c("spearman", "tanh", "normalscore", "closesubset", "spatialsign") for(i in cand){ U <- determin.start(x=x, strategy=i, alpha=alpha) mu <- apply(U,2,mean) if(is.null(b.choice)) { set.seed(321) bM <- mvtnorm::rmvnorm(p,mean = rep(0,q),sigma = diag(q)) b <- qr.Q(qr(bM)) update=findpcs0(x=U, B=b, mu=mu, Npc=Npc, tol=tol) b=update$Bmat mu=update$mu }else{ b <- b.choice } rm(U) update=findpcs2(x=x, B=b, mu=mu, h=h, s=0, N1=N1, N2=N2, Npc=Npc, tol=tol, fixed=!is.null(b.choice)) b=update$Bmat mu=update$mu s=update$scale if(s < keep_s){ opt_cand <- i keep_s <- s keep_mu <- mu keep_b <- b } } mu <- keep_mu b <- keep_b s <- keep_s update=findpcs(x=x, B=b, mu=mu, h=h, s=s, N1=0, N2=N2bis, Npc=Npc, tol=tol, fixed=!is.null(b.choice)) b=update$Bmat mu=update$mu s=update$scale ws <- rep(0,n) ws[update$index] <- 1 res<-list(b=b, mu=mu, best.obj=s, ws=ws, best.cand=opt_cand) return(res) }
qasl <- function(p, theta = 0, mu = 0, sigma = 1, lower.tail = TRUE, log.p = FALSE){ if(sigma <= 0){ stop("sigma > 0 is required.") } kappa <- (sqrt(2 * sigma^2 + mu^2) - mu) / sqrt(2 * sigma) qasla(p, theta, kappa, sigma, lower.tail = lower.tail, log.p = log.p) } qasla <- function(p, theta = 0, kappa = 1, sigma = 1, lower.tail = TRUE, log.p = FALSE){ if(sigma <= 0){ stop("sigma > 0 is required.") } if(kappa <= 0){ stop("kappa > 0 is required.") } ret <- do.call("c", lapply(p, qasla.one.log, theta, kappa, sigma, lower.tail = lower.tail, log.p = log.p)) ret } qasla.one.log <- function(p, theta, kappa, sigma, lower.tail = TRUE, log.p = FALSE){ if(log.p){ if(p > 0){ return(NaN) } } else{ if(p < 0 | p > 1){ return(NaN) } } if(log.p){ p <- exp(p) } if(! lower.tail){ p <- 1 - p } if(p == 0){ ret <- -Inf } else if(p == 1){ ret <- Inf } else{ ret <- theta if(p <= kappa^2 / (1 + kappa^2)){ ret <- ret + sigma * kappa / sqrt(2) * log((1 + kappa^2) / kappa^2 * p) } else{ ret <- ret - sigma / (sqrt(2) * kappa) * log((1 + kappa^2)* (1- p)) } } ret }
grid_terrain = function(las, res = 1, algorithm, ..., keep_lowest = FALSE, full_raster = FALSE, use_class = c(2L,9L), Wdegenerated = TRUE, is_concave = FALSE) { UseMethod("grid_terrain", las) } grid_terrain.LAS = function(las, res = 1, algorithm, ..., keep_lowest = FALSE, full_raster = FALSE, use_class = c(2L,9L), Wdegenerated = TRUE, is_concave = FALSE) { if (!is_a_number(res) & !is(res, "RasterLayer")) stop("res is not a number or a RasterLayer", call. = FALSE) if (is_a_number(res)) assert_all_are_non_negative(res) assert_is_algorithm(algorithm) assert_is_algorithm_spi(algorithm) assert_is_a_bool(keep_lowest) assert_is_a_bool(full_raster) assert_is_a_bool(is_concave) if (full_raster & is_concave) stop("'full_raster' and 'is_concave' cannot both be 'TRUE'", call. = FALSE) if (!"Classification" %in% names(las@data)) stop("LAS object does not contain 'Classification' attribute", call. = FALSE) if (any(as.integer(use_class) != use_class)) stop("'add_class' is not a vector of integers'", call. = FALSE) use_class <- as.integer(use_class) ellipsis <- list(...) fast <- isTRUE(ellipsis[["fast"]]) . <- 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) verbose("Generating interpolation coordinates...") layout <- rOverlay(las, res) names(layout) <- "Z" grid <- raster2dataframe(layout, xy = TRUE, fast = fast) data.table::setDT(grid) grid[, Z := NULL] data.table::setnames(grid, names(grid), c("X", "Y")) if (!full_raster) { if (is_concave) hull <- concaveman(coordinates(las), concavity = 10, length_threshold = 100) else hull <- convex_hull(las@data$X, las@data$Y) hull <- sf::st_polygon(list(as.matrix(hull))) hull <- sf::st_sfc(hull) hull <- sf::st_buffer(hull, dist = raster::res(layout)[1]) hull <- sf::st_coordinates(hull)[,1:2] keep <- sp::point.in.polygon(grid$X, grid$Y, hull[,1], hull[,2], TRUE) > 0 if (!all(keep)) grid = grid[keep] } verbose("Interpolating ground points...") lidR.context <- "grid_terrain" ground <- LAS(ground, las@header, proj4string = las@proj4string, check = FALSE, index = las@index) Zg <- algorithm(ground, grid) Zg[is.nan(Zg)] <- NA_real_ fast_quantization(Zg, las@header@PHB[["Z scale factor"]], las@header@PHB[["Z offset"]]) cells <- raster::cellFromXY(layout, grid[, .(X,Y)]) if (fast) { layout@data@values[cells] <- Zg layout@data@inmemory <- TRUE } else { suppressWarnings(layout[cells] <- Zg) } if (keep_lowest) { verbose("Forcing the lowest ground points to be retained...") reso <- raster::res(layout)[1] lasg <- filter_poi(las, Classification %in% c(use_class)) rmin <- grid_metrics(lasg, ~list(Z = min(Z)), reso) suppressWarnings(layout[] <- pmin(layout[], rmin[], na.rm = TRUE)) } return(layout) } grid_terrain.LAScluster = function(las, res = 1, algorithm, ..., keep_lowest = FALSE, full_raster = FALSE, use_class = c(2L,9L), Wdegenerated = TRUE, is_concave = FALSE) { x <- readLAS(las) if (is.empty(x)) return(NULL) bbox <- raster::extent(las) dtm <- grid_terrain(x, res, algorithm, keep_lowest = keep_lowest, full_raster = full_raster, use_class = use_class, Wdegenerated = Wdegenerated, is_concave = is_concave) dtm <- raster::crop(dtm, bbox) raster::crs(dtm) <- crs(x) return(dtm) } grid_terrain.LAScatalog = function(las, res = 1, algorithm, ..., keep_lowest = FALSE, full_raster = FALSE, use_class = c(2L,9L), Wdegenerated = TRUE, is_concave = FALSE) { if (!is_a_number(res) & !is(res, "RasterLayer")) stop("res is not a number or a RasterLayer") if (is_a_number(res)) assert_all_are_non_negative(res) assert_is_algorithm(algorithm) assert_is_algorithm_spi(algorithm) opt_select(las) <- "xyzc" alignment <- list(res = res, start = c(0,0)) if (is(res, "RasterLayer")) { ext <- raster::extent(res) r <- raster::res(res)[1] las <- catalog_intersect(las, res) start <- c(ext@xmin, ext@ymin) alignment <- list(res = r, start = start) } 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, grid_terrain, res = res, algorithm = algorithm, ..., keep_lowest = keep_lowest, full_raster = full_raster, use_class = use_class, Wdegenerated = Wdegenerated, is_concave = is_concave, .options = options) return(output) }
setAs("CHMfactor", "sparseMatrix", function(from) .Call(CHMfactor_to_sparse, from)) setAs("CHMfactor", "triangularMatrix", function(from) .Call(CHMfactor_to_sparse, from)) setAs("CHMfactor", "Matrix", function(from) .Call(CHMfactor_to_sparse, from)) setAs("CHMfactor", "pMatrix", function(from) as(from@perm + 1L, "pMatrix")) setMethod("expand", signature(x = "CHMfactor"), function(x, ...) list(P = as(x, "pMatrix"), L = as(x, "sparseMatrix"))) isLDL <- function(x) { stopifnot(is(x, "CHMfactor")) as.logical(! x@type[2]) } .isLDL <- function(x) as.logical(! x@type[2]) setMethod("image", "CHMfactor", function(x, ...) image(as(as(x, "sparseMatrix"), "dgTMatrix"), ...)) .CHM_solve <- function(a, b, system = c("A", "LDLt", "LD", "DLt", "L", "Lt", "D", "P", "Pt"), ...) { chk.s(..., which.call=-2) sysDef <- eval(formals()$system) .Call(CHMfactor_solve, a, b, match(match.arg(system, sysDef), sysDef, nomatch = 0L)) } setMethod("solve", signature(a = "CHMfactor", b = "ddenseMatrix"), .CHM_solve, valueClass = "dgeMatrix") setMethod("solve", signature(a = "CHMfactor", b = "matrix"), .CHM_solve, valueClass = "dgeMatrix") setMethod("solve", signature(a = "CHMfactor", b = "numeric"), function(a, b, ...) .CHM_solve(a, matrix(if(is.double(b)) b else as.double(b), length(b), 1L), ...), valueClass = "dgeMatrix") setMethod("solve", signature(a = "CHMfactor", b = "dsparseMatrix"), function(a, b, system = c("A", "LDLt", "LD", "DLt", "L", "Lt", "D", "P", "Pt"), ...) { chk.s(..., which.call=-2) sysDef <- eval(formals()$system) .Call(CHMfactor_spsolve, a, as(as(b, "CsparseMatrix"), "dgCMatrix"), match(match.arg(system, sysDef), sysDef, nomatch = 0L)) }, valueClass = "CsparseMatrix") setMethod("solve", signature(a = "CHMfactor", b = "diagonalMatrix"), function(a, b, ...) solve(a, as(b, "dsparseMatrix"), ...)) setMethod("solve", signature(a = "CHMfactor", b = "missing"), function(a, b, system = c("A", "LDLt", "LD","DLt", "L","Lt", "D", "P","Pt"), ...) { chk.s(..., which.call=-2) sysDef <- eval(formals()$system) system <- match.arg(system, sysDef) i.sys <- match(system, sysDef, nomatch = 0L) as(.Call(CHMfactor_spsolve, a, .sparseDiagonal(a@Dim[1], shape="g"), i.sys), switch(system, A=, LDLt = "symmetricMatrix", LD=, DLt=, L=, Lt =, D = "dtCMatrix", P=, Pt = "pMatrix")) }) setMethod("solve", signature(a = "CHMfactor", b = "ANY"), function(a, b, system = c("A", "LDLt", "LD","DLt", "L","Lt", "D", "P","Pt"), ...) solve(a, as(b, "dMatrix"), system, ...)) setMethod("chol2inv", signature(x = "CHMfactor"), function (x, ...) { chk.s(..., which.call=-2) solve(x, system = "A") }) setMethod("determinant", signature(x = "CHMfactor", logarithm = "missing"), function(x, logarithm, ...) determinant(x, TRUE)) setMethod("determinant", signature(x = "CHMfactor", logarithm = "logical"), function(x, logarithm, ...) { ldet <- .Call(CHMfactor_ldetL2, x) / 2 mkDet(logarithm=logarithm, ldet=ldet, sig = 1L) }) setMethod("update", signature(object = "CHMfactor"), function(object, parent, mult = 0, ...) { stopifnot(extends(clp <- class(parent), "sparseMatrix")) d <- dim(parent) if(!extends(clp, "dsparseMatrix")) clp <- class(parent <- as(parent, "dsparseMatrix")) if(!extends(clp, "CsparseMatrix")) clp <- class(parent <- as(parent, "CsparseMatrix")) if(d[1] == d[2] && !extends(clp, "dsCMatrix") && !is.null(v <- getOption("Matrix.verbose")) && v >= 1) message(gettextf("Quadratic matrix '%s' (=: A) is not formally\n symmetric. Will be treated as A A' ", "parent"), domain=NA) chk.s(..., which.call=-2) .Call(CHMfactor_update, object, parent, mult) }) .updateCHMfactor <- function(object, parent, mult) .Call(CHMfactor_update, object, parent, mult) setMethod("updown", signature(update="ANY", C="ANY", L="ANY"), function(update,C,L) stop("'update' must be logical or '+' or '-'; 'C' a matrix, and 'L' a \"CHMfactor\"")) setMethod("updown", signature(update="logical", C="mMatrix", L="CHMfactor"), function(update,C,L){ bnew <- as(L,'pMatrix') %*% C .Call(CHMfactor_updown,update, as(bnew,'sparseMatrix'), L) }) setMethod("updown", signature(update="character", C="mMatrix", L="CHMfactor"), function(update,C,L){ if(! update %in% c("+","-")) stop("update must be TRUE/FALSE or '+' or '-'") update <- update=="+" bnew <- as(L,'pMatrix') %*% C .Call(CHMfactor_updown,update, as(bnew,'sparseMatrix'), L) }) ldetL2up <- function(x, parent, Imult) { stopifnot(is(x, "CHMfactor"), is(parent, "CsparseMatrix"), nrow(x) == nrow(parent)) .Call(CHMfactor_ldetL2up, x, parent, as.double(Imult)) } destructive_Chol_update <- function(L, parent, Imult = 1) { stopifnot(is(L, "CHMfactor"), is(parent, "sparseMatrix")) .Call(destructive_CHM_update, L, parent, Imult) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(JWileymisc) mtcars$cyl <- factor(mtcars$cyl) m <- stats::lm(mpg ~ hp + cyl, data = mtcars) mp <- modelPerformance(m) print(mp) mp$Performance[, F2] mt <- modelTest(m) print(mt) APAStyler(mt) m2 <- stats::lm(mpg ~ hp * cyl, data = mtcars) APAStyler(modelTest(m2))
knitr::opts_chunk$set(collapse = TRUE, comment = " fig.width = 6, fig.height = 4, fig.align = "center") library(simmer) library(parallel) patient <- trajectory("patients' path") %>% seize("nurse", 1) %>% timeout(function() rnorm(1, 15)) %>% release("nurse", 1) %>% seize("doctor", 1) %>% timeout(function() rnorm(1, 20)) %>% release("doctor", 1) %>% seize("administration", 1) %>% timeout(function() rnorm(1, 5)) %>% release("administration", 1) envs <- mclapply(1:100, function(i) { simmer("SuperDuperSim") %>% add_resource("nurse", 1) %>% add_resource("doctor", 2) %>% add_resource("administration", 1) %>% add_generator("patient", patient, function() rnorm(1, 10, 2)) %>% run(80) %>% wrap() }) library(simmer.plot) resources <- get_mon_resources(envs) plot(resources, metric = "utilization") plot(resources, metric = "usage", c("nurse", "doctor"), items = "server") plot(get_mon_resources(envs[[6]]), metric = "usage", "doctor", items = "server", steps = TRUE) arrivals <- get_mon_arrivals(envs) plot(arrivals, metric = "flow_time")
context("semicont_single") library(testthat) library(hmi) set.seed(123) y_imp <- iris[, 1] y_imp[sample(1:length(y_imp), size = 60)] <- 0 y_imp[sample(1:length(y_imp), size = 20)] <- NA X_imp <- cbind(1, iris[, 2:4]) imp1 <- imp_semicont_single(y_imp = y_imp, X_imp = X_imp, pvalue = 1) test_that("semicont_single returns plausible values", { expect_equal(class(imp1$y_ret), "array") expect_equal(sum(is.na(imp1$y_ret)), 0) })
rf_list_to_matrix <- function(input.twopt, thresh.LOD.ph = 0, thresh.LOD.rf = 0, thresh.rf = 0.5, ncpus = 1L, shared.alleles = FALSE, verbose = TRUE) { if (inherits(input.twopt, "mappoly.twopt")){ pair_input <- input.twopt$pairwise marnames <- rownames(get(input.twopt$data.name, pos = 1)$geno.dose)[sort(input.twopt$seq.num)] marindex <- sort(input.twopt$seq.num) lod.ph.mat <- lod.mat <- rec.mat <- matrix(NA, input.twopt$n.mrk, input.twopt$n.mrk) if(shared.alleles) ShP <- ShQ <- lod.mat if (ncpus > 1) { start <- proc.time() if (verbose) cat("INFO: Using ", ncpus, " CPUs.\n") cl <- parallel::makeCluster(ncpus) parallel::clusterExport(cl, varlist = c("thresh.LOD.ph", "thresh.LOD.rf", "thresh.rf", "shared.alleles"), envir = environment()) rf.lod.mat <- parallel::parSapply(cl, pair_input, "select_rf", thresh.LOD.ph, thresh.LOD.rf, thresh.rf, shared.alleles) parallel::stopCluster(cl) end <- proc.time() if (verbose) { cat("INFO: Done with", length(pair_input), " pairs of markers \n") cat("INFO: Operation took:", round((end - start)[3], digits = 3), "seconds\n") } } else { if (verbose) { cat("INFO: Going singlemode. Using one CPU.\n") } rf.lod.mat <- sapply(pair_input, select_rf, thresh.LOD.ph, thresh.LOD.rf, thresh.rf, shared.alleles) } rec.mat[lower.tri(rec.mat)] <- as.numeric(rf.lod.mat[1,]) rec.mat[upper.tri(rec.mat)] <- t(rec.mat)[upper.tri(rec.mat)] lod.mat[lower.tri(lod.mat)] <- as.numeric(rf.lod.mat[2,]) lod.mat[upper.tri(lod.mat)] <- t(lod.mat)[upper.tri(lod.mat)] lod.ph.mat[lower.tri(lod.ph.mat)] <- as.numeric(rf.lod.mat[3,]) lod.ph.mat[upper.tri(lod.ph.mat)] <- t(lod.ph.mat)[upper.tri(lod.ph.mat)] dimnames(lod.ph.mat) <- dimnames(rec.mat) <- dimnames(lod.mat) <- list(marnames, marnames) if(shared.alleles){ ShP[lower.tri(ShP)] <- as.numeric(rf.lod.mat[4,]) ShP[upper.tri(ShP)] <- t(ShP)[upper.tri(ShP)] ShQ[lower.tri(ShQ)] <- as.numeric(rf.lod.mat[5,]) ShQ[upper.tri(ShQ)] <- t(ShQ)[upper.tri(ShQ)] dimnames(ShP) <- dimnames(ShQ) <- list(marindex, marindex) } else{ ShP <- ShQ <- NULL } structure(list(thresh.LOD.ph = thresh.LOD.ph, thresh.LOD.rf = thresh.LOD.rf, thresh.rf = thresh.rf, rec.mat = rec.mat, lod.mat = abs(lod.mat), lod.ph.mat = abs(lod.ph.mat), ShP = ShP, ShQ = ShQ, data.name = input.twopt$data.name, chisq.pval.thres = input.twopt$chisq.pval.thres, chisq.pval = input.twopt$chisq.pval, cl = class(input.twopt)), class = "mappoly.rf.matrix") } else if (inherits(input.twopt, "mappoly.twopt2")){ rec.mat <- input.twopt$pairwise$rf lod.mat <- abs(input.twopt$pairwise$LOD.rf) lod.ph.mat <- abs(input.twopt$pairwise$LOD.ph) ShP <- input.twopt$pairwise$Sh.P1 ShQ <- input.twopt$pairwise$Sh.P2 dimnames(rec.mat) <- dimnames(lod.mat) <- dimnames(lod.ph.mat) <- dimnames(ShP) <- dimnames(ShQ) <- list(input.twopt$seq.mrk.names, input.twopt$seq.mrk.names) if(thresh.LOD.ph > 0){ rec.mat[lod.ph.mat < thresh.LOD.ph] <- NA lod.mat[lod.ph.mat < thresh.LOD.ph] <- NA lod.ph.mat[lod.ph.mat < thresh.LOD.ph] <- NA ShP[lod.ph.mat < thresh.LOD.ph] <- NA ShQ[lod.ph.mat < thresh.LOD.ph] <- NA } if(thresh.LOD.rf > 0){ rec.mat[lod.mat < thresh.LOD.rf] <- NA lod.mat[lod.mat < thresh.LOD.rf] <- NA lod.ph.mat[lod.mat < thresh.LOD.rf] <- NA ShP[lod.mat < thresh.LOD.rf] <- NA ShQ[lod.mat < thresh.LOD.rf] <- NA } if(thresh.rf < 0.5){ rec.mat[rec.mat < thresh.rf] <- NA lod.mat[rec.mat < thresh.rf] <- NA lod.ph.mat[rec.mat < thresh.rf] <- NA ShP[rec.mat < thresh.rf] <- NA ShQ[rec.mat < thresh.rf] <- NA } structure(list(thresh.LOD.ph = thresh.LOD.ph, thresh.LOD.rf = thresh.LOD.rf, thresh.rf = thresh.rf, rec.mat = rec.mat, lod.mat = lod.mat, lod.ph.mat = lod.ph.mat, ShP = ShP, ShQ = ShQ, data.name = input.twopt$data.name, chisq.pval.thres = input.twopt$chisq.pval.thres, chisq.pval = input.twopt$chisq.pval), class = "mappoly.rf.matrix") } else{ stop(deparse(substitute(input.twopt)), " is not an object of class 'mappoly.twopt' or 'mappoly.twopt2'") } } print.mappoly.rf.matrix <- function(x, ...) { cat(" This is an object of class 'mappoly.rf.matrix'\n\n") cat(" Criteria used to filter markers:\n\n") cat( " Configuration phase LOD: ", x$thresh.LOD.ph, "\n Recombination fraction LOD: ", x$thresh.LOD.rf, "\n Maximum recombination fraction: ", x$thresh.rf, "\n" ) n.mrk <- ncol(x$rec.mat) per.fill <- round(100 * sum(!is.na(x$rec.mat)) / (length(x$rec.mat)-ncol(x$rec.mat)), 1) cat("\n No. markers: ", n.mrk, "\n") cat(" Percentage filled: ", per.fill, "%\n") } plot.mappoly.rf.matrix <- function(x, type = c("rf", "lod"), ord = NULL, rem = NULL, main.text = NULL, index = FALSE, fact = 1, ...){ type <- match.arg(type) if(inherits(ord, "mappoly.sequence")) ord <- ord$seq.mrk.names if(type == "rf"){ w <- x$rec.mat if(!is.null(ord)) { w <- w[ord,ord] } if(!(is.null(rem) || sum(colnames(x$rec.mat)%in%rem) == 0)) { o <- which(colnames(x$rec.mat)%in%rem) w <- w[-o,-o] } if(fact > 1) w <- aggregate_matrix(w, fact) if(is.null(main.text)) main.text <- "Recombination fraction matrix" col.range <- na.omit(rev(fields::tim.colors())[1:(ceiling(128 * max(x$rec.mat, na.rm = TRUE)) + 1)]) brks <- NULL } else if(type == "lod") { w <- x$lod.mat if(!is.null(ord)) { w <- w[ord,ord] } if(!(is.null(rem) || sum(colnames(x$rec.mat)%in%rem) == 0)) { o <- which(colnames(x$rec.mat)%in%rem) w <- w[-o,-o] } if(fact > 1) w <- aggregate_matrix(w, fact) w[w < 1e-4] <- 1e-4 w <- log10(w) if(is.null(main.text)) main.text <- "log(LOD) Score matrix" col.range <- na.omit(fields::tim.colors()[1:(ceiling(128 * max(x$lod.mat, na.rm = TRUE)) + 1)]) col.range <- col.range[ceiling(seq(1, length(col.range), length.out = 10))] brks <- seq(min(w, na.rm = TRUE), max(w, na.rm = TRUE), length.out = 11) brks <- round(exp(brks/log10(exp(1))),1) } else stop("Invalid matrix type.") fields::image.plot( w, col = col.range, lab.breaks = brks, main = main.text, useRaster = FALSE, axes = FALSE ) if(ncol(w) < 100) ft <- .7 else ft <- 100/ncol(w) if(index) text(x = seq(0,1, length.out = ncol(w)), y = seq(0,1, length.out = ncol(w)), labels = colnames(w), cex = ft) } select_rf <- function(x, thresh.LOD.ph, thresh.LOD.rf, thresh.rf, shared.alleles = FALSE) { if(any(is.na(x))) { if(shared.alleles){return(c(NA,NA,NA,NA,NA))} else return(c(NA,NA,NA)) } if((nrow(x) == 1 || abs(x[2 , 1]) >= thresh.LOD.ph) && abs(x[1, 3]) >= thresh.LOD.rf && abs(x[1, 2]) <= thresh.rf) { if(shared.alleles){ y <- strsplit(rownames(x), "-") return(c(x[1,2:3], x[2,1], as.numeric(y[[1]][1]), as.numeric(y[[1]][2]))) } else { return(c(x[1,2:3], x[2,1])) } } else{ { if(shared.alleles){return(c(NA,NA,NA,NA,NA))} else return(c(NA,NA,NA)) } } }
cifti_brain_structs = function(file) { if (is.cifti(file)) { cii = file } else { cii = read_cifti(file) } struct_names = sapply(cii$BrainModel, attr, "BrainStructure") return(struct_names) }
probitCJS = function(ddl,dml,parameters,design.parameters,burnin, iter, initial=NULL, imat=NULL){ sample.z = function(id, mu.y, mu.z, yvec){ .Call("sampleZ", ID=id, PVec=pnorm(mu.y), PhiVec=pnorm(mu.z), yVec=yvec, PACKAGE="marked") } make.ztilde.idx = function(id, zvec){ .Call("makeZtildeIdx", ID=id, zvec=zvec, PACKAGE="marked") } restricted.dml = create.dml(ddl,parameters,design.parameters,restrict=TRUE) is.phi.re=!is.null(restricted.dml$Phi$re) is.p.re=!is.null(restricted.dml$p$re) yvec = as.vector(t(ddl$ehmat[,-1])) yvec=yvec[ddl$p$Time>=ddl$p$Cohort] n=length(yvec) ddl$p = ddl$p[ddl$p$Time>=ddl$p$Cohort,] Xy = as.matrix(restricted.dml$p$fe) pn.p = colnames(Xy) Xz = as.matrix(restricted.dml$Phi$fe) pn.phi = colnames(Xz) id = ddl$p$id if(is.phi.re){ n.phi.re=sapply(restricted.dml$Phi$re$re.list, function(x){dim(x)[2]}) K.phi=do.call("cbind", restricted.dml$Phi$re$re.list) ind.phi.re=rep(1:length(n.phi.re), n.phi.re) if(length(n.phi.re)>1){ m.phi.re=model.matrix(~factor(ind.phi.re)-1) } else{ m.phi.re=matrix(1, nrow=n.phi.re[[1]]) } colnames(m.phi.re)=names(n.phi.re) } if(is.p.re){ n.p.re=sapply(restricted.dml$p$re$re.list, function(x){dim(x)[2]}) K.p=do.call("cbind", restricted.dml$p$re$re.list) ind.p.re=rep(1:length(n.p.re), n.p.re) if(length(n.p.re)>1){ m.p.re=model.matrix(~factor(ind.p.re)-1) } else m.p.re=matrix(1, nrow=n.p.re[[1]]) colnames(m.p.re)=names(n.p.re) } if(is.null(parameters$Phi$prior)){ tau.b.z = 0.01 mu.b.z = rep(0,ncol(Xz)) }else{ tau.b.z = parameters$Phi$prior$tau mu.b.z = parameters$Phi$prior$mu } if(is.null(parameters$p$prior)){ tau.b.y = 0.01 mu.b.y = rep(0,ncol(Xy)) }else{ tau.b.y = parameters$p$prior$tau mu.b.y = parameters$p$prior$mu } if(is.phi.re){ if(is.null(parameters$Phi$prior$re)){ a.phi=rep(2,length(n.phi.re)) b.phi=rep(1.0E-4,length(n.phi.re)) Q.phi=lapply(n.phi.re, function(x){Diagonal(x)}) rnks.phi=n.phi.re } else{ a.phi=parameters$Phi$prior$re$a b.phi=parameters$Phi$prior$re$b Q.phi=parameters$Phi$prior$re$Q if(!is.list(Q.phi)) {Q.phi = list(Q.phi)} rnks.phi=unlist(lapply(Q.phi, function(x){sum(eigen(x)$values>nrow(x)*.Machine$double.eps)})) } Q.phi=.bdiag(Q.phi) dimnames(Q.phi)=list(colnames(K.phi), colnames(K.phi)) } if(is.p.re){ if(is.null(parameters$p$prior$re)){ a.p=rep(2,length(n.p.re)) b.p=rep(1.0E-4,length(n.p.re)) Q.p=lapply(n.p.re, function(x){Diagonal(x)}) rnks.p=n.p.re }else{ a.p=parameters$p$prior$re$a b.p=parameters$p$prior$re$b Q.p=parameters$p$prior$re$Q if(!is.list(Q.p)) {Q.p = list(Q.p)} rnks.p=unlist(lapply(Q.p, function(x){sum(eigen(x)$values>nrow(x)*.Machine$double.eps)})) } Q.p=.bdiag(Q.p) dimnames(Q.p)=list(colnames(K.p), colnames(K.p)) } if(is.null(initial)) { beta = cjs.initial(dml,imat=imat,link="probit") } else beta = set.initial(c("Phi","p"),dml,initial)$par beta.z = beta$Phi beta.y = beta$p if(is.phi.re){ alpha.phi = rep(0,ncol(K.phi)) eta.phi = as.vector(K.phi%*%alpha.phi) tau.phi = a.phi/b.phi Tau.phi.mat = Matrix(diag(x=rep(tau.phi, n.phi.re))) Q.alpha.phi = suppressMessages(Tau.phi.mat%*%Q.phi) } else eta.phi = rep(0,nrow(Xz)) if(is.p.re){ alpha.p = rep(0,ncol(K.p)) eta.p = as.vector(K.p%*%alpha.p) tau.p = a.p/b.p Tau.p.mat = Diagonal(x=rep(tau.p, n.p.re)) Q.alpha.p = suppressMessages(Tau.p.mat%*%Q.p) } else eta.p = rep(0,nrow(Xy)) beta.z.stor = matrix(NA, iter, ncol(Xz)) beta.y.stor = matrix(NA, iter, ncol(Xy)) colnames(beta.z.stor) = pn.phi colnames(beta.y.stor) = pn.p if(is.phi.re){ alpha.phi.stor = matrix(NA, iter, length(alpha.phi)) colnames(alpha.phi.stor) = colnames(K.phi) eta.phi.stor = matrix(NA, iter, length(eta.phi)) tau.phi.stor = matrix(NA, iter, length(n.phi.re)) } if(is.p.re){ alpha.p.stor = matrix(NA, iter, n.p.re) colnames(alpha.p.stor) = colnames(K.p) eta.p.stor = matrix(NA, iter, length(eta.p)) tau.p.stor = matrix(NA, iter, length(n.p.re)) } message("probitCJS MCMC beginning...") message("p model = ", as.character(parameters$p$formula)) message("phi model = ", as.character(parameters$Phi$formula)) flush.console() tot.iter = burnin + iter st = Sys.time() for(m in 1:tot.iter){ zvec = sample.z(id=id, mu.y=as.vector(Xy%*%beta.y+eta.p), mu.z=as.vector(Xz%*%beta.z+eta.phi), yvec) a = ifelse(zvec==0, -Inf, 0) b = ifelse(zvec==0, 0, Inf) z.tilde = truncnorm::rtruncnorm(n, a=a, b=b, mean=as.vector(Xz%*%beta.z+eta.phi), sd=1) idx.z.tilde = make.ztilde.idx(id, zvec) V.beta.z.inv = crossprod(Xz[idx.z.tilde,]) + tau.b.z m.beta.z = solve(V.beta.z.inv, crossprod(Xz[idx.z.tilde,],z.tilde[idx.z.tilde]-eta.phi[idx.z.tilde]) + tau.b.z*mu.b.z) beta.z = m.beta.z + solve(chol(V.beta.z.inv), rnorm(ncol(Xz),0,1)) if(m>burnin)beta.z.stor[m-burnin,] = beta.z a = ifelse(yvec==0, -Inf, 0) b = ifelse(yvec==0, 0, Inf) y.tilde = truncnorm::rtruncnorm(n, a=a, b=b, mean=as.vector(Xy%*%beta.y+eta.p), sd=1) V.beta.y.inv = crossprod(Xy[zvec==1,]) + tau.b.y m.beta.y = solve(V.beta.y.inv, crossprod(Xy[zvec==1,],y.tilde[zvec==1]-eta.p[zvec==1])+tau.b.y*mu.b.y) beta.y = m.beta.y + solve(chol(V.beta.y.inv), rnorm(ncol(Xy),0,1)) if(m>burnin) beta.y.stor[m-burnin,] = beta.y if(is.phi.re){ Xbeta = Xz[idx.z.tilde,]%*%beta.z V.alpha.phi.inv = crossprod(K.phi[idx.z.tilde,]) + Q.alpha.phi m.alpha.phi = solve(V.alpha.phi.inv, crossprod(K.phi[idx.z.tilde,],z.tilde[idx.z.tilde]-Xbeta)) alpha.phi = m.alpha.phi + solve(chol(V.alpha.phi.inv), rnorm(ncol(K.phi),0,1)) eta.phi = K.phi%*%alpha.phi quad.phi = suppressMessages(crossprod(m.phi.re*alpha.phi,Q.phi))%*%(m.phi.re*alpha.phi)/2 tau.phi = rgamma(length(n.phi.re), rnks.phi/2 + a.phi, as.numeric(quad.phi) + b.phi) Tau.phi.mat = Diagonal(x=rep(tau.phi, n.phi.re)) Q.alpha.phi = Tau.phi.mat%*%Q.phi if(m>burnin) { alpha.phi.stor[m-burnin,] = as.vector(alpha.phi) eta.phi.stor[m-burnin,] = as.vector(eta.phi) tau.phi.stor[m-burnin,] = as.vector(tau.phi) } } if(is.p.re){ Xbeta = Xy[zvec==1,]%*%beta.y V.alpha.p.inv = crossprod(K.p[zvec==1,]) + Q.alpha.p m.alpha.p = solve(V.alpha.p.inv, crossprod(K.p[zvec==1,],y.tilde[zvec==1]-Xbeta)) alpha.p = m.alpha.p + solve(chol(V.alpha.p.inv), rnorm(ncol(K.p),0,1)) eta.p = K.p%*%alpha.p quad.p = suppressMessages(crossprod(m.p.re*alpha.p,Q.p))%*%(m.p.re*alpha.p)/2 tau.p = rgamma(length(n.p.re), rnks.p/2 + a.p, as.numeric(quad.p) + b.p) Tau.p.mat = Diagonal(x=rep(tau.p, n.p.re)) Q.alpha.p = Tau.p.mat%*%Q.p if(m>burnin) { alpha.p.stor[m-burnin,] = as.vector(alpha.p) eta.p.stor[m-burnin,] = as.vector(eta.p) tau.p.stor[m-burnin,] = as.vector(tau.p) } } if(m==30){ tpi = as.numeric(difftime(Sys.time(), st, units="secs"))/30 ttc = round((tot.iter-30)*tpi/3600, 2) if(ttc>=1) cat("Approximate time till completion: ", ttc, " hours\n") else cat("Approximate time till completion: ", ttc*60, " minutes\n") } if(100*(m/tot.iter) >= 10 & (100*(m/tot.iter))%%10==0) { cat(100*(m/tot.iter), "% completed\n") flush.console() } } message("MCMC complete, processing output...") phibeta.mcmc = mcmc(beta.z.stor) hpd.phi = HPDinterval(phibeta.mcmc) beta.phi = data.frame(mode = apply(beta.z.stor, 2, mcmc_mode), mean=apply(beta.z.stor, 2, mean), sd=apply(beta.z.stor,2,sd),CI.lower=hpd.phi[,1], CI.upper=hpd.phi[,2]) pbeta.mcmc = mcmc(beta.y.stor) hpd.p = HPDinterval(pbeta.mcmc) beta.p = data.frame( mode = apply(beta.y.stor, 2, mcmc_mode), mean=apply(beta.y.stor, 2, mean), sd=apply(beta.y.stor,2,sd), CI.lower=hpd.p[,1], CI.upper=hpd.p[,2]) if(is.phi.re){ vc.phi=mcmc(1/tau.phi.stor) colnames(vc.phi) = names(n.phi.re) vc.phi.df=data.frame(mode=apply(vc.phi, 2, mcmc_mode),mean=apply(vc.phi, 2, mean), sd=apply(vc.phi,2,sd), CI.lower=HPDinterval(vc.phi)[,1], CI.upper=HPDinterval(vc.phi)[,2]) re.struc.Phi=list(K=K.phi, Q=Q.phi) phialpha.mcmc=mcmc(alpha.phi.stor) hpd.phi = HPDinterval(phialpha.mcmc) alpha.phi = data.frame( mode = apply(alpha.phi.stor, 2, mcmc_mode), mean=apply(alpha.phi.stor, 2, mean), sd=apply(alpha.phi.stor,2,sd), CI.lower=hpd.phi[,1], CI.upper=hpd.phi[,2]) } else { vc.phi=NULL vc.phi.df=NULL re.struc.Phi=NULL alpha.phi=NULL phialpha.mcmc=NULL } if(is.p.re){ vc.p=mcmc(1/tau.p.stor) colnames(vc.p) = names(n.p.re) vc.p.df=data.frame(mode=apply(vc.p, 2, mcmc_mode),mean=apply(vc.p, 2, mean), sd=apply(vc.p,2,sd), CI.lower=HPDinterval(vc.p)[,1], CI.upper=HPDinterval(vc.p)[,2]) re.struc.p=list(K=K.p, Q=Q.p) palpha.mcmc=mcmc(alpha.p.stor) hpd.p = HPDinterval(palpha.mcmc) alpha.p = data.frame( mode = apply(alpha.p.stor, 2, mcmc_mode), mean=apply(alpha.p.stor, 2, mean), sd=apply(alpha.p.stor,2,sd), CI.lower=hpd.p[,1], CI.upper=hpd.p[,2]) } else { vc.p=NULL vc.p.df=NULL re.struc.p=NULL alpha.p=NULL palpha.mcmc=NULL } res=list(beta=list(Phi=beta.phi,p=beta.p), alpha=list(Phi=alpha.phi,p=alpha.p), var.comp=list(Phi=vc.phi.df, p=vc.p.df), beta.mcmc=list(Phi=phibeta.mcmc, p=pbeta.mcmc), alpha.mcmc=list(Phi=phialpha.mcmc, p=palpha.mcmc), var.comp.mcmc=list(Phi=vc.phi, p=vc.p), model_data=list(Phi.dm=dml$Phi$fe,p.dm=dml$p$fe), re.struct=list(Phi=re.struc.Phi, p=re.struc.p) ) class(res)=c("crm","mcmc","probitCJS") return(res) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) mets <- lava:::versioncheck('mets', 1) fullVignette <- Sys.getenv("_R_FULL_VIGNETTE_") %in% c("1","TRUE") library('lava') f <- function(x) cos(1.25*x) + x - 0.25*x^2 m <- lvm(x1+x2+x3 ~ eta1, y1+y2+y3 ~ eta2, latent=~eta1+eta2) regression(m) <- eta1+eta2 ~ z functional(m, eta2~eta1) <- f d <- sim(m, n=200, seed=42) plot(m, plot.engine="visNetwork") m1 <- lvm(x1+x2+x3 ~ eta1, eta1 ~ z, latent=~eta1) m2 <- lvm(y1+y2+y3 ~ eta2, eta2 ~ z, latent=~eta2) nonlinear(m2, type="quadratic") <- eta2 ~ eta1 e1 <- twostage(m1, m2, data=d) e1 e0 <- estimate(regression(m1%++%m2, eta2~eta1), d) estimate(e0,keep="^eta2~[a-z]",regex=TRUE) newd <- expand.grid(eta1=seq(-4, 4, by=0.1), z=0) pred1 <- predict(e1, newdata=newd, x=TRUE) head(pred1) kn <- seq(-3,3,length.out=5) nonlinear(m2, type="spline", knots=kn) <- eta2 ~ eta1 e2 <- twostage(m1, m2, data=d) e2 p <- cbind(eta1=newd$eta1, estimate(e2,f=function(p) predict(e2,p=p,newdata=newd))$coefmat) head(p) plot(I(eta2-z) ~ eta1, data=d, col=Col("black",0.5), pch=16, xlab=expression(eta[1]), ylab=expression(eta[2]), xlim=c(-4,4)) lines(Estimate ~ eta1, data=as.data.frame(p), col="darkblue", lwd=5) confband(p[,1], lower=p[,4], upper=p[,5], polygon=TRUE, border=NA, col=Col("darkblue",0.2)) m2a <- nonlinear(m2, type="linear", eta2~eta1) m2b <- nonlinear(m2, type="quadratic", eta2~eta1) kn1 <- seq(-3,3,length.out=5) kn2 <- seq(-3,3,length.out=8) m2c <- nonlinear(m2, type="spline", knots=kn1, eta2~eta1) m2d <- nonlinear(m2, type="spline", knots=kn2, eta2~eta1) if (fullVignette) { fit.cv$fit <- NULL saveRDS(fit.cv, "nonlinear_fitcv.rds") } else { fit.cv <- readRDS("nonlinear_fitcv.rds") } summary(fit.cv) fit <- lapply(list(m2a,m2b,m2c,m2d), function(x) { e <- twostage(m1,x,data=d) pr <- cbind(eta1=newd$eta1,predict(e,newdata=newd$eta1,x=TRUE)) return(list(estimate=e,predict=as.data.frame(pr))) }) plot(I(eta2-z) ~ eta1, data=d, col=Col("black",0.5), pch=16, xlab=expression(eta[1]), ylab=expression(eta[2]), xlim=c(-4,4)) col <- c("orange","darkred","darkgreen","darkblue") lty <- c(3,4,1,5) for (i in seq_along(fit)) { with(fit[[i]]$pr, lines(eta2 ~ eta1, col=col[i], lwd=4, lty=lty[i])) } legend("bottomright", c("linear","quadratic","spline(df=4)","spline(df=6)"), col=col, lty=lty, lwd=3) if (fullVignette) { saveRDS(summary(selmod), "nonlinear_selmod.rds") } else { selmod <- readRDS("nonlinear_selmod.rds") } selmod d$g <- (d$z<0)*1 mm1 <- regression(m1, ~g) mm2 <- regression(m2, eta2~ u1+u2+u1:g+u2:g+z) pred <- function(mu,var,data,...) { cbind("u1"=mu[,1],"u2"=mu[,1]^2+var[1], "u1:g"=mu[,1]*data[,"g"],"u2:g"=(mu[,1]^2+var[1])*data[,"g"]) } ee1 <- twostage(mm1, model2=mm2, data=d, predict.fun=pred) estimate(ee1,keep="eta2~u",regex=TRUE) summary(estimate(ee1,keep="(:g)", regex=TRUE)) m1 <- baptize(m1) intercept(m1, ~x1+eta1) <- list(0,NA) regression(m1,x1~eta1) <- 1 if (fullVignette) { saveRDS(em0, "nonlinear_em0.rds") } else { em0 <- readRDS("nonlinear_em0.rds") } summary(em0) e0 <- estimate(m1,data=d) AIC(e0,em0) em2 <- twostage(em0,m2,data=d) em2 plot(I(eta2-z) ~ eta1, data=d, col=Col("black",0.5), pch=16, xlab=expression(eta[1]), ylab=expression(eta[2])) lines(Estimate ~ eta1, data=as.data.frame(p), col="darkblue", lwd=5) confband(p[,1], lower=p[,4], upper=p[,5], polygon=TRUE, border=NA, col=Col("darkblue",0.2)) pm <- cbind(eta1=newd$eta1, estimate(em2, f=function(p) predict(e2,p=p,newdata=newd))$coefmat) lines(Estimate ~ eta1, data=as.data.frame(pm), col="darkred", lwd=5) confband(pm[,1], lower=pm[,4], upper=pm[,5], polygon=TRUE, border=NA, col=Col("darkred",0.2)) legend("bottomright", c("Gaussian","Mixture"), col=c("darkblue","darkred"), lwd=2, bty="n")
"print.varstabil" <- function(x, ...){ print(x[[1]], ...) }
mvNcdf <- function(l, u, Sig, n = 1e5){ d=length(l); if (length(u) !=d | d != sqrt(length(Sig)) | any(l > u)){ stop('l, u, and Sig have to match in dimension with u>l') } if(d == 1L){ return(list(prob = exp(lnNpr(a = l / sqrt(Sig[1]), b = u / sqrt(Sig[1]))), err = NA, relErr = NA, upbnd = NA)) } out <- cholperm(Sig, l, u) L <- out$L l <- out$l u <- out$u D <- diag(L) if (any(D < 1e-10)){ warning('Method may fail as covariance matrix is singular!') } L <- L / D u <- u / D l <- l / D L <- L - diag(d) x0 <- rep(0, 2 * length(l) - 2) solvneq <- nleqslv::nleqslv(x0, fn = gradpsi, jac = jacpsi, L = L, l = l, u = u, global = "pwldog", method = "Broyden", control = list(maxit = 500L)) xmu <- solvneq$x exitflag <- solvneq$termcd flag <- TRUE if(!(exitflag %in% 1:2) || !isTRUE(all.equal(solvneq$fvec, rep(0, length(x0)), tolerance = 1e-6))){ flag <- FALSE } x <- xmu[1:(d-1)] mu <- xmu[d:(2*d-2)] if(any((out$L %*% c(x,0) - out$u)[-d] > 0, (-out$L %*% c(x,0) + out$l)[-d] > 0)){ warning("Solution to exponential tilting problem using Powell's dogleg method \n does not lie in convex set l < Lx < u.") flag <- FALSE } if(!flag){ solvneqc <- alabama::auglag(par = xmu, fn = function(par, l=l, L=L, u=u){ ps <- try(-psy(x = c(par[1:(d-1)],0), mu = c(par[d:(2*d-2)],0), l = l, L = L, u = u)) return(ifelse(is.character(ps), -1e10, ps))}, gr = function(x, l=l, L=L, u=u){gradpsi(y=x, L=L,l=l, u=u)}, L=L, l=l, u=u, heq = function(x, l, L, u){gradpsi(y = x, l=l, L=L, u = u)[d:(2*d-2)]}, hin= function(par,...){c((out$u - out$L %*% c(par[1:(d-1)],0))[-d] > 0, (out$L %*% c(par[1:(d-1)],0) - out$l)[-d])}, control.outer = list(trace = FALSE,method="nlminb")) if(solvneqc$convergence == 0){ x <- solvneqc$par[1:(d-1)] mu <- solvneqc$par[d:(2*d-2)] } else{ stop('Did not find a solution to the nonlinear system in `mvNqmc`!') } } est <- mvnpr(n, L, l, u, mu) est$upbnd <- exp(psy(x, L, l, u, mu)) return(est) }
utils::globalVariables(c(".")) NULL
setUnderlyingBounds = function(variable, data){ variable$lowerBoundZ[data[variable$variableName] == 0] = -Inf variable$lowerBoundZ[data[variable$variableName] == 1] = 0 variable$upperBoundZ[data[variable$variableName] == 0] = 0 variable$upperBoundZ[data[variable$variableName] == 1] = Inf return(variable) }
QRLMM = function(y,x,z,groups,p=0.5,precision=0.0001,MaxIter=300,M=10,cp=0.25,beta=NA,sigma=NA,Psi=NA,show.convergence=TRUE,CI=95) { nj = c(as.data.frame(table(groups))[,2]) if(length(p)==1) { if( (length(x) == 0) | (length(y) == 0) | (length(z) == 0)) stop("All parameters must be provided.") if(sum(y[is.na(y)==TRUE]) > 0) stop("There are some NA's values in y") if(sum(y[is.na(x)==TRUE]) > 0) stop("There are some NA's values in x") if(sum(y[is.na(z)==TRUE]) > 0) stop("There are some NA's values in z") if(ncol(as.matrix(y)) > 1) stop("y must have just one column") if( length(y) != sum(nj) ) stop("nj does not match with the provided data. (length(y) != sum(nj))") if( length(y) != nrow(as.matrix(x)) ) stop("x variable does not have the same number of lines than y") if( length(y) != nrow(as.matrix(z)) ) stop("z variable does not have the same number of lines than y") if(p >= 1 | p <= 0) stop("p must be a real number in (0,1)") if(precision <= 0) stop("precision must be a positive value (suggested to be small)") if(MaxIter <= 0 |MaxIter%%1!=0) stop("MaxIter must be a positive integer value") if(M <= 0 |M%%1!=0) stop("M must be a positive integer value >= 10") if(cp > 1 | cp < 0) stop("cp must be a real number in [0,1]") if(is.logical(show.convergence) == FALSE) stop("show.convergence must be TRUE or FALSE.") namesz <- ('z1') if(ncol(as.matrix(z))>1){ for(i in 2:ncol(as.matrix(z))){namesz <- c(namesz, paste("z",i,sep=""))} } if(is.na(beta) == FALSE) {if(length(beta) != ncol(as.matrix(x))) stop("beta must be a vector of dimension equal to columns of x")} if(is.na(sigma) == FALSE) {if(sigma <= 0) stop("sigma must be a positive number")} if(is.na(Psi) == FALSE) { if( (ncol(as.matrix(D)) != ncol(as.matrix(z))) | ((nrow(as.matrix(D)) != ncol(as.matrix(z)))) ) stop("D must be a square matrix of dims equal to the columns of z") if(det(D)<=0) stop("D must be a square symmetrical real posite definite matrix.") } if(is.na(beta) == TRUE){beta = suppressWarnings(rq(y ~ -1 + x,tau = p))$coefficients} if(is.na(sigma) == TRUE){dif = y - x%*%beta; sigma = (1/length(y))*(sum(p*dif[dif>0]) - sum((1-p)*dif[dif<0]))} if(is.na(Psi) == TRUE){Psi = diag(ncol(as.matrix(z)))} out <- suppressWarnings(QSAEM_COM_7(y,x,z,nj,p,precision,MaxIter,M,pc=cp,beta=beta,sigmae=sigma,D=Psi)) cat('\n') cat('---------------------------------------------------\n') cat('Quantile Regression for Linear Mixed Model\n') cat('---------------------------------------------------\n') cat('\n') cat("Quantile =",p) cat('\n') cat("Subjects =",length(nj),";",'Observations =',sum(nj), ifelse(sum(nj==nj[1])==length(nj),'; Balanced =',""), ifelse(sum(nj==nj[1])==length(nj),nj[1],"")) cat('\n') cat('\n') cat('-----------\n') cat('Estimates\n') cat('-----------\n') cat('\n') cat('- Fixed effects \n') cat('\n') print(round(out$res$table,5)) cat('\n') cat('sigma =',round(out$res$sigmae,5),'\n') cat('\n') cat('Random effects \n') cat('\n') cat('i) Weights \n') print(round(out$res$weights,5)) cat('\n') cat('ii) Variance-Covariance Matrix \n') dimnames(out$res$D) <- list(namesz,namesz) print(round(out$res$D,5)) cat('\n') cat('------------------------\n') cat('Model selection criteria\n') cat('------------------------\n') cat('\n') critFin <- c(out$res$loglik, out$res$AIC, out$res$BIC, out$res$HQ) critFin <- round(t(as.matrix(critFin)),digits=3) dimnames(critFin) <- list(c("Value"),c("Loglik", "AIC", "BIC","HQ")) print(critFin) cat('\n') cat('-------\n') cat('Details\n') cat('-------\n') cat('\n') cat("Convergence reached? =",(out$res$iter < MaxIter)) cat('\n') cat('Iterations =',out$res$iter,"/",MaxIter) cat('\n') cat('Criteria =',round(out$res$criterio,5)) cat('\n') cat('MC sample =',M) cat('\n') cat('Cut point =',cp) cat('\n') cat("Processing time =",out$res$time,units(out$res$time)) if(show.convergence=="TRUE") { cpl = cp*MaxIter d = dim(x)[2] q = dim(z)[2] ndiag = (q*(1+q)/2) npar = d+1+ndiag labels = list() for(i in 1:d){labels[[i]] = bquote(beta[.(i)])} labels[[d+1]] = bquote(sigma) for(i in 1:ndiag){labels[[i+d+1]] = bquote(psi[.(i)])} par(mar=c(4, 4.5, 1, 0.5)) op <- par(mfrow=c(ifelse(npar%%3==0,npar%/%3,(npar%/%3)+1),3)) for(i in 1:npar) { plot.ts(out$conv$teta[i,],xlab="Iteration",ylab=labels[[i]]) abline(v=cpl,lty=2) } } par(mfrow=c(1,1)) res = list(iter = out$res$iter,criteria = out$res$criterio,beta = out$res$beta,weights = round(out$res$weights,5), sigma= out$res$sigmae,Psi = out$res$D,SE=out$res$EP,table = out$res$table,loglik=out$res$loglik,AIC=out$res$AIC,BIC=out$res$BIC,HQ=out$res$HQ,time = out$res$time) obj.out = list(conv=out$conv,res = res) class(obj.out) = "QRLMM" return(obj.out) } else { p = sort(p) obj.out = vector("list", length(p)) if( (length(x) == 0) | (length(y) == 0) | (length(z) == 0)) stop("All parameters must be provided.") if(sum(y[is.na(y)==TRUE]) > 0) stop("There are some NA's values in y") if(sum(y[is.na(x)==TRUE]) > 0) stop("There are some NA's values in x") if(sum(y[is.na(z)==TRUE]) > 0) stop("There are some NA's values in z") if(ncol(as.matrix(y)) > 1) stop("y must have just one column") if( length(y) != sum(nj) ) stop("nj does not match with the provided data. (length(y) != sum(nj))") if( length(y) != nrow(as.matrix(x)) ) stop("x variable does not have the same number of lines than y") if( length(y) != nrow(as.matrix(z)) ) stop("z variable does not have the same number of lines than y") if(all(p > 0 && p < 1) == FALSE) stop("p vector must contain real values in (0,1)") if(precision <= 0) stop("precision must be a positive value (suggested to be small)") if(MaxIter <= 0 |MaxIter%%1!=0) stop("MaxIter must be a positive integer value") if(M <= 0 |M%%1!=0) stop("M must be a positive integer value >= 10") if(cp >= 1 | cp <= 0) stop("cp must be a real number in [0,1]") if(is.logical(show.convergence) == FALSE) stop("show.convergence must be TRUE or FALSE.") namesz <- ('z1') if(ncol(as.matrix(z))>1){ for(i in 2:ncol(as.matrix(z))){namesz <- c(namesz, paste("z",i,sep=""))} } pb2 = tkProgressBar(title = "QRLMM for several quantiles", min = 0,max = length(p), width = 300) for(k in 1:length(p)) { setTkProgressBar(pb2, k-1, label=paste("Running quantile ",p[k]," - ",k-1,"/",length(p)," - ",round((k-1)/length(p)*100,0),"% done",sep = "")) beta = suppressWarnings(rq(y ~ -1 + x,tau = p[k]))$coefficients dif = y - x%*%beta sigma = (1/length(y))*(sum(p[k]*dif[dif>0]) - sum((1-p[k])*dif[dif<0])) Psi = diag(ncol(as.matrix(z))) out <- suppressWarnings(QSAEM_COM_7(y,x,z,nj,p[k],precision,MaxIter,M,pc=cp,beta=beta,sigmae=sigma,D=Psi)) cat('\n') cat('---------------------------------------------------\n') cat('Quantile Regression for Linear Mixed Model\n') cat('---------------------------------------------------\n') cat('\n') cat("Quantile =",p) cat('\n') cat("Subjects =",length(nj),";",'Observations =',sum(nj), ifelse(sum(nj==nj[1])==length(nj),'; Balanced =',""), ifelse(sum(nj==nj[1])==length(nj),nj[1],"")) cat('\n') cat('\n') cat('-----------\n') cat('Estimates\n') cat('-----------\n') cat('\n') cat('- Fixed effects \n') cat('\n') print(round(out$res$table,5)) cat('\n') cat('sigma =',round(out$res$sigmae,5),'\n') cat('\n') cat('Random effects Variance-Covariance Matrix matrix \n') dimnames(out$res$D) <- list(namesz,namesz) print(round(out$res$D,5)) cat('\n') cat('------------------------\n') cat('Model selection criteria\n') cat('------------------------\n') cat('\n') critFin <- c(out$res$loglik, out$res$AIC, out$res$BIC, out$res$HQ) critFin <- round(t(as.matrix(critFin)),digits=3) dimnames(critFin) <- list(c("Value"),c("Loglik", "AIC", "BIC","HQ")) print(critFin) cat('\n') cat('-------\n') cat('Details\n') cat('-------\n') cat('\n') cat("Convergence reached? =",(out$res$iter < MaxIter)) cat('\n') cat('Iterations =',out$res$iter,"/",MaxIter) cat('\n') cat('Criteria =',round(out$res$criterio,5)) cat('\n') cat('MC sample =',M) cat('\n') cat('Cut point =',cp) cat('\n') cat("Processing time =",out$res$time,units(out$res$time)) res = list(iter = out$res$iter,criteria = out$res$criterio,beta = out$res$beta,weights = round(out$res$weights,5),sigma= out$res$sigmae,Psi = out$res$D,SE=out$res$EP,table = out$res$table,loglik=out$res$loglik,AIC=out$res$AIC,BIC=out$res$BIC,HQ=out$res$HQ,time = out$res$time) obj.outk = list(conv=out$conv,res = res) obj.out[[k]] = obj.outk } close(pb2) par(mfrow=c(1,1)) d=length(obj.out[[1]]$res$beta) betas = eps = matrix(NA,length(p),d+1) for (i in 1:length(p)) { j = p[i] betas[i,] = rbind(obj.out[[i]]$res$beta,obj.out[[i]]$res$sigma) eps[i,] = obj.out[[i]]$res$SE[1:(d+1)] } LIMSUP = t(betas + qnorm(1-((1-(CI/100))/2))*eps) LIMINF = t(betas - qnorm(1-((1-(CI/100))/2))*eps) labels = list() for(i in 1:d){labels[[i]] = bquote(beta[.(i)])} labels[[d+1]] = bquote(sigma) par(mar=c(4, 4.5, 1, 0.5)) op <- par(mfrow=c(ifelse((d+1)%%2==0,(d+1)%/%2,((d+1)%/%2)+1),2),oma=c(0,0,2,0)) for(i in 1:(d+1)){ if(length(p)<4) { ymin = min(betas[,i],LIMSUP[i,],LIMINF[i,]) ymax = max(betas[,i],LIMSUP[i,],LIMINF[i,]) plot(p,betas[,i],ylim=c(ymin-2*mean(eps[,i]),ymax+2*mean(eps[,i])),xaxt='n', type='n',xlab='quantiles',ylab=labels[[i]]) axis(side=1, at=p) polygon(c(p,rev(p)),c(LIMSUP[i,],rev(LIMINF[i,])), col = "gray50", border = NA) lines(p,betas[,i]) lines(p,LIMSUP[i,]) lines(p,LIMINF[i,]) } else { smoothingSpline = smooth.spline(p, betas[,i], spar=0.1) smoothingSplineU = smooth.spline(p, betas[,i]+(qnorm(1-((1-(CI/100))/2)))*eps[,i], spar=0.1) smoothingSplineL = smooth.spline(p, betas[,i]-(qnorm(1-((1-(CI/100))/2)))*eps[,i], spar=0.1) plot(p, betas[,i], type='n',xaxt='n',xlab='quantiles',lwd=2,ylim=c(min(smoothingSplineL$y)-2*mean(eps[,i]),max(smoothingSplineU$y)+2*mean(eps[,i])),ylab=labels[[i]]) axis(side=1, at=p) polygon(c(smoothingSplineL$x,rev(smoothingSplineU$x)),c(smoothingSplineU$y,rev(smoothingSplineL$y)), col = "gray50", border = NA) lines(p, betas[,i], type='l',lwd=1) lines(smoothingSplineU,lwd=1) lines(smoothingSplineL,lwd=1) } } title("Point estimative and 95% CI for model parameters", outer=TRUE) par(mfrow=c(1,1)) if(show.convergence=="TRUE") { cpl = cp*MaxIter d = dim(x)[2] q = dim(z)[2] ndiag = (q*(1+q)/2) npar = d+1+ndiag labels = list() for(i in 1:d){labels[[i]] = bquote(beta[.(i)])} labels[[d+1]] = bquote(sigma) for(i in 1:ndiag){labels[[i+d+1]] = bquote(psi[.(i)])} for(k in 1:length(p)) { cat('\n') cat ("Press [ENTER] to see next plot:") line <- readline() par(mar=c(4, 4.5, 1, 0.5)) op <- par(mfrow=c(ifelse(npar%%3==0,npar%/%3,(npar%/%3)+1),3),oma=c(0,0,2,0)) for(i in 1:npar) { plot.ts(obj.out[[k]]$conv$teta[i,],xlab="Iteration",ylab=labels[[i]]) abline(v=cpl,lty=2) } title(paste("Convergence plots for quantile",p[k]), outer=TRUE) par(mfrow=c(1,1)) } } class(obj.out) = "QRLMM" return(obj.out) } }
setClass("tscopula", contains = c("VIRTUAL")) setGeneric("sim", function(object, ...) { standardGeneric("sim") }) setClass("swncopula", contains = "tscopula") swncopula <- function() { new("swncopula") } setMethod("sim", "swncopula", function(object, n = 1000) { runif(n) }) setMethod("coef", "swncopula", function(object) { NULL }) setMethod("show", "swncopula", function(object) { cat("SWN \n") }) setGeneric("kendall", function(object, ...) { standardGeneric("kendall") })
fit.c.clines <- function(reg.out=NULL, hi.index=NULL, sam=NULL, n.ind=NULL){ if (length(coef(reg.out))>2){ AA.slope<-coef(reg.out)[2,2] AA.int<-coef(reg.out)[2,1] Aa.slope<-coef(reg.out)[1,2] Aa.int<-coef(reg.out)[1,1] Hx<-exp(AA.slope*hi.index+AA.int) + exp(Aa.slope*hi.index+Aa.int) AA.fitted<-exp(AA.slope*hi.index+AA.int)/(1+Hx) Aa.fitted<-exp(Aa.slope*hi.index+Aa.int)/(1+Hx) aa.fitted<-1-(Aa.fitted+AA.fitted) } else if (length(coef(reg.out))==2){ if(sum(sam==2,na.rm=TRUE)>=1 & sum(sam==1,na.rm=TRUE)>=1){ AA.slope<-coef(reg.out)[2] AA.int<-coef(reg.out)[1] Aa.slope<-NA Aa.int<-NA Hx<-exp(AA.slope*hi.index+AA.int) AA.fitted<-exp(AA.slope*hi.index+AA.int)/(1+Hx) Aa.fitted<-1-exp(AA.slope*hi.index+AA.int)/(1+Hx) aa.fitted<-rep(0,n.ind) } else if(sum(sam==2,na.rm=TRUE)>=1 & sum(sam==0,na.rm=TRUE)>=1){ AA.slope<-coef(reg.out)[2] AA.int<-coef(reg.out)[1] Aa.slope<-NA Aa.int<-NA Hx<-exp(AA.slope*hi.index+AA.int) AA.fitted<-exp(AA.slope*hi.index+AA.int)/(1+Hx) Aa.fitted<-rep(0,n.ind) aa.fitted<-1-exp(AA.slope*hi.index+AA.int)/(1+Hx) } else if(sum(sam==1,na.rm=TRUE)>=1 & sum(sam==0,na.rm=TRUE)>=1){ AA.slope<-NA AA.int<-NA Aa.slope<-coef(reg.out)[2] Aa.int<-coef(reg.out)[1] Hx<-exp(Aa.slope*hi.index+Aa.int) AA.fitted<-rep(0,n.ind) Aa.fitted<-exp(Aa.slope*hi.index+Aa.int)/(1+Hx) aa.fitted<-1-exp(Aa.slope*hi.index+Aa.int)/(1+Hx) } } fitted.mat<-rbind(AA.fitted,Aa.fitted,aa.fitted) return(fitted.mat) }
context("library() ok") test_that("library is ok here", { library("stats") expect_true(TRUE) })
test_that("helpers run before tests", { expect_equal(abcdefghi, 10) })
context("Test on CDF") test_that("CDF in [0,1]", { tVect <-seq(from = -10, to = 200, by = 1) expect_cdfRange_01 <- function(t, m, devel, thres) { cdfValue <- givitiStatCdf(t, m, devel, thres) expect_equal(cdfValue >= 0 & cdfValue <= 1, T) } for (t in tVect) { expect_cdfRange_01(t,1,"external",0.95) expect_cdfRange_01(t,2,"external",0.95) expect_cdfRange_01(t,3,"external",0.95) expect_cdfRange_01(t,4,"external",0.95) expect_cdfRange_01(t,2,"internal",0.95) expect_cdfRange_01(t,3,"internal",0.95) expect_cdfRange_01(t,4,"internal",0.95) expect_cdfRange_01(t,1,"external",0.8) expect_cdfRange_01(t,2,"external",0.8) expect_cdfRange_01(t,3,"external",0.8) expect_cdfRange_01(t,4,"external",0.8) expect_cdfRange_01(t,2,"internal",0.8) expect_cdfRange_01(t,3,"internal",0.8) expect_cdfRange_01(t,4,"internal",0.8) } })
fhm_new <- function(v, n) { .Call(`_phangorn_fhm_new`, v, n) } allDescCPP <- function(orig, nTips) { .Call(`_phangorn_allDescCPP`, orig, nTips) } countCycle_cpp <- function(M) { .Call(`_phangorn_countCycle_cpp`, M) } countCycle2_cpp <- function(M) { .Call(`_phangorn_countCycle2_cpp`, M) } out_cpp <- function(d, r, n) { .Call(`_phangorn_out_cpp`, d, r, n) } getIndex <- function(left, right, n) { .Call(`_phangorn_getIndex`, left, right, n) } Transfer_Index <- function(bp, orig, l) { .Call(`_phangorn_Transfer_Index`, bp, orig, l) } bipartCPP <- function(orig, nTips) { .Call(`_phangorn_bipartCPP`, orig, nTips) } bipCPP <- function(orig, nTips) { .Call(`_phangorn_bipCPP`, orig, nTips) } bip_shared <- function(tree1, tree2, nTips) { .Call(`_phangorn_bip_shared`, tree1, tree2, nTips) } allChildrenCPP <- function(orig) { .Call(`_phangorn_allChildrenCPP`, orig) } allSiblingsCPP <- function(edge) { .Call(`_phangorn_allSiblingsCPP`, edge) } p2dna <- function(xx, eps = 0.999) { .Call(`_phangorn_p2dna`, xx, eps) } node_height_cpp <- function(edge1, edge2, edge_length) { .Call(`_phangorn_node_height_cpp`, edge1, edge2, edge_length) } cophenetic_cpp <- function(edge, edge_length, nTips, nNode) { .Call(`_phangorn_cophenetic_cpp`, edge, edge_length, nTips, nNode) } threshStateC <- function(x, thresholds) { .Call(`_phangorn_threshStateC`, x, thresholds) }
thresholds <- function(object)UseMethod("thresholds")
context("Check TS_on_LDA functions") data(rodents) lda_data <- rodents$document_term_table document_term_table <- rodents$document_term_table document_covariate_table <- rodents$document_covariate_table topics <- 2 nseeds <- 1 formulas <- ~ 1 nchangepoints <- 0 weights <- document_weights(document_term_table) timename <- "newmoon" LDAs <- LDA_set(document_term_table, topics, nseeds) LDA_models <- select_LDA(LDAs) mods <- TS_on_LDA(LDA_models, document_covariate_table, formulas, nchangepoints = 0:1, timename, weights, control = list(nit = 20)) test_that("check prep_TS_data", { mods <- expand_TS(LDA_models, formulas=c(~1, ~sin_year, ~newmoon), nchangepoints = 0:1) nmods <- nrow(mods) TSmods <- vector("list", nmods) for (i in 1:nmods){ data_i <- prep_TS_data(document_covariate_table, LDA_models, mods, i) expect_is(data_i, "data.frame") expect_equal(dim(data_i), c(436, 4)) } expect_error(prep_TS_data(document_covariate_table, LDA_models, mods, "ok")) expect_error(prep_TS_data(document_covariate_table, LDA_models, "ok", i)) expect_error(prep_TS_data(document_covariate_table, "ok", mods, i)) expect_error(prep_TS_data("ok", LDA_models, mods, i)) data_1 <- prep_TS_data(document_covariate_table, LDA_models[[1]], mods, 1) data_i <- prep_TS_data(document_covariate_table, LDA_models, mods, 1) expect_equal(data_1, data_i) }) test_that("check select_TS", { sel_mod <- select_TS(mods, list()) expect_equal(length(mods), 2) expect_equal(length(sel_mod), 17) expect_is(mods, "TS_on_LDA") expect_is(sel_mod, "TS_fit") expect_error(select_TS(mods, "ok")) expect_error(select_TS("ok", list())) xxfun <- function(x){x} expect_warning(select_TS(mods, list(selector = xxfun))) }) test_that("check package_TS_on_LDA", { mods <- expand_TS(LDA_models, formulas, nchangepoints = 0:1) nmods <- nrow(mods) TSmods <- vector("list", nmods) for(i in 1:nmods){ print_model_run_message(mods, i, LDA_models, list()) formula_i <- mods$formula[[i]] nchangepoints_i <- mods$nchangepoints[i] data_i <- prep_TS_data(document_covariate_table, LDA_models, mods, i) TSmods[[i]] <- TS(data_i, formula_i, nchangepoints_i,timename, weights, control = list(nit = 20)) } expect_is(package_TS_on_LDA(TSmods, LDA_models, mods), "TS_on_LDA") expect_is(package_TS_on_LDA(TSmods, LDA_models[[1]], mods), "TS_on_LDA") expect_error(package_TS_on_LDA(TSmods, LDA_models, "ok")) expect_error(package_TS_on_LDA("ok", LDA_models, mods)) expect_error(package_TS_on_LDA(TSmods, "ok", mods)) }) test_that("check TS_on_LDA", { expect_is(mods, "TS_on_LDA") expect_equal(length(mods), 2) expect_is(mods[[1]], "TS_fit") expect_is(mods[[2]], "TS_fit") expect_error(TS_on_LDA()) expect_error(TS_on_LDA("ok", document_covariate_table, formulas, nchangepoints, timename, weights, list())) expect_error(TS_on_LDA(LDA_models, "ok", formulas, nchangepoints, timename, weights, list())) expect_error(TS_on_LDA(LDA_models, document_covariate_table, "ok", nchangepoints, timename, weights, list())) expect_error(TS_on_LDA(LDA_models, document_covariate_table, formulas, "ok", timename, weights, list())) expect_error(TS_on_LDA(LDA_models, document_covariate_table, formulas, nchangepoints, timename, "ok", list())) expect_error(TS_on_LDA(LDA_models, document_covariate_table, formulas, nchangepoints, "ok", weights, list())) expect_error(TS_on_LDA(LDA_models, document_covariate_table, formulas, nchangepoints, timename, weights, "ok")) }) test_that("check printing for TS_on_LDA", { expect_output(print(mods)) }) test_that("check print_model_run_message", { mods <- expand_TS(LDA_models, formulas, nchangepoints) expect_message(print_model_run_message(mods, 1, LDA_models, list())) expect_silent(print_model_run_message(mods, 1, LDA_models, control = list(quiet = TRUE))) }) test_that("check expand_TS", { exp_TS <- expand_TS(LDA_models, formulas, nchangepoints) expect_is(exp_TS, "data.frame") expect_equal(dim(exp_TS), c(1, 3)) exp_TS <- expand_TS(LDA_models, c(~1, ~newmoon), 3:10) expect_is(exp_TS, "data.frame") expect_equal(dim(exp_TS), c(16, 3)) exp_TS <- expand_TS(LDA_models[[1]], c(~1, ~newmoon), 3:10) expect_is(exp_TS, "data.frame") expect_equal(dim(exp_TS), c(16, 3)) expect_error(expand_TS("ok", formulas, nchangepoints)) expect_error(expand_TS(LDA_models, "ok", nchangepoints)) expect_error(expand_TS(LDA_models, c("~1", "ok"), nchangepoints)) expect_error(expand_TS(LDA_models, list("~1", "ok"), nchangepoints)) expect_error(expand_TS(LDA_models, formulas, 2.5)) }) test_that("check check_nchangepoints", { expect_silent(check_nchangepoints(1)) expect_silent(check_nchangepoints(0)) expect_silent(check_nchangepoints(1:10)) expect_error(check_nchangepoints(2.5)) expect_error(check_nchangepoints(-1)) expect_error(check_nchangepoints(NULL)) }) test_that("check check_weights", { expect_equal(check_weights(TRUE), NULL) expect_error(check_weights(FALSE)) expect_silent(check_weights(weights)) expect_silent(check_weights(1)) expect_silent(check_weights(NULL)) expect_error(check_weights("ok")) expect_error(check_weights(-1)) expect_warning(check_weights(100)) }) test_that("check check_LDA_models", { expect_silent(check_LDA_models(LDA_models)) expect_silent(check_LDA_models(LDA_models[[1]])) expect_error(check_LDA_models("ok")) }) test_that("check check_document_covariate_table", { expect_silent(check_document_covariate_table(document_covariate_table)) expect_silent(check_document_covariate_table(document_covariate_table, LDA_models = LDA_models)) expect_silent(check_document_covariate_table(document_covariate_table, LDA_models = LDAs)) expect_silent(check_document_covariate_table(document_covariate_table, document_term_table = document_term_table)) expect_error(check_document_covariate_table(document_covariate_table, LDA_models = 1)) expect_error(check_document_covariate_table(document_covariate_table, document_term_table = 1)) expect_error(check_document_covariate_table(document_covariate_table = 1, LDA_models = LDA_models)) expect_error(check_document_covariate_table(document_covariate_table = 1, document_term_table = document_term_table)) expect_error(check_document_covariate_table(lm(1~1), LDA_models)) }) test_that("check check_timename", { expect_silent(check_timename(document_covariate_table, timename)) expect_error(check_timename("ok", timename)) expect_error(check_timename(document_covariate_table, "ok")) expect_error(check_timename(document_covariate_table, 1)) expect_error(check_timename(document_covariate_table, rep(timename, 2))) expect_error(check_timename(document_covariate_table, 1)) expect_error(check_timename(data.frame(letters), "letters")) dct2 <- document_covariate_table dct2[,timename] <- dct2[,timename] + 0.1 expect_error(check_timename(dct2, timename)) }) test_that("check check_formulas", { expect_silent(check_formulas(formulas, document_covariate_table, list())) expect_error(check_formulas("ok", document_covariate_table, list())) expect_error(check_formulas(~newmoon, "ok", list())) expect_error(check_formulas(c(~1, "ok"), document_covariate_table, list())) expect_error(check_formulas(list(~1, "ok"), document_covariate_table, list())) expect_error(check_formulas(formulas, document_covariate_table, "ok")) }) test_that("check check_TS_on_LDA_inputs", { expect_silent( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas, nchangepoints, timename, weights, list())) expect_error( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas, nchangepoints, timename, weights, "ok")) expect_error( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas, nchangepoints, timename, "ok", list())) expect_error( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas, "ok", weights, timename, weights, list())) expect_error( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, "ok", nchangepoints, timename, weights, list())) expect_error( check_TS_on_LDA_inputs(LDA_models, "ok", formulas, nchangepoints, timename, weights, list())) expect_error( check_TS_on_LDA_inputs("ok", document_covariate_table, formulas, nchangepoints, timename, weights, list())) expect_error( check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas, nchangepoints, "ok", weights, list())) })
get.minutesplayed = function (AllEvents) { Matches <- AllEvents %>% group_by(match_id) %>% filter(ElapsedTime == max(ElapsedTime)) %>% select(match_id, GameEnd = ElapsedTime) %>% dplyr::slice(1) StartingXI <- AllEvents %>% filter(type.name == "Starting XI") %>% select(id, match_id, team.id, tactics.lineup) myList <- StartingXI$tactics.lineup fixnull <- function(x) { if (is.data.frame(x)) { return(x) } else { return(setNames(data.frame(matrix(ncol = ncol(myList[[1]]), nrow = 1)), names(myList[[1]]))) } } myList <- lapply(myList, fixnull) df <- bind_rows(myList, .id = "id") idtable <- df %>% mutate(id = as.numeric(id)) %>% group_by(id) %>% dplyr::slice(1) %>% select(id) %>% ungroup() %>% mutate(sbid = StartingXI$id) %>% mutate(id = as.character(id)) %>% mutate(match_id = StartingXI$match_id, team.id = StartingXI$team.id) df <- left_join(df, idtable) df <- df %>% select(-id) %>% rename(id = sbid) %>% select(id, everything()) df <- df %>% mutate(TimeOn = 0) df <- df %>% select(player.id, match_id, team.id, TimeOn) Subs <- AllEvents %>% filter(type.name == "Substitution" | bad_behaviour.card.name=="Red Card" | foul_committed.card.name=="Red Card" | bad_behaviour.card.name=="Second Yellow" | foul_committed.card.name=="Second Yellow") %>% select(match_id, ElapsedTime, Off = player.id, team.id, On = substitution.replacement.id) %>% tidyr::gather(Off, On, key = "Player", value = "OnOff") %>% arrange(match_id, ElapsedTime) SubsOff <- Subs %>% filter(Player == "Off") %>% select(-Player, TimeOff = ElapsedTime, player.id = OnOff) df <- left_join(df, SubsOff, by = c("player.id", "match_id", "team.id"), suffix = c("", ".S")) SubsOn <- Subs %>% filter(Player == "On") %>% select(-Player, TimeOn = ElapsedTime, player.id = OnOff) df <- bind_rows(df, SubsOn) %>% arrange(match_id, team.id, TimeOn) df <- df %>% left_join(Matches) df <- df %>% mutate(TimeOff = ifelse(is.na(TimeOff), GameEnd, TimeOff)) df <- df %>% mutate(MinutesPlayed = (TimeOff - TimeOn)/60, TimeOn = TimeOn/60, TimeOff = TimeOff/60, GameEnd = GameEnd/60) %>% filter(!is.na(player.id)) return(df) }
wrangled_csv <- function(casestudy, outpath = NULL){ repo_names = c("ocs-bp-rural-and-urban-obesity", "ocs-bp-air-pollution", "ocs-bp-vaping-case-study", "ocs-bp-opioid-rural-urban", "ocs-bp-RTC-wrangling", "ocs-bp-RTC-analysis", "ocs-bp-youth-disconnection", "ocs-bp-youth-mental-health", "ocs-bp-school-shootings-dashboard", "ocs-bp-co2-emissions", "ocs-bp-diet") if (casestudy %in% repo_names){ if (is.null(outpath)) { if (interactive()){ wd = getwd() cat(paste("No destination directory specified. Would you like to save the", "data files to your current working directory?\n")) cat(paste("Current working directory:\n", wd, "\n")) cat(paste("Responses:", "1. Yes, save to my current working directory.", "2. Specify a different directory", "3. Cancel ", sep = "\n")) response = readline(prompt = "Answer with a number 1-3: ") if (response == '1'){ outpath = wd } else if (response == '2'){ cat(paste("Enter the file path of the desired directory\n")) outpath = readline(prompt = "File path: ") } else { return("Canceled.") } } else{ msg = paste("Error: No destination directory specified. Please enter the file path for where the data files should be downloaded in the 'outpath' argument.") return(msg) } } if (dir.exists(outpath)) { outpath = file.path(outpath,'OCS_data') dir.create(outpath, showWarnings = FALSE) datapath = file.path(outpath,'data') dir.create(datapath, showWarnings = FALSE) wrangledpath = file.path(datapath,'wrangled') dir.create(wrangledpath, showWarnings = FALSE) repo_url = paste0("https://api.github.com/repos/opencasestudies/", casestudy, "/git/trees/master?recursive=1") repo = GET(url=repo_url) repocont = content(repo) repounlist = unlist(repocont, recursive = FALSE) paths = map(repounlist,'path') paths = paths[!sapply(paths,is.null)] for (fname in paths){ if (grepl('data/', fname, fixed = TRUE)) { if (grepl('/wrangled/', fname, fixed = TRUE)) { if (grepl('.', fname, fixed = TRUE)) { if (grepl('.csv',fname, fixed = TRUE)) { githuburl = paste0('https://github.com/opencasestudies/', casestudy, '/blob/master/',fname,'?raw=true') GET(githuburl, write_disk(file.path(outpath, fname))) } } else { subpath = file.path(outpath, fname) dir.create(subpath) } } } } cat(paste("The downloaded files are in:", wrangledpath, " ")) return(TRUE) } else { return("The specified directory does not exist.") } } else { return(cat(paste("Not a valid case study name. Please use the name of the case study \nGitHub repository.", "Use ?wrangled_data to view a list of valid names."))) } }
gradient.truncation.region.function <- function(x, q, r){ q/2/sqrt(x) + r/2/sqrt(1+x) }
boolSkip=F test_that("Check 22.1 - isQuasiBalancedGame - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,60,60,60,72) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.2 - isQuasiBalancedGame - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,4,5,18,14,9,24) result = isQuasiBalancedGame(v) expect_equal(result, TRUE) }) test_that("Check 22.3 - isQuasiBalancedGame - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,40,50,20,100) result = isQuasiBalancedGame(v) expect_equal(result, TRUE) }) test_that("Check 22.4 - isQuasiBalancedGame - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,4,5,18,20,20,24) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.5 - isQuasiBalancedGame - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,4,5,18,20,20,18) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.6 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 30, 30, 30, 30, 30, 60, 72, 72, 72, 72, 108) result = isQuasiBalancedGame(v) expect_equal(result, TRUE) }) test_that("Check 22.7 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 30, 30, 30, 30, 30, 60, 72, 72, 72, 72, 50) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.8 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.9 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 12, 12, 12, 12, 22) result = isQuasiBalancedGame(v) expect_equal(result, TRUE) }) test_that("Check 22.10 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 4) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) }) test_that("Check 22.11 - isQuasiBalancedGame - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 4, 3, 2, 1, 7) result = isQuasiBalancedGame(v) expect_equal(result, TRUE) }) test_that("Check 22.12 - isQuasiBalancedGame - 4 players - example from TUGLAB",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 4, 3, 2, 1, -2) result = isQuasiBalancedGame(v) expect_equal(result, FALSE) })
context("Test server error messages") test_that("error messages from server are shown to the user", { skip_on_cran() ss <- function(lon, lat) { mt_subset(product = "MOD11A2", lat = lat, lon = lon, band = "LST_Day_1km", start = "2004-01-01", end = "2004-01-02", progress = FALSE) } expect_silent( x <- ss(-110, 40) ) expect_error( ss(40, -110), "Invalid argument: Latitude must be between -90 and 90 degrees." ) expect_error( ss(400, -40), "Invalid argument: Longitude must be between -180 and 180 degrees." ) })
filter.rare.variants <- function(x, ref.level = NULL, filter = c("whole", "controls", "any"), maf.threshold = 0.01, min.nb.snps = 2, min.cumulative.maf = NULL, group = NULL, genomic.region = NULL) { if (is.null(genomic.region) & !("genomic.region" %in% colnames(x@snps))) stop("genomic.region should be provided or already in x@snps") if (!is.null(genomic.region)){ if(nrow(x@snps)!=length(genomic.region)) stop("genomic.region should have the same length as the number of markers in x") if("genomic.region" %in% colnames(x@snps)) warning("genomic.region was already in x@snps, x@snps will be replaced.\n") x@snps$genomic.region=genomic.region } if(!is.factor(x@snps$genomic.region)) stop("'x@snps$genomic.region' should be a factor") x@snps$genomic.region <- droplevels(x@snps$genomic.region) filter <- match.arg(filter) if(filter != "whole"){ if(is.null(group)){ group <- x@ped$pheno }else{ if(length(group) != nrow(x@ped)) stop("group has wrong length") } if(!is.factor(group)) stop("'group' should be a factor") } filter <- match.arg(filter) if(filter == "controls") { if(is.null(ref.level)) stop("Need to specify the controls group") which.controls <- group == ref.level st <- .Call('gg_geno_stats_snps', PACKAGE = "Ravages", x@bed, rep(TRUE, ncol(x)), which.controls)$snps p <- (st$N0.f + 0.5*st$N1.f)/(st$N0.f + st$N1.f + st$N2.f) maf <- pmin(p, 1-p) w <- (maf < maf.threshold) } if(filter == "any"){ w <- rep(FALSE, ncol(x)) for(i in unique(group)) { which.c <- (group == i) st <- .Call('gg_geno_stats_snps', PACKAGE = "Ravages", x@bed, rep(TRUE, ncol(x)), which.c)$snps p <- (st$N0.f + 0.5*st$N1.f)/(st$N0.f + st$N1.f + st$N2.f) maf <- pmin(p, 1-p) w <- w | (maf < maf.threshold) } } if(filter == "whole"){ w <- (x@snps$maf < maf.threshold) } x <- select.snps(x, w & x@snps$maf > 0) nb.snps <- table(x@snps$genomic.region) keep <- names(nb.snps)[nb.snps >= min.nb.snps] x <- select.snps(x, x@snps$genomic.region %in% keep) x@snps$genomic.region <- droplevels(x@snps$genomic.region) if(!is.null(min.cumulative.maf)) { cmaf.snps <- by(x@snps$maf, x@snps$genomic.region, sum) keep <- names(cmaf.snps)[cmaf.snps >= min.cumulative.maf] x <- select.snps(x, x@snps$genomic.region %in% keep) x@snps$genomic.region <- droplevels(x@snps$genomic.region) } x }
heatmap_wave.local.multiple.correlation <- function(Lst, xaxt="s", ci=NULL, pdf.write=NULL) { if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor J <- length(Lst$YmaxR)-1 par(mfcol=c(1,1), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(0.1,1.2,1.2,1.2)) scale.labs <- c(paste0(2^(1:J),"-",2^((1:J)+1)),"smooth") if (!is.null(pdf.write)) cairo_pdf(paste0("heat_",pdf.write,"_WLMC.pdf"), width=11.69,height=8.27) if (is.null(ci)||ci=="center") {val <- sapply(cor,function(x){x[["val"]]}) } else if (ci=="lower") {val <- sapply(cor,function(x){x[["lo"]]}) } else if (ci=="upper"){val <- sapply(cor,function(x){x[["up"]]})} clim <- range(sapply(cor,function(x){x[["val"]]})) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") plot3D::image2D(z=val, x=1:nrow(val), y=1:ncol(val), main="", sub="", xlab="", ylab="", xaxt=xaxt, yaxt="n", cex.axis=0.75, colkey=list(cex.axis=0.75), clim=clim, clab=expression(varphi), rasterImage=TRUE, contour=list(lwd=2, col=plot3D::jet.col(11))) if(xaxt!="s") {axis(side=1, at=at, labels=label, cex.axis=0.75)} axis(side=2, at=1:ncol(val),labels=scale.labs, las=1, cex.axis=0.75) text(x=grconvertX(0.1,from="npc"), y=grconvertY(0.98,from="npc"), labels=mark, col=rgb(0,0,0,.1),cex=.2) par(las=0) title(main='Wavelet Local Multiple Correlation', outer=TRUE) mtext("period", side=2, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() return() }
somersD = function(formula, data) { if(methods::is(data, "survey.design")!=TRUE) message(paste(sep="","Warning: Dataset \"", deparse(substitute(data)), "\" not a design dataset. Try gssD, nesD, statesD, or worldD instead.")) tablesomersDC(survey::svytable(formula, data)) }
def_ren <- new.env(parent = emptyenv()) .onLoad <- function(...) { register_s3_method("knitr", "knit_print", "gganim") register_s3_method("knitr", "knit_print", "gif_image") register_s3_method("knitr", "knit_print", "video_file") register_s3_method("knitr", "knit_print", "sprite_image") def_ren$has_proper <- TRUE if (requireNamespace('gifski', quietly = TRUE)) { def_ren$renderer <- gifski_renderer() } else if (requireNamespace('magick', quietly = TRUE)) { def_ren$renderer <- magick_renderer() } else if (requireNamespace('av', quietly = TRUE)) { def_ren$renderer <- av_renderer() } else { def_ren$renderer <- file_renderer() def_ren$has_proper <- FALSE } invisible() } .onAttach <- function(...) { if (!isTRUE(def_ren$has_proper)) { packageStartupMessage( 'No renderer backend detected. gganimate will default to writing frames to separate files\n', 'Consider installing:\n', '- the `gifski` package for gif output\n', '- the `av` package for video output\n', 'and restarting the R session' ) } } register_s3_method <- function(pkg, generic, class, fun = NULL) { stopifnot(is.character(pkg), length(pkg) == 1) stopifnot(is.character(generic), length(generic) == 1) stopifnot(is.character(class), length(class) == 1) if (is.null(fun)) { fun <- get(paste0(generic, ".", class), envir = parent.frame()) } else { stopifnot(is.function(fun)) } if (pkg %in% loadedNamespaces()) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } setHook( packageEvent(pkg, "onLoad"), function(...) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } ) }
num1to100.gen <- setNumericWithRange("Numeric", min = 1, max = 100) par.gen <- setRefClass("Graph", properties(list(size = "NumericWithMin1Max100"))) pars <- par.gen$new(size = new("NumericWithMin1Max100", 5)) pars$size try(pars$size <- 300) pars$size <- 10 par.gen <- setRefClass("PI", properties(list(size = "PositiveInteger"), list(size = PositiveInteger(2)))) obj <- par.gen$new() try(obj$size <- -1) obj$size <- 3
htmlTr <- function(children=NULL, id=NULL, n_clicks=NULL, n_clicks_timestamp=NULL, key=NULL, role=NULL, accessKey=NULL, className=NULL, contentEditable=NULL, contextMenu=NULL, dir=NULL, draggable=NULL, hidden=NULL, lang=NULL, spellCheck=NULL, style=NULL, tabIndex=NULL, title=NULL, loading_state=NULL, ...) { wildcard_names = names(dash_assert_valid_wildcards(attrib = list('data', 'aria'), ...)) props <- list(children=children, id=id, n_clicks=n_clicks, n_clicks_timestamp=n_clicks_timestamp, key=key, role=role, accessKey=accessKey, className=className, contentEditable=contentEditable, contextMenu=contextMenu, dir=dir, draggable=draggable, hidden=hidden, lang=lang, spellCheck=spellCheck, style=style, tabIndex=tabIndex, title=title, loading_state=loading_state, ...) if (length(props) > 0) { props <- props[!vapply(props, is.null, logical(1))] } component <- list( props = props, type = 'Tr', namespace = 'dash_html_components', propNames = c('children', 'id', 'n_clicks', 'n_clicks_timestamp', 'key', 'role', 'accessKey', 'className', 'contentEditable', 'contextMenu', 'dir', 'draggable', 'hidden', 'lang', 'spellCheck', 'style', 'tabIndex', 'title', 'loading_state', wildcard_names), package = 'dashHtmlComponents' ) structure(component, class = c('dash_component', 'list')) }
H.als.b <- function(Z, Hs, Ht, Hst.ls, rho, reg, b.lag=-1, Hs0=NULL, Ht0=NULL, Hst0.ls=NULL) { tau <- nrow(Z) n <- ncol(Z) Z.als <- matrix(NA, tau, n) if( is.null( Hs ) ) { use.Hs <- FALSE ; d.s <- 0 } else { use.Hs <- TRUE ; d.s <- ncol( Hs ) } if( is.null( Ht ) ) { use.Ht <- FALSE ; d.t <- 0 } else { use.Ht <- TRUE ; d.t <- ncol( Ht ) } if( is.null( Hst.ls ) ) { use.Hst.ls <- FALSE ; d.st <- 0 } else { use.Hst.ls <- TRUE ; d.st <- ncol( Hst.ls[[1]] ) } d <- d.s + d.t + d.st B <- matrix(0, tau, d) reg.mx <- diag( reg, d ) LHH <- 0 LHy <- 0 g <- 1 use.H0 <- !is.null(Hs0) | !is.null(Ht0) | !is.null(Hst0.ls) if( use.H0 ) { if( !is.null(Hs0) ) { n0 <- nrow(Hs0) ; Z.als.0 <- matrix(NA, tau, n0) } else { n0 <- nrow(Hst0.ls[[1]]) } } low.ndx <- max( 1, 1-b.lag ) top.ndx <- min( tau, tau-b.lag ) for(i in low.ndx:top.ndx) { if( use.Ht ) { this.Ht.mx <- matrix( Ht[ i, ], n, d.t, byrow=TRUE ) } else { this.Ht.mx <- NULL } this.H <- cbind( Hs, this.Ht.mx, Hst.ls[[i]] ) if( use.H0 ) { if( use.Ht ) { this.Ht0.mx <- matrix( Ht0[ i, ], n0, d.t, byrow=TRUE ) } else { this.Ht0.mx <- NULL } this.H0 <- cbind( Hs0, this.Ht0.mx, Hst0.ls[[i]] ) } this.HH <- crossprod(this.H) this.Hy <- crossprod(this.H, Z[ i, ]) LHH <- LHH + g * ( this.HH - LHH ) LHy <- LHy + g * ( this.Hy - LHy ) inv.LHH <- try( solve( LHH + reg.mx ), silent=TRUE ) if( is(inv.LHH, "try-error") ) { inv.LHH <- matrix(0, d, d) } B[ i, ] <- inv.LHH %*% LHy Z.als[ i, ] <- B[ i + b.lag, ] %*% t(this.H) if( use.H0 ) { Z.als.0[ i, ] <- B[ i + b.lag, ] %*% t(this.H0) } else { Z.als.0 <- NULL } g <- (g+rho) / (g+rho+1) } return( list("Z.hat"=Z.als, "B"=B, "Z0.hat"=Z.als.0, "inv.LHH"=inv.LHH, "ALS.g"=g) ) }
src_sqlite <- function(dbname = ":memory:", ...) { con <- DBI::dbConnect( drv = RSQLite::SQLite(), dbname = dbname, ...) if (inherits( try( DBI::dbGetQuery( conn = con, statement = paste0("SELECT json_patch('{\"a\":1}','{\"a\":9}');") ), silent = TRUE ), "try-error")) { stop("SQLite does not have json1 extension enabled. Call ", "install.packages('RSQLite') to install a current version.") } if (inherits( try({ RSQLite::initRegExp(db = con) DBI::dbExecute( conn = con, statement = paste0('SELECT * FROM (VALUES ("Astring")) WHERE 1 REGEXP "[A-Z]+";')) }, silent = TRUE ), "try-error")) { stop("SQLite does not support REGEXP. Call ", "install.packages('RSQLite') to install a current version.") } DBI::dbExecute(con, "PRAGMA busy_timeout = 10000;") structure(list(con = con, dbname = dbname, ...), class = c("src_sqlite", "docdb_src")) } print.src_sqlite <- function(x, ...) { dbname <- x$dbname dbsize <- file.size(dbname) srv <- rev(RSQLite::rsqliteVersion())[1] cat(sprintf( "src: sqlite\nSQLite library version: %s\n size: %s kBytes\n dbname: %s\n", srv, dbsize / 2^10, dbname)) if (grepl(":memory:", dbname)) { warning( "Database is only in memory, will not persist after R ends! Consider to copy ", "it with \nRSQLite::sqliteCopyDatabase(\n", " from = <your nodbi::src_sqlite() object>$con, \n", " to = <e.g. RSQLite::dbConnect(RSQLite::SQLite(), 'local_file.db')>\n", " )", call. = FALSE) } }
toLatex.sts <- function(object, caption = "",label=" ", columnLabels = NULL, subset = NULL, alarmPrefix = "\\textbf{\\textcolor{red}{", alarmSuffix = "}}", ubColumnLabel = "UB", ...) { isEmpty <- function(o) is.null(o) if (isEmpty(object)) stop("object must not be null or NA.") if (is.list(object)) stop("supplying a list of sts has been removed from the api. Sorry.") if (!isS4(object) || !is(object, "sts")) stop("object must be of type sts from the surveillance package.") if (!is.character(caption)) stop("caption must be a character.") if (!isEmpty(labels) && length(labels) != length(object)) stop("number of labels differ from the number of sts objects.") tableLabels <- colnames(object@observed) if (!is.null(columnLabels) && length(columnLabels) != ncol(object@observed) * 2 + 2) { stop("the number of labels must match the number of columns in the resulting table; i.e. 2 * columns of sts + 2.") } tableCaption <- caption tableLabel <- label vectorOfDates <- epoch(object, as.Date = TRUE) yearColumn <- Map(function(d)isoWeekYear(d)$ISOYear, vectorOfDates) if (object@freq == 12 ) monthColumn <- Map(function(d) as.POSIXlt(d)$mon, vectorOfDates) if (object@freq == 52 ) weekColumn <- Map(function(d)isoWeekYear(d)$ISOWeek, vectorOfDates) dataTable <- data.frame(unlist(yearColumn)) colnames(dataTable) <- "year" if (object@freq == 12 ) { dataTable$month <- unlist(monthColumn) } if (object@freq == 52 ) { dataTable$week <- unlist(weekColumn) } if (object@freq == 365 ) { dataTable$day <- unlist(vectorOfDates) dataTable <- dataTable[c(2)] } noCols <- ncol(dataTable) j <- 1 + noCols tableLabelsWithUB <- c() for (k in 1:(ncol(object@observed))) { upperbounds <- round(object@upperbound[,k], 2) observedValues <- object@observed[,k] alarms <- object@alarm[,k] ubCol <- c() for (l in 1:length(upperbounds)) { if (is.na(upperbounds[l])) { ubCol <- c(ubCol, NA) } else { ubCol <- c(ubCol, upperbounds[l]) if (!is.na(alarms[l]) && alarms[l]) { observedValues[l] <- paste0(alarmPrefix, observedValues[l], alarmSuffix) } } } dataTable[,(j)] <- observedValues dataTable[,(j + 1)] <- ubCol tableLabelsWithUB <- c(tableLabelsWithUB, tableLabels[k]) tableLabelsWithUB <- c(tableLabelsWithUB, ubColumnLabel) j <- j + 2 } if (is.null(subset)) subset <- 1:nrow(dataTable) else if (min(subset) < 1 || max(subset) > nrow(dataTable)) stop("'subset' must be a subset of 1:nrow(observed), i.e., 1:", nrow(dataTable)) dataTable <- dataTable[subset,] newColNames <- c(colnames(dataTable)[1:noCols], tableLabelsWithUB) if (!is.null(columnLabels)) { colnames(dataTable) <- columnLabels } else { colnames(dataTable) <- newColNames } xDataTable <- xtable(dataTable, label = tableLabel, caption = tableCaption, digits = c(0)) toLatex(xDataTable, ...) } setMethod("toLatex", "sts", toLatex.sts)
context("datasets [backPain]") tol <- 1e-4 backPainLong <- expandCategorical(backPain, "pain") stereotype <- gnm(count ~ pain + Mult(pain, x1 + x2 + x3), eliminate = id, family = "poisson", data = backPainLong, verbose = FALSE) test_that("sterotype model as expected for backPain data", { size <- tapply(backPainLong$count, backPainLong$id, sum)[backPainLong$id] expect_equal(round(sum(stereotype$y * log(stereotype$fitted/size)), 2), -151.55) expect_equivalent(stereotype$rank - nlevels(stereotype$eliminate), 12) })
l1.reg.default <- function (X, Y, lambda=1) { if (length(Y)!=ncol(X)) stop("Dimention doesn't match! Columns of feature matrix X must be the number of cases") cases <- length(Y) predictors <- nrow(X) X <-rbind(rep(1,ncol(X)),X) return_data <- .Fortran ("L1GREEDY", as.double(X), Y=as.double(as.vector(Y)), as.double (lambda), as.integer (cases), as.integer (predictors+1), L1 = as.double(0), penalty = as.double(0), objective = as.double(0), estimate = as.double(as.vector(rep(0,predictors+1))), r = as.double(as.vector(rep(0,cases))), PACKAGE = "CDLasso") selected<-c() nonzeros<-0 for (j in 2:(predictors+1)) { if (return_data$estimate[j]!=0) { nonzeros<-nonzeros+1 selected<-c(selected,j-1) } } out <- list (X = X, Y = Y, cases = cases, predictors = predictors, lambda = lambda, objective = return_data$objective, residual = return_data$r, L1 = return_data$L1, intercept = return_data$estimate[1], estimate = return_data$estimate[2:(predictors+1)], nonzeros = nonzeros, selected = selected, call=sys.call ()) class (out) <- "l1.reg" return(out) }
summary.colspace <- function(object, by = NULL, ...) { chkDots(...) if (is.null(attr(object, "clrsp"))) { message("Cannot return full colspace summary on subset data") return(summary(as.data.frame(object))) } if (is.numeric(by) && attr(object, "clrsp") == "tcs" && nrow(object) %% by != 0) { stop("The value passed to 'by' is not a multiple of the number of spectra") } if (!is.null(attr(object, "data.maxgamut"))) { maxgamut <- attr(object, "data.maxgamut") if (attr(object, "clrsp") == "dispace") { maxvol <- max(maxgamut) - min(maxgamut) } else { maxvol <- tryCatch( convhulln(attr(object, "data.maxgamut"), "FA")$vol, error = function(e) NA ) } } else { maxvol <- NA } cat( "Colorspace & visual model options:\n", "* Colorspace:", attr(object, "clrsp"), "\n", "* Quantal catch:", attr(object, "qcatch"), "\n", "* Visual system, chromatic:", attr(object, "visualsystem.chromatic"), "\n", "* Visual system, achromatic:", attr(object, "visualsystem.achromatic"), "\n", "* Illuminant:", attr(object, "illuminant"), "\n", "* Background:", attr(object, "background"), "\n", "* Relative:", attr(object, "relative"), "\n", "* Max possible chromatic volume:", maxvol, "\n" ) cat("\n") if (attr(object, "clrsp") != "tcs") { return(summary.data.frame(object)) } if (attr(object, "clrsp") == "tcs") { if (!is.null(by)) { if (length(by) == 1) { by.many <- by by <- rep(seq_len(dim(object)[1] / by), each = by) by <- factor(by, labels = row.names(object)[seq(1, length(row.names(object)), by = by.many)] ) } by <- factor(by) res.c <- data.frame(t(sapply(levels(by), function(z) tcssum(object[which(by == z), ])))) row.names(res.c) <- levels(by) } else { res.c <- data.frame(t(tcssum(object))) row.names(res.c) <- "all.points" } if (anyNA(res.c$c.vol)) { warning("Not enough points to calculate volume", call. = FALSE) } res.c } }
GITHUB_PATTERN <- '^https?://github.com' get_pkgs_url <- function() { pkgs <- utils::installed.packages(priority = 'NA', fields = c('URL', 'BugReports', 'GithubRepo', 'GithubUsername')) repos_from_cran_url <- filter_github_cran(pkgs[, c('URL')]) repos_from_cran_bugreports <- filter_github_cran(pkgs[, c('BugReports')]) repos_from_cran <- union(repos_from_cran_url, repos_from_cran_bugreports) repos_by_devtools <- filter_github_devtool(pkgs[, c('GithubRepo', 'GithubUsername')]) repos <- union(repos_from_cran, repos_by_devtools) return(repos) } filter_github_cran <- function(pkgs) { GITHUB_PATTERN <- '^https?://github.com' pkgs <- strsplit(pkgs, '( |,| pkgs <- sapply(pkgs, function(pkg) { grep(GITHUB_PATTERN, pkg, value = TRUE)[1] }) pkgs <- pkgs[!is.na(pkgs)] pkgs <- strsplit(pkgs, '/') repo_name <- sapply(pkgs, function(vec) paste(vec[4:5], collapse = '/')) return(repo_name) } filter_github_devtool <- function(pkgs) { pkgs <- na.omit(data.frame(pkgs)) repos_name <- paste(pkgs$GithubUsername, pkgs$GithubRepo, sep = "/") return(repos_name) }
lavMultipleGroups <- function(model = NULL, dataList = NULL, ndat = length(dataList), cmd = "sem", ..., store.slots = c("partable"), FUN = NULL, show.progress = FALSE, parallel = c("no", "multicore", "snow"), ncpus = max(1L, parallel::detectCores() - 1L), cl = NULL) { dotdotdot <- list() fit <- do.call("lavaanList", args = c(list(model = model, dataList = dataList, ndat = ndat, cmd = cmd, store.slots = store.slots, FUN = FUN, show.progress = show.progress, parallel = parallel, ncpus = ncpus, cl = cl), dotdotdot)) fit@meta$lavMultipleGroups <- TRUE fit@meta$group.label <- names(dataList) fit }
scatterD3 <- function(x, y, data = NULL, lab = NULL, x_log = FALSE, y_log = FALSE, point_size = 64, labels_size = 10, labels_positions = NULL, point_opacity = 1, opacities = NULL, hover_size = 1, hover_opacity = NULL, fixed = FALSE, col_var = NULL, col_continuous = NULL, colors = NULL, ellipses = FALSE, ellipses_level = 0.95, symbol_var = NULL, symbols = NULL, size_var = NULL, size_range = c(10,300), sizes = NULL, col_lab = NULL, symbol_lab = NULL, size_lab = NULL, key_var = NULL, type_var = NULL, opacity_var = NULL, unit_circle = FALSE, url_var = NULL, tooltips = TRUE, tooltip_text = NULL, tooltip_position = "bottom right", xlab = NULL, ylab = NULL, html_id = NULL, width = NULL, height = NULL, legend_width = 150, left_margin = 30, xlim = NULL, ylim = NULL, dom_id_reset_zoom = "scatterD3-reset-zoom", dom_id_svg_export = "scatterD3-svg-export", dom_id_lasso_toggle = "scatterD3-lasso-toggle", transitions = FALSE, menu = TRUE, lasso = FALSE, lasso_callback = NULL, click_callback = NULL, init_callback = NULL, zoom_callback = NULL, zoom_on = NULL, zoom_on_level = NULL, disable_wheel = FALSE, lines = data.frame(slope = c(0, Inf), intercept = c(0, 0), stroke_dasharray = c(5,5)), axes_font_size = "100%", legend_font_size = "100%", caption = NULL) { if (is.null(xlab)) xlab <- deparse(substitute(x)) if (is.null(ylab)) ylab <- deparse(substitute(y)) if (is.null(col_lab)) col_lab <- deparse(substitute(col_var)) if (is.null(symbol_lab)) symbol_lab <- deparse(substitute(symbol_var)) if (is.null(size_lab)) size_lab <- deparse(substitute(size_var)) opacity_lab <- deparse(substitute(opacity_var)) if (is.null(html_id)) html_id <- paste0("scatterD3-", paste0(sample(LETTERS, 8, replace = TRUE), collapse = "")) if (!is.null(data)) { null_or_name <- function(varname) { if (varname != "NULL") return(data[, varname]) else return(NULL) } x <- data[, deparse(substitute(x))] y <- data[, deparse(substitute(y))] lab <- deparse(substitute(lab)) col_var <- deparse(substitute(col_var)) size_var <- deparse(substitute(size_var)) symbol_var <- deparse(substitute(symbol_var)) opacity_var <- deparse(substitute(opacity_var)) url_var <- deparse(substitute(url_var)) key_var <- deparse(substitute(key_var)) type_var <- deparse(substitute(type_var)) lab <- null_or_name(lab) col_var <- null_or_name(col_var) size_var <- null_or_name(size_var) symbol_var <- null_or_name(symbol_var) opacity_var <- null_or_name(opacity_var) url_var <- null_or_name(url_var) key_var <- null_or_name(key_var) type_var <- null_or_name(type_var) } x_categorical <- is.factor(x) || !is.numeric(x) y_categorical <- is.factor(y) || !is.numeric(y) x_levels <- levels(x) y_levels <- levels(y) if (x_log) { if (any(x <= 0)) stop("Logarithmic scale and negative values in x") lines <- lines[!(lines$slope == 0 & lines$intercept == 0),] } if (y_log) { if (any(y <= 0)) stop("Logarithmic scale and negative values in y") lines <- lines[!(lines$slope == Inf & lines$intercept == 0),] } if (!is.null(colors) && !is.null(names(colors))) { colors <- as.list(colors) if (!setequal(names(colors), unique(col_var))) warning("Set of colors and col_var values do not match") } if (!is.null(symbols) && !is.null(names(symbols))) { symbols <- as.list(symbols) if (!setequal(names(symbols), unique(symbol_var))) warning("Set of symbols and symbol_var values do not match") } if (!is.null(sizes) && !is.null(names(sizes))) { sizes <- as.list(sizes) if (!setequal(names(sizes), unique(size_var))) warning("Set of sizes and size_var values do not match") } if (!is.null(opacities) && !is.null(names(opacities))) { opacities <- as.list(opacities) if (!setequal(names(opacities), unique(opacity_var))) warning("Set of opacities and opacity_var values do not match") } if (is.null(col_continuous)) { col_continuous <- FALSE if (!is.factor(col_var) && is.numeric(col_var) && length(unique(col_var)) > 6) { col_continuous <- TRUE } } if (is.character(caption)) { caption <- list(text = caption) } tooltip_position_x <- gsub("^.* ([a-z]+) *$", "\\1", tooltip_position) tooltip_position_y <- gsub("^ *([a-z]+) .*$", "\\1", tooltip_position) if (!(tooltip_position_x %in% c("left", "right")) || !(tooltip_position_y %in% c("top", "bottom"))) { warning("tooltip_position must be a combination of 'top' or 'bottom' and 'left' or 'right'.") tooltip_position_x <- "right" tooltip_position_y <- "bottom" } data <- data.frame(x = x, y = y) col_levels <- NULL symbol_levels <- NULL if (!is.null(lab)) data <- cbind(data, lab = lab) if (!is.null(col_var) && !col_continuous) { if (is.factor(col_var)) col_levels <- levels(col_var) col_var <- as.character(col_var) col_var[is.na(col_var)] <- "NA" data <- cbind(data, col_var = col_var) } if (!is.null(col_var) && col_continuous) { if (any(is.na(col_var))) warning("NA values in continuous col_var. Values set to min(0, col_var)") col_var[is.na(col_var)] <- min(0, col_var, na.rm = TRUE) data <- cbind(data, col_var = col_var) } if (!is.null(symbol_var)) { if (is.factor(symbol_var)) symbol_levels <- levels(symbol_var) symbol_var <- as.character(symbol_var) symbol_var[is.na(symbol_var)] <- "NA" data <- cbind(data, symbol_var = symbol_var) } if (!is.null(size_var)) { if (any(is.na(size_var))) warning("NA values in size_var. Values set to min(0, size_var)") size_var[is.na(size_var)] <- min(0, size_var, na.rm = TRUE) data <- cbind(data, size_var = size_var) } if (!is.null(type_var)) data <- cbind(data, type_var = type_var) if (!is.null(url_var)) { url_var[is.na(url_var)] <- "" data <- cbind(data, url_var = url_var) if (!is.null(click_callback)) { click_callback <- NULL warning("Both url_var and click_callback defined, click_callback set to NULL") } } if (!is.null(opacity_var)) data <- cbind(data, opacity_var = opacity_var) if (!is.null(key_var)) { data <- cbind(data, key_var = key_var) } else { data <- cbind(data, key_var = seq_along(x)) } if (!is.null(tooltip_text)) data <- cbind(data, tooltip_text = tooltip_text) compute_ellipse <- function(x, y, level = ellipses_level, npoints = 50) { cx <- mean(x) cy <- mean(y) data.frame(ellipse::ellipse(stats::cov(cbind(x,y)), centre = c(cx, cy), level = level, npoints = npoints)) } ellipses_data <- list() if (ellipses && !col_continuous && !x_categorical && !y_categorical) { if (is.null(col_var)) { ell <- compute_ellipse(x, y) ellipses_data <- append(ellipses_data, list(list(level = "_scatterD3_all", data = ell))) } else { for (l in unique(col_var)) { sel <- col_var == l & !is.na(col_var) if (sum(sel) > 2) { tmpx <- x[sel] tmpy <- y[sel] ell <- compute_ellipse(tmpx, tmpy) ellipses_data <- append(ellipses_data, list(list(level = l, data = ell))) } } } } else { ellipses <- FALSE } hashes <- list() if (transitions) { for (var in c("x", "y", "lab", "key_var", "col_var", "symbol_var", "size_var", "ellipses_data", "opacity_var", "lines", "labels_positions")) { hashes[[var]] <- digest::digest(get(var), algo = "sha256") } } n_lab <- sum(lab != "") if (n_lab > 500 && !is.null(labels_positions) && labels_positions == "auto") { warning(gettext("More than 500 labels, automatic labels positioning has been disabled")) labels_positions <- NULL } settings <- list( x_log = x_log, y_log = y_log, labels_size = labels_size, labels_positions = labels_positions, point_size = point_size, point_opacity = point_opacity, opacities = opacities, hover_size = hover_size, hover_opacity = hover_opacity, xlab = xlab, ylab = ylab, has_labels = !is.null(lab), col_lab = col_lab, col_continuous = col_continuous, col_levels = col_levels, colors = colors, ellipses = ellipses, ellipses_data = ellipses_data, symbol_lab = symbol_lab, symbol_levels = symbol_levels, symbols = symbols, size_range = size_range, size_lab = size_lab, sizes = sizes, opacity_lab = opacity_lab, opacities = opacities, unit_circle = unit_circle, has_color_var = !is.null(col_var), has_symbol_var = !is.null(symbol_var), has_size_var = !is.null(size_var), has_opacity_var = !is.null(opacity_var), has_url_var = !is.null(url_var), has_legend = (!is.na(col_lab) && !is.null(col_var)) || (!is.na(symbol_lab) && !is.null(symbol_var)) || (!is.na(size_lab) && !is.null(size_var)), has_tooltips = tooltips, tooltip_text = tooltip_text, tooltip_position_x = tooltip_position_x, tooltip_position_y = tooltip_position_y, has_custom_tooltips = !is.null(tooltip_text), click_callback = htmlwidgets::JS(click_callback), init_callback = htmlwidgets::JS(init_callback), zoom_callback = htmlwidgets::JS(zoom_callback), zoom_on = zoom_on, zoom_on_level = zoom_on_level, disable_wheel = disable_wheel, fixed = fixed, legend_width = legend_width, left_margin = left_margin, html_id = html_id, xlim = xlim, ylim = ylim, x_categorical = x_categorical, y_categorical = y_categorical, x_levels = x_levels, y_levels = y_levels, menu = menu, lasso = lasso, lasso_callback = htmlwidgets::JS(lasso_callback), dom_id_reset_zoom = dom_id_reset_zoom, dom_id_svg_export = dom_id_svg_export, dom_id_lasso_toggle = dom_id_lasso_toggle, transitions = transitions, axes_font_size = axes_font_size, legend_font_size = legend_font_size, caption = caption, lines = lines, hashes = hashes ) x <- list( data = data, settings = settings ) htmlwidgets::createWidget( name = 'scatterD3', x, width = width, height = height, package = 'scatterD3', sizingPolicy = htmlwidgets::sizingPolicy( browser.fill = TRUE, browser.defaultWidth = "100%", browser.defaultHeight = "85vh", viewer.fill = TRUE, viewer.defaultWidth = "100%", viewer.defaultHeight = "85vh" ) ) } scatterD3Output <- function(outputId, width = '100%', height = '600px'){ htmlwidgets::shinyWidgetOutput(outputId, 'scatterD3', width, height, package = 'scatterD3') } renderScatterD3 <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, scatterD3Output, env, quoted = TRUE) }
context("test-g01-lin_ops") NEG <- "neg" PARAM <- "param" DENSE_CONST <- "dense_const" SPARSE_CONST <- "sparse_const" SCALAR_CONST <- "scalar_const" SUM_ENTRIES <- "sum_entries" VARIABLE <- "variable" create_const <- CVXR:::create_const create_eq <- CVXR:::create_eq create_leq <- CVXR:::create_leq create_param <- CVXR:::create_param create_var <- CVXR:::create_var get_expr_vars <- CVXR:::get_expr_vars lo.neg_expr <- CVXR:::lo.neg_expr lo.sum_expr <- CVXR:::lo.sum_expr lo.sum_entries <- CVXR:::lo.sum_entries test_that("Test creating a variable", { skip_on_cran() var <- create_var(c(5, 4), var_id = 1) expect_equal(var$dim, c(5, 4)) expect_equal(var$data, 1) expect_equal(length(var$args), 0) expect_equal(var$type, VARIABLE) }) test_that("Test creating a parameter", { skip_on_cran() A <- Parameter(5, 4) var <- create_param(A, c(5, 4)) expect_equal(var$dim, c(5, 4)) expect_equal(length(var$args), 0) expect_equal(var$type, PARAM) }) test_that("Test creating a constant", { skip_on_cran() dim <- c(1, 1) mat <- create_const(1.0, dim) expect_equal(mat$dim, dim) expect_equal(length(mat$args), 0) expect_equal(mat$type, SCALAR_CONST) expect_equal(mat$data, 1.0) dim <- c(5, 4) mat <- create_const(matrix(1, nrow = dim[1], ncol = dim[2]), dim) expect_equal(mat$dim, dim) expect_equal(length(mat$args), 0) expect_equal(mat$type, DENSE_CONST) expect_equal(mat$data, matrix(1, nrow = dim[1], ncol = dim[2])) dim <- c(5, 5) mat <- create_const(Matrix::sparseMatrix(i = 1:5, j = 1:5, x = 1), dim, sparse = TRUE) expect_equal(mat$dim, dim) expect_equal(length(mat$args), 0) expect_equal(mat$type, SPARSE_CONST) expect_equivalent(as.matrix(mat$data), diag(rep(1, 5))) }) test_that("Test adding lin expr", { skip_on_cran() dim <- c(5, 4) x <- create_var(dim) y <- create_var(dim) add_expr <- lo.sum_expr(list(x, y)) expect_equal(add_expr$dim, dim) expect_equal(length(add_expr$args), 2) }) test_that("Test getting vars from an expression", { skip_on_cran() dim <- c(5, 4) x <- create_var(dim) y <- create_var(dim) A <- create_const(matrix(1, nrow = dim[1], ncol = dim[2]), dim) add_expr <- lo.sum_expr(list(x, y, A)) vars_ <- get_expr_vars(add_expr) expect_equal(vars_[[1]], list(x$data, dim)) expect_equal(vars_[[2]], list(y$data, dim)) }) test_that("Test negating an expression", { skip_on_cran() dim <- c(5, 4) var <- create_var(dim) expr <- lo.neg_expr(var) expect_equal(length(expr$args), 1) expect_equal(expr$dim, dim) expect_equal(expr$type, NEG) }) test_that("Test creating an equality constraint", { skip_on_cran() dim <- c(5, 5) x <- create_var(dim) y <- create_var(dim) lh_expr <- lo.sum_expr(list(x, y)) value <- matrix(1, nrow = dim[1], ncol = dim[2]) rh_expr <- create_const(value, dim) constr <- create_eq(lh_expr, rh_expr) expect_equal(constr$dim, dim) vars_ <- get_expr_vars(constr$expr) ref <- list(list(x$data, dim), list(y$data, dim)) expect_equal(vars_, ref) }) test_that("Test creating a less than or equal constraint", { skip_on_cran() dim <- c(5, 5) x <- create_var(dim) y <- create_var(dim) lh_expr <- lo.sum_expr(list(x, y)) value <- matrix(1, nrow = dim[1], ncol = dim[2]) rh_expr <- create_const(value, dim) constr <- create_leq(lh_expr, rh_expr) expect_equal(constr$dim, dim) vars_ <- get_expr_vars(constr$expr) ref <- list(list(x$data, dim), list(y$data, dim)) expect_equal(vars_, ref) }) test_that("Test sum entries op", { skip_on_cran() dim <- c(5, 5) x <- create_var(dim) expr <- lo.sum_entries(x, c(1, 1)) expect_equal(expr$dim, c(1, 1)) expect_equal(length(expr$args), 1) expect_equal(expr$type, SUM_ENTRIES) })
context("optimize_folder") test_that("optimize non recursively in a folder", { tmp_dir <- tempdir() base_dir <- paste0(tmp_dir, "/folder1/") sub_dir <- paste0(base_dir, "subdir/") unlink(base_dir, force = TRUE, recursive = TRUE) dir.create(base_dir, showWarnings = FALSE) dir.create(sub_dir, showWarnings = FALSE) file_opt <- paste0(base_dir, "file_opt.R") file_unopt <- paste0(base_dir, "file_unopt.R") subd_file_opt <- paste0(sub_dir, "file_opt.R") subd_file_unopt <- paste0(sub_dir, "file_unopt.R") opt_code <- "var1 <- 3; var2 <- 15" unopt_code <- "var1 <- 3; var2 <- var1 * 5" write_code_file(opt_code, file_opt) expect_true(file.copy(file_opt, subd_file_opt)) write_code_file(unopt_code, file_unopt) expect_true(file.copy(file_unopt, subd_file_unopt)) optimize_folder(base_dir, recursive = FALSE) expect_true(length(dir(base_dir)) == 4) expect_true(length(dir(sub_dir)) == 2) expect_equal( read_code_file(paste0(base_dir, "optimized_", basename(file_unopt))), read_code_file(file_opt) ) }) test_that("optimize recursively in a folder", { tmp_dir <- tempdir() base_dir <- paste0(tmp_dir, "/folder2/") sub_dir <- paste0(base_dir, "subdir/") unlink(base_dir, force = TRUE, recursive = TRUE) dir.create(base_dir, showWarnings = FALSE) dir.create(sub_dir, showWarnings = FALSE) file_opt <- paste0(base_dir, "file_opt.R") file_unopt <- paste0(base_dir, "file_unopt.R") subd_file_opt <- paste0(sub_dir, "file_opt.R") subd_file_unopt <- paste0(sub_dir, "file_unopt.R") opt_code <- "var1 <- 3; var2 <- 15" unopt_code <- "var1 <- 3; var2 <- var1 * 5" write_code_file(opt_code, file_opt) expect_true(file.copy(file_opt, subd_file_opt)) write_code_file(unopt_code, file_unopt) expect_true(file.copy(file_unopt, subd_file_unopt)) optimize_folder(base_dir, recursive = TRUE) expect_true(length(dir(base_dir)) == 4) expect_true(length(dir(sub_dir)) == 3) expect_equal( read_code_file(paste0(base_dir, "optimized_", basename(file_unopt))), read_code_file(file_opt) ) expect_equal( read_code_file(paste0(sub_dir, "optimized_", basename(file_unopt))), read_code_file(file_opt) ) }) test_that("error on non-exiting folder", { expect_error(optimize_folder("non_existing_folder")) }) test_that("optimize empty folder", { tmp_dir <- tempdir() base_dir <- paste0(tmp_dir, "/folder3/") unlink(base_dir, force = TRUE, recursive = TRUE) dir.create(base_dir, showWarnings = FALSE) expect_null(optimize_folder(base_dir)) })
.googlesheets4 <- new.env(parent = emptyenv())
context("rl_version functions") test_that("rl_version works", { skip_on_cran() vcr::use_cassette("rl_version", { aa <- rl_version() expect_is(aa, "character") expect_match(aa, "[0-9]{4}-[0-9]") }) }) test_that("rl_version curl options work", { skip_on_cran() expect_error(rl_version(timeout_ms = 1), "Timeout was reached") })
CondIndTest <- function(Y, E, X, method = "KCI", alpha = 0.05, parsMethod = list(), verbose = FALSE){ dimY <- NCOL(Y) dimE <- NCOL(E) if(method %in% c("KCI", "InvariantEnvironmentPrediction")) dimY <- 1 if(!(method %in% c("InvariantEnvironmentPrediction", "InvariantResidualDistributionTest", "InvariantConditionalQuantilePrediction"))) dimE <- 1 nTests <- dimY*dimE results <- vector("list", nTests) pval_bonf <- 1 k <- 1 for(de in 1:dimE){ for(dy in 1:dimY){ argsSet <- list(Y = if(dimY > 1) Y[, dy] else Y, E = if(dimE > 1) E[, de] else E, X = X, alpha = alpha, verbose = verbose) switch(method, "KCI" = { result <- do.call(KCI, c(argsSet, parsMethod)) }, "InvariantConditionalQuantilePrediction" = { result <- do.call(InvariantConditionalQuantilePrediction, c(argsSet, parsMethod)) }, "InvariantEnvironmentPrediction" = { result <- do.call(InvariantEnvironmentPrediction, c(argsSet, parsMethod)) }, "InvariantResidualDistributionTest" = { result <- do.call(InvariantResidualDistributionTest, c(argsSet, parsMethod)) }, "InvariantTargetPrediction" = { result <- do.call(InvariantTargetPrediction, c(argsSet, parsMethod)) }, "ResidualPredictionTest" = { result <- do.call(ResidualPredictionTest, c(argsSet, parsMethod)) }, { stop(paste("Method ", method," not implemented")) } ) pval_bonf <- min(pval_bonf, result$pvalue) results[[k]] <- result names(results[[k]])[which(names(results[[k]]) == "pvalue")] <- "pvalue_individual" if(dimY > 1 & dimE > 1) name <- paste("Y", dy, "E", de, sep = "") else if(dimY > 1) name <- paste("Y", dy, sep = "") else if(dimE > 1) name <- paste("E", de, sep = "") else name <- paste("Y", dy, sep = "") names(results)[[k]] <- name k <- k+1 } } results$pvalue <- min(1, pval_bonf*nTests) return(results) }
meBb <- function (x,size,warn=FALSE) { if(!requireNamespace("rmutil")) stop("The package \"rmutil\" seems not to be available.\n") x <- x[!is.na(x)] m1 <- mean(x) m2 <- mean(x^2) denom <- size*(m2/m1 - m1 - 1) + m1 numAlpha <- size*m1 - m2 numBeta <- (size - m1)*(size - m2/m1) alphaHat <- numAlpha/denom betaHat <- numBeta/denom sHat <- alphaHat + betaHat mHat <- alphaHat/sHat if(warn) { if(sHat <= 0 | mHat < 0 | mHat > 1) { whinge <- paste0("The moment estimates of the parameters are\n", " sHat = ",sHat," and mHat = ",mHat,". The value of\n", " \"sHat\" should be strictly positive and\n", " the value of \"mHat\" should be between 0 and 1.\n") warning(whinge) } } c(m=mHat,s=sHat) }
plot.gofobj <- function(x, parm = TRUE, ...) { stopifnot(inherits(x, 'gofobj')) stopifnot(is.logical(parm) & length(parm) == 1) SimStats <- attributes(x)$SimStats N <- attributes(x)$N directed <- attributes(x)$directed nd <- N * (N - 1) / (2 - directed) stats <- names(SimStats) nsim <- nrow(SimStats[[1]]) - 1 ngofst <- length(stats) if(directed){ allstats <- c('idegree', 'odegree', 'esp', 'dsp', 'triadcensus', 'distance') allxlab <- c('in degree', 'out degree', 'edge-wise shared partners', 'dyad-wise shared partners', 'triad census', 'minimum geodesic distance') allylab <- c('proportion of nodes', 'proportion of nodes', 'proportion of edges', 'proportion of dyads', 'proportion of triads', 'proportion of dyads') } else { allstats <- c('degree', 'esp', 'dsp', 'triadcensus', 'distance') allxlab <- c('degree', 'edge-wise shared partners', 'dyad-wise shared partners', 'triad census', 'minimum geodesic distance') allylab <- c('proportion of nodes', 'proportion of edges', 'proportion of dyads', 'proportion of triads', 'proportion of dyads') } names(allxlab) <- allstats names(allylab) <- allstats GOFxlab <- allxlab[stats %in% allstats] GOFylab <- allylab[stats %in% allstats] sumstats <- list() if(parm){ if(ngofst == 2 ){ par(mfrow = c(1,2)) } if(ngofst %in% c(3,4) ){ par(mfrow = c(2,2)) } if(ngofst > 4 ){ par(mfrow = c(2,3)) } } for(gf in stats) { if(gf != 'distance'){ if(gf %in% c('degree', 'idegree', 'odegree')){ sumstats <- cbind(x[[gf]][,1], apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .025), apply(SimStats[[gf]][, -(nsim + 1)], 1, mean), apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .975)) / N simstats <- t(SimStats[[gf]][, -(nsim + 1)]) / N } if(gf == 'esp'){ ne <- colSums(attributes(x)$SimStats[['esp']]) sumstats <- cbind(x[[gf]][,1] / ne[nsim + 1], apply(t(SimStats[[gf]][, -(nsim + 1)]) / ne[ -(nsim + 1)], 2, quantile, probs = .025), apply(t(SimStats[[gf]][, -(nsim + 1)]) / ne[ -(nsim + 1)], 2, mean), apply(t(SimStats[[gf]][, -(nsim + 1)]) / ne[ -(nsim + 1)], 2, quantile, probs = .975)) simstats <- t(SimStats[[gf]][, -(nsim + 1)]) / ne[ -(nsim + 1)] } if(gf == 'dsp'){ sumstats <- cbind(x[[gf]][,1], apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .025), apply(SimStats[[gf]][, -(nsim + 1)], 1, mean), apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .975)) / nd simstats <- t(SimStats[[gf]][, -(nsim + 1)]) / nd } if(gf == 'triadcensus'){ nt <- sum(x[['triadcensus']][,1]) sumstats <- cbind(x[[gf]][,1], apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .025), apply(SimStats[[gf]][, -(nsim + 1)], 1, mean), apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = .975)) / nt simstats <- t(SimStats[[gf]][, -(nsim + 1)]) / nt } boxplot(simstats, xlab = GOFxlab[gf] , ylab = GOFylab[gf], ylim = range(simstats, sumstats[,1]), outline = FALSE) matlines(sumstats[, c(2, 4)], col = 'gray', lty = 1) matpoints(sumstats[, c(2,4)], col = 1, pch = 1) lines(sumstats[,1], col = 'red', lwd = 2) } else { obsstats <- x[[gf]][,1] / nd simstatsCI <- t(apply(SimStats[[gf]][, -(nsim + 1)], 1, quantile, probs = c(.025, .975))) / nd simstats <- t(SimStats[[gf]][, -(nsim + 1)]) / nd nssd <- length(obsstats) boxplot(simstats, xlab = GOFxlab[gf] , ylab =GOFylab[gf], ylim = range(simstats, obsstats), outline = FALSE) matlines(simstatsCI[-nssd, ], col = 'gray', lty = 1) matpoints(simstatsCI, col = 1, pch = 1) points(rep(nssd,2), simstatsCI[nssd, ] / nd, col = 'gray', pch = '_') lines(obsstats[-nssd], col = 'red', lwd = 2) points(nssd, obsstats[nssd], col = 'red', pch = 16, cex = 1) } } mtext("Goodness-of-fit diagnostics", side = 3, outer = TRUE, cex = 1.5, padj = 2) if(parm) par(mfrow = c(1,1)) }
ReistTrans <- function(data,reg,Rp=0,Ri=0){ dat.rem.ind.pop<-function(data,ind=0,pop=0){ data=as.data.frame(data); dat.rem.ind<-function(dat,ind){ nb.rem.ind=length(ind); nb.ind=dim(dat)[1]; for(i in 1:nb.rem.ind) dat=dat[row.names(dat)[1:(nb.ind-i+1)]!=ind[i],]; return(dat)}; dat.rem.pop<-function(dat,pop){ nb.rem.pop=length(pop); for(i in 1:nb.rem.pop) dat=dat[dat[,1]!=pop[i],]; return(dat);} if (ind[1]!=0) data=dat.rem.ind(data,ind); if (pop[1]!=0) data=dat.rem.pop(data,pop); return(data);} Reitra.va<-function(dat,clm,re){ dat=dat[is.finite(dat[,re]),]; log.dat=dat; mea=mean(dat[is.finite(dat[,clm]),re]); log.dat[,clm]=log(dat[,clm],base=10); log.dat[,re]=log(dat[,re],base=10); mea.clm=mean(log.dat[is.finite(log.dat[,clm]),clm],na.rm=TRUE); mea.reg=mean(log.dat[is.finite(log.dat[,clm]),re],na.rm=TRUE); a=sum((log.dat[is.finite(log.dat[,clm]),re]-mea.reg)*log.dat[is.finite(log.dat[,clm]),clm])/sum((log.dat[is.finite(log.dat[,clm]),re]-mea.reg)*(log.dat[is.finite(log.dat[,clm]),re]-mea.reg)); dat[,clm]=log.dat[,clm]-a*(log.dat[,re]-log(mea,base=10)); return(dat);} nb.var=dim(data)[2]-1; for (i in 1:nb.var) {if (names(data)[i+1]==reg) reg=i}; if (is.numeric(reg)==FALSE) return("reg value does not exist!"); data=dat.rem.ind.pop(data,ind=Ri,pop=Rp); if (reg==1) for (i in 2:nb.var) data=Reitra.va(data,clm=i+1,re=2) else {for (i in 2:reg) data=Reitra.va(data,clm=i,re=reg+1); if (reg<nb.var) for (j in (reg+1):nb.var) data=Reitra.va(data,clm=j+1,re=reg+1);}; return(data[-(reg+1)]);}
context("Preparation of master matrix") test_that("Correct creation of master_matrix", { variables <- raster::stack(system.file("extdata/variables.tif", package = "biosurvey")) names(variables) <- c("Mean_temperature", "Max_temperature", "Min_temperature", "Annual_precipitation", "Prec_wettest_month", "Prec_driest_month") m_matrix <- prepare_master_matrix(region = mx, variables = variables) m_matrix1 <- prepare_master_matrix(region = mx, variables = variables, do_pca = T, scale = T, variables_in_matrix = c("Mean_temperature", "Annual_precipitation")) cnam <- names(m_matrix) inams <- colnames(m_matrix$data_matrix) inams1 <- colnames(m_matrix1$data_matrix) anames <- c("data_matrix", "preselected_sites", "region", "mask", "raster_base", "PCA_results" ) enams <- c("Longitude", "Latitude", "Mean_temperature", "Max_temperature", "Min_temperature", "Annual_precipitation", "Prec_wettest_month", "Prec_driest_month") enams1 <- c("Longitude", "Latitude", "Mean_temperature", "Annual_precipitation", "PC1", "PC2") testthat::expect_s3_class(m_matrix, "master_matrix") testthat::expect_null(m_matrix$mask) testthat::expect_null(m_matrix$PCA_results) testthat::expect_s3_class(m_matrix1$PCA_results, "prcomp") testthat::expect_s4_class(m_matrix$region, "SpatialPolygonsDataFrame") testthat::expect_s4_class(m_matrix$raster_base, "RasterLayer") testthat::expect_length(m_matrix, 6) testthat::expect_equal(cnam, anames) testthat::expect_equal(inams, enams) testthat::expect_equal(inams1, enams1) }) test_that("Errors and messages master_matrix", { variables <- raster::stack(system.file("extdata/variables.tif", package = "biosurvey")) testthat::expect_message(prepare_master_matrix(region = mx, variables = variables)) testthat::expect_error(prepare_master_matrix(region = mx, variables = variables[[1]])) testthat::expect_error(prepare_master_matrix(region = mx)) testthat::expect_error(prepare_master_matrix(variables = variables)) testthat::expect_error(prepare_master_matrix(region = mx, variables = mx)) testthat::expect_error(prepare_master_matrix(region = variables, variables = variables)) })