code
stringlengths
1
13.8M
quadFuncModel <- function( yName, xNames, data, shifterNames, linear, homWeights, regScale ) { checkNames( c( yName, xNames, shifterNames ), names( data ) ) .quadFuncCheckHomWeights( homWeights, xNames ) result <- list() result$isPanel <- inherits( data, c( "pdata.frame", "plm.dim" ) ) if( result$isPanel ) { estData <- data[ , 1:2 ] estData$y <- data[[ yName ]] } else { estData <- data.frame( y = data[[ yName ]] ) } if( !is.null( homWeights ) ) { estData$deflator <- 0 for( i in seq( along = homWeights ) ) { estData$deflator <- estData$deflator + homWeights[ i ] * data[[ names( homWeights )[ i ] ]] } xOmit <- names( homWeights )[ 1 ] iOmit <- which( xNames == xOmit ) } else { iOmit <- 0 xOmit <- NULL } estFormula <- "y ~ 1" for( i in seq( along = xNames ) ) { if( i != iOmit ) { xName <- paste( "a", as.character( i ), sep = "_" ) estData[[ xName ]] <- .quadFuncVarHom( data, xNames[ i ], homWeights, estData$deflator, xOmit ) / regScale estFormula <- paste( estFormula, "+", xName ) } } if( !linear ) { for( i in seq( along = xNames ) ) { for( j in i:length( xNames ) ) { if( i != iOmit & j != iOmit ) { xName <- paste( "b", as.character( i ), as.character( j ), sep = "_" ) estData[[ xName ]] <- 0.5 * ifelse( i == j, 1, 2 ) * .quadFuncVarHom( data, xNames[ i ], homWeights, estData$deflator, xOmit ) * .quadFuncVarHom( data, xNames[ j ], homWeights, estData$deflator, xOmit ) / regScale estFormula <- paste( estFormula, "+", xName ) } } } } for( i in seq( along = shifterNames ) ) { if( is.factor( data[[ shifterNames[ i ] ]] ) | is.logical( data[[ shifterNames[ i ] ]] ) ) { xName <- paste( "d", "_", as.character( i ), "_", sep = "" ) estData[[ xName ]] <- data[[ shifterNames[ i ] ]] } else { xName <- paste( "d", as.character( i ), sep = "_" ) estData[[ xName ]] <- data[[ shifterNames[ i ] ]] / regScale } estFormula <- paste( estFormula, "+", xName ) } result$estData <- estData result$estFormula <- estFormula result$iOmit <- iOmit return( result ) }
processPhotoId <- function(file_path = "", idType = "auto", imageSource = "auto", correctOrientation = "true", correctSkew = "true", description = "", pdfPassword = "", ...) { if ( !file.exists(file_path)) { stop("File Doesn't Exist. Please check the path.") } querylist <- list(idType = idType, imageSource = imageSource, correctOrientation = correctOrientation, correctSkew = correctSkew, description = description, pdfPassword = pdfPassword) body <- upload_file(file_path) process_details <- abbyy_POST("processPhotoId", query = NULL, body = body, ...) resdf <- ldply(process_details, rbind, .id = NULL) row.names(resdf) <- NULL resdf[] <- lapply(resdf, as.character) cat("Status of the task: ", resdf$status, "\n") cat("Task ID: ", resdf$id, "\n") resdf }
ppexp <- function(q, x, cuts) { if (!is.matrix(x)) { ppout <- ppexpV(q, x, cuts) } else if (is.matrix(x)) { ppout <- ppexpM(q, x, cuts) } else { stop("Error: input x is in the wrong format.") } return(ppout) } .onUnload <- function(libpath) { library.dynam.unload("bayesDP", libpath) }
cmaRs.derivative_more_than_one <- function (BF, DMS, i, j) { i.chr <- as.character(i) j.chr <- as.character(j) second_part <- paste("xfirst", as.character(i.chr), sep = "") third_part <- paste("xfirst", as.character(j.chr), sep = "") first_part <- parse(text = paste(BF, sep = "")) derv1 <- D(first_part, second_part) derv2 <- D(derv1, third_part) derv1.dms <- as.expression(derv2) DMS[i,j] <- as.character(derv1.dms) return(list(DMS = DMS, BF = BF)) }
gates_inf <- function(dx, dy, marks, par=list(a=1, b=4, smark=1)) { with(as.list(par), pmax(0, marks[[smark]]^a - (b * sqrt(dx^2 + dy^2))^a)^(1/a) ) }
library(shiny) library(detect) library(bSims) MAXDIS <- 10 EXTENT <- 10 DURATION <- 10 TINT <- list( "0-3-5-10 min"=c(3, 5, 10), "0-10 min"=c(10), "0-1-2-3 min"=c(1, 2, 3), "0-5-10 min"=c(5, 10), "0-3 min"=c(3), "0-1-2-3-4-5 min"=c(1, 2, 3, 4, 5) ) RINT <- list( "0-50-100-Inf m"=c(0.5, 1, Inf), "0-Inf m"=c(Inf), "0-50-Inf m"=c(0.5, Inf), "0-50-100-150-Inf m"=c(0.5, 1, 1.5, Inf), "0-50-100-150-200-Inf m"=c(0.5, 1, 1.5, 2, Inf), "0-50-100 m"=c(0.5, 1), "0-50 m"=c(0.5), "0-50-100-150 m"=c(0.5, 1, 1.5), "0-50-100-150-200 m"=c(0.5, 1, 1.5, 2) ) rv <- reactiveValues(seed=0) estimate_bsims <- function(REM) { MaxDur <- max(tint) MaxDis <- max(rint) Ydur <- matrix(colSums(REM), 1) Ddur <- matrix(tint, 1) Ydis <- matrix(rowSums(REM), 1) Ddis <- matrix(rint, 1) if (length(tint) > 1 && sum(REM) > 0) { Mrem <- cmulti.fit(Ydur, Ddur, type="rem") phi <- exp(Mrem$coef) p <- 1-exp(-MaxDur*phi) } else { Mrem <- NULL phi <- NA p <- NA } if (length(rint) > 1 && sum(REM) > 0) { Mdis <- cmulti.fit(Ydis, Ddis, type="dis") tau <- exp(Mdis$coef) q <- if (is.infinite(MaxDis)) 1 else (tau^2/MaxDis^2) * (1-exp(-(MaxDis/tau)^2)) A <- if (is.infinite(MaxDis)) pi * tau^2 else pi * MaxDis^2 } else { Mdis <- NULL tau <- NA q <- NA A <- NA } D <- sum(REM) / (A * p * q) list( Ydur=Ydur, Ddur=Ddur, Ydis=Ydis, Ddis=Ddis, Mrem=Mrem, Mdis=Mdis, phi=phi, tau=tau, A=A, p=p, q=q, D=D) } summarize_bsims <- function(res) { data.frame( D=sapply(res, "[[", "D"), phi=sapply(res, "[[", "phi"), tau=sapply(res, "[[", "tau")) } ui <- navbarPage("bSims (HER)", tabPanel("Initialize", column(6, plotOutput(outputId = "plot_ini")), column(6, actionButton("seed", "Change random seed"), sliderInput("road", "Road half width", 0, EXTENT/2, 0, EXTENT/40), sliderInput("edge", "Edge width", 0, EXTENT/2, 0, EXTENT/40), sliderInput("offset", "Offset for road position", -EXTENT/2, EXTENT/2, 0, EXTENT/20) ) ), tabPanel("Populate", column(6, plotOutput(outputId = "plot_pop") ), column(6, sliderInput("DH", "Density in habitat stratum", 0, 20, 1, 0.1), sliderInput("DE", "Density in edge stratum", 0, 20, 1, 0.1), sliderInput("DR", "Density in road stratum", 0, 20, 1, 0.1), radioButtons("spfun", "Spatial pattern", c("Random"="random", "Regular"="regular", "Clustered"="clustered")) ) ), tabPanel("Animate", column(6, plotOutput(outputId = "plot_ani")), column(6, sliderInput("phiH", "Vocal in habitat stratum", 0, 10, 0.5, 0.1), sliderInput("phiE", "Vocal in edge stratum", 0, 10, 0.5, 0.1), sliderInput("phiR", "Vocal in road stratum", 0, 10, 0.5, 0.1), sliderInput("phim", "Movement rate", 0, 10, 1, 0.1), sliderInput("SDm", "Movement SD", 0, 1, 0, 0.05), radioButtons("avoid", "Avoid", c("None"="none", "Road"="R", "Edge and road"="ER")), checkboxInput("overlap", "Territory overlap allowed", TRUE), checkboxInput("show_tess", "Show tessellation", FALSE), checkboxInput("init_loc", "Initial location", FALSE) ) ), tabPanel("Detect", column(6, plotOutput(outputId = "plot_det") ), column(6, sliderInput("tauH", "EDR in habitat stratum", 0, MAXDIS, 1, MAXDIS/200), sliderInput("tauE", "EDR in edge stratum", 0, MAXDIS, 1, MAXDIS/200), sliderInput("tauR", "EDR in road stratum", 0, MAXDIS, 1, MAXDIS/200), radioButtons("event", "Event type", c("Vocalization"="vocal", "Movement"="move", "Both"="both")) ) ), tabPanel("Transcribe", fluidRow( column(6, plotOutput(outputId = "plot_tra") ), column(6, selectInput("tint", "Time intervals", names(TINT)), selectInput("rint", "Distance intervals", names(RINT)), sliderInput("derr", "Distance error", 0, 1, 0, 0.1), radioButtons("condition", "Condition", c("1st event"="event1", "1st detection"="det1", "All detections"="alldet")), sliderInput("percept", "Percepted ratio", 0, 2, 1, 0.05), checkboxInput("oucount", "Over/under count", FALSE) ) ), fluidRow( column(6, tableOutput(outputId = "table_rem") ), column(6, plotOutput(outputId = "plot_est") ) ) ), tabPanel("Settings", tagList( singleton( tags$head( tags$script(src = 'clipboard.min.js') ) ) ), column(12, verbatimTextOutput("settings"), uiOutput("clip") ) ), tabPanel("Documentation", column(12, tags$iframe(src="https://psolymos.github.io/bSims/", height=600, width="100%", frameBorder=0) ) ) ) server <- function(input, output) { observeEvent(input$seed, { rv$seed <- rv$seed + 1 }) dis <- seq(0, MAXDIS, MAXDIS/200) l <- reactive({ set.seed(rv$seed) bsims_init(extent = EXTENT, road = input$road, edge = input$edge, offset = input$offset) }) xy_fun <- reactive({ switch(input$spfun, "random"=function(d) rep(1, length(d)), "regular"=function(d) (1-exp(-d^2/1^2) + dlnorm(d, 2)/dlnorm(2,2)) / 2, "clustered"=function(d) exp(-d^2/1^2) + 0.5*(1-exp(-d^2/4^2)) ) }) a <- reactive({ margin <- switch(input$spfun, "random"=0, "regular"=2, "clustered"=5) bsims_populate(l(), density = c(input$DH, input$DE, input$DR), xy_fun = xy_fun(), margin = margin) }) b <- reactive({ if (input$avoid == "R" && input$DR > 0) { showNotification("Only 0 abundance stratum can be avoided, set road density to 0", type="error") return(NULL) } if (input$avoid == "ER" && (input$DE > 0 || input$DR > 0)) { showNotification("Only 0 abundance stratum can be avoided, set road and edge densities to 0", type="error") return(NULL) } bsims_animate(a(), duration = DURATION, vocal_rate = c(input$phiH, input$phiE, input$phiR), move_rate = input$phim, movement = input$SDm, mixture = 1, avoid = input$avoid, allow_overlap = input$overlap, initial_location = input$init_loc) }) o <- reactive({ bsims_detect(b(), xy = c(0, 0), tau = c(input$tauH, input$tauE, input$tauR), dist_fun = NULL, event_type = input$event) }) m <- reactive({ pr <- if (!input$oucount) NULL else input$percept bsims_transcribe(o(), tint = TINT[[input$tint]], rint = RINT[[input$rint]], error = input$derr, condition = input$condition, event_type = input$event, perception = pr ) }) e <- reactive({ REM <- get_table(m()) MaxDur <- max(TINT[[input$tint]]) MaxDis <- max(RINT[[input$rint]]) Ydur <- matrix(colSums(REM), 1) Ddur <- matrix(TINT[[input$tint]], 1) Ydis <- matrix(rowSums(REM), 1) Ddis <- matrix(RINT[[input$rint]], 1) if (length(TINT[[input$tint]]) > 1 && sum(REM) > 0) { Mrem <- try(cmulti.fit(Ydur, Ddur, type="rem")) if (!inherits(Mrem, "try-error")) { phi <- exp(Mrem$coef) p <- 1-exp(-MaxDur*phi) } else { Mrem <- NULL phi <- NA p <- NA } } else { Mrem <- NULL phi <- NA p <- NA } if (length(RINT[[input$rint]]) > 1 && sum(REM) > 0) { Mdis <- try(cmulti.fit(Ydis, Ddis, type="dis")) if (!inherits(Mdis, "try-error")) { tau <- exp(Mdis$coef) q <- if (is.infinite(MaxDis)) 1 else (tau^2/MaxDis^2) * (1-exp(-(MaxDis/tau)^2)) A <- if (is.infinite(MaxDis)) pi * tau^2 else pi * MaxDis^2 } else { Mdis <- NULL tau <- NA q <- NA A <- NA } } else { Mdis <- NULL tau <- NA q <- NA A <- NA } D <- sum(REM) / (A * p * q) list( Ydur=Ydur, Ddur=Ddur, Ydis=Ydis, Ddis=Ddis, Mrem=Mrem, Mdis=Mdis, phi=phi, tau=tau, A=A, p=p, q=q, D=D) }) getset <- reactive({ xc <- function(x) paste0("c(", paste0(x, collapse=", "), ")") xq <- function(x) paste0("'", x, "'", collapse="") margin <- switch(input$spfun, "random"=0, "regular"=2, "clustered"=5) pr <- if (!input$oucount) "NULL" else input$percept paste0("bsims_all(", "\n extent = ", EXTENT, ",\n road = ", input$road, ",\n edge = ", input$edge, ",\n offset = ", input$offset, ",\n density = ", xc(c(input$DH, input$DE, input$DR)), ",\n xy_fun = ", paste0(deparse(xy_fun()), collapse=''), ",\n margin = ", margin, ",\n duration = ", DURATION, ",\n vocal_rate = ", xc(c(input$phiH, input$phiE, input$phiR)), ",\n move_rate = ", input$phim, ",\n movement = ", input$SDm, ",\n mixture = 1", ",\n allow_overlap = ", input$overlap, ",\n initial_location = ", input$init_loc, ",\n tau = ", xc(c(input$tauH, input$tauE, input$tauR)), ",\n xy = c(0, 0)", ",\n event_type = ", xq(input$event), ",\n tint = ", xc(TINT[[input$tint]]), ",\n rint = ", xc(RINT[[input$rint]]), ",\n error = ", input$derr, ",\n condition = ", xq(input$condition), ",\n perception = ", pr, ")", collapse="") }) output$plot_ini <- renderPlot({ op <- par(mar=c(0,0,0,0)) plot(l()) par(op) }) output$plot_pop <- renderPlot({ req(a()) op <- par(mar=c(0,0,0,0)) plot(a()) par(op) }) output$plot_ani <- renderPlot({ req(b()) op <- par(mar=c(0,0,0,0)) plot(b(), event_type=input$event) if (input$show_tess && !is.null(b()$tess)) plot(b()$tess, add=TRUE, wlines="tess", showpoints=FALSE, cmpnt_col="grey", cmpnt_lty=1) par(op) }) output$plot_det <- renderPlot({ req(o()) op <- par(mar=c(0,0,0,0)) plot(o(), event_type=input$event, condition=input$condition) par(op) }) output$plot_tra <- renderPlot({ req(m()) op <- par(mar=c(0,0,0,0)) plot(m()) par(op) }) output$table_rem <- renderTable({ req(m()) tab <- get_table(m()) tab <- cbind(tab, Total=rowSums(tab)) tab <- rbind(tab, Total=colSums(tab)) tab }, rownames = TRUE, colnames = TRUE, digits = 0) output$plot_est <- renderPlot({ req(e()) v <- e() col <- c(" op <- par(mfrow=c(1,3)) barplot(c(True=input$phiH, Estimate=v$phi), col=col, main=expression(phi)) barplot(c(True=input$tauH, Estimate=v$tau), col=col, main=expression(tau)) barplot(c(True=input$DH, Estimate=v$D), col=col, main=expression(D)) par(op) }) output$settings <- renderText({ getset() }) output$clip <- renderUI({ tagList( actionButton("clipbtn", label = "Copy settings to clipboard", icon = icon("clipboard"), `data-clipboard-text` = paste( getset(), collapse="") ), tags$script( 'new ClipboardJS(".btn", document.getElementById("clipbtn") );') ) }) } shinyApp(ui = ui, server = server)
RnpdMAP <- function (Rpop, Lp = NULL, NNegEigs = 1, NSmoothPosEigs = 4, NSubjects = NULL, NSamples = 0, MaxIts = 15000, PRINT=FALSE, Seed = NULL) { if(NSmoothPosEigs == 0) NSmoothPosEigs <- NULL prbs2 <- NULL if(is.null(Seed)){ Seed<- as.integer((as.double(Sys.time())*1000+Sys.getpid()) %% 2^31) } set.seed(Seed) prbs1Fnc <- function(){ prbs <- 1 if(NNegEigs > 1){ prbs <- 1- c(log(sort(runif(NNegEigs-1,1,100), decreasing = TRUE))/log(100),0) } prbs } if( NSamples > 0 ){ WishartArray <- rWishart(n = NSamples, df = NSubjects-1, Sigma = Rpop) WishartList <-lapply( seq(dim(WishartArray)[3]), function(x) WishartArray[ , , x] ) corList<-lapply(WishartList,cov2cor) } else if (NSamples == 0) corList <- list(Rpop) Lpop <- eigen(Rpop, only.values = TRUE)$values proj.S.Lp <- function(A, Lp, Nvar, prbs1, prbs2){ VLV <- eigen(A) V <- VLV$vectors L <- VLV$values L[L < Lp] <- Lp if(NNegEigs == 1){ L[Nvar] <- Lp } else{ L[ (Nvar - (NNegEigs - 1)):Nvar] <- prbs1 * Lp if(!is.null(NSmoothPosEigs)){ L[(Nvar - (NNegEigs + NSmoothPosEigs )):(Nvar - (NNegEigs + 1 ))] <- prbs2 * Lpop[(Nvar - (NNegEigs + NSmoothPosEigs )):(Nvar - (NNegEigs + 1 ))] } } A <- V %*% diag(L)%*% t(V) (A + t(A))/2 } proj.U <- function(A){ diag(A) <- 1 rc.ind <- which(abs(A) > 1, arr.ind = TRUE) A[rc.ind] <- sign(A[rc.ind]) A } RAPA <- function(R, Lp, MaxIts = 1000){ Nvar <- ncol(R) EigTest <- FALSE tries <- 0 converged <- TRUE EigHx <- rep(0, MaxIts) Rk <- R prbs1 <- prbs1Fnc() if(!is.null(NSmoothPosEigs)){ prbs2 <- log(sort(runif(NSmoothPosEigs,1,100), decreasing = TRUE))/log(100) } while (!EigTest) { tries <- tries + 1 if (tries > MaxIts) { converged = FALSE break } Sk <- proj.S.Lp(Rk, Lp, Nvar, prbs1, prbs2) Uk <- proj.U(Sk) Rk <- Uk minEig <- eigen(Rk, symmetric = TRUE, only.values = TRUE)$val[Nvar] EigHx[tries] <- minEig if(PRINT){ cat("\nAt iter ", tries, " min eig = ", eigen(Rk)$val[Nvar]) } if(1e+10*(minEig - Lp)^2 < 1e-12) EigTest <- TRUE } EigHx <- EigHx[1:tries] colnames(Rk) <- rownames(Rk) <- colnames(R) feasible <- TRUE if(max(abs(Rk)) > 1) feasible <- FALSE list(Rpop = Rpop, R=R, Rnpd = Rk, Lp = Lp, ObsLp = minEig, EigHx = EigHx, converged = converged, feasible = feasible, Seed = Seed, prbs1 = prbs1, prbs2 = prbs2) } lapply(corList, RAPA, Lp, MaxIts) }
args <- commandArgs(trailingOnly = TRUE) packageDir <- args[2] registryDir <- file.path(getwd(), "inst", "extdata", "cwb", "registry") for (corpus in list.files(registryDir)){ registryFile <- file.path(registryDir, corpus) registry <- readLines(registryFile) homeDir <- file.path(packageDir, "extdata", "cwb", "indexed_corpora", corpus) infoFileLine <- grep("^INFO", registry) infoFileBasename <- basename(gsub('^INFO\\s+(.*?)"*\\s*$', "\\1", registry[infoFileLine])) infoFileNew <- file.path(homeDir, infoFileBasename) if (.Platform$OS.type == "windows"){ registry[grep("^HOME", registry)] <- sprintf('HOME "%s"', homeDir) registry[infoFileLine] <- sprintf('INFO "%s"', infoFileNew) } else { if (grepl(" ", homeDir)){ registry[grep("^HOME", registry)] <- sprintf('HOME "%s"', homeDir) registry[infoFileLine] <- sprintf('INFO "%s"', infoFileNew) } else { registry[grep("^HOME", registry)] <- sprintf("HOME %s", homeDir) registry[infoFileLine] <- sprintf("INFO %s", infoFileNew) } } writeLines(text = registry, con = registryFile, sep = "\n") }
estimateSiteHRs<-function(tableList,initialHR=1,endpoint=Inf,confidence=0.95){ nDP=length(tableList) for (k in 1:nDP){ if(dim(tableList[[k]]$ipwTable)[2]==9){ timeK=tableList[[k]]$ipwTable$eventTime timeInd=which(timeK<=endpoint) tableList[[k]]$ipwTable=tableList[[k]]$ipwTable[timeInd,] tableList[[k]]$stabTable= tableList[[k]]$stabTable[timeInd,] }else if(dim(tableList[[k]]$ipwTable)[2]==8&endpoint!=Inf){ stop('endpoint should be left as default when some riskset tables do not share event times') } else{ } risksetFullShare=tableList[[k]]$ipwTable risksetFullsShare=tableList[[k]]$stabTable orderDP=order(risksetFullShare$sumSquareE,risksetFullShare$sumSquareUnE,decreasing=TRUE) tableList[[k]]$ipwTable=risksetFullShare[orderDP,] orderDP=order(risksetFullsShare$sumSquareE,risksetFullsShare$sumSquareUnE,decreasing=TRUE) tableList[[k]]$stabTable=risksetFullsShare[orderDP,] } HRest=rep(0, nDP) HRests=rep(0, nDP) robuStdErr=rep(0, nDP) robuStdErrS=rep(0, nDP) output=NULL siteTag=NULL for (k in 1:nDP){ coxScore<-function(HR){ risksetFull=tableList[[k]]$ipwTable y=sum(risksetFull$sumEC-risksetFull$sumC*(risksetFull$sumE*HR)/ (risksetFull$sumE*HR+risksetFull$sumUnE)) y } HRest[k]=nleqslv(initialHR, coxScore)$x coxScores<-function(HR){ risksetFull=tableList[[k]]$stabTable y=sum(risksetFull$sumEC-risksetFull$sumC*(risksetFull$sumE*HR)/ (risksetFull$sumE*HR+risksetFull$sumUnE)) y } HRests[k]=nleqslv(initialHR, coxScores)$x risksetFull=tableList[[k]]$ipwTable S0DP=risksetFull$sumE*HRest[k]+risksetFull$sumUnE S1DP=risksetFull$sumE*HRest[k] AA=sum(risksetFull$sumC*(S1DP/S0DP-(S1DP/S0DP)^2)) q1DP=sum((1-S1DP/S0DP)^2*risksetFull$sumSquareEC+(S1DP/S0DP)^2*risksetFull$sumSquareUnEC) sumSquEdiffDP=risksetFull$sumSquareE-c(risksetFull$sumSquareE[-1],0) sumSquUnEdiffDP=risksetFull$sumSquareUnE-c(risksetFull$sumSquareUnE[-1],0) cumsum1EDP=cumsum(risksetFull$sumC/S0DP) cumsum2EDP=cumsum(risksetFull$sumC*S1DP/(S0DP^2)) q2DP=(exp(2*log(HRest[k])))*sum(sumSquEdiffDP*cumsum1EDP^2) q3DP=(exp(2*log(HRest[k])))*sum(sumSquEdiffDP*cumsum2EDP^2)+sum(sumSquUnEdiffDP*cumsum2EDP^2) q4DP=HRest[k]*sum(risksetFull$sumSquareEC*(1-S1DP/S0DP)*cumsum1EDP) q5DP=HRest[k]*sum(risksetFull$sumSquareEC*(1-S1DP/S0DP)*cumsum2EDP)+sum(risksetFull$sumSquareUnEC*(0-S1DP/S0DP)*cumsum2EDP) q6DP=(exp(2*log(HRest[k])))*sum(sumSquEdiffDP*cumsum1EDP*cumsum2EDP) q=q1DP+q2DP+q3DP-2*q4DP+2*q5DP-2*q6DP robuVar=q/(AA^2) robuStdErr[k]=robuVar^0.5 risksetFulls=tableList[[k]]$stabTable S0DP=risksetFulls$sumE*HRests[k]+risksetFulls$sumUnE S1DP=risksetFulls$sumE*HRests[k] AA=sum(risksetFulls$sumC*(S1DP/S0DP-(S1DP/S0DP)^2)) q1DP=sum((1-S1DP/S0DP)^2*risksetFulls$sumSquareEC+(S1DP/S0DP)^2*risksetFulls$sumSquareUnEC) sumSquEdiffDP=risksetFulls$sumSquareE-c(risksetFulls$sumSquareE[-1],0) sumSquUnEdiffDP=risksetFulls$sumSquareUnE-c(risksetFulls$sumSquareUnE[-1],0) cumsum1EDP=cumsum(risksetFulls$sumC/S0DP) cumsum2EDP=cumsum(risksetFulls$sumC*S1DP/(S0DP^2)) q2DP=(exp(2*log(HRests[k])))*sum(sumSquEdiffDP*cumsum1EDP^2) q3DP=(exp(2*log(HRests[k])))*sum(sumSquEdiffDP*cumsum2EDP^2)+sum(sumSquUnEdiffDP*cumsum2EDP^2) q4DP=HRests[k]*sum(risksetFulls$sumSquareEC*(1-S1DP/S0DP)*cumsum1EDP) q5DP=HRests[k]*sum(risksetFulls$sumSquareEC*(1-S1DP/S0DP)*cumsum2EDP)+sum(risksetFulls$sumSquareUnEC*(0-S1DP/S0DP)*cumsum2EDP) q6DP=(exp(2*log(HRests[k])))*sum(sumSquEdiffDP*cumsum1EDP*cumsum2EDP) q=q1DP+q2DP+q3DP-2*q4DP+2*q5DP-2*q6DP robuVar=q/(AA^2) robuStdErrS[k]=robuVar^0.5 lowProp=log(HRest[k])-qnorm(1-(1-confidence)/2)*robuStdErr[k] upProp=log(HRest[k])+qnorm(1-(1-confidence)/2)*robuStdErr[k] lowPropS=log(HRests[k])-qnorm(1-(1-confidence)/2)*robuStdErrS[k] upPropS=log(HRests[k])+qnorm(1-(1-confidence)/2)*robuStdErrS[k] est=c(log(HRest[k]),log(HRests[k])) hrest=exp(est) se=c(robuStdErr[k],robuStdErrS[k]) low=exp(c(lowProp,lowPropS)) up=exp(c(upProp,upPropS)) outputAdd=cbind(est,se,hrest,low,up) rownames(outputAdd)=c(paste("Site ",k,"-IPW",sep = ""),paste("Site ",k,"-stabilized",sep = "")) output=rbind(output,outputAdd) colnames(output)=c("log HR Estimate","Standard Error","HR Estimate", paste("HR ", confidence*100,"% CI", "-low", sep =""), paste("HR ", confidence*100,"% CI", "-up", sep ="")) } output }
effectivemass.cf <- function(cf, Thalf, type="solve", nrObs=1, replace.inf=TRUE, interval=c(0.000001,2.), weight.factor = NULL, deltat=1, tmax=Thalf-1) { if(missing(cf)) { stop("cf must be provided to effectivemass.cf! Aborting...\n") } if(length(dim(cf)) == 2) { Cor <- apply(cf, 2, mean) } else { Cor <- cf } if(length(Cor) != nrObs*(tmax+1)) { stop("cf does not have the correct time extent in effectivemass.cf! Aborting...!\n") } tt <- c(1:(nrObs*(tmax+1))) cutii <- c() cutii2 <- c() for(i in 1:nrObs) { cutii <- c(cutii, (i-1)*(tmax+1)+1, i*(tmax+1)) cutii2 <- c(cutii2, i*(tmax+1)) } t2 <- tt[-cutii2] effMass <- rep(NA, nrObs*(tmax+1)) if(type == "acosh" || type == "temporal" || type == "shifted" || type == "weighted") { t <- tt[-cutii] if(type == "acosh") effMass[t] <- acosh((Cor[t+1] + Cor[t-1])/2./Cor[t]) else { if(type == "shifted" || type == "weighted") { Ratio <- Cor[t+1]/Cor[t] } else Ratio <- (Cor[t]-Cor[t+1]) / (Cor[t-1]-Cor[t]) w <- 1 if(type == "weighted") { stopifnot(!is.null(weight.factor)) w <- weight.factor } fn <- function(m, t, Time, Ratio, w) { return(Ratio - ( ( exp(-m*(t+1))+exp(-m*(Time-t-1)) - w*( exp(-m*(t+1-deltat))+exp(-m*(Time-(t+1-deltat))) ) ) / ( exp(-m*t)+exp(-m*(Time-t)) - w*( exp(-m*(t-deltat))+exp(-m*(Time-(t-deltat))) ) ) ) ) } for(i in t) { if(is.na(Ratio[i])) effMass[i] <- NA else if(fn(interval[1], t=(i %% (tmax+1)), Time=2*Thalf, Ratio = Ratio[i], w=w)*fn(interval[2], t=(i %% (tmax+1)), Time=2*Thalf, Ratio = Ratio[i], w=w) > 0) effMass[i] <- NA else effMass[i] <- uniroot(fn, interval=interval, t=(i %% (tmax+1)), Time=2*Thalf, Ratio = Ratio[i], w=w)$root } } } else { t <- tt[c(1:(length(tt)-1))] Ratio <- Cor[t]/Cor[t+1] if(type == "log") { effMass[t2] <- log(Ratio[t2]) } else { for(t in t2) { effMass[t] <- invcosh(Ratio[t], timeextent=2*Thalf, t=(t %% (tmax+1))) } } } if(replace.inf) effMass[is.infinite(effMass)] <- NA return(invisible(effMass[t2])) } bootstrap.effectivemass <- function(cf, type="solve") { stopifnot(inherits(cf, 'cf_meta')) stopifnot(inherits(cf, 'cf_boot')) deltat <- 1 if(type == "shifted" && any(names(cf) == "deltat")) { deltat <- cf$deltat } Nt <- length(cf$cf0) tmax <- cf$Time/2 if(!cf$symmetrised){ tmax <- cf$Time-1 } nrObs <- floor(Nt/(tmax+1)) effMass <- effectivemass.cf(cf$cf0, Thalf=cf$Time/2, tmax=tmax, type=type, nrObs=nrObs, deltat=deltat, weight.factor = cf$weight.factor) effMass.tsboot <- t(apply(cf$cf.tsboot$t, 1, effectivemass.cf, Thalf=cf$Time/2, tmax=tmax, type=type, nrObs=nrObs, deltat=deltat, weight.factor = cf$weight.factor)) deffMass=apply(effMass.tsboot, 2, cf$error_fn, na.rm=TRUE) ret <- list(t.idx=c(1:(tmax)), effMass=effMass, deffMass=deffMass, effMass.tsboot=effMass.tsboot, opt.res=NULL, t1=NULL, t2=NULL, type=type, useCov=NULL, CovMatrix=NULL, invCovMatrix=NULL, boot.R = cf$boot.R, boot.l = cf$boot.l, seed = cf$seed, massfit.tsboot=NULL, Time=cf$Time, nrObs=nrObs, dof=NULL, chisqr=NULL, Qval=NULL ) ret$cf <- cf ret$t0 <- effMass ret$t <- effMass.tsboot ret$se <- apply(ret$t, MARGIN=2L, FUN=cf$error_fn, na.rm=TRUE) attr(ret, "class") <- c("effectivemass", class(ret)) return(ret) } fit.constant <- function(M, y) { res <- list() if(is.matrix(M)){ m.eff <- sum(M %*% y)/sum(M) res$value <- (y-m.eff) %*% M %*% (y-m.eff) }else{ m.eff <- sum(M*y)/sum(M) res$value <- sum(M*(y-m.eff)^2) } res$par <- c(m.eff) return(res) } fit.effectivemass <- function(cf, t1, t2, useCov=FALSE, replace.na=TRUE, boot.fit=TRUE, autoproceed=FALSE, every) { stopifnot(inherits(cf, 'effectivemass')) tmax <- cf$Time/2 if(!cf$cf$symmetrised) { tmax <- cf$Time-1 } stopifnot(t1 < t2) stopifnot(0 <= t1) stopifnot(t2 <= tmax) cf$effmassfit <- list() cf$t1 <- t1 cf$effmassfit$t1 <- t1 cf$t2 <- t2 cf$effmassfit$t2 <- t2 cf$useCov <- useCov cf$effmassfit$useCov <- useCov cf$replace.na <- replace.na cf$effmassfit$replace.na <- replace.na ii <- c() if(missing(every)){ for(i in 1:cf$nrObs) { ii <- c(ii, ((i-1)*tmax+t1+1):((i-1)*tmax+t2+1)) } }else{ for(i in 1:cf$nrObs) { ii <- c(ii, seq((i-1)*tmax+t1+1, (i-1)*tmax+t2+1, by=every)) } } if(any(is.na(cf$effMass[ii]))) { ii.na <- which(is.na(cf$t0[ii])) ii <- ii[-ii.na] } CovMatrix <- cf$cf$cov_fn(cf$t[,ii]) M <- diag(1/cf$se[ii]^2) cf$CovMatrix <- CovMatrix cf$effmassfit$CovMatrix <- CovMatrix tb.save <- cf$t ii.remove <- c() if(replace.na && any(is.na(cf$t))) { for(k in ii) { cf$t[is.nan(cf$t[,k]),k] <- NA if(any(is.na(cf$t[,k]))) { jj <- which(is.na(cf$t[,k])) if( length(cf$t[-jj, k]) > length(jj) ) { rj <- sample.int(n=length(cf$t[-jj, k]), size=length(jj), replace=FALSE) cf$t[jj, k] <- cf$t[-jj, k][rj] } else { ii.remove <- c( ii.remove, which( ii == k ) ) } } } } if( length( ii.remove ) > 0 ) { ii <- ii[ -ii.remove ] message("Due to NAs we have removed the time slices ", ii.remove-1, " from the fit\n") } cf$ii <- ii cf$dof <- length(ii)-1 cf$effmassfit$ii <- ii cf$effmassfit$dof <- length(ii)-1 if(useCov) { M <- try(invertCovMatrix(cf$t[,ii], boot.samples=TRUE), silent=TRUE) if(inherits(M, "try-error")) { if( autoproceed ){ M <- M[ -ii.remove, -ii.remove] warning("[fit.effectivemass] inversion of variance covariance matrix failed, continuing with uncorrelated chi^2\n") useCov <- FALSE } else { stop("[fit.effectivemass] inversion of variance covariance matrix failed!\n") } } } else { if( length( ii.remove ) > 0 ) { M <- M[ -ii.remove, -ii.remove] M <- diag(M) } } opt.res <- fit.constant(M=M, y = cf$effMass[ii]) par <- opt.res$par cf$chisqr <- opt.res$value cf$Qval <- 1-pchisq(cf$chisqr, cf$dof) cf$effmassfit$chisqr <- opt.res$value cf$effmassfit$Qval <- 1-pchisq(cf$chisqr, cf$dof) if( boot.fit ) { massfit.tsboot <- array(0, dim=c(cf$boot.R, 2)) for(i in c(1:cf$boot.R)) { opt <- fit.constant(M=M, y = cf$t[i,ii]) massfit.tsboot[i, 1] <- opt$par[1] massfit.tsboot[i, 2] <- opt$value } cf$massfit.tsboot <- massfit.tsboot } else { cf$massfit.tsboot <- NA } cf$effmassfit$t <- cf$massfit.tsboot cf$effmassfit$t0 <- c(opt.res$par, opt.res$value) cf$effmassfit$se <- cf$cf$error_fn(massfit.tsboot[c(1:(dim(massfit.tsboot)[1]-1)),1]) cf$effmassfit$cf <- cf$cf cf$t <- tb.save if(!is.matrix(M)){ M <- diag(M) } cf$invCovMatrix <- M cf$opt.res <- opt.res cf$useCov <- useCov cf$effmassfit$useCov <- useCov attr(cf, "class") <- c("effectivemassfit", class(cf)) return(invisible(cf)) } summary.effectivemass <- function (object, ...) { effMass <- object cat("\n ** effective mass values **\n\n") cat("no. measurements\t=\t", effMass$N, "\n") cat("boot.R\t=\t", effMass$boot.R, "\n") cat("boot.l\t=\t", effMass$boot.l, "\n") cat("Time extent\t=\t", effMass$Time, "\n") cat("total NA count in bootstrap samples:\t", length(which(is.na(effMass$t))), "\n") cat("values with errors:\n\n") print(data.frame(t= effMass$t.idx-1, m = effMass$t0, dm = effMass$se)) } summary.effectivemassfit <- function(object, ..., verbose = FALSE) { effMass <- object cat("\n ** Result of effective mass analysis **\n\n") cat("no. measurements\t=\t", effMass$N, "\n") cat("type\t=\t", effMass$type, "\n") cat("boot.R\t=\t", effMass$boot.R, "\n") cat("boot.l\t=\t", effMass$boot.l, "\n") cat("Time extent\t=\t", effMass$Time, "\n") cat("NA count in fitted bootstrap samples:\t", length(which(is.na(effMass$t[,effMass$ii]))), "(",100*length(which(is.na(effMass$t[,effMass$ii])))/ length(effMass$t[,effMass$ii]), "%)\n") cat("NAs replaced in fit:", effMass$effmassfit$replace.na, "\n") cat("time range from", effMass$effmassfit$t1, " to ", effMass$effmassfit$t2, "\n") cat("No correlation functions", effMass$nrObs, "\n") if(verbose) { cat("values with errors:\n\n") print(data.frame(t= effMass$t, m = effMass$t0, dm = effMass$se)) } cat("correlated fit\t=\t", effMass$effmassfit$useCov, "\n") cat("m\t=\t", effMass$effmassfit$t0[1], "\n") cat("dm\t=\t", effMass$effmassfit$se[1], "\n") cat("chisqr\t=\t", effMass$effmassfit$chisqr, "\n") cat("dof\t=\t", effMass$effmassfit$dof, "\n") cat("chisqr/dof=\t", effMass$effmassfit$chisqr/effMass$effmassfit$dof, "\n") cat("Quality of the fit (p-value):", effMass$effmassfit$Qval, "\n") } print.effectivemassfit <- function (x, ..., verbose = FALSE) { effMass <- x summary(effMass, verbose = verbose, ...) } plot.effectivemass <- function (x, ..., ref.value, col, col.fitline) { effMass <- x if(missing(col)) { col <- c("black", rainbow(n=(effMass$nrObs-1))) } if(missing(col.fitline)) { col.fitline <- col[1] } t <- effMass$t.idx suppressWarnings(plotwitherror(x=t-1, y=effMass$effMass[t], dy=effMass$deffMass[t], col=col[1], ...)) if(effMass$nrObs > 1) { for(i in 1:(effMass$nrObs-1)) { suppressWarnings(plotwitherror(x=t-1, y=effMass$t0[t+i*length(t)], dy=effMass$se[t+i*length(t)], rep=TRUE, col=col[i+1], ...)) } } if(!missing(ref.value)) { abline(h=ref.value, col=c("darkgreen"), lwd=c(3)) } if(!is.null(effMass$effmassfit)){ lines(x=c(effMass$t1,effMass$t2), y=c(effMass$effmassfit$t0[1],effMass$effmassfit$t0[1]), col=col.fitline, lwd=1.3) pcol <- col2rgb(col.fitline,alpha=TRUE)/255 pcol[4] <- 0.65 pcol <- rgb(red=pcol[1],green=pcol[2],blue=pcol[3],alpha=pcol[4]) rect(xleft=effMass$t1, ybottom=effMass$effmassfit$t0[1]-effMass$effmassfit$se[1], xright=effMass$t2, ytop=effMass$effmassfit$t0[1]+effMass$effmassfit$se[1], col=pcol, border=NA) } }
dccTabs <- function(children=NULL, id=NULL, value=NULL, className=NULL, content_className=NULL, parent_className=NULL, style=NULL, parent_style=NULL, content_style=NULL, vertical=NULL, mobile_breakpoint=NULL, colors=NULL, loading_state=NULL, persistence=NULL, persisted_props=NULL, persistence_type=NULL) { props <- list(children=children, id=id, value=value, className=className, content_className=content_className, parent_className=parent_className, style=style, parent_style=parent_style, content_style=content_style, vertical=vertical, mobile_breakpoint=mobile_breakpoint, colors=colors, loading_state=loading_state, persistence=persistence, persisted_props=persisted_props, persistence_type=persistence_type) if (length(props) > 0) { props <- props[!vapply(props, is.null, logical(1))] } component <- list( props = props, type = 'Tabs', namespace = 'dash_core_components', propNames = c('children', 'id', 'value', 'className', 'content_className', 'parent_className', 'style', 'parent_style', 'content_style', 'vertical', 'mobile_breakpoint', 'colors', 'loading_state', 'persistence', 'persisted_props', 'persistence_type'), package = 'dashCoreComponents' ) structure(component, class = c('dash_component', 'list')) }
set.seed(1234) test_that("themes look good", { p <- ggdag(test_dag) expect_identical(theme_dag, theme_dag_blank) expect_identical(theme_dag_gray, theme_dag_grey) expect_identical(theme_dag_gray_grid, theme_dag_grey_grid) expect_doppelganger("theme_dag()", p + theme_dag()) expect_doppelganger("theme_dag_grid()", p + theme_dag_grid()) expect_doppelganger("theme_dag_gray()", p + theme_dag_gray()) expect_doppelganger("theme_dag_gray_grid()", p + theme_dag_gray_grid()) })
sat <- hijack(normal_round, mean = 1500, sd = 100, name = "SAT", digits = 0, min = 0, max = 2400 )
lmExact <- function( x = 1:20, y = NULL, ny = 1, intercept = 0, slope = 0.1, error = 0.1, seed = 123, pval = NULL, rsq = NULL, plot = TRUE, verbose = FALSE, ...) { lmEnv <- new.env() x <- rep(x, each = ny) if (length(error) == 1) { set.seed(seed) errorVec <- rnorm(length(x), 0, error) } else { error <- as.numeric(error) if (length(error) != length(x)) stop("'error' must have same length as 'x'!") errorVec <- error } if (!is.null(y)) { if (length(x) != length(y)) stop("'x' and 'y' must be of same length!") } optFct <- function(slope) { if (is.null(y)) y <- intercept + slope * x + errorVec LM <- lm(y ~ x, ...) RESID <- residuals(LM) y <- intercept + slope * x + RESID LM <- lm(y ~ x, ...) PVAL <- summary(LM)$coefficients[2, 4] OUT <- abs(PVAL - pval) assign("LM", LM, envir = lmEnv) return(OUT) } if (!is.null(pval)) { OPT <- suppressWarnings(optim(slope, optFct, control = list(trace = 0, maxit = 500))) LM <- get("LM", envir = lmEnv) if(is.character(all.equal(pval, summary(LM)$coefficients[2, 4], tolerance = 0.01 * pval))) print("Warning: Optimizer has not converged to the desired p-value! Try a different 'slope' starting value.") } else if (!is.null(rsq)) { if (rsq < 0 | rsq > 1) stop("R-square must be in [0, 1] !") if (is.null(y)) y <- intercept + slope * x + errorVec rho <- sqrt(rsq) theta <- acos(rho) MAT <- cbind(x, y) scaleMAT <- scale(MAT, center = TRUE, scale = FALSE) Id <- diag(length(x)) Q <- qr.Q(qr(scaleMAT[ , 1, drop=FALSE])) P <- tcrossprod(Q) x2o <- (Id-P) %*% scaleMAT[ , 2] Xc2 <- cbind(scaleMAT[ , 1], x2o) tempY <- Xc2 %*% diag(1/sqrt(colSums(Xc2^2))) y <- tempY[ , 2] + (1 / tan(theta)) * tempY[ , 1] LM <- lm(y ~ x, ...) INTER <- coef(LM)[1] y <- y + (intercept - coef(LM)[1]) LM <- lm(y ~ x, ...) assign("LM", LM, envir = lmEnv) } else { if (is.null(y)) y <- intercept + slope * x + errorVec LM <- lm(y ~ x, ...) RESID <- residuals(LM) y <- intercept + slope * x + RESID LM <- lm(y ~ x, ...) assign("LM", LM, envir = lmEnv) } LM <- get("LM", envir = lmEnv) if (plot) { DATA <- LM$model plot(DATA[, 2], DATA[, 1], pch = 16, xlab = "x", ylab = "y", las = 1, ...) abline(LM, ...) grid() } if (verbose) print(summary(LM)) return(list(lm = LM, x = LM$model[, 2], y = LM$model[, 1], summary = summary(LM))) }
setMethod( f = "convert", signature = c(target = "NmModel", source = "ANY", component = "ObsNormalCombined"), definition = function(target, source, component, options) { ruv_add_dcl <- declaration(~0) ruv_prop_dcl <- declaration(~0) values <- parameter_values(component) if (component@additive_term) { target <- target + nm_sigma("add", initial = values["var_add"]) eps_index <- index_of(target@facets$NmSigmaParameterFacet, "add") ruv_add_dcl <- dcl_substitute(declaration(~eps[i]), c(i = eps_index)) } if (component@proportional_term) { target <- target + nm_sigma("prop", initial = values["var_prop"]) eps_index <- index_of(target@facets$NmSigmaParameterFacet, "prop") ruv_prop_dcl <- dcl_substitute(declaration(~f*eps[i]), c(i = eps_index)) } ipred_dcl <- component@prediction if (vec_size(source@facets$CompartmentFacet@entries) > 0) { ipred_dcl <- replace_compartment_references(ipred_dcl, target, source) } f <- dcl_id(ipred_dcl) if (is.null(f[[1]])) { f <- dcl_def(ipred_dcl) ipred_dcl <- NULL } ruv_dcl <- vec_c(declaration(y~f), ruv_add_dcl, ruv_prop_dcl) %>% dcl_sum() %>% dcl_substitute( list( f = f ) ) d <- vec_c(ipred_dcl, ruv_dcl) target <- target + nm_error(statement = as_statement(d)) target } ) replace_compartment_references <- function(dcl, target, source){ if (any(c("C","A","dadt") %in% dcl_vars_chr(dcl))) { conc_dcls <- as.list(generate_concentration_substitutions(source@facets[["CompartmentFacet"]]@entries)) compartment_indicies <- name_index_map(target@facets$NmCompartmentFacet) dcl <- dcl %>% dcl_substitute(substitutions = conc_dcls) %>% dcl_substitute_index("A", compartment_indicies) %>% dcl_substitute_index("dadt", compartment_indicies) } return(dcl) } generate_concentration_substitutions <- function(cmps){ names <- names(cmps) volume <- vec_c(!!!unname(purrr::map(cmps, "volume"))) d <- dcl_substitute(declaration(C[name]~A[name]), substitutions = list(name = names)) dcl_devide(d, volume) }
source("~/repo/instrument-directionality/scripts/simulation-functions.r") library(devtools) load_all() devtools::install_github("MRCIEU/TwoSampleMR") library(TwoSampleMR) bp <- read.table(system.file(package="TwoSampleMR", "data/DebbieData_2.txt")) names(bp) <- c("beta.exposure", "se.exposure", "beta.outcome", "se.outcome") bp$mr_keep <- TRUE bp$id.exposure <- bp$id.outcome <- bp$exposure <- bp$outcome <- 1 bp$SNP <- paste0("SNP", 1:nrow(bp)) a <- mr_all(bp) r1 <- mr_rucker(bp[1:3,]) r2 <- mr_rucker_cooksdistance(bp[1:3,]) r1$selected r2$selected a1 <- mr_rucker(bp) a <- mr_rucker_cooksdistance(bp) b <- mr_rucker_bootstrap(bp) bp2 <- subset(bp, ! SNP %in% a$removed_snps) c <- mr_rucker_bootstrap(bp2) pdf("rucker_bootstrap.pdf", width=10, height=10) gridExtra::grid.arrange( b$q_plot + labs(title="All variants Rucker bootstrap"), c$q_plot + labs(title="Excluding Cooks D > 4/n Rucker bootstrap"), b$e_plot + labs(title="All variants Rucker bootstrap"), c$e_plot + labs(title="Excluding Cooks D > 4/n Rucker bootstrap"), ncol=2 ) dev.off() res1 <- array(0, 100) res2 <- array(0, 100) res3 <- array(0, 100) for(i in 1:100) { message(i) bp3 <- bp index <- sample(1:nrow(bp3), replace=FALSE) bp3$beta.outcome <- bp3$beta.outcome[index] bp3$se.outcome <- bp3$se.outcome[index] r1 <- mr_rucker_cooksdistance(bp3) r2 <- rucker_bootstrap(bp3) r3 <- rucker_bootstrap(subset(bp3, ! SNP %in% r1$removed_snps)) res1[i] <- r1$selected$P res2[i] <- r2$res$P[5] res3[i] <- r3$res$P[5] } res4 <- array(0, 100) for(i in 1:100) { message(i) bp3 <- bp index <- sample(1:nrow(bp3), replace=FALSE) bp3$beta.outcome <- bp3$beta.outcome[index] bp3$se.outcome <- bp3$se.outcome[index] res4[i] <- with(bp3, mr_ivw(beta.exposure, beta.outcome, se.exposure, se.outcome))$pval } a <- influence.measures(mod) cooks.distance(mod) > 4/nrow(bp) max(cooks.distance(mod)) a <- mr_all(bp) mr_scatter_plot(mr(bp), bp) mr_scatter_plot(mr(bp2), bp2) a$rucker$rucker n1 <- 50000 n2 <- 50000 nsnp <- 50 effs <- make_effs(ninst1=nsnp, var_xy=0.2, var_g1x=0.5, var_g1y=0, mu_g1y=0) pop1 <- make_pop(effs, n1) pop2 <- make_pop(effs, n2) dat1 <- get_effs(pop1$x, pop1$y, pop1$G1) dat2 <- get_effs(pop2$x, pop2$y, pop2$G1) datA <- recode_dat(make_dat(dat1, dat2)) a <- mr_all(datA) datAp <- subset(datA, pval.exposure < 5e-8) dim(datAp) b <- mr_all(datAp) plot(beta.outcome ~ beta.exposure, datA) plot(beta.outcome ~ beta.exposure, datAp) a$rucker$q_plot b$rucker$q_plot a$rucker$e_plot a$res with(datA, mr_mode(beta.exposure, beta.outcome, se.exposure, se.outcome)) effs <- make_effs(ninst1=nsnp, var_xy=0.05, var_g1x=0.2, var_g1y=0.01, mu_g1y=0) pop1 <- make_pop(effs, n1) pop2 <- make_pop(effs, n2) dat1 <- get_effs(pop1$x, pop1$y, pop1$G1) dat2 <- get_effs(pop2$x, pop2$y, pop2$G1) datB <- recode_dat(make_dat(dat1, dat2)) b <- mr_all(datB) b$rucker$q_plot b$rucker$e_plot r <- rucker_bootstrap(datB) plot(beta.outcome ~ beta.exposure, datB) r$q_plot mr_pleiotropy_test(datB) effs <- make_effs(ninst1=nsnp, var_xy=0.5, var_g1x=0.5, var_g1y=0, mu_g1y=0.1) pop1 <- make_pop(effs, n1) pop2 <- make_pop(effs, n2) dat1 <- get_effs(pop1$x, pop1$y, pop1$G1) dat2 <- get_effs(pop2$x, pop2$y, pop2$G1) datC <- recode_dat(make_dat(dat1, dat2)) run_rucker(datC) plot(beta.outcome ~ beta.exposure, datC) effs <- make_effs(ninst1=nsnp, var_xy=0.5, var_g1x=0.1, var_g1y=0.002, mu_g1y=0.1) pop1 <- make_pop(effs, n1) pop2 <- make_pop(effs, n2) dat1 <- get_effs(pop1$x, pop1$y, pop1$G1) dat2 <- get_effs(pop2$x, pop2$y, pop2$G1) datD <- recode_dat(make_dat(dat1, dat2)) plot(beta.outcome ~ beta.exposure, datD) d <- mr_all(datD) d$rucker$q_plot plot(beta.outcome ~ beta.exposure, datD) param <- expand.grid( nsim = c(1:50), nsnp = c(5,20,50), nid1 = 50000, nid2 = 50000, var_xy = c(0, 0.05, 0.1, 0.5), var_g1x = c(0, 0.025, 0.1), mu_g1y = c(-0.1, 0, 0.1) ) dim(param) out <- list() for(i in 1:nrow(param)) { effs <- make_effs(ninst1=param$nsnp[i], var_xy=param$var_xy[i], var_g1x=param$var_g1x[i], mu_g1y=param$mu_g1y[i]) pop1 <- make_pop(effs, param$nid1[i]) pop2 <- make_pop(effs, param$nid2[i]) dat1 <- get_effs(pop1$x, pop1$y, pop1$G1) dat2 <- get_effs(pop2$x, pop2$y, pop2$G1) dat <- recode_dat(make_dat(dat1, dat2)) out <- run_rucker(dat) out$param <- param[i,] res[[i]] <- out } xi <- 1:5 yi <- c(0,2,14,19,30) mi <- rep(40, 5) summary(lmI <- glm(cbind(yi, mi -yi) ~ xi, family = binomial)) signif(cooks.distance(lmI), 3) (imI <- influence.measures(lmI)) for(i in 1:BootSim){ BXG = rnorm(length(BetaXG),BetaXG,seBetaXG) BYG = rnorm(length(BetaYG),BetaYG,seBetaYG) if(weights==1){W = BXG^2/seBetaYG^2} if(weights==2){W = 1/(seBetaYG^2/BXG^2 + (BYG^2)*seBetaXG^2/BXG^4)} BIVw = BIV*sqrt(W) sW = sqrt(W) IR = lm(BIVw ~ -1+sW);IVW[i] = IR$coef[1] MR = lm(BIVw ~ sW);E[i] = MR$coef[2] DF1 = length(BetaYG)-1 phi_IVW = summary(IR)$sigma^2 QQ[i] = DF1*phi_IVW DF2 = length(BetaYG)-2 phi_E = summary(MR)$sigma^2 QQd[i] = DF2*phi_E Qp = 1-pchisq(Q,DF1) if(QQ[i] <= qchisq(1-alpha,DF1)){Mod[i]=1} if(QQ[i] >= qchisq(1-alpha,DF1)){Mod[i]=2} if(QQ[i] >= qchisq(1-alpha,DF1) & QQ[i] - QQd[i] >= qchisq(1-alpha,1)){Mod[i]=3} if(QQ[i] >= qchisq(1-alpha,DF1)& QQ[i] - QQd[i] >= qchisq(1-alpha,1)& QQd[i] >=qchisq(1-alpha,DF2)){Mod[i]=4} }
gl.report.callrate <- function(x, method="loc", boxplot="adjusted", range=1.5, verbose=NULL) { funname <- match.call()[[1]] build <- "Jacob" if (is.null(verbose)){ if(!is.null(x@other$verbose)){ verbose <- x@other$verbose } else { verbose <- 2 } } if (verbose < 0 | verbose > 5){ cat(paste(" Warning: Parameter 'verbose' must be an integer between 0 [silent] and 5 [full report], set to 2\n")) verbose <- 2 } if (verbose >= 1){ if(verbose==5){ cat("Starting",funname,"[ Build =",build,"]\n") } else { cat("Starting",funname,"\n") } } if(class(x)!="genlight") { stop("Fatal Error: genlight object required!\n") } if (all(x@ploidy == 1)){ cat(" Processing Presence/Absence (SilicoDArT) data\n") } else if (all(x@ploidy == 2)){ cat(" Processing a SNP dataset\n") } else { stop("Fatal Error: Ploidy must be universally 1 (fragment P/A data) or 2 (SNP data)!\n") } if (!x@other$loc.metrics.flags$monomorphs) { if(verbose >= 1){cat(" Warning: genlight object contains monomorphic loci which will be factored into Callrate calculations\n")} } if (!x@other$loc.metrics.flags$monomorphs){ x <- utils.recalc.callrate(x, verbose=0) } p1 <- p2 <- NULL if(method == "loc") { callrate <- x@other$loc.metrics$CallRate if (all(x@ploidy==2)){ title1 <- paste0("SNP data - Call Rate by Locus") } else { title1 <- paste0("Fragment P/A data - Call Rate by Locus") } p1 <- ggplot(data.frame(callrate), aes(y=callrate))+geom_boxplot() +coord_flip()+theme()+xlim(range=c(-1,1))+ylim(0,1)+ylab(" ")+ggtitle(title1) p2 <- ggplot(data.frame(callrate), aes(x=callrate))+geom_histogram(bins = 50)+ coord_cartesian(xlim = c(0,1)) grid.arrange(p1,p2) cat(" Reporting Call Rate by Locus\n") cat(" No. of loci =", nLoc(x), "\n") cat(" No. of individuals =", nInd(x), "\n") cat(" Miniumum Call Rate: ",round(min(x@other$loc.metrics$CallRate),2),"\n") cat(" Maximum Call Rate: ",round(max(x@other$loc.metrics$CallRate),2),"\n") cat(" Average Call Rate: ",round(mean(x@other$loc.metrics$CallRate),3),"\n") cat(" Missing Rate Overall: ",round(sum(is.na(as.matrix(x)))/(nLoc(x)*nInd(x)),2),"\n") retained <- array(NA,21) pc.retained <- array(NA,21) filtered <- array(NA,21) pc.filtered <- array(NA,21) percentile <- array(NA,21) for (index in 1:21) { i <- (index-1)*5 percentile[index] <- i/100 retained[index] <- length(callrate[callrate>=percentile[index]]) pc.retained[index] <- round(retained[index]*100/nLoc(x),1) filtered[index] <- nLoc(x) - retained[index] pc.filtered[index] <- 100 - pc.retained[index] } df <- cbind(percentile,retained,pc.retained,filtered,pc.filtered) df <- data.frame(df) colnames(df) <- c("Threshold", "Retained", "Percent", "Filtered", "Percent") df <- df[order(-df$Threshold),] rownames(df) <- NULL } if(method == "ind") { ind.call.rate <- 1 - rowSums(is.na(as.matrix(x)))/nLoc(x) if (all(x@ploidy==2)){ title1 <- paste0("SNP data (DArTSeq)\nCall Rate by Individual") } else { title1 <- paste0("Fragment P/A data (SilicoDArT)\nCall Rate by Individual") } p1 <- ggplot(data.frame(ind.call.rate), aes(y=ind.call.rate))+geom_boxplot() +coord_flip()+theme()+xlim(range=c(-1,1))+ylim(0,1)+ylab(" ")+ggtitle(title1) p2 <- ggplot(data.frame(ind.call.rate), aes(x=ind.call.rate))+geom_histogram(bins = 50)+ coord_cartesian(xlim = c(0,1)) grid.arrange(p1,p2) cat(" Reporting Call Rate by Individual\n") cat(" No. of loci =", nLoc(x), "\n") cat(" No. of individuals =", nInd(x), "\n") cat(" Miniumum Call Rate: ",round(min(ind.call.rate),2),"\n") cat(" Maximum Call Rate: ",round(max(ind.call.rate),2),"\n") cat(" Average Call Rate: ",round(mean(ind.call.rate),3),"\n") cat(" Missing Rate Overall: ",round(sum(is.na(as.matrix(x)))/(nLoc(x)*nInd(x)),2),"\n\n") retained <- array(NA,21) pc.retained <- array(NA,21) filtered <- array(NA,21) pc.filtered <- array(NA,21) percentile <- array(NA,21) crate <- ind.call.rate for (index in 1:21) { i <- (index-1)*5 percentile[index] <- i/100 retained[index] <- length(crate[crate>=percentile[index]]) pc.retained[index] <- round(retained[index]*100/nInd(x),1) filtered[index] <- nInd(x) - retained[index] pc.filtered[index] <- 100 - pc.retained[index] } df <- cbind(percentile,retained,pc.retained,filtered,pc.filtered) df <- data.frame(df) colnames(df) <- c("Threshold", "Retained", "Percent", "Filtered", "Percent") df <- df[order(-df$Threshold),] rownames(df) <- NULL } if (verbose >= 1) { cat("Completed:",funname,"\n") } return(list(callrates=df, boxplot=p1, hist=p2)) }
library(patternplot) library(png) library(ggplot2) group1<-c("Wind", "Hydro", "Solar", "Coal", "Natural Gas", "Oil") pct1<-c(12, 15, 8, 22, 18, 25) label1<-paste(group1, " \n ", pct1 , "%", sep="") group2<-c("Renewable", "Non-Renewable") pct2<-c(35, 65) label2<-paste(group2, " \n ", pct2 , "%", sep="") pattern.type1<-rep(c( "blank"), times=6) pattern.type2<-c('grid', 'blank') pattern.type.inner<-"blank" pattern.color1<-rep('white', length(group1)) pattern.color2<-rep('white', length(group2)) background.color1<-c("darkolivegreen1", "white", "indianred", "gray81", "white", "sandybrown" ) background.color2<-c("seagreen", "deepskyblue") density1<-rep(10, length(group1)) density2<-rep(10, length(group2)) pattern.line.size1=rep(6, length(group1)) pattern.line.size2=rep(2, length(group2)) pattern.line.size.inner=1 g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.75, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2,pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black", pattern.line.size.inner, background.color.inner="white", pixel.inner=6, density.inner=5, frame.color='black',frame.size=1,r1=2.45, r2=4.25, r3=5) g<-g+annotate(geom="text", x=0, y=0, label="Earth's Energy",color="black",size=5) g<-g+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6)) g g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.7, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2,pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black", pattern.line.size.inner, background.color.inner="white", pixel.inner=1, density.inner=2, frame.color='black',frame.size=1, r1=0.005, r2=4, r3=4.75) g<-g+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6)) g
data(gaussplot_sample_data) samp_dat <- gaussplot_sample_data[,1:3] bad_data1 <- cbind(samp_dat[,c(1,3)], yvalz = rnorm(nrow(samp_dat))) bad_data2 <- cbind(samp_dat[,c(1,2)], Z_values = rnorm(nrow(samp_dat))) test_that("characterize_gaussian_fits() fails when nonsense is supplied", { expect_error(characterize_gaussian_fits("steve")) expect_error(characterize_gaussian_fits(c("a", "b", "c"))) expect_error(characterize_gaussian_fits()) expect_error(characterize_gaussian_fits(samp_dat[,1:2])) expect_error(characterize_gaussian_fits(bad_data1)) expect_error(characterize_gaussian_fits(bad_data2)) expect_error(characterize_gaussian_fits(samp_dat, method = "steve")) expect_error(characterize_gaussian_fits(samp_dat, method = 4)) expect_error(characterize_gaussian_fits(data.frame(rnorm(100)))) expect_error(characterize_gaussian_fits(samp_dat, comparison_method = 2)) expect_error(characterize_gaussian_fits(samp_dat, comparison_method = "yes")) expect_error(characterize_gaussian_fits(samp_dat, comparison_method = c(2, 5))) expect_error(characterize_gaussian_fits(samp_dat, maxiter = "2")) expect_error(characterize_gaussian_fits(samp_dat, simplify = "yes")) }) gauss_fit_ue <- fit_gaussian_2D(samp_dat, method = "elliptical", constrain_orientation = "unconstrained") gauss_fit_uel <- fit_gaussian_2D(samp_dat, method = "elliptical_log", constrain_orientation = "unconstrained") gauss_fit_uel_CA <- fit_gaussian_2D(samp_dat, method = "elliptical_log", constrain_orientation = "unconstrained", constrain_amplitude = TRUE) gauss_fit_cir <- fit_gaussian_2D(samp_dat, method = "circular") bad_models_list1 <- list( unconstrained_elliptical = gauss_fit_ue, unconstrained_elliptical_log = gauss_fit_uel, circular = gauss_fit_cir ) bad_models_list2 <- list( unconstrained_elliptical_log = gauss_fit_uel, unconstrained_elliptical_log = gauss_fit_uel, unconstrained_elliptical_log = gauss_fit_uel ) bad_models_list3 <- list( unconstrained_elliptical_log = gauss_fit_uel ) bad_models_list4 <- list( unconstrained_elliptical_log = gauss_fit_uel, gauss_fit_uel_CA = gauss_fit_uel_CA ) bad_models_list5 <- list( unconstrained_elliptical_log = gauss_fit_uel, unconstrained_elliptical_log = gauss_fit_uel, gauss_fit_uel_CA = gauss_fit_uel_CA ) test_that("characterize_gaussian_fits() fails bad models are supplied", { expect_error(characterize_gaussian_fits(bad_models_list1)) expect_error(characterize_gaussian_fits(bad_models_list2)) expect_error(characterize_gaussian_fits(bad_models_list3)) expect_error(characterize_gaussian_fits(bad_models_list4)) expect_error(characterize_gaussian_fits(bad_models_list5)) }) no_models <- characterize_gaussian_fits(data = samp_dat) gauss_fit_uel <- fit_gaussian_2D(samp_dat, method = "elliptical_log", constrain_orientation = "unconstrained", constrain_amplitude = FALSE) gauss_fit_zer <- fit_gaussian_2D(samp_dat, method = "elliptical_log", constrain_orientation = 0, constrain_amplitude = FALSE) gauss_fit_ngo <- fit_gaussian_2D(samp_dat, method = "elliptical_log", constrain_orientation = -1, constrain_amplitude = FALSE) good_models <- list( gauss_fit_uel = gauss_fit_uel, gauss_fit_zer = gauss_fit_zer, gauss_fit_ngo = gauss_fit_ngo ) with_models <- characterize_gaussian_fits(good_models)
pamr.fdr <- function(trained.obj, data, nperms=100, xl.mode=c("regular","firsttime","onetime","lasttime"), xl.time=NULL, xl.prevfit=NULL){ this.call <- match.call() xl.mode=match.arg(xl.mode) if(xl.mode=="regular" | xl.mode=="firsttime"){ y= data$y m=nrow(data$x) nclass=length(table(y)) threshold <- trained.obj$threshold n.threshold=length(threshold) tt <- scale((trained.obj$centroids - trained.obj$centroid.overall)/trained.obj$sd, FALSE, trained.obj$threshold.scale * trained.obj$se.scale) ttstar <- array(NA,c(m,nperms,nclass)) results=NULL pi0=NULL } if(xl.mode=="onetime" | xl.mode=="lasttime"){ y=xl.prevfit$y m=xl.prevfit$m nclass=xl.prevfit$nclass threshold=xl.prevfit$threshold n.threshold=xl.prevfit$n.threshold tt=xl.prevfit$tt ttstar=xl.prevfit$ttstar nperms=xl.prevfit$nperms results=xl.prevfit$results pi0=xl.prevfit$pi0 } if(xl.mode=="regular"){ first=1;last=nperms } if(xl.mode=="firsttime"){ first=1;last=1 } if(xl.mode=="onetime"){ first=xl.time;last=xl.time } if(xl.mode=="lasttime"){ first=nperms;last=nperms } for(i in first:last){ cat("",fill=T) cat(c("perm=",i),fill=T) ystar <- sample(y) data2 <- data data2$y <- ystar foo<-pamr.train(data2, threshold=0, scale.sd = trained.obj$scale.sd, threshold.scale = trained.obj$threshold.scale, se.scale = trained.obj$se.scale, offset.percent = 50, hetero = trained.obj$hetero, prior = trained.obj$prior, sign.contrast = trained.obj$sign.contrast) sdstar=foo$sd-foo$offset+trained.obj$offset ttstar[,i,] =scale((foo$centroids - foo$centroid.overall)/sdstar, FALSE, foo$threshold.scale * foo$se.scale) } if(xl.mode=="regular" | xl.mode=="lasttime"){ fdr=rep(NA,n.threshold) fdr90=rep(NA,n.threshold) ngenes=rep(NA,n.threshold) for(j in 1:n.threshold){ nobs=sum(drop((abs(tt)-threshold[j] > 0) %*% rep(1, ncol(tt))) > 0) temp=abs(ttstar)-threshold[j] >0 temp2=rowSums(temp, dims=2) nnull=colSums(temp2>0) fdr[j]=median(nnull)/nobs fdr90[j]=quantile(nnull,.9)/nobs ngenes[j]=nobs } q1 <- quantile(ttstar, .25) q2 <- quantile(ttstar, .75) pi0 <- min(sum( tt> q1 & tt< q2 )/(.5*m*nclass) ,1 ) fdr <- fdr*pi0 fdr90=fdr90*pi0 fdr=pmin(fdr,1) fdr90=pmin(fdr90,1) results <- cbind(threshold, ngenes, fdr*ngenes, fdr, fdr90) om=is.na(fdr) results=results[!om,] dimnames(results) <- list(NULL,c("Threshold", "Number of significant genes", "Median number of null genes", "Median FDR", "90th percentile of FDR")) y=NULL;x=NULL;m=NULL;threshold=NULL;n.threshold=NULL;tt=NULL;nperms=NULL; ttstar=NULL } return(list(results=results,pi0=pi0, y=y,m=m,threshold=threshold,n.threshold=n.threshold, tt=tt,ttstar=ttstar, nperms=nperms)) }
lexicon_loughran <- function(dir = NULL, delete = FALSE, return_path = FALSE, clean = FALSE, manual_download = FALSE) { load_dataset(data_name = "loughran", name = "LoughranMcDonald.rds", dir = dir, delete = delete, return_path = return_path, clean = clean, manual_download = manual_download) } download_loughran <- function(folder_path) { file_path <- path(folder_path, "LoughranMcDonald_MasterDictionary_2018 - LoughranMcDonald_MasterDictionary_2018.csv") if (file_exists(file_path)) { return(invisible()) } download.file(url = "https://drive.google.com/uc?id=12ECPJMxV2wSalXG8ykMmkpa1fq_ur0Rf&export=download", destfile = file_path) } process_loughran <- function(folder_path, name_path) { data <- read_csv(path(folder_path, "LoughranMcDonald_MasterDictionary_2018 - LoughranMcDonald_MasterDictionary_2018.csv"), col_types = cols_only(Word = col_character(), Negative = col_double(), Positive = col_double(), Uncertainty = col_double(), Litigious = col_double(), Constraining = col_double(), Superfluous = col_double())) types <- c("Negative", "Positive", "Uncertainty", "Litigious", "Constraining", "Superfluous") out <- list() for (type in types) { out[[type]] <- tibble(word = tolower(as.character(data$Word[data[[type]] != 0])), sentiment = tolower(type)) } write_rds(Reduce(rbind, out), name_path) }
context("standardisation tests") d <- c('2019-04-18', '2019-04-14', '2019-03-31', '2019-04-03', '2019-03-30', '2019-04-05', '2019-03-12', '2019-04-07', '2019-04-02', '2019-03-09', '2019-04-20', '2019-04-23', '2019-03-07', '2019-03-25', '2019-03-27', '2019-04-13', '2019-04-15', '2019-04-04', '2019-03-30', '2019-03-19') test_that("standard will override first_date", { expect_output(print(incidence(d, interval = "week", standard = TRUE)), "2019-03-04") expect_output(print(incidence(d, interval = "week", standard = TRUE)), "2019-W10") expect_output(print(incidence(d, interval = "isoweek", standard = TRUE)), "2019-W10") expect_output(print(incidence(d, interval = "1 isoweek", standard = TRUE)), "2019-W10") expect_output(print(incidence(d, interval = "monday week", standard = TRUE)), "2019-W10") expect_output(print(incidence(d, interval = "week", standard = FALSE)), "2019-03-07") expect_error(incidence(d, interval = "isoweek", standard = FALSE), "The interval 'isoweek' implies a standard and cannot be used with `standard = FALSE`") expect_error(incidence(d, interval = "monday week", standard = FALSE), "The interval 'monday week' implies a standard and cannot be used with `standard = FALSE`") expect_output(print(incidence(d, interval = "month", standard = TRUE)), "2019-03-01") expect_output(print(incidence(d, interval = "month", standard = FALSE)), "2019-03-07") expect_output(print(incidence(d, interval = "year", standard = TRUE)), "2019-01-01") expect_output(print(incidence(d, interval = "year", standard = FALSE)), "2019-03-07") })
"psp.weight" <- function(svals, ips = 1, xk = 1.06){ n <- length(svals) fvals <- double(n) storage.mode(svals) <- "double" f.res <- .Fortran("srpspamm", n = as.integer(n), svals = svals, fvals = fvals, as.integer(ips), as.double(xk)) f.res$fvals}
predict.rem <- function(object,newdata=NULL,compute=FALSE,int.range=NULL,...){ model <- object if(!is.null(newdata)){ compute <- TRUE xmat <- newdata }else{ xmat <- model$mr$data } xmat$distance <- 0 ddfobj <- model$ds$ds$aux$ddfobj if(ddfobj$type=="gamma"){ xmat$distance <- rep(apex.gamma(ddfobj),2) } xmat$offsetvalue <- 0 p.0 <- predict(model$mr,newdata=xmat,integrate=FALSE,compute=compute)$fitted if(is.null(newdata)){ pdot <- predict(model$ds,esw=FALSE,compute=compute, int.range=int.range)$fitted }else{ pdot <- predict(model$ds,newdata=newdata[newdata$observer==1,], esw=FALSE,compute=compute,int.range=int.range)$fitted } fitted <- p.0*pdot if(is.null(newdata)){ names(fitted) <- model$mr$mr$data$object[model$mr$mr$data$observer==1] }else{ names(fitted) <- newdata$object[newdata$observer==1] } return(list(fitted=fitted)) }
make_seasLAI <- function(method="b90", year, maxlai, winlaifrac = 0, budburst_doy = 121, leaffall_doy = 279, emerge_dur = 28, leaffall_dur = 58, shp_optdoy=220, shp_budburst=0.5, shp_leaffall=10, lai_doy = c(1,121,150,280,320,365), lai_frac = c(0,0,0.5,1,0.5,0)) { method <- match.arg(method, choices = c("b90", "linear", "Coupmodel")) if (method %in% c("b90", "Coupmodel")) { dat <- suppressWarnings( data.table::data.table(year = year, maxlai = maxlai, winlaifrac = winlaifrac, budburst_doy = budburst_doy, leaffall_doy = leaffall_doy, emerge_dur = emerge_dur, leaffall_dur = leaffall_dur, shp_optdoy = shp_optdoy, shp_budburst = shp_budburst, shp_leaffall = shp_leaffall) ) maxdoy <- NULL; minlai <- NULL dat$maxdoy <- with(dat, ifelse( ((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0), 366, 365)) dat$minlai <- with(dat, winlaifrac*maxlai) if (method == "b90") { out <- dat[, plant_b90(minval = minlai, maxval = maxlai, doy.incr = budburst_doy, incr.dur = emerge_dur, doy.decr = leaffall_doy, decr.dur = leaffall_dur, maxdoy = maxdoy), by = year]$V1 } if (method == "Coupmodel") { out <- dat[, plant_coupmodel(minval = minlai, maxval = maxlai, doy.incr = budburst_doy, doy.max = shp_optdoy, doy.min = leaffall_doy + leaffall_dur, shape.incr = shp_budburst, shape.decr = shp_leaffall, maxdoy = maxdoy), by = year]$V1 } } else { dat <- data.table::data.table(year, maxdoy = ifelse( ((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0), 366, 365), maxlai = maxlai) out <- dat[, plant_linear(doys = lai_doy, values = lai_frac*maxlai, maxdoy = maxdoy), by = year]$V1 } return(out) }
test_that("uses scale limits, not data limits", { dat <- data_frame(x = c(0.1, 1:100)) dat$y <- dexp(dat$x) base <- ggplot(dat, aes(x, y)) + stat_function(fun = dexp) full <- base + scale_x_continuous(limits = c(0.1, 100)) + scale_y_continuous() ret <- layer_data(full) full_log <- base + scale_x_log10(limits = c(0.1, 100)) + scale_y_continuous() ret_log <- layer_data(full_log) expect_equal(ret$y[c(1, 101)], ret_log$y[c(1, 101)]) expect_equal(range(ret$x), c(0.1, 100)) expect_equal(range(ret_log$x), c(-1, 2)) expect_false(any(is.na(ret$y))) expect_false(any(is.na(ret_log$y))) }) test_that("works in plots without any data", { f <- function(x) 2*x base <- ggplot() + geom_function(fun = f, n = 6) ret <- layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) expect_identical(ret$y, 2*ret$x) base <- ggplot() + xlim(0, 2) + geom_function(fun = f, n = 6) ret <- layer_data(base) expect_identical(ret$x, seq(0, 2, length.out = 6)) expect_identical(ret$y, 2*ret$x) base <- ggplot() + geom_function(fun = f, n = 6, xlim = c(0, 2)) ret <- layer_data(base) expect_identical(ret$x, seq(0, 2, length.out = 6)) expect_identical(ret$y, 2*ret$x) base <- ggplot() + geom_function(aes(color = "fun"), fun = f, n = 6) + scale_color_manual(values = c(fun = " ret <- layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) expect_identical(ret$y, 2*ret$x) expect_identical(ret$colour, rep(" }) test_that("works with discrete x", { dat <- data_frame(x = c("a", "b")) base <- ggplot(dat, aes(x, group = 1)) + stat_function(fun = as.numeric, geom = "point", n = 2) ret <- layer_data(base) expect_equal(ret$x, new_mapped_discrete(1:2)) expect_equal(ret$y, 1:2) }) test_that("works with transformed scales", { dat <- data_frame(x = 1:10, y = (1:10)^2) base <- ggplot(dat, aes(x, group = 1)) + stat_function(fun = ~ .x^2, n = 5) ret <- layer_data(base) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(1, 10, length.out = 5)) expect_equal(ret$y, ret$x^2) ret <- layer_data(base + scale_x_log10()) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(0, 1, length.out = 5)) expect_equal(ret$y, (10^ret$x)^2) ret <- layer_data(base + scale_y_log10()) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(1, 10, length.out = 5)) expect_equal(10^ret$y, ret$x^2) ret <- layer_data(base + scale_x_log10() + scale_y_log10()) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(0, 1, length.out = 5)) expect_equal(10^ret$y, (10^ret$x)^2) base <- ggplot(dat, aes(x, y)) + geom_point() + stat_function(fun = ~ .x^2, n = 5) ret <- layer_data(base, 2) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(1, 10, length.out = 5)) expect_equal(ret$y, ret$x^2) ret <- layer_data(base + scale_x_log10(), 2) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(0, 1, length.out = 5)) expect_equal(ret$y, (10^ret$x)^2) ret <- layer_data(base + scale_y_log10(), 2) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(1, 10, length.out = 5)) expect_equal(10^ret$y, ret$x^2) ret <- layer_data(base + scale_x_log10() + scale_y_log10(), 2) expect_equal(nrow(ret), 5) expect_equal(ret$x, seq(0, 1, length.out = 5)) expect_equal(10^ret$y, (10^ret$x)^2) }) test_that("works with formula syntax", { dat <- data_frame(x = 1:10) base <- ggplot(dat, aes(x, group = 1)) + stat_function(fun = ~ .x^2, geom = "point", n = 5) + scale_x_continuous(limits = c(0, 10)) ret <- layer_data(base) s <- seq(0, 10, length.out = 5) expect_equal(ret$x, s) expect_equal(ret$y, s^2) }) test_that("Warn when drawing multiple copies of the same function", { df <- data_frame(x = 1:3, y = letters[1:3]) p <- ggplot(df, aes(x, color = y)) + stat_function(fun = identity) f <- function() {pdf(NULL); print(p); dev.off()} expect_warning(f(), "Multiple drawing groups") }) test_that("Line style can be changed via provided data", { df <- data_frame(fun = " base <- ggplot(df) + geom_function(aes(color = fun), fun = identity, n = 6) + scale_color_identity() ret <- layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) expect_identical(ret$y, ret$x) expect_identical(ret$colour, rep(" base <- ggplot() + geom_function( data = df, aes(color = fun), fun = identity, n = 6 ) + scale_color_identity() ret <- layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) expect_identical(ret$y, ret$x) expect_identical(ret$colour, rep(" base <- ggplot() + stat_function( data = df, aes(color = fun), fun = identity, n = 6 ) + scale_color_identity() ret <- layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) expect_identical(ret$y, ret$x) expect_identical(ret$colour, rep(" })
setMethod("learn.network", c("BN"), function(x, y = NULL, algo = "mmhc", scoring.func = "BDeu", initial.network = NULL, alpha = 0.05, ess = 1, bootstrap = FALSE, layering = c(), max.fanin = num.variables(y) -1, max.fanin.layers = NULL, max.parents = num.variables(y) -1, max.parents.layers = NULL, layer.struct = NULL, cont.nodes = c(), use.imputed.data = FALSE, use.cpc = TRUE, mandatory.edges = NULL, ...) { if (is.null(y) || !inherits(y, "BNDataset")) stop("A BNDataset must be provided in order to learn a network from it. ", "Please take a look at the documentation of the method: > ?learn.network") bn <- x dataset <- y if (num.time.steps(dataset) > 1) { bn <- learn.dynamic.network(bn, dataset, num.time.steps(dataset), algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) } else { bn <- learn.structure(bn, dataset, algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) if (!bootstrap && algo != "mmpc") bn <- learn.params(bn, dataset, ess, use.imputed.data) } return(bn) }) setMethod("learn.network", c("BNDataset"), function(x, algo = "mmhc", scoring.func = "BDeu", initial.network = NULL, alpha = 0.05, ess = 1, bootstrap = FALSE, layering = c(), max.fanin = num.variables(x) - 1, max.fanin.layers = NULL, max.parents = num.variables(x) - 1, max.parents.layers = NULL, layer.struct = NULL, cont.nodes = c(), use.imputed.data = FALSE, use.cpc = TRUE, mandatory.edges = NULL, ...) { dataset <- x bn <- BN(dataset) if (num.time.steps(dataset) > 1) { bn <- learn.dynamic.network(bn, dataset, num.time.steps(dataset), algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) } else { bn <- learn.structure(bn, dataset, algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) if (!bootstrap && algo != "mmpc") bn <- learn.params(bn, dataset, ess, use.imputed.data) } return(bn) }) setMethod("learn.dynamic.network", c("BN"), function(x, y = NULL, num.time.steps = num.time.steps(y), algo = "mmhc", scoring.func = "BDeu", initial.network = NULL, alpha = 0.05, ess = 1, bootstrap = FALSE, layering = c(), max.fanin = num.variables(y) - 1, max.fanin.layers = NULL, max.parents = num.variables(y) - 1, max.parents.layers = NULL, layer.struct = NULL, cont.nodes = c(), use.imputed.data = FALSE, use.cpc = TRUE, mandatory.edges = NULL, ...) { if (is.null(y) || !inherits(y, "BNDataset")) stop("A BNDataset must be provided in order to learn a network from it. ", "Please take a look at the documentation of the method: > ?learn.dynamic.network") bn <- x dataset <- y if (num.variables(dataset) %% num.time.steps != 0) { stop("There should be the same number of variables in each time step.") } nv <- num.variables(dataset) / num.time.steps nl <- layering ls <- layer.struct if (is.null(layering)) { nl <- rep(1,nv) } else { if (length(layering) != nv && length(layering) != num.variables(y)) { stop("If a layering is provided, it should be either as long as the number of variables in each time step, or as the total number of variables in all the time steps.") } } num.layers <- length(unique(nl)) copynl <- nl while (length(nl) < num.variables(y)) { nl <- c(nl, copynl+max(nl)) } layering <- nl if (is.null(layer.struct)) { ls <- matrix(0, num.layers * num.time.steps, num.layers * num.time.steps) ls[upper.tri(ls, diag=TRUE)] <- 1 layer.struct <- ls } else { tmp.ls <- NULL for (i in 1:num.time.steps) { if (i == 1) nr <- ls else nr <- matrix(0, num.layers, num.layers) for (j in 2:num.time.steps) { if (j < i) { nr <- cbind(nr, matrix(0, num.layers, num.layers)) } else if (i == j) { nr <- cbind(nr, ls) } else { nr <- cbind(nr, matrix(1, num.layers, num.layers)) } } tmp.ls <- rbind(tmp.ls, nr) } layer.struct <- tmp.ls } bn <- learn.structure(bn, dataset, algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) if (!bootstrap && algo != "mmpc") bn <- learn.params(bn, dataset, ess, use.imputed.data) return(bn) }) setMethod("learn.dynamic.network", c("BNDataset"), function(x, num.time.steps = num.time.steps(x), algo = "mmhc", scoring.func = "BDeu", initial.network = NULL, alpha = 0.05, ess = 1, bootstrap = FALSE, layering = c(), max.fanin = num.variables(x) - 1, max.fanin.layers = NULL, max.parents = num.variables(x) - 1, max.parents.layers = NULL, layer.struct = NULL, cont.nodes = c(), use.imputed.data = FALSE, use.cpc = TRUE, mandatory.edges = NULL, ...) { dataset <- x bn <- BN(dataset) if (num.variables(x) %% num.time.steps != 0) { stop("There should be the same number of variables in each time step.") } nv <- num.variables(x) / num.time.steps nl <- layering ls <- layer.struct if (is.null(layering)) { nl <- rep(1,nv) } else { if (length(layering) != nv && length(layering) != num.variables(x)) { stop("If a layering is provided, it should be either as long as the number of variables in each time step, or as the total number of variables in all the time steps.") } } num.layers <- length(unique(nl)) copynl <- nl while (length(nl) < num.variables(x)) { nl <- c(nl, copynl+max(nl)) } layering <- nl if (is.null(layer.struct)) { ls <- matrix(0, num.layers * num.time.steps, num.layers * num.time.steps) ls[upper.tri(ls, diag=TRUE)] <- 1 layer.struct <- ls } else { tmp.ls <- NULL for (i in 1:num.time.steps) { if (i == 1) nr <- ls else nr <- matrix(0, num.layers, num.layers) for (j in 2:num.time.steps) { if (j < i) { nr <- cbind(nr, matrix(0, num.layers, num.layers)) } else if (i == j) { nr <- cbind(nr, ls) } else { nr <- cbind(nr, matrix(1, num.layers, num.layers)) } } tmp.ls <- rbind(tmp.ls, nr) } layer.struct <- tmp.ls } bn <- learn.structure(bn, dataset, algo, scoring.func, initial.network, alpha, ess, bootstrap, layering, max.fanin, max.fanin.layers, max.parents, max.parents.layers, layer.struct, cont.nodes, use.imputed.data, use.cpc, mandatory.edges, ...) if (!bootstrap && algo != "mmpc") bn <- learn.params(bn, dataset, ess, use.imputed.data) return(bn) }) setMethod("learn.params", c("BN", "BNDataset"), function(bn, dataset, ess = 1, use.imputed.data = FALSE) { if (struct.algo(bn) == "mmpc") { bnstruct.start.log("no parameter learning possible for network learnt using the MMPC algorithm") return(bn) } bnstruct.start.log("learning network parameters ... ") if (use.imputed.data) data <- as.matrix(imputed.data(dataset)) else data <- as.matrix(raw.data(dataset)) node.sizes <- node.sizes(bn) dag <- dag(bn) n.nodes <- num.nodes(bn) variables <- variables(bn) storage.mode(node.sizes) <- "integer" cont.nodes <- which(!discreteness(bn)) levels <- rep( 0, n.nodes ) levels[cont.nodes] <- node.sizes[cont.nodes] out.data <- quantize.matrix( data, levels ) data <- out.data$quant quantiles(bn) <- out.data$quantiles quantiles(dataset) <- out.data$quantiles cpts <- list("list",n.nodes) var.names <- c(unlist(variables)) d.names <- mapply(function(name,size)(1:size),var.names,node.sizes) for ( i in 1:n.nodes ) { family <- c( which(dag[,i]!=0), i ) counts <- .Call( "bnstruct_compute_counts_nas", data[,family], node.sizes[family], PACKAGE = "bnstruct" ) counts <- array(c(counts), c(node.sizes[family])) cpts[[i]] <- counts.to.probs( counts + ess / prod(dim(counts)) ) dms <- NULL dns <- NULL for (j in 1:length(family)) { dms[[j]] <- as.list(c(1:node.sizes[family[j]])) dns[[j]] <- c(var.names[family[j]]) } dimnames(cpts[[i]]) <- dms names( dimnames(cpts[[i]]) ) <- dns } names(cpts) <- var.names cpts(bn) <- cpts bnstruct.end.log("parameter learning done.") return(bn) } ) setMethod("learn.structure", c("BN", "BNDataset"), function(bn, dataset, algo = "mmhc", scoring.func = "BDeu", initial.network = NULL, alpha = 0.05, ess = 1, bootstrap = FALSE, layering = c(), max.fanin = num.variables(dataset) - 1, max.fanin.layers = NULL, max.parents = num.variables(dataset) - 1, max.parents.layers = NULL, layer.struct = NULL, cont.nodes = c(), use.imputed.data = FALSE, use.cpc = TRUE, mandatory.edges = NULL, ...) { num.nodes(bn) <- num.variables(dataset) node.sizes(bn) <- node.sizes(dataset) variables(bn) <- variables(dataset) validObject(bn) node.sizes <- node.sizes(bn) num.nodes <- num.nodes(bn) if (length(cont.nodes) == 0) cont.nodes <- setdiff(1:num.nodes,which(discreteness(dataset))) if (bootstrap) { if (!has.boots(dataset)) stop("Bootstrap samples not available. Please generate samples before learning with bootstrap.\nSee > ?bootstrap for help.") if (use.imputed.data && !has.imputed.boots(dataset)) stop("Imputed samples not available. Please generate imputed samples before learning.\nSee > ?bootstrap for help.") num.boots <- num.boots(dataset) } else { if (use.imputed.data && has.imputed.data(dataset)) data <- imputed.data(dataset) else if (use.imputed.data && !has.imputed.data(dataset)) stop("Imputed data not available. Please impute data before learning.\nSee > ?impute for help.") else data <- raw.data(dataset) } scoring.func <- match(tolower(scoring.func), c("bdeu", "aic", "bic")) if (is.na(scoring.func)) { bnstruct.log("scoring function not recognized, using BDeu") scoring.func <- 0 } else { scoring.func <- scoring.func - 1 } scoring.func(bn) <- c("BDeu", "AIC", "BIC")[scoring.func + 1] algo <- tolower(algo) if (!algo %in% c("sm", "mmhc", "sem", "mmpc", "hc")) { bnstruct.log("structure learning algorithm not recognized, using MMHC") bnstruct.log("(available options are: SM, MMHC, MMPC, HC, SEM)") algo <- "mmhc" } if (!is.null(initial.network)) { if (inherits(initial.network, "BN")) init.net <- initial.network else if (inherits(initial.network, "matrix")) { init.net <- BN(dataset) dag(init.net) <- initial.network init.net <- learn.params(init.net, dataset) } else if (inherits(initial.network, "character") && tolower(initial.network) == "random.chain") init.net <- sample.chain(dataset) else init.net <- NULL if (!is.null(init.net)) validObject(init.net) } else init.net <- NULL other.args <- list(...) if ("tabu.tenure" %in% names(other.args)) tabu.tenure <- as.numeric(other.args$tabu.tenure) else tabu.tenure <- 100 if ("seed" %in% names(other.args)) set.seed(as.numeric(other.args$seed)) else set.seed(0) if ("wm.max" %in% names(other.args)) wm.max <- as.numeric(other.args$wm.max) else wm.max <- 15 if ("initial.cpc" %in% names(other.args)) initial.cpc <- as.numeric(other.args$initial.cpc) else initial.cpc <- NULL if (algo == "sm") { if ( max.fanin < max.parents || (is.null(max.parents.layers) && !is.null(max.fanin.layers)) ) { bnstruct.log ("SM uses 'max.parents' and 'max.parents.layers' parameters, ", "but apparently you set 'max.fanin' and 'max.fanin.layers', ", "changing accordingly.") max.parents <- max.fanin max.parents.layers <- max.fanin.layers } bnstruct.start.log("learning the structure using SM ...") if (bootstrap) { finalPDAG <- matrix(0,num.nodes,num.nodes) for( i in seq_len(num.boots(dataset)) ) { data <- boot(dataset, i, use.imputed.data = use.imputed.data) dag <- sm(data, node.sizes, scoring.func, cont.nodes, max.parents, layering, max.parents.layers, ess, initial.cpc, mandatory.edges) finalPDAG <- finalPDAG + dag.to.cpdag( dag, layering, layer.struct ) } wpdag(bn) <- finalPDAG } else { dag(bn) <- sm(data, node.sizes, scoring.func, cont.nodes, max.parents, layering, max.parents.layers, ess, initial.cpc, mandatory.edges) } bnstruct.end.log("learning using SM completed.") } if (algo == "sem") { bnstruct.start.log("learning the structure using SEM ...") bn <- sem(bn, dataset, scoring.func = c("BDeu", "AIC", "BIC")[scoring.func + 1], initial.network = init.net, alpha = alpha, ess = ess, bootstrap = bootstrap, layering = layering, max.fanin.layers = max.fanin.layers, max.fanin = max.fanin, max.parents = max.parents, cont.nodes = cont.nodes, use.imputed.data = use.imputed.data, use.cpc = use.cpc, mandatory.edges = mandatory.edges, ...) bnstruct.end.log("learning using SEM completed.") } if (algo == "mmpc") { if ( max.parents < max.fanin) { bnstruct.log ("MMPC uses 'max.fanin', ", "but apparently you set 'max.parents', ", "changing accordingly.") max.parents <- max.fanin max.parents.layers <- max.fanin.layers } bnstruct.start.log("learning the structure using MMPC ...") if (bootstrap) { finalPDAG <- matrix(0,num.nodes,num.nodes) for( i in seq_len(num.boots(dataset)) ) { data <- boot(dataset, i, use.imputed.data=use.imputed.data) cpc <- mmpc( data, node.sizes, cont.nodes, alpha, layering, layer.struct, max.fanin=max.fanin, mandatory.edges = mandatory.edges ) finalPDAG <- finalPDAG + cpc } wpdag(bn) <- finalPDAG } else { cpc <- mmpc( data, node.sizes, cont.nodes, alpha, layering, layer.struct, max.fanin=max.fanin, mandatory.edges = mandatory.edges ) wpdag(bn) <- cpc } bnstruct.end.log("learning using MMPC completed.") } if (algo == "hc") { if ( max.parents < max.fanin || (is.null(layer.struct) && !is.null(max.parents.layers)) ) { bnstruct.log ("HC uses 'max.fanin' and 'layer.struct' parameters, ", "but apparently you set 'max.parents' and 'max.parents.layers', ", "changing accordingly.") max.parents <- max.fanin max.parents.layers <- max.fanin.layers } bnstruct.start.log("learning the structure using HC ...") if (!is.null(init.net)) in.dag <- dag(init.net) else in.dag <- NULL if (bootstrap) { finalPDAG <- matrix(0,num.nodes,num.nodes) for( i in seq_len(num.boots(dataset)) ) { data <- boot(dataset, i, use.imputed.data=use.imputed.data) cpc <- matrix(rep(1, num.nodes*num.nodes), nrow = num.nodes, ncol = num.nodes) dag <- hc( data, node.sizes, scoring.func, cpc, cont.nodes, ess = ess, tabu.tenure = tabu.tenure, max.parents = max.parents, init.net = in.dag, wm.max=wm.max, layering=layering, layer.struct=layer.struct, mandatory.edges = mandatory.edges) finalPDAG <- finalPDAG + dag.to.cpdag( dag, layering, layer.struct ) } wpdag(bn) <- finalPDAG } else { if (is.null(initial.cpc)) { cpc <- matrix(rep(1, num.nodes*num.nodes), nrow = num.nodes, ncol = num.nodes) } else { cpc <- initial.cpc } dag(bn) <- hc( data, node.sizes, scoring.func, cpc, cont.nodes, ess = ess, tabu.tenure = tabu.tenure, max.parents = max.parents, init.net = in.dag, wm.max=wm.max, layering=layering, layer.struct=layer.struct, mandatory.edges = mandatory.edges) } bnstruct.end.log("learning using HC completed.") } if (algo == "mmhc") { if ( max.fanin < max.parents) { bnstruct.log ("MMHC uses 'max.fanin', ", "but apparently you set 'max.parents', ", "changing accordingly.") max.parents <- max.fanin max.parents.layers <- max.fanin.layers } bnstruct.start.log("learning the structure using MMHC ...") if (!is.null(init.net)) in.dag <- dag(init.net) else in.dag <- NULL if (bootstrap) { finalPDAG <- matrix(0,num.nodes,num.nodes) for( i in seq_len(num.boots(dataset)) ) { data <- boot(dataset, i, use.imputed.data=use.imputed.data) if (use.cpc){ if (!is.null(initial.cpc)) { cpc <- initial.cpc } else { cpc <- mmpc( data, node.sizes, cont.nodes, alpha, layering, layer.struct, max.fanin=max.fanin, mandatory.edges = mandatory.edges ) } } else { cpc <- matrix(rep(1, num.nodes*num.nodes), nrow = num.nodes, ncol = num.nodes) } dag <- hc( data, node.sizes, scoring.func, cpc, cont.nodes, ess = ess, tabu.tenure = tabu.tenure, max.parents = max.parents, init.net = in.dag, wm.max=wm.max, layering=layering, layer.struct=layer.struct, mandatory.edges = mandatory.edges ) finalPDAG <- finalPDAG + dag.to.cpdag( dag, layering, layer.struct ) } wpdag(bn) <- finalPDAG } else { if (use.cpc) if (!is.null(initial.cpc)) { cpc <- initial.cpc } else { cpc <- mmpc( data, node.sizes, cont.nodes, alpha, layering, layer.struct, max.fanin=max.fanin, mandatory.edges = mandatory.edges ) } else cpc <- matrix(rep(1, num.nodes*num.nodes), nrow = num.nodes, ncol = num.nodes) dag(bn) <- hc( data, node.sizes, scoring.func, cpc, cont.nodes, ess = ess, tabu.tenure = tabu.tenure, max.parents = max.parents, init.net = in.dag, wm.max=wm.max, layering=layering, layer.struct=layer.struct, mandatory.edges = mandatory.edges ) } bnstruct.end.log("learning using MMHC completed.") } struct.algo(bn) <- algo return(bn) }) counts.to.probs <- function( counts ) { d <- dim(counts) if( length(d) == 1 ) return( counts / sum(counts) ) else { tmp.d <- c( prod(d[1:(length(d)-1)]), d[length(d)] ) dim(counts) <- tmp.d nor <- rowSums( counts ) nor <- nor + (nor == 0) counts <- counts / array(nor,tmp.d) dim(counts) <- d return( counts ) } }
library(carSurv) checkRes <- carVarSelect(carSurvScores=c(NA, 5, Inf, 6:10)) stopifnot(is.na(checkRes))
makeMOP7Function = function() { fn = function(x) { assertNumeric(x, len = 2L, any.missing = FALSE, all.missing = FALSE) return(.Call("mof_MOP7", x)) } makeMultiObjectiveFunction( name = "MOP7 function", id = sprintf("MOP7-%id-%io", 2L, 3L), description = "MOP7 function", fn = fn, par.set = makeNumericParamSet( len = 2L, id = "x", lower = rep(-400, 2L), upper = rep(400, 2L), vector = TRUE ), n.objectives = 3L ) } class(makeMOP7Function) = c("function", "smoof_generator") attr(makeMOP7Function, "name") = c("MOP7") attr(makeMOP7Function, "type") = c("multi-objective") attr(makeMOP7Function, "tags") = c("multi-objective")
HSIplotter <- function(SI, figure.name){ oldpar <- par("mfrow", "mgp", "mar") on.exit(par(oldpar)) nSI <- length(colnames(SI)) / 2 SI.cont <- c() for(i in 1:nSI){SI.cont[i] <- is.numeric(SI[1,2*i-1])} jpeg(filename=figure.name, units="in", width=12, height=4*ceiling(nSI/3), res=400) par(mfrow=c(ceiling(nSI/3),3), mgp=c(2,0.5,0), mar=c(3.5,3.5,3,1)) for(i in 1:nSI){ if(SI.cont[i] == TRUE){ plot(SI[,2*i-1], SI[,2*i], pch=19, col="black", xlab=colnames(SI)[2*i-1], ylab="Suitability Index", ylim=c(0,1)) lines(SI[,2*i-1], SI[,2*i], lwd=2, col="black") box() } else { barplot(SI[,2*i], names.arg=SI[,2*i-1], col="black", xlab=colnames(SI)[2*i-1], ylab="Suitability Index", ylim=c(0,1)) box() } } invisible(dev.off()) }
beaParamVals <- function(beaKey, setName, paramName) { beaMetaSpecs <- list( 'method' = 'GetParameterValues', 'UserID' = beaKey, 'datasetname'=setName, 'ParameterName'=paramName, 'ResultFormat' = 'json' ) beaResponse <- bea.R::beaGet(beaMetaSpecs, asList = TRUE, asTable = FALSE, isMeta = TRUE) return(beaResponse) }
context("CollapseCatalog") test_that("Collapse1536CatalogTo96 block 1", { skip_if("" == system.file(package = "BSgenome.Hsapiens.1000genomes.hs37d5")) stopifnot(requireNamespace("BSgenome.Hsapiens.1000genomes.hs37d5")) cat.SBS1536 <- ReadCatalog("testdata/regress.cat.sbs.1536.csv", ref.genome = "GRCh37", region = "genome", catalog.type = "counts") x1 <- Collapse1536CatalogTo96(cat.SBS1536) expect_equal(colSums(cat.SBS1536), colSums(x1)) expect_equal("SBS96Catalog", class(x1)[1]) cat.SBS1536.density <- TransformCatalog(cat.SBS1536, target.ref.genome = "GRCh37", target.region = "genome", target.catalog.type = "density") x2 <- Collapse1536CatalogTo96(cat.SBS1536.density) expect_equal(colSums(cat.SBS1536.density), colSums(x2)) expect_equal("SBS96Catalog", class(x2)[1]) cat.SBS1536.counts.signature <- TransformCatalog(cat.SBS1536, target.ref.genome = "GRCh37", target.region = "genome", target.catalog.type = "counts.signature") x3 <- Collapse1536CatalogTo96(cat.SBS1536.counts.signature) expect_equal(colSums(cat.SBS1536.counts.signature), colSums(x3)) expect_equal("SBS96Catalog", class(x3)[1]) cat.SBS1536.density.signature <- TransformCatalog(cat.SBS1536, target.ref.genome = "GRCh37", target.region = "genome", target.catalog.type = "density.signature") x4 <- Collapse1536CatalogTo96(cat.SBS1536.density.signature) expect_equal(colSums(cat.SBS1536.density.signature), colSums(x4)) expect_equal("SBS96Catalog", class(x4)[1]) }) test_that("Collapse192CatalogTo96 block 2", { skip_if("" == system.file(package = "BSgenome.Hsapiens.1000genomes.hs37d5")) stopifnot(requireNamespace("BSgenome.Hsapiens.1000genomes.hs37d5")) cat.SBS192 <- ReadCatalog("testdata/regress.cat.sbs.192.csv", ref.genome = "GRCh37", region = "transcript", catalog.type = "counts") x1 <- Collapse192CatalogTo96(cat.SBS192) expect_equal(colSums(cat.SBS192), colSums(x1)) expect_equal("SBS96Catalog", class(x1)[1]) cat.SBS192.density <- TransformCatalog(cat.SBS192, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "density") x2 <- Collapse192CatalogTo96(cat.SBS192.density) expect_equal(colSums(cat.SBS192.density), colSums(x2)) expect_equal("SBS96Catalog", class(x2)[1]) cat.SBS192.counts.signature <- TransformCatalog(cat.SBS192, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "counts.signature") x3 <- Collapse192CatalogTo96(cat.SBS192.counts.signature) expect_equal(colSums(cat.SBS192.counts.signature), colSums(x3)) expect_equal("SBS96Catalog", class(x3)[1]) cat.SBS192.density.signature <- TransformCatalog(cat.SBS192, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "density.signature") x4 <- Collapse192CatalogTo96(cat.SBS192.density.signature) expect_equal(colSums(cat.SBS192.density.signature), colSums(x4)) expect_equal("SBS96Catalog", class(x4)[1]) }) test_that("Collapse144CatalogTo78", { skip_if("" == system.file(package = "BSgenome.Hsapiens.1000genomes.hs37d5")) stopifnot(requireNamespace("BSgenome.Hsapiens.1000genomes.hs37d5")) cat.DBS144 <- ReadCatalog("testdata/regress.cat.dbs.144.csv", ref.genome = "GRCh37", region = "transcript", catalog.type = "counts") x1 <- Collapse144CatalogTo78(cat.DBS144) expect_equal(colSums(cat.DBS144), colSums(x1)) expect_equal("DBS78Catalog", class(x1)[1]) cat.DBS144.density <- TransformCatalog(cat.DBS144, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "density") x2 <- Collapse144CatalogTo78(cat.DBS144.density) expect_equal(colSums(cat.DBS144.density), colSums(x2)) expect_equal("DBS78Catalog", class(x2)[1]) cat.DBS144.counts.signature <- TransformCatalog(cat.DBS144, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "counts.signature") x3 <- Collapse144CatalogTo78(cat.DBS144.counts.signature) expect_equal(colSums(cat.DBS144.counts.signature), colSums(x3)) expect_equal("DBS78Catalog", class(x3)[1]) cat.DBS144.density.signature <- TransformCatalog(cat.DBS144, target.ref.genome = "GRCh37", target.region = "transcript", target.catalog.type = "density.signature") x4 <- Collapse144CatalogTo78(cat.DBS144.density.signature) expect_equal(colSums(cat.DBS144.density.signature), colSums(x4)) expect_equal("DBS78Catalog", class(x4)[1]) })
check_schema_df <- function(df, schema, success_msg = "Data is valid against the schema", fail_msg = "Data is invalid against the schema") { if (!requireNamespace("jsonvalidate", quietly = TRUE)) { stop( "Package \"jsonvalidate\" needed for this function to work. Please install it.", call. = FALSE ) } json_list <- df_to_json_list(df) results <- purrr::map(json_list, function(x) { jsonvalidate::json_validate( json = x, schema = schema, verbose = TRUE, greedy = TRUE, engine = "ajv" ) }) behavior <- "Data should conform to the schema" if (all(purrr::map_lgl(results, function(x) x))) { check_pass( msg = success_msg, behavior = behavior ) } else { return_data <- purrr::map( results, function(x) { dat <- attr(x, "errors") glue::glue("{dat$dataPath} {dat$message}") } ) check_fail( msg = fail_msg, behavior = behavior, data = return_data ) } }
test_that("Check bar-sd plots", { db1 <- plot_bar_sd(data_2w_Tdeath, Genotype, PI, TextXAngle = 45, ColPal = "muted", ColRev = T) + facet_wrap("Time") db1 expect_equal(db1$data, data_2w_Tdeath) expect_s3_class(db1, "gg") expect_equal(db1$theme$text$size, 20) expect_match(as.character(rlang::quo_get_expr(db1$labels$x)), "Genotype") expect_match(as.character(db1$labels$y), "PI") expect_match(as.character(rlang::quo_get_expr(db1$labels$fill)), "Genotype") expect_equal(db1$guides$x$angle, 45) }) test_that("Check bar-sd single colour plots", { db2 <- plot_bar_sd_sc(data_2w_Tdeath, Genotype, PI, TextXAngle = 45, colour = " facet_wrap("Time") db2 expect_equal(db2$data, data_2w_Tdeath) expect_s3_class(db2, "gg") expect_equal(db2$theme$text$size, 20) expect_match(as.character(rlang::quo_get_expr(db2$labels$x)), "Genotype") expect_match(as.character(db2$labels$y), "PI") expect_equal(db2$guides$x$angle, 45) })
brierScore <- function (dataSet, trainIndices, survModelFormula, linkFunc="logit", censColumn, idColumn=NULL) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!is.list(trainIndices)) {stop("Argument *trainIndices* is not in the correct format! Please specify a list.")} InputCheck1 <- all(sapply(1:length(trainIndices), function (x) is.integer(trainIndices [[x]]))) if(!InputCheck1) {stop("Sublists of *trainIndices* are not all integer values! Please specify a list of integer Indices.")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x + z.")} if(!any(names(dataSet)==censColumn)) {stop("Argument *censColumn* is not available in *dataSet*! Please specify the correct column name of the event indicator.")} B <- function(k) { probs <- estMargProb (LambdaSplit [[k]] [, "Lambda" ]) if(length(probs [-length(probs)])!=0) { brierVec <- as.numeric(tail(LambdaSplit [[k]] [, censColumn], 1) * (1 - tail(probs, 1))^2 + sum (probs [-length(probs)])) } else { brierVec <- as.numeric(tail(LambdaSplit [[k]] [, censColumn], 1) * (1 - tail(probs, 1))^2) } return(brierVec) } RET <- vector("list", length(trainIndices)) for(i in 1:length(trainIndices)) { TrainSet <- dataSet [trainIndices [[i]], ] if(length(trainIndices)!=1) { TestSet <- dataSet [-trainIndices [[i]], ] } else { TestSet <- TrainSet } if(!is.null(idColumn)) { TrainLong <- dataLongTimeDep (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn, idColumn=idColumn) } else { TrainLong <- dataLong (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn) } TrainLong <- dataCensoring (dataSetLong=TrainLong, respColumn="y", timeColumn="timeInt") if(!is.null(idColumn)) { TestLong <- dataLongTimeDep (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn, idColumn=idColumn) } else { TestLong <- dataLong (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn) } SurvnewFormula <- update(survModelFormula, y ~ timeInt + .) SurvFit <- glm (formula=SurvnewFormula, data=TrainLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) Check <- "error" %in% class(tryCatch(predict(SurvFit, TestLong, type="response"), error= function (e) e)) if(Check) { IndexFactor <- which(sapply(1:dim(TestLong)[2], function (x) is.factor(TestLong [, x]))==TRUE) TestLevelsFactor <- sapply(IndexFactor, function (x) levels(TestLong [, x])) TrainLevelsFactor <- sapply(IndexFactor, function (x) levels(TrainLong [, x+1])) InLevelsFactor <- lapply(1:length(TestLevelsFactor), function (x) which((TestLevelsFactor [[x]] %in% TrainLevelsFactor [[x]])==FALSE)) ExcludeRows <- lapply (1:length(IndexFactor), function (j) which(TestLong [, IndexFactor [j]] %in% TestLevelsFactor [[j]] [InLevelsFactor [[j]]])) ExcludeRows <- do.call(c, ExcludeRows) TestLong <- TestLong [-ExcludeRows, ] } Lambda <- predict(SurvFit, TestLong, type="response") LambdaSplit <- split(cbind(Lambda=Lambda, TestLong), TestLong$obj) RET [[i]] <- sapply(1:length(LambdaSplit), B) } RET <- do.call(cbind, RET) RET <- rowMeans(RET) return(RET) } tprUno <- function(timepoint, dataSet, trainIndices, survModelFormula, censModelFormula, linkFunc="logit", idColumn=NULL, timeAsFactor=TRUE) { if(length(timepoint)!=1 || !(timepoint==floor(timepoint))) {stop("Argument *timepoint* is not in the correct format! Please specify as integer scalar value.")} if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!is.list(trainIndices)) {stop("Argument *trainIndices* is not in the correct format! Please specify a list.")} InputCheck1 <- all(sapply(1:length(trainIndices), function (x) is.integer(trainIndices [[x]]))) if(!InputCheck1) {stop("Sublists of *trainIndices* are not all integer values! Please specify a list of integer Indices.")} if(length(trainIndices)!=1) { InputCheck2 <- all(sort(as.numeric(do.call(c, lapply(trainIndices, function (x) setdiff(1:dim(dataSet) [1], x)))))==(1:dim(dataSet) [1])) } else { InputCheck2 <- all(trainIndices [[1]]==(1:dim(dataSet) [1])) } if(!InputCheck2) {stop("Argument *trainIndices* does not contain cross validation samples! Please ensure that the union of all test indices equals the indices of the complete data set.")} if(!("formula" %in% class(censModelFormula))) {stop("*censModelFormula* is not of class formula! Please specify a valid formula, e. g. yCens ~ 1")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x")} if(!(any(names(dataSet)==idColumn) | is.null(idColumn))) {stop("Argument *idColumn* is not available in *dataSet*! Please specify the correct column name of the identification number.")} sens <- function(k) { sensNum <- sum((marker > k) * (newTime == timepoint) * newEvent / GT, na.rm = TRUE) sensDenom <- sum((newTime == timepoint) * newEvent / GT, na.rm = TRUE) if (sensDenom > 0) return(sensNum / sensDenom) else return(0) } markerList <- vector("list", length(trainIndices)) ExcludeRowsCensList <- vector("list", length(trainIndices)) ExcludeRowsDataSetList <- vector("list", length(trainIndices)) oneMinuslambdaList <- vector("list", length(trainIndices)) if(!is.null(idColumn)) { TrainLongFull <- dataLongTimeDep (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], idColumn=idColumn, timeAsFactor=timeAsFactor) } else { TrainLongFull <- dataLong (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], timeAsFactor=timeAsFactor) } for(i in 1:length(trainIndices)) { TrainSet <- dataSet [trainIndices [[i]], ] if(length(trainIndices)!=1) { TestSet <- dataSet [-trainIndices [[i]], ] } else { TestSet <- TrainSet } if(!is.null(idColumn)) { TrainLong <- dataLongTimeDep (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], idColumn=idColumn, timeAsFactor=timeAsFactor) } else { TrainLong <- dataLong (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], timeAsFactor=timeAsFactor) } TrainLong <- dataCensoring (dataSetLong=TrainLong, respColumn="y", timeColumn="timeInt") if(!is.null(idColumn)) { TestLong <- dataLongTimeDep (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], idColumn=idColumn, timeAsFactor=timeAsFactor) } else { TestLong <- dataLong (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], timeAsFactor=timeAsFactor) } CensnewFormula <- update(censModelFormula, yCens ~ timeInt + .) CensFit <- glm (formula=CensnewFormula, data=TrainLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) Check <- "error" %in% class(tryCatch(predict(CensFit, TestLong, type="response"), error= function (e) e)) if(Check) { IndexFactor <- which(sapply(1:dim(TestLong)[2], function (x) is.factor(TestLong [, x]))==TRUE) TestLevelsFactor <- sapply(IndexFactor, function (x) levels(TestLong [, x])) TrainLevelsFactor <- sapply(IndexFactor, function (x) levels(TrainLong [, x+1])) InLevelsFactor <- lapply(1:length(TestLevelsFactor), function (x) which((TestLevelsFactor [[x]] %in% TrainLevelsFactor [[x]])==FALSE)) ExcludeRows <- lapply (1:length(IndexFactor), function (j) which(TestLong [, IndexFactor [j]] %in% TestLevelsFactor [[j]] [InLevelsFactor [[j]]])) ExcludeRows <- do.call(c, ExcludeRows) ExcludeRowsConv <- vector("integer", length(ExcludeRows)) for(j in 1:length(ExcludeRows)) { I1 <- sapply(1:dim(TrainLongFull) [1], function(x) TrainLongFull [x, -1] == TestLong [ExcludeRows [j], -1]) ExcludeRowsConv [j] <- which(sapply(1:dim(I1) [2], function (x) all(I1 [, x]))==TRUE) } ExcludeRowsCensList [[i]] <- ExcludeRowsConv TestLong <- TestLong [-ExcludeRows, ] } oneMinuslambdaList [[i]] <- 1 - predict(CensFit, TestLong, type="response") SurvnewFormula <- update(survModelFormula, y ~ timeInt + .) SurvFit <- glm (formula=SurvnewFormula, data=TrainLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) if(timeAsFactor) { TestSetExt <- cbind(TestSet, timeInt=factor(TestSet [, as.character(survModelFormula) [2] ])) TrainSetExt <- cbind(TrainSet, timeInt=factor(TrainSet [, as.character(survModelFormula) [2] ])) } else{ TestSetExt <- cbind(TestSet, timeInt=TestSet [, as.character(survModelFormula) [2] ]) TrainSetExt <- cbind(TrainSet, timeInt=TrainSet [, as.character(survModelFormula) [2] ]) } Check <- "error" %in% class(tryCatch(predict(SurvFit, TestSetExt), error= function (e) e)) if(Check) { IndexFactor <- which(sapply(1:dim(TestSetExt)[2], function (x) is.factor(TestSetExt [, x]))==TRUE) TestLevelsFactor <- sapply(IndexFactor, function (x) levels(TestSetExt [, x])) TrainLevelsFactor <- sapply(IndexFactor, function (x) levels(TrainSetExt [, x])) InLevelsFactor <- lapply(1:length(TestLevelsFactor), function (x) which((TestLevelsFactor [[x]] %in% TrainLevelsFactor [[x]])==FALSE)) ExcludeRows <- lapply (1:length(IndexFactor), function (j) which(TestSetExt [, IndexFactor [j]] %in% TestLevelsFactor [[j]] [InLevelsFactor [[j]] ])) ExcludeRows <- do.call(c, ExcludeRows) ExcludeRowsConvShort <- vector("integer", length(ExcludeRows)) for(j in 1:length(ExcludeRows)) { I1 <- sapply(1:dim(dataSet) [1], function(x) dataSet [x, ] == TestSetExt [ExcludeRows [j], -dim(TestSetExt) [2] ]) ExcludeRowsConvShort [j] <- which(sapply(1:dim(I1) [2], function (x) all(I1 [, x]))==TRUE) } ExcludeRowsDataSetList [[i]] <- ExcludeRowsConvShort TestSetExt <- TestSetExt [-ExcludeRows, ] } markerList [[i]] <- predict(SurvFit, TestSetExt) } oneMinuslambda <- do.call(c, oneMinuslambdaList) ExcludeRowsCens <- do.call(c, ExcludeRowsCensList) ExcludeRowsDataSet <- do.call(c, ExcludeRowsDataSetList) if(!is.null(ExcludeRowsCens)) { TrainLongFullExc <- TrainLongFull [-ExcludeRowsCens, ] } else { TrainLongFullExc <- TrainLongFull } G <- aggregate(oneMinuslambda ~ obj, FUN = cumprod, data = TrainLongFullExc, simplify = FALSE) if(!is.null(ExcludeRowsDataSet)) { newEvent <- dataSet [-ExcludeRowsDataSet, as.character(censModelFormula) [2]] newTime <- dataSet [-ExcludeRowsDataSet, as.character(survModelFormula) [2]] } else { newEvent <- dataSet [, as.character(censModelFormula) [2]] newTime <- dataSet [, as.character(survModelFormula) [2]] } n <- length(newEvent) if(is.null(idColumn)) { GT <- sapply(1:n, function(u){ if (newTime[u] > 1) return(G[[2]] [u] [[1]] [newTime[u]-1]) else return(1) } ) } else{ GT <- sapply(1:n, function(u){ if (newTime[u] > 1) return(G[[2]] [TrainLongFullExc [dataSet[u, idColumn], "obj"] ] [[1]] [newTime[u]-1]) else return(1) } ) } marker <- do.call(c, markerList) RET <- sapply(marker, sens) orderMarker <- order(marker) tempDat <- data.frame(cutoff = marker[orderMarker], tpr = RET[orderMarker]) rownames(tempDat) <- 1:dim(tempDat) [1] RET <- list(Output=tempDat, Input=list(timepoint=timepoint, dataSet=dataSet, trainIndices=trainIndices, survModelFormula=survModelFormula, censModelFormula=censModelFormula, linkFunc=linkFunc, idColumn=idColumn, Short=FALSE, timeAsFactor=timeAsFactor, orderMarker=orderMarker)) class(RET) <- "discSurvTprUno" return(RET) } print.discSurvTprUno <- function (x, ...) { x$Output[, "cutoff"] <- round(x$Output[, "cutoff"], 4) if(!any(is.na(x$Output[, "tpr"]))) { x$Output[, "tpr"] <- round(x$Output[, "tpr"], 4) } print(x$Output, ...) } plot.discSurvTprUno <- function (x, ...) { if(any(is.na(x$Output [, "tpr"]))) { return("No plot available, because there are missing values in tpr!") } plot(x=x$Output [, "cutoff"], y=x$Output [, "tpr"], xlab="Cutoff", ylab="Tpr", las=1, type="l", main=paste("Tpr(c, t=", x$Input$timepoint, ")", sep=""), ...) } tprUnoShort <- function (timepoint, marker, newTime, newEvent, trainTime, trainEvent) { dataSetShort <- data.frame(trainTime=trainTime, trainEvent=trainEvent) dataSetLongCensTrans <- dataCensoringShort (dataSet=dataSetShort, eventColumns="trainEvent", timeColumn="trainTime") markerInput <- marker newEventInput <- newEvent newTimeInput <- newTime selectInd <- newTime %in% intersect(newTime, trainTime) marker <- marker[selectInd] newEvent <- newEvent[selectInd] newTime <- newTime[selectInd] if(length(newTime)==0){ orderMarker <- order(marker) tempDat <- data.frame(cutoff = marker[orderMarker], tpr = NA) rownames(tempDat) <- 1:dim(tempDat) [1] RET <- list(Output=tempDat, Input=list(timepoint=timepoint, marker=markerInput, newTime=newTimeInput, newEvent=newEventInput, trainTime=trainTime, trainEvent=trainEvent, Short=TRUE, selectInd=selectInd, orderMarker=orderMarker)) class(RET) <- "discSurvTprUno" return(RET) } tempLifeTab <- lifeTable (dataSet=dataSetLongCensTrans, timeColumn="timeCens", censColumn="yCens") preG <- tempLifeTab [[1]] [, "S"] GT <- c(1, preG) GT <- GT [newTime] sens <- function(k) { sensNum <- sum( (marker > k) * (newTime == timepoint) * newEvent / GT) sensDenom <- sum( (newTime == timepoint) * newEvent / GT) if (sensDenom > 0) { return(sensNum / sensDenom) } else{ return(NA) } } RET <- sapply(marker, sens) orderMarker <- order(marker) tempDat <- data.frame(cutoff = marker[orderMarker], tpr = RET[orderMarker]) rownames(tempDat) <- 1:dim(tempDat) [1] RET <- list(Output=tempDat, Input=list(timepoint=timepoint, marker=markerInput, newTime=newTimeInput, newEvent=newEventInput, trainTime=trainTime, trainEvent=trainEvent, Short=TRUE, selectInd=selectInd, orderMarker=orderMarker)) class(RET) <- "discSurvTprUno" return(RET) } fprUno <- function(timepoint, dataSet, trainIndices, survModelFormula, censModelFormula, linkFunc="logit", idColumn=NULL, timeAsFactor=TRUE) { if(length(timepoint)!=1 || !(timepoint==floor(timepoint))) {stop("Argument *timepoint* is not in the correct format! Please specify as integer scalar value.")} if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!is.list(trainIndices)) {stop("Argument *trainIndices* is not in the correct format! Please specify a list.")} InputCheck1 <- all(sapply(1:length(trainIndices), function (x) is.integer(trainIndices [[x]]))) if(!InputCheck1) {stop("Sublists of *trainIndices* are not all integer values! Please specify a list of integer Indices.")} if(length(trainIndices)!=1) { InputCheck2 <- all(sort(as.numeric(do.call(c, lapply(trainIndices, function (x) setdiff(1:dim(dataSet) [1], x)))))==(1:dim(dataSet) [1])) } else { InputCheck2 <- all(trainIndices [[1]]==(1:dim(dataSet) [1])) } if(!InputCheck2) {stop("Argument *trainIndices* does not contain cross validation samples! Please ensure that the union of all test indices equals the indices of the complete data set.")} if(!("formula" %in% class(censModelFormula))) {stop("*censModelFormula* is not of class formula! Please specify a valid formula, e. g. yCens ~ 1.")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x")} if(!(any(names(dataSet)==idColumn) | is.null(idColumn))) {stop("Argument *idColumn* is not available in *dataSet*! Please specify the correct column name of the identification number.")} spec <- function(k){ specNum <- sum( (marker <= k) * (newTime > timepoint), na.rm = TRUE) specDenom <- sum(newTime > timepoint, na.rm = TRUE) if (specDenom > 0) return(specNum / specDenom) else return(0) } RET <- vector("list", length(trainIndices)) markerList <- vector("list", length(trainIndices)) ExcludeRowsDataSetList <- vector("list", length(trainIndices)) for(i in 1:length(trainIndices)) { TrainSet <- dataSet [trainIndices [[i]], ] if(length(trainIndices)!=1) { TestSet <- dataSet [-trainIndices [[i]], ] } else { TestSet <- TrainSet } if(!is.null(idColumn)) { TrainLong <- dataLongTimeDep (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], idColumn=idColumn, timeAsFactor=timeAsFactor) } else { TrainLong <- dataLong (dataSet=TrainSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], timeAsFactor=timeAsFactor) } TrainLong <- dataCensoring (dataSetLong=TrainLong, respColumn="y", timeColumn="timeInt") if(!is.null(idColumn)) { TestLong <- dataLongTimeDep (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], idColumn=idColumn, timeAsFactor=timeAsFactor) } else { TestLong <- dataLong (dataSet=TestSet, timeColumn=as.character(survModelFormula) [2], censColumn=as.character(censModelFormula) [2], timeAsFactor=timeAsFactor) } SurvnewFormula <- update(survModelFormula, y ~ timeInt + .) SurvFit <- glm (formula=SurvnewFormula, data=TrainLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) if(timeAsFactor) { TestSetExt <- cbind(TestSet, timeInt=factor(TestSet [, as.character(survModelFormula) [2] ])) TrainSetExt <- cbind(TrainSet, timeInt=factor(TrainSet [, as.character(survModelFormula) [2] ])) } else{ TestSetExt <- cbind(TestSet, timeInt=TestSet [, as.character(survModelFormula) [2] ]) TrainSetExt <- cbind(TrainSet, timeInt=TrainSet [, as.character(survModelFormula) [2] ]) } Check <- "error" %in% class(tryCatch(predict(SurvFit, TestSetExt), error= function (e) e)) if(Check) { IndexFactor <- which(sapply(1:dim(TestSetExt)[2], function (x) is.factor(TestSetExt [, x]))==TRUE) TestLevelsFactor <- sapply(IndexFactor, function (x) levels(TestSetExt [, x])) TrainLevelsFactor <- sapply(IndexFactor, function (x) levels(TrainSet [, x])) InLevelsFactor <- lapply(1:length(TestLevelsFactor), function (x) which((TestLevelsFactor [[x]] %in% TrainLevelsFactor [[x]])==FALSE)) ExcludeRows <- lapply (1:length(IndexFactor), function (j) which(TestSetExt [, IndexFactor [j]] %in% TestLevelsFactor [[j]] [InLevelsFactor [[j]] ])) ExcludeRows <- do.call(c, ExcludeRows) ExcludeRowsConvShort <- vector("integer", length(ExcludeRows)) for(j in 1:length(ExcludeRows)) { I1 <- sapply(1:dim(dataSet) [1], function(x) dataSet [x, ] == TestSetExt [ExcludeRows [j], -dim(TestSetExt) [2] ]) ExcludeRowsConvShort [j] <- which(sapply(1:dim(I1) [2], function (x) all(I1 [, x]))==TRUE) } ExcludeRowsDataSetList [[i]] <- ExcludeRowsConvShort TestSetExt <- TestSetExt [-ExcludeRows, ] } markerList [[i]] <- predict(SurvFit, TestSetExt) } marker <- do.call(c, markerList) ExcludeRowsDataSet <- do.call(c, ExcludeRowsDataSetList) if(!is.null(ExcludeRowsDataSet)) { newEvent <- dataSet [-ExcludeRowsDataSet, as.character(censModelFormula) [2]] newTime <- dataSet [-ExcludeRowsDataSet, as.character(survModelFormula) [2]] } else { newEvent <- dataSet [, as.character(censModelFormula) [2]] newTime <- dataSet [, as.character(survModelFormula) [2]] } RET <- sapply(marker, spec) orderMarker <- order(marker) tempDat <- data.frame(cutoff = marker[orderMarker], fpr = 1-RET[orderMarker]) rownames(tempDat) <- 1:dim(tempDat) [1] RET <- list(Output=tempDat, Input=list(timepoint=timepoint, dataSet=dataSet, trainIndices=trainIndices, survModelFormula=survModelFormula, censModelFormula=censModelFormula, linkFunc=linkFunc, idColumn=idColumn, Short=FALSE, timeAsFactor=timeAsFactor, orderMarker=orderMarker)) class(RET) <- "discSurvFprUno" return(RET) } print.discSurvFprUno <- function (x, ...) { x$Output[, "cutoff"] <- round(x$Output[, "cutoff"], 4) if(!any(is.na(x$Output[, "fpr"]))) { x$Output[, "fpr"] <- round(x$Output[, "fpr"], 4) } print(x$Output, ...) } plot.discSurvFprUno <- function (x, ...) { if(any(is.na(x$Output [, "fpr"]))) { return("No plot available, because there are missing values in tpr!") } plot(x=x$Output [, "cutoff"], y=x$Output [, "fpr"], xlab="Cutoff", ylab="Fpr", las=1, type="l", main=paste("Fpr(c, t=", x$Input$timepoint, ")", sep=""), ...) } fprUnoShort <- function (timepoint, marker, newTime) { spec <- function(k){ specNum <- sum( (marker <= k) * (newTime > timepoint) ) specDenom <- sum(newTime > timepoint) if (specDenom > 0) { return(specNum / specDenom) } else { return(NA) } } RET <- sapply(marker, spec) orderMarker <- order(marker) tempDat <- data.frame(cutoff = marker[orderMarker], fpr = 1 - RET[orderMarker]) rownames(tempDat) <- 1:dim(tempDat) [1] RET <- list(Output=tempDat, Input=list(timepoint=timepoint, marker=marker, newTime=newTime, Short=TRUE, orderMarker=orderMarker)) class(RET) <- "discSurvFprUno" return(RET) } aucUno <- function (tprObj, fprObj) { if(class(tprObj)!="discSurvTprUno") {stop("This object has not the appropriate class! Please specify an object of class *discSurvTprUno*.")} if(class(fprObj)!="discSurvFprUno") {stop("This object has not the appropriate class! Please specify an object of class *discSurvFprUno*.")} if(tprObj$Input$Short!=fprObj$Input$Short) {stop("Tpr and fpr were computed using different functions! Please ensure that both are estimated either by the cross validated version or the short version.")} if(!tprObj$Input$Short) { InputCheck <- identical(tprObj$Input, fprObj$Input) if(!InputCheck) {stop("Some input parameters of *tprObj* or *fprObj* are not identical! Please check if both objects were estimated using exact identical input values.")} } else { InputCheck1 <- identical(tprObj$Input$timepoint, fprObj$Input$timepoint) InputCheck2 <- identical(tprObj$Input$marker, fprObj$Input$marker) InputCheck <- all(InputCheck1, InputCheck2) if(!InputCheck) {stop("Some input parameters of *tprObj* or *fprObj* are not identical! Please check if both objects were estimated using exact identical input values.")} } if(tprObj$Input$Short){ tpr <- c(1, tprObj$Output$tpr) fpr <- c(1, fprObj$Output$fpr[ tprObj$Input$selectInd[tprObj$Input$orderMarker] ]) } else{ tpr <- c(1, tprObj$Output$tpr) fpr <- c(1, fprObj$Output$fpr) } trapz <- function (x, y){ idx = 2:length(x) return(as.double((x[idx] - x[idx - 1]) %*% (y[idx] + y[idx - 1]))/2) } Output <- - trapz(fpr, tpr) names(Output) <- paste("AUC(t=", tprObj$Input$timepoint, ")", sep="") auc <- list(Output = Output, Input=list(tprObj=tprObj, fprObj=fprObj)) class(auc) <- "discSurvAucUno" return(auc) } print.discSurvAucUno <- function (x, ...) { print(round(x$Output, 4)) } plot.discSurvAucUno <- function (x, ...) { tprVal <- x$Input$tprObj$Output [, "tpr"] if(x$Input$tprObj$Input$Short) { fprVal <- x$Input$fprObj$Output [ x$Input$tprObj$Input$selectInd[ x$Input$tprObj$Input$orderMarker], "fpr"] } else{ fprVal <- x$Input$fprObj$Output [, "fpr"] } if(any(is.na(tprVal)) | any(is.na(fprVal))) { return("No plot available, because either tprVal or fprVal contains missing values!") } plot(x=fprVal, y=tprVal, xlab="Fpr", ylab="Tpr", las=1, type="l", main=paste("ROC(c, t=", x$Input$tprObj$Input$timepoint, ")", sep=""), ...) lines(x=seq(0, 1, length.out=500), y=seq(0, 1, length.out=500), lty=2) } concorIndex <- function (aucObj, printTimePoints=FALSE) { if(class(aucObj)!="discSurvAucUno") {stop("This object has not the appropriate class! Please specify an object of class *discSurvAucUno*.")} if(aucObj$Input$tprObj$Input$Short) { marker <- aucObj$Input$tprObj$Input$marker newTime <- aucObj$Input$tprObj$Input$newTime newEvent <- aucObj$Input$tprObj$Input$newEvent trainTime <- aucObj$Input$tprObj$Input$trainTime trainEvent <- aucObj$Input$tprObj$Input$trainEvent MaxTime <- max(trainTime)-1 AUCalltime <- vector("numeric", MaxTime) for(i in 1:MaxTime) { tempTPR <- tprUnoShort (timepoint=i, marker=marker, newTime=newTime, newEvent=newEvent, trainTime=trainTime, trainEvent=trainEvent) tempFPR <- fprUnoShort (timepoint=i, marker=marker, newTime=newTime) AUCalltime [i] <- as.numeric(aucUno (tprObj=tempTPR, fprObj=tempFPR)$Output) if(printTimePoints) {cat("Progress:", round(i/MaxTime*100, 2), "%;", "Timepoint =", i, "\n")} } tempLifeTab <- lifeTable (dataSet=data.frame(trainTime=trainTime, trainEvent=trainEvent), timeColumn="trainTime", censColumn="trainEvent") MargHaz <- tempLifeTab [[1]] [, "hazard"] MargSurv <- estSurv(MargHaz) MargProb <- estMargProb(MargHaz) } else { MaxTime <- max(aucObj$Input$tprObj$Input$dataSet [, as.character(aucObj$Input$tprObj$Input$survModelFormula) [2] ])-1 DataSet <- aucObj$Input$tprObj$Input$dataSet TrainIndices <- aucObj$Input$tprObj$Input$trainIndices SurvModelFormula <- aucObj$Input$tprObj$Input$survModelFormula CensModelFormula <- aucObj$Input$tprObj$Input$censModelFormula LinkFunc <- aucObj$Input$tprObj$Input$linkFunc IdColumn <- aucObj$Input$tprObj$Input$idColumn timeAsFactor <- aucObj$Input$tprObj$Input$timeAsFactor AUCalltime <- vector("numeric", MaxTime) for(i in 1:MaxTime) { tempTPR <- tprUno (timepoint=i, dataSet=DataSet, trainIndices=TrainIndices, survModelFormula=SurvModelFormula, censModelFormula=CensModelFormula, linkFunc=LinkFunc, idColumn=IdColumn, timeAsFactor=timeAsFactor) tempFPR <- fprUno (timepoint=i, dataSet=DataSet, trainIndices=TrainIndices, survModelFormula=SurvModelFormula, censModelFormula=CensModelFormula, linkFunc=LinkFunc, idColumn=IdColumn, timeAsFactor=timeAsFactor) AUCalltime [i] <- as.numeric(aucUno (tprObj=tempTPR, fprObj=tempFPR)$Output) if(printTimePoints) {cat("Progress:", round(i/MaxTime*100, 2), "%;", "Timepoint =", i, "\n")} } if(!is.null(IdColumn)) { TrainLongFull <- dataLongTimeDep (dataSet=DataSet, timeColumn=as.character( SurvModelFormula) [2], censColumn=as.character( CensModelFormula) [2], idColumn=IdColumn, timeAsFactor=timeAsFactor) } else { TrainLongFull <- dataLong (dataSet=DataSet, timeColumn=as.character( SurvModelFormula) [2], censColumn=as.character( CensModelFormula) [2], timeAsFactor=timeAsFactor) } MargFormula <- y ~ timeInt MargFit <- glm (formula=MargFormula, data=TrainLongFull, family=binomial(link=LinkFunc), control=glm.control(maxit=2500)) if(timeAsFactor) { PredMargData <- data.frame(timeInt=factor( min(TrainLongFull [, as.character(SurvModelFormula) [2] ]): max(TrainLongFull [, as.character(SurvModelFormula) [2] ]))) } else{ PredMargData <- data.frame(timeInt=min( TrainLongFull [, as.character(SurvModelFormula) [2] ]): max(TrainLongFull [, as.character(SurvModelFormula) [2] ])) } MargHaz <- as.numeric(predict(MargFit, PredMargData, type="response")) MargSurv <- estSurv(MargHaz) MargProb <- estMargProb(MargHaz) } weights1 <- MargProb * MargSurv / sum(MargProb * MargSurv) AUCind <- is.finite(AUCalltime) & is.finite(weights1[-length(weights1)]) Concor <- sum( AUCalltime[AUCind] * weights1[-length(weights1)][AUCind] )/ sum( weights1[-length(weights1)][AUCind] ) names(Concor) <- "C*" names(AUCalltime) <- paste("AUC(t=", 1:MaxTime, "|x)", sep="") Output <- list(Output=Concor, Input=list(aucObj=aucObj, AUC=AUCalltime, MargProb=MargProb, MargSurv=MargSurv)) class(Output) <- "discSurvConcorIndex" return(Output) } print.discSurvConcorIndex <- function (x, ...) { print(round(x$Output, 4)) } summary.discSurvConcorIndex <- function (object, ...) { cat("Concordance: Should be higher than 0.5 (random assignment)", "\n") print(round(object$Output, 4)) cat("\n", "AUC(t): Should be higher than 0.5 for all time points (random assignment)", "\n") print(round(object$Input$AUC, 4)) cat("\n", "Marginal P(T=t) without covariates (used in weighting)", "\n") print(round(object$Input$MargProb, 4)) cat("\n", "Marginal S(T=t) without covariates (used in weighting)", "\n") print(round(object$Input$MargSurv, 4)) } print.discSurvPredErrDisc <- function (x, ...) { print(round(x$Output$predErr, 4)) } summary.discSurvPredErrDisc <- function (object, ...) { cat("Prediction error curve: Should be lower than 0.25 (random assignment) for all timepoints", "\n") print(round(object$Output$predErr, 4)) cat("Corresponding weights given by the censoring survival function", "\n") tempDat <- lapply(1:length(object$Output$weights), function (x) {round(object$Output$weights [[x]], 4)}) names(tempDat) <- paste("Time interval = ", 1:length(object$Output$weights), sep="") print(tempDat) } predErrDiscShort <- function (timepoints, estSurvList, newTime, newEvent, trainTime, trainEvent) { WeightFunction <- function () { PartialSum1 <- newEventTemp * (1 - Sobs) / GT PartialSum2 <- Sobs / GTfixed return(PartialSum1 + PartialSum2) } predErr <- function () { sum(weights1[IncludeInd][finiteCheck] * (estSurvInd[IncludeInd][finiteCheck] - Sobs[IncludeInd][finiteCheck])^2) / sum(finiteCheck) } dataSetLong <- dataLong (dataSet=data.frame( trainTime=trainTime, trainEvent=trainEvent), timeColumn="trainTime", censColumn="trainEvent") dataSetLongCens <- dataCensoring (dataSetLong=dataSetLong, respColumn="y", timeColumn="timeInt") dataSetLongCens <- na.omit(dataSetLongCens) glmCovariateFree <- glm(yCens ~ timeInt, data=dataSetLongCens, family=binomial(), control=glm.control(maxit = 2500)) factorPrep <- factor(1:max(as.numeric(as.character(dataSetLongCens$timeInt)))) GT_est <- cumprod(1 - predict(glmCovariateFree, newdata=data.frame(timeInt=factorPrep), type="response")) predErrorValues <- vector("numeric", length(timepoints)) StoreWeights <- vector("list", length(timepoints)) for( k in 1:length(timepoints) ) { newTimeTemp <- newTime newEventTemp <- newEvent IncludeInd <- ifelse(newTimeTemp < timepoints [k] & newEventTemp == 0, FALSE, TRUE) GT <- c(1, GT_est) GT <- GT [newTimeTemp] GTfixed <- GT_est [timepoints [k] ] Sobs <- ifelse(timepoints [k] < newTimeTemp, 1, 0) estSurvInd <- sapply(1:length(estSurvList), function (x) estSurvList [[x]] [timepoints [k] ]) weights1 <- WeightFunction () StoreWeights [[k]] <- weights1 finiteCheck <- is.finite(weights1[IncludeInd]) & is.finite(estSurvInd[IncludeInd]) & is.finite(Sobs[IncludeInd]) predErrorValues [k] <- predErr () } names(predErrorValues) <- paste("T=", timepoints, sep="") RET <- list(Output=list(predErr = predErrorValues, weights = StoreWeights), Input=list(timepoints=timepoints, estSurvList=estSurvList, newTime=newTime, newEvent=newEvent, trainTime=trainTime, trainEvent=trainEvent, Short=TRUE)) class(RET) <- "discSurvPredErrDisc" return(RET) } intPredErrDisc <- function (predErrObj, tmax=NULL) { if(!(class(predErrObj)=="discSurvPredErrDisc")) { stop("Object *predErrObj* is not of class *discSurvPredErrDisc*! Please give an appropriate objecte type as input.")} predErrDiscTime <- function (t) { predErrDiscShort (timepoints= t, estSurvList=EstSurvList, newTime=NewTime, newEvent=NewEvent, trainTime=TrainTime, trainEvent=TrainEvent) } MaxTime <- max(predErrObj$Input$trainTime) if(!is.null(tmax)) { if(tmax <= MaxTime) { MaxTime <- tmax } else { warning("Argument *tmax* is higher than the latest observed interval in training data. Only prediction errors up to the latest observed interval time are given.") } } EstSurvList <- predErrObj$Input$estSurvList NewTime <- predErrObj$Input$newTime NewEvent <- predErrObj$Input$newEvent TrainTime <- predErrObj$Input$trainTime TrainEvent <- predErrObj$Input$trainEvent TrainLongFull <- dataLong (dataSet=data.frame(TrainTime=TrainTime, TrainEvent=TrainEvent), timeColumn="TrainTime", censColumn="TrainEvent") MargFormula <- y ~ timeInt MargFit <- glm (formula=MargFormula, data=TrainLongFull, family=binomial(), control=glm.control(maxit=2500)) PredMargData <- data.frame(timeInt=factor(1:MaxTime)) MargHaz <- as.numeric(predict(MargFit, PredMargData, type="response")) MargProbs <- estMargProb(MargHaz) PredsErrorCurve <- predErrDiscTime (1:MaxTime)$Output$predErr IncludedIndices <- is.finite(PredsErrorCurve) & is.finite(MargProbs) PredsErrorCurve <- PredsErrorCurve [IncludedIndices] MargProbs <- as.numeric(MargProbs [IncludedIndices]) Result <- sum(PredsErrorCurve * MargProbs) / sum(MargProbs) return(c(IntPredErr=Result)) } martingaleResid <- function (dataSet, survModelFormula, censColumn, linkFunc="logit", idColumn=NULL) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x + z.")} if(!any(names(dataSet)==censColumn)) {stop("Argument *censColumn* is not available in *dataSet*! Please specify the correct column name of the event indicator.")} if(!(any(names(dataSet)==idColumn) | is.null(idColumn))) {stop("Argument *idColumn* is not available in *dataSet*! Please specify the correct column name of the identification numbers of persons.")} if(!is.null(idColumn)) { dataSetLong <- dataLongTimeDep (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn, idColumn=idColumn) } else { dataSetLong <- dataLong (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn) } NewFormula <- update(survModelFormula, y ~ timeInt + .) glmFit <- glm(formula=NewFormula, data=dataSetLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) hazards <- predict(glmFit, type="response") splitHazards <- split(hazards, dataSetLong$obj) splitY <- split(dataSetLong$y, dataSetLong$obj) martResid <- sapply(1:length(splitY), function (x) sum(splitY [[x]] - splitHazards [[x]])) Output <- list(Output=list(MartingaleResid=martResid, GlmFit=glmFit), Input=list(dataSet=dataSet, survModelFormula=survModelFormula, censColumn=censColumn, linkFunc=linkFunc, idColumn=idColumn)) class(Output) <- "discSurvMartingaleResid" return(Output) } print.discSurvMartingaleResid <- function (x, ...) { print(round(x$Output$MartingaleResid, 4)) } plot.discSurvMartingaleResid <- function (x, ...) { if(!is.null(x$Input$idColumn)) { dataSetLong <- dataLongTimeDep (dataSet=x$Input$dataSet, timeColumn=as.character(x$Input$survModelFormula) [2], censColumn=x$Input$censColumn, idColumn=x$Input$idColumn) } else { dataSetLong <- dataLong (dataSet=x$Input$dataSet, timeColumn=as.character(x$Input$survModelFormula) [2], censColumn=x$Input$censColumn) } splitDataSetLong <- split(dataSetLong, dataSetLong$obj) tailSplitDataSetLong <- lapply(splitDataSetLong, function (x) tail(x, 1)) tailSplitDataSetLong <- do.call(rbind, tailSplitDataSetLong) LengthSurvFormula <- length(attr(terms(x$Input$survModelFormula), "term.labels")) CovarSurvFormula <- attr(terms(x$Input$survModelFormula), "term.labels") for(i in 1:LengthSurvFormula) { tempData <- data.frame(x=tailSplitDataSetLong [, CovarSurvFormula [i] ], y=x$Output$MartingaleResid) tempData <- tempData [order(tempData$x), ] plot(x=tempData$x, y=tempData$y, las=1, xlab=CovarSurvFormula [i], ylab="Martingale Residuals", ...) if(is.numeric(tempData$x)) { loessPred <- predict(loess(formula=y ~ x, data=tempData)) lines(x=tempData$x, y=loessPred) } abline(h=0, lty=2) } } devResid <- function (dataSet, survModelFormula, censColumn, linkFunc="logit", idColumn=NULL) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x + z.")} if(!any(names(dataSet)==censColumn)) {stop("Argument *censColumn* is not available in *dataSet*! Please specify the correct column name of the event indicator.")} if(!(any(names(dataSet)==idColumn) | is.null(idColumn))) {stop("Argument *idColumn* is not available in *dataSet*! Please specify the correct column name of the identification numbers of persons.")} SquDevResid <- function (x) {-2*sum(splitY [[x]] * log(splitHazards [[x]]) + (1 - splitY [[x]]) * log(1 - splitHazards [[x]] ))} if(!is.null(idColumn)) { dataSetLong <- dataLongTimeDep (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn, idColumn=idColumn) } else { dataSetLong <- dataLong (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn) } NewFormula <- update(survModelFormula, y ~ timeInt + .) glmFit <- glm(formula=NewFormula, data=dataSetLong, family=binomial(link=linkFunc), control=glm.control(maxit=2500)) hazards <- predict(glmFit, type="response") splitHazards <- split(hazards, dataSetLong$obj) splitY <- split(dataSetLong$y, dataSetLong$obj) Residuals <- sapply(1:length(splitY), SquDevResid) Output <- list(Output=list(DevResid=sqrt(Residuals), GlmFit=glmFit), Input=list(dataSet=dataSet, survModelFormula=survModelFormula, censColumn=censColumn, linkFunc=linkFunc, idColumn=idColumn)) class(Output) <- "discSurvDevResid" return(Output) } print.discSurvDevResid <- function (x, ...) { print(round(x$Output$DevResid, 4)) } adjDevResid <- function (dataSet, survModelFormula, censColumn, linkFunc="logit", idColumn=NULL) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!("formula" %in% class(survModelFormula))) {stop("*survModelFormula* is not of class formula! Please specify a valid formula, e. g. y ~ x + z.")} if(!any(names(dataSet)==censColumn)) {stop("Argument *censColumn* is not available in *dataSet*! Please specify the correct column name of the event indicator.")} if(!(any(names(dataSet)==idColumn) | is.null(idColumn))) {stop("Argument *idColumn* is not available in *dataSet*! Please specify the correct column name of the identification numbers of persons.")} AdjDevResid <- function (x) { LogTerm1 <- ifelse(splitY [[x]]==1, -log(splitHazards [[x]]), 0) LogTerm2 <- ifelse(splitY [[x]]==0, -log (1 - splitHazards [[x]]), 0) FirstPartialSum <- sum(sign(splitY [[x]] - splitHazards [[x]]) * (sqrt(splitY [[x]] * LogTerm1 + (1 - splitY [[x]]) * LogTerm2))) SecondPartialSum <- sum( (1 - 2*splitHazards [[x]]) / sqrt (splitHazards [[x]] * (1 - splitHazards [[x]]) * 36) ) return(FirstPartialSum + SecondPartialSum) } if(!is.null(idColumn)) { dataSetLong <- dataLongTimeDep (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn, idColumn=idColumn) } else { dataSetLong <- dataLong (dataSet=dataSet, timeColumn=as.character(survModelFormula) [2], censColumn=censColumn) } NewFormula <- update(survModelFormula, y ~ timeInt + .) glmFit <- glm(formula=NewFormula, data=dataSetLong, family=binomial(link=linkFunc)) hazards <- predict(glmFit, type="response") splitHazards <- split(hazards, dataSetLong$obj) splitY <- split(dataSetLong$y, dataSetLong$obj) Residuals <- sapply(1:length(splitY), AdjDevResid) Output <- list(Output=list(AdjDevResid=Residuals, GlmFit=glmFit), Input=list(dataSet=dataSet, survModelFormula=survModelFormula, censColumn=censColumn, linkFunc=linkFunc, idColumn=idColumn)) class(Output) <- "discSurvAdjDevResid" return(Output) } print.discSurvAdjDevResid <- function (x, ...) { print(round(x$Output$AdjDevResid, 4)) } plot.discSurvAdjDevResid <- function (x, ...) { qqnorm (y=x$Output$AdjDevResid, las=1, ...) qqline(y=x$Output$AdjDevResid, ...) } adjDevResidShort <- function (dataSet, hazards) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!all(hazards>=0 & hazards<=1)) {stop("Argument *hazards* must contain probabilities in the closed interval from zero to one. Please verify that *hazards* are estimated hazard rates")} if(!(dim(dataSet)[1]==length(hazards))) {stop("The length of argument *hazards* must match the number of observations")} AdjDevResid <- function (x) { LogTerm1 <- ifelse(splitY [[x]]==1, -log(splitHazards [[x]]), 0) LogTerm2 <- ifelse(splitY [[x]]==0, -log (1 - splitHazards [[x]]), 0) FirstPartialSum <- sum(sign(splitY [[x]] - splitHazards [[x]]) * (sqrt(splitY [[x]] * LogTerm1 + (1 - splitY [[x]]) * LogTerm2))) SecondPartialSum <- sum( (1 - 2*splitHazards [[x]]) / sqrt (splitHazards [[x]] * (1 - splitHazards [[x]]) * 36) ) return(FirstPartialSum + SecondPartialSum) } splitHazards <- split(hazards, dataSet$obj) splitY <- split(dataSet$y, dataSet$obj) Residuals <- sapply(1:length(splitY), AdjDevResid) Output <- list(Output=list(AdjDevResid=Residuals), Input=list(dataSet=dataSet, hazards=hazards)) class(Output) <- "discSurvAdjDevResid" return(Output) } devResidShort <- function (dataSet, hazards) { if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")} if(!all(hazards>=0 & hazards<=1)) {stop("Argument *hazards* must contain probabilities in the closed interval from zero to one. Please verify that *hazards* are estimated hazard rates")} if(!(dim(dataSet)[1]==length(hazards))) {stop("The length of argument *hazards* must match the number of observations")} SquDevResid <- function (x) {-2*sum(splitY [[x]] * log(splitHazards [[x]]) + (1 - splitY [[x]]) * log(1 - splitHazards [[x]] ))} splitHazards <- split(hazards, dataSet$obj) splitY <- split(dataSet$y, dataSet$obj) Residuals <- sapply(1:length(splitY), SquDevResid) Output <- list(Output=list(DevResid=sqrt(Residuals)), Input=list(dataSet=dataSet, hazards=hazards)) class(Output) <- "discSurvDevResid" return(Output) } evalCindex <- function(marker, newTime, newEvent, trainTime, trainEvent){ tprFit <- tprUnoShort (timepoint = 1, marker, newTime, newEvent, trainTime, trainEvent) fprFit <- fprUnoShort(timepoint = 1, marker, newTime) aucFit <- aucUno(tprFit, fprFit) CFit <- unname(concorIndex(aucFit)$Output) return(CFit) } evalIntPredErr <- function(hazPreds, survPreds=NULL, newTimeInput, newEventInput, trainTimeInput, trainEventInput, testDataLong, tmax=NULL){ if( any(is.null(survPreds)) ){ oneMinusPredHaz <- 1 - hazPreds predSurv <- aggregate(formula=oneMinusPredHaz ~ obj, data=testDataLong, FUN=cumprod, na.action=NULL) pecObj <- predErrDiscShort(timepoints=1, estSurvList=predSurv[[2]], newTime=newTimeInput, newEvent=newEventInput, trainTime=trainTimeInput, trainEvent=trainEventInput) ipecVal <- unname(intPredErrDisc(predErrObj=pecObj, tmax=tmax)) return(ipecVal) } else{ pecObj <- predErrDiscShort(timepoints=1, estSurvList=survPreds, newTime=newTimeInput, newEvent=newEventInput, trainTime=trainTimeInput, trainEvent=trainEventInput) ipecVal <- unname(intPredErrDisc(predErrObj=pecObj, tmax=tmax)) return(ipecVal) } }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(tidyfst) library(nycflights13) flights2 <- flights %>% select_dt(year,month,day, hour, origin, dest, tailnum, carrier) flights2 %>% left_join_dt(airlines) flights2 %>% left_join_dt(weather) flights2 %>% left_join_dt(planes, by = "tailnum") flights2 %>% left_join_dt(airports, c("dest" = "faa")) flights2 %>% left_join_dt(airports, c("origin" = "faa")) df1 <- data.table(x = c(1, 2), y = 2:1) df2 <- data.table(x = c(1, 3), a = 10, b = "a") df1 %>% inner_join_dt(df2) df1 %>% left_join_dt(df2) df1 %>% right_join_dt(df2) df1 %>% full_join_dt(df2) df1 <- data.frame(x = c(1, 1, 2), y = 1:3) df2 <- data.frame(x = c(1, 1, 2), z = c("a", "b", "a")) df1 %>% left_join_dt(df2) flights %>% anti_join_dt(planes, by = "tailnum") %>% count_dt(tailnum, sort = TRUE) df1 <- data.frame(x = c(1, 1, 3, 4), y = 1:4) df2 <- data.frame(x = c(1, 1, 2), z = c("a", "b", "a")) df1 %>% nrow() df1 %>% inner_join_dt(df2, by = "x") %>% nrow() df1 %>% semi_join_dt(df2, by = "x") %>% nrow() x = iris[c(2,3,3,4),] x2 = iris[2:4,] y = iris[c(3:5),] intersect_dt(x, y) intersect_dt(x, y, all=TRUE) setdiff_dt(x, y) setdiff_dt(x, y, all=TRUE) union_dt(x, y) union_dt(x, y, all=TRUE) setequal_dt(x, x2, all=FALSE) setequal_dt(x, x2)
expected <- eval(parse(text="list(1L, 3.14159265358979, 3+5i, \"testit\", TRUE, structure(1L, .Label = \"foo\", class = \"factor\"))")); test(id=0, code={ argv <- eval(parse(text="list(1L, 3.14159265358979, 3+5i, \"testit\", TRUE, structure(1L, .Label = \"foo\", class = \"factor\"))")); do.call(`list`, argv); }, o=expected);
allmodels_autoDI <- function(y, block, density, prop, treat, FG, data, family, total, estimate_theta, nSpecies, treat_flag, even_flag, P_int_flag, FGnames) { if(is.null(FG)) use_FG <- FALSE else use_FG <- TRUE mod_STR <- DI_STR(y = y, block = block, density = density, data = data, family = family, total = total)$model mod_ID <- DI_ID(y = y, block = block, density = density, prop = prop, data = data, family = family, total = total)$model if(!even_flag) { mod_AV_both <- DI_AV(y = y, block = block, density = density, prop = prop, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_AV <- mod_AV_both$model } if(use_FG) { mod_FG_both <- DI_FG(y = y, block = block, density = density, prop = prop, FG = FG, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total, FGnames = FGnames) mod_FG <- mod_FG_both$model } else { if(!P_int_flag) { mod_ADD_both <- DI_ADD(y = y, block = block, density = density, prop = prop, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_ADD <- mod_ADD_both$model } } fmla_FULL <- as.formula(paste("~", block, "+", density, " + (", paste(prop, collapse = "+"),")^2")) X_FULL <- model.matrix(fmla_FULL, data = data) X_pairwise <- X_FULL[,grep(":", colnames(X_FULL))] FULL_flag <- nrow(X_FULL) > ncol(X_FULL) if(FULL_flag) { FULL_flag <- DI_matrix_check(X_pairwise) } if(!FULL_flag) { message("Not all pairwise interactions can be estimated.\nTherefore, the FULL model is not included in the selection process.\n") } if(FULL_flag) { mod_FULL_both <- DI_FULL(y = y, block = block, density = density, prop = prop, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_FULL <- mod_FULL_both$model if(even_flag) { model_list_theta <- list("FULL_model" = mod_FULL_both$theta) } else if(use_FG) { model_list_theta <- list("AV_model" = mod_AV_both$theta, "FG_model" = mod_FG_both$theta, "FULL_model" = mod_FULL_both$theta) } else if(P_int_flag) { model_list_theta <- list("AV_model" = mod_AV_both$theta, "FULL_model" = mod_FULL_both$theta) } else { model_list_theta <- list("AV_model" = mod_AV_both$theta, "ADD_model" = mod_ADD_both$theta, "FULL_model" = mod_FULL_both$theta) } } else { if(even_flag) { model_list_theta <- list() } else if(use_FG) { model_list_theta <- list("AV_model" = mod_AV_both$theta, "FG_model" = mod_FG_both$theta) } else if(P_int_flag) { model_list_theta <- list("AV_model" = mod_AV_both$theta) } else { model_list_theta <- list("AV_model" = mod_AV_both$theta, "ADD_model" = mod_ADD_both$theta) } } if(!treat_flag) { mod_STR_treat <- DI_STR_treat(y = y, block = block, density = density, treat = treat, data = data, family = family, total = total)$model mod_ID_treat <- DI_ID_treat(y = y, block = block, density = density, prop = prop, treat = treat, data = data, family = family, total = total)$model if(!even_flag) { mod_AV_both_treat <- DI_AV_treat(y = y, block = block, density = density, prop = prop, treat = treat, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_AV_treat <- mod_AV_both_treat$model } if(use_FG) { mod_FG_both_treat <- DI_FG_treat(y = y, block = block, density = density, prop = prop, FG = FG, treat = treat, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total, FGnames = FGnames) mod_FG_treat <- mod_FG_both_treat$model } else { if(!P_int_flag) { mod_ADD_both_treat <- DI_ADD_treat(y = y, block = block, density = density, prop = prop, treat = treat, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_ADD_treat <- mod_ADD_both_treat$model } } fmla_FULL_treat <- as.formula(paste("~", block, "+", density, "+", treat, " + (", paste(prop, collapse = "+"),")^2")) X_FULL_treat <- model.matrix(fmla_FULL_treat, data = data) X_pairwise_treat <- X_FULL_treat[,grep(":", colnames(X_FULL_treat))] FULL_flag <- nrow(X_FULL_treat) > ncol(X_FULL_treat) if(FULL_flag) { FULL_flag <- DI_matrix_check(X_pairwise_treat) } if(!FULL_flag) { message("Not all pairwise interactions can be estimated.\nTherefore, the FULL model is not included in the selection process.\n") } if(FULL_flag) { mod_FULL_both_treat <- DI_FULL_treat(y = y, block = block, density = density, prop = prop, treat = treat, data = data, family = family, estimate_theta = estimate_theta, nSpecies = nSpecies, total = total) mod_FULL_treat <- mod_FULL_both_treat$model if(even_flag) { model_list_theta_treat <- list("FULL_model_treat" = mod_FULL_both_treat$theta) } else if(use_FG) { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta, "FG_model_treat" = mod_FG_both_treat$theta, "FULL_model_treat" = mod_FULL_both_treat$theta) } else if(P_int_flag) { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta, "FULL_model_treat" = mod_FULL_both_treat$theta) } else { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta, "ADD_model_treat" = mod_ADD_both_treat$theta, "FULL_model_treat" = mod_FULL_both_treat$theta) } } else { if(even_flag) { model_list_theta_treat <- list() } else if(use_FG) { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta, "FG_model_treat" = mod_FG_both_treat$theta) } else if(P_int_flag) { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta) } else { model_list_theta_treat <- list("AV_model_treat" = mod_AV_both_treat$theta, "ADD_model_treat" = mod_ADD_both_treat$theta) } } } model_list <- list("STR_model" = mod_STR, "ID_model" = mod_ID) if(!even_flag) { model_list$AV_model <- mod_AV } if(use_FG) { model_list$FG_model <- mod_FG } else if(!P_int_flag) { model_list$ADD_model <- mod_ADD } if(FULL_flag) { model_list$FULL_model <- mod_FULL } if(!treat_flag) { model_list_treat <- list("STR_model_treat" = mod_STR_treat, "ID_model_treat" = mod_ID_treat) if(!even_flag) { model_list_treat$AV_model_treat <- mod_AV_treat } if(use_FG) { model_list_treat$FG_model_treat <- mod_FG_treat } else if(!P_int_flag) { model_list_treat$ADD_model_treat <- mod_ADD_treat } if(FULL_flag) { model_list_treat$FULL_model_treat <- mod_FULL_treat } } if(treat_flag) { return(list("model_list" = model_list, "model_list_theta" = model_list_theta, "model_list_treat" = list(), "model_list_theta_treat" = list())) } else { return(list("model_list" = model_list, "model_list_theta" = model_list_theta, "model_list_treat" = model_list_treat, "model_list_theta_treat" = model_list_theta_treat)) } } namesub_autoDI <- Vectorize(function(name) { thename <- switch(name, "STR_model" = "Structural 'STR' DImodel", "ID_model" = "Species identity 'ID' DImodel", "FULL_model" = "Separate pairwise interactions 'FULL' DImodel", "AV_model" = "Average interactions 'AV' DImodel", "E_model" = "Evenness 'E' DImodel", "ADD_model" = "Additive species contributions to interactions 'ADD' DImodel", "FG_model" = "Functional group effects 'FG' DImodel", "STR_model_treat" = "Structural 'STR' DImodel with treatment", "ID_model_treat" = "Species identity 'ID' DImodel with treatment", "FULL_model_treat" = "Separate pairwise interactions 'FULL' DImodel with treatment", "AV_model_treat" = "Average interactions 'AV' DImodel with treatment", "E_model_treat" = "Evenness 'E' DImodel with treatment", "ADD_model_treat" = "Additive species contributions to interactions 'ADD' DImodel with treatment", "FG_model_treat" = "Functional group effects 'FG' DImodel with treatment", "FULL_model_theta" = "Separate pairwise interactions 'FULL' DImodel, estimating theta", "AV_model_theta" = "Average interactions 'AV' DImodel, estimating theta", "E_model_theta" = "Evenness 'E' DImodel, estimating theta", "ADD_model_theta" = "Additive species contributions to interactions 'ADD' DImodel, estimating theta", "FG_model_theta" = "Functional group effects 'FG' DImodel, estimating theta", "FULL_model_treat_theta" = "Separate pairwise interactions 'FULL' DImodel with treatment, estimating theta", "AV_model_treat_theta" = "Average interactions 'AV' DImodel with treatment, estimating theta", "E_model_treat_theta" = "Evenness 'E' DImodel with treatment, estimating theta", "ADD_model_treat_theta" = "Additive species contributions to interactions 'ADD' DImodel with treatment, estimating theta", "FG_model_treat_theta" = "Functional group effects 'FG' DImodel with treatment, estimating theta", stop("not yet implemented")) return(thename) }, "name") reftest_autoDI <- function(model_to_compare, ref_model, family) { if(family %in% c("poisson","binomial")) { ref_test <- "Chisq" } else { ref_test <- "F" } anovas <- anova(model_to_compare, ref_model, test = ref_test) anovas_format <- as.data.frame(anovas) anovas_format <- round(anovas_format, 4) anovas_format[is.na(anovas_format)] <- "" names(anovas_format)[c(2,4)] <- c("Resid. SSq","SSq") anovas_format$"Resid. MSq" <- round(anovas_format[,2]/anovas_format[,1], 4) anovas_format <- anovas_format[,c(1,2,7,3:6)] model_tokens <- c("Selected","Reference") anovas_format$model <- model_tokens anovas_format <- anovas_format[,c(8,1:7)] row.names(anovas_format) <- paste("DI Model", row.names(anovas_format)) anovas_format[,8][anovas_format[,8] == 0] <- "<0.0001" message("\n") old <- options() options(scipen = 999) on.exit(options(old)) print(anovas_format) } test_autoDI <- function(model_list, family, treat) { if(family %in% c("poisson","binomial")) { message("Selection using X2 tests", "\n") Test <- "Chisq" } else { message("Selection using F tests", "\n") Test <- "F" } model_names <- names(model_list) treat_flag <- grep("treatment", namesub_autoDI(model_names)) theta_flag <- grep("theta", namesub_autoDI(model_names)) treat_output <- rep("none", length(model_names)) treat_output[treat_flag] <- paste("'", treat, "'", sep = "") theta_output <- rep(FALSE, length(model_names)) theta_output[theta_flag] <- TRUE model_tokens <- gsub("_", "", gsub("[:a-z:]", "", names(model_list))) names(model_list) <- NULL anovas <- eval(parse(text = paste("anova(", paste("model_list[[", 1:length(model_list), "]]", sep = "", collapse = ","), ",test ='", Test, "')", sep = "") )) if(family %in% c("poisson","binomial")) { p_values <- anovas$"Pr(>Chi)" } else { p_values <- anovas$"Pr(>F)" } p_less <- which(p_values < .05) p_value_selected <- ifelse(length(p_less) == 0, 1, max(p_less)) selected <- model_names[p_value_selected] anovas_format <- as.data.frame(anovas) anovas_format <- round(anovas_format, 4) anovas_format[is.na(anovas_format)] <- "" names(anovas_format)[c(2,4)] <- c("Resid. SSq","SSq") anovas_format$"Resid. MSq" <- round(anovas_format[,2]/anovas_format[,1], 4) anovas_format <- anovas_format[,c(1,2,7,3:6)] anovas_format$model <- model_tokens anovas_format$treat <- treat_output anovas_format$theta <- theta_output anovas_format <- anovas_format[,c(8:10,1:7)] names(anovas_format)[1] <- "DI_model" names(anovas_format)[3] <- "estimate_theta" row.names(anovas_format) <- paste("DI Model", row.names(anovas_format)) anovas_format[,10][anovas_format[,10] == 0] <- "<0.0001" desc_table <- data.frame("Description" = namesub_autoDI(model_names)) row.names(desc_table) <- paste("DI Model", 1:nrow(anovas_format)) print(desc_table, right = FALSE) message("\n") old <- options() options(scipen = 999) on.exit(options(old)) print(anovas_format) return(selected) } AICsel_autoDI <- function(model_list, mAIC, treat) { message("Selection by AIC\nWarning: DI Model with the lowest AIC will be selected, even if the difference is very small.\nPlease inspect other models to see differences in AIC.", "\n\n", sep = "") model_names <- names(model_list) treat_flag <- grep("treatment", namesub_autoDI(model_names)) theta_flag <- grep("theta", namesub_autoDI(model_names)) treat_output <- rep("none", length(model_names)) treat_output[treat_flag] <- paste("'", treat, "'", sep = "") theta_output <- rep(FALSE, length(model_names)) theta_output[theta_flag] <- TRUE model_tokens <- gsub("_", "", gsub("[:a-z:]", "", model_names)) model_descriptions <- namesub_autoDI(model_names) the_table <- data.frame("AIC" = mAIC, "DI_Model" = model_tokens, "treat" = treat_output, "theta" = theta_output, "Description" = model_descriptions, row.names = NULL) print(the_table, right = FALSE) selected <- names(model_list)[which.min(mAIC)] return(selected) } AICcsel_autoDI <- function(model_list, mAICc, treat) { message("Selection by AICc\nWarning: DI Model with the lowest AICc will be selected, even if the difference is very small.\nPlease inspect other models to see differences in AICc.", "\n\n", sep = "") model_names <- names(model_list) treat_flag <- grep("treatment", namesub_autoDI(model_names)) theta_flag <- grep("theta", namesub_autoDI(model_names)) treat_output <- rep("none", length(model_names)) treat_output[treat_flag] <- paste("'", treat, "'", sep = "") theta_output <- rep(FALSE, length(model_names)) theta_output[theta_flag] <- TRUE model_tokens <- gsub("_", "", gsub("[:a-z:]", "", model_names)) model_descriptions <- namesub_autoDI(model_names) the_table <- data.frame("AICc" = mAICc, "DI_Model" = model_tokens, "treat" = treat_output, "theta" = theta_output, "Description" = model_descriptions, row.names = NULL) print(the_table, right = FALSE) selected <- names(model_list)[which.min(mAICc)] return(selected) } BICsel_autoDI <- function(model_list, mBIC, treat) { message("Selection by BIC\nWarning: DI Model with the lowest BIC will be selected, even if the difference is very small.\nPlease inspect other models to see differences in BIC.", "\n\n", sep = "") model_names <- names(model_list) treat_flag <- grep("treatment", namesub_autoDI(model_names)) theta_flag <- grep("theta", namesub_autoDI(model_names)) treat_output <- rep("none", length(model_names)) treat_output[treat_flag] <- paste("'", treat, "'", sep = "") theta_output <- rep(FALSE, length(model_names)) theta_output[theta_flag] <- TRUE model_tokens <- gsub("_", "", gsub("[:a-z:]", "", model_names)) model_descriptions <- namesub_autoDI(model_names) the_table <- data.frame("BIC" = mBIC, "DI_Model" = model_tokens, "treat" = treat_output, "theta" = theta_output, "Description" = model_descriptions, row.names = NULL) print(the_table, right = FALSE) selected <- names(model_list)[which.min(mBIC)] return(selected) } BICcsel_autoDI <- function(model_list, mBICc, treat) { message("Selection by BICc\nWarning: DI Model with the lowest BICc will be selected, even if the difference is very small.\nPlease inspect other models to see differences in BICc.", "\n\n", sep = "") model_names <- names(model_list) treat_flag <- grep("treatment", namesub_autoDI(model_names)) theta_flag <- grep("theta", namesub_autoDI(model_names)) treat_output <- rep("none", length(model_names)) treat_output[treat_flag] <- paste("'", treat, "'", sep = "") theta_output <- rep(FALSE, length(model_names)) theta_output[theta_flag] <- TRUE model_tokens <- gsub("_", "", gsub("[:a-z:]", "", model_names)) model_descriptions <- namesub_autoDI(model_names) the_table <- data.frame("BICc" = mBICc, "DI_Model" = model_tokens, "treat" = treat_output, "theta" = theta_output, "Description" = model_descriptions, row.names = NULL) print(the_table, right = FALSE) selected <- names(model_list)[which.min(mBICc)] return(selected) } DI_matrix_check <- function(model_matrix) { n_parms <- ncol(model_matrix) matrix_rank <- qr(model_matrix)$rank if(matrix_rank == n_parms) { return(TRUE) } else { return(FALSE) } } autoDI_step0 <- function(y, block, density, treat, family, data) { if(is.na(block) & is.na(density) & is.na(treat)) { return(invisible()) } message("\n", strrep("-", getOption("width"))) message("\nSequential analysis: Investigating only non-diversity experimental design structures\n") fmla1 <- paste(y, "~", 1) fit1 <- glm(fmla1, family = family, data = data) if(!is.na(block) & !is.na(density) & !is.na(treat)) { fmla2 <- paste(y, "~", block) fmla3 <- paste(y, "~", block, "+", density) fmla4 <- paste(y, "~", block, "+", density, "+", treat) fit2 <- glm(fmla2, family = family, data = data) fit3 <- glm(fmla3, family = family, data = data) fit4 <- glm(fmla4, family = family, data = data) model_list <- list(fit1, fit2, fit3, fit4) model_tokens <- c("Intercept only","block","block + density","block + density + treat") } if(!is.na(block) & !is.na(density) & is.na(treat)) { fmla2 <- paste(y, "~", block) fmla3 <- paste(y, "~", block, "+", density) fit2 <- glm(fmla2, family = family, data = data) fit3 <- glm(fmla3, family = family, data = data) model_list <- list(fit1, fit2, fit3) model_tokens <- c("Intercept only","block","block + density") } if(!is.na(block) & is.na(density) & !is.na(treat)) { fmla2 <- paste(y, "~", block) fmla3 <- paste(y, "~", block, "+", treat) fit2 <- glm(fmla2, family = family, data = data) fit3 <- glm(fmla3, family = family, data = data) model_list <- list(fit1, fit2, fit3) model_tokens <- c("Intercept only","block","block + treat") } if(is.na(block) & !is.na(density) & !is.na(treat)) { fmla2 <- paste(y, "~", density) fmla3 <- paste(y, "~", density, "+", treat) fit2 <- glm(fmla2, family = family, data = data) fit3 <- glm(fmla3, family = family, data = data) model_list <- list(fit1, fit2, fit3) model_tokens <- c("Intercept only","density","density + treat") } if(!is.na(block) & is.na(density) & is.na(treat)) { fmla2 <- paste(y, "~", block) fit2 <- glm(fmla2, family = family, data = data) model_list <- list(fit1, fit2) model_tokens <- c("Intercept only","block") } if(is.na(block) & !is.na(density) & is.na(treat)) { fmla2 <- paste(y, "~", density) fit2 <- glm(fmla2, family = family, data = data) model_list <- list(fit1, fit2) model_tokens <- c("Intercept only","density") } if(is.na(block) & is.na(density) & !is.na(treat)) { fmla2 <- paste(y, "~", treat) fit2 <- glm(fmla2, family = family, data = data) model_list <- list(fit1, fit2) model_tokens <- c("Intercept only","treat") } if(family %in% c("poisson","binomial")) { Test <- "Chisq" } else { Test <- "F" } anovas <- eval(parse(text = paste("anova(", paste("model_list[[", 1:length(model_list), "]]", sep = "", collapse = ","), ",test ='", Test, "')", sep = "") )) anovas_format <- as.data.frame(anovas) anovas_format <- round(anovas_format, 4) anovas_format[is.na(anovas_format)] <- "" names(anovas_format)[c(2,4)] <- c("Resid. SSq","SSq") anovas_format$"Resid. MSq" <- round(anovas_format[,2]/anovas_format[,1], 4) anovas_format <- anovas_format[,c(1,2,7,3:6)] anovas_format$model <- model_tokens anovas_format <- anovas_format[,c(8,1:7)] anovas_format[,8][anovas_format[,8] == 0] <- "<0.0001" message("\n") old <- options() options(scipen = 999) on.exit(options(old)) print(anovas_format) }
unblanker <- function(x)subset(x, nchar(x)>0)
context("Checking Outputs") test_that("checking value",{ expect_identical(round(pBetaBin(2,4,0.5,0.4),4), 0.5056) }) test_that("checking class",{ expect_that(pBetaBin(2,4,0.5,0.1), is_a("numeric")) }) test_that("checking length of output",{ expect_equal(length(pBetaBin(1:2,4,0.5,1)),2) })
`relative.importance` <- function(dataset) { dataset <- prepare.data(dataset) no_classes <- length(levels(dataset$class)) data_class <- create.classdata(dataset) n <- rep(as.numeric(NA), each=no_classes) for (i in 1:no_classes) { n[i] <- dim(data_class[[i]])[1] } n.total <- dim(dataset)[1] parameters <- matrix(data = NA, nrow = no_classes, ncol = 4) parameters <- as.data.frame(parameters) names(parameters) <- c("alpha", "beta", "mu", "sigma") fit <- list() for (i in 1:no_classes) { fit[[i]] <- glm(transition ~ performance, data=data_class[[i]], family="binomial") } for (i in 1:no_classes) { parameters$alpha[i] <- as.numeric(fit[[i]]$coefficients[1]) parameters$beta[i] <- as.numeric(fit[[i]]$coefficients[2]) parameters$mu[i] <- mean(data_class[[i]]$performance) parameters$sigma[i] <- sd(data_class[[i]]$performance) } perc.class <- rep(as.numeric(NA), no_classes) for (i in 1:no_classes) { temp1 <- data_class[[i]] temp2 <- dim(temp1[(temp1$transition==1),])[1] perc.class[i] <- temp2 / (dim(temp1)[1]) } perc.total <- (dim(dataset[(dataset$transition==1),])[1]) / (dim(dataset)[1]) fifty.point <- rep(as.numeric(NA), no_classes) for (i in 1:no_classes) { fifty.point[i] <- - parameters$alpha[i] / parameters$beta[i] } gamma <- rep(as.numeric(NA), no_classes) for (i in 1:no_classes) { gamma[i] <- parameters$alpha[i] + (parameters$beta[i] * parameters$mu[i]) } k <- 0.61 log.odds <- function(g, s, b) as.numeric(g/sqrt(1+(k*s*b)^2)) log_odds <- rep(as.numeric(NA), no_classes) odds <- rep(as.numeric(NA), no_classes) for (i in 1:no_classes) { log_odds[i] <- log.odds(gamma[i], parameters$sigma[i], parameters$beta[i]) } for (i in 1:no_classes) { odds[i] <- exp(log_odds[i]) } no_oddsratios <- function(no_classes) { N <- no_classes no_oddsratios <- 0 for (j in 1:(N-1)) { no_oddsratios <- no_oddsratios + j } no_oddsratios } oddsratios <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(oddsratios)[1]) { for (j in 1:dim(oddsratios)[2]) { if (i < j) { oddsratios[i, j] <- odds[i] / odds[j] } } } logistic <- function(x) exp(x)/(1+exp(x)) logit <- function(x) log(x/(1-x)) trans.prob <- rep(as.numeric(NA), no_classes) for (i in 1:no_classes) { trans.prob[i] <- logistic(log_odds[i]) } tr.pr <- function(g, s, b) { pnorm(as.numeric(k*g / sqrt(1 + (k*s*b)^2))) } logodds <- matrix(NA, nrow = no_classes, ncol = no_classes) for (i in 1:no_classes) { for (j in 1:no_classes) { logodds[i, j] <- log.odds(parameters$alpha[j] + (parameters$beta[j] * parameters$mu[i]), parameters$sigma[i], parameters$beta[j]) } } transprob <- matrix(NA, nrow = no_classes, ncol = no_classes) for (i in 1:no_classes) { for (j in 1:no_classes) { transprob[i, j] <- tr.pr(parameters$alpha[j] + (parameters$beta[j] * parameters$mu[i]), parameters$sigma[i], parameters$beta[j]) } } rel.imp.sec1 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.sec1)[1]) { for (j in 1:dim(rel.imp.sec1)[2]) { if (i < j) { rel.imp.sec1[i, j] <- (logodds[i, i] - logodds[i, j]) / (logodds[i, i] - logodds[j, j]) } } } rel.imp.sec2 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.sec2)[1]) { for (j in 1:dim(rel.imp.sec2)[2]) { if (i < j) { rel.imp.sec2[i, j] <- (logodds[j, i] - logodds[j, j]) / (logodds[i, i] - logodds[j, j]) } } } rel.imp.sec.avg <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.sec.avg)[1]) { for (j in 1:dim(rel.imp.sec.avg)[2]) { if (i < j) { rel.imp.sec.avg[i, j] <- (rel.imp.sec1[i, j] + rel.imp.sec2[i, j]) / 2 } } } rel.imp.prim1 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.prim1)[1]) { for (j in 1:dim(rel.imp.prim1)[2]) { if (i < j) { rel.imp.prim1[i, j] <- 1 - rel.imp.sec1[i, j] } } } rel.imp.prim2 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.prim2)[1]) { for (j in 1:dim(rel.imp.prim2)[2]) { if (i < j) { rel.imp.prim2[i, j] <- 1 - rel.imp.sec2[i, j] } } } rel.imp.prim.avg <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(rel.imp.prim.avg)[1]) { for (j in 1:dim(rel.imp.prim.avg)[2]) { if (i < j) { rel.imp.prim.avg[i, j] <- 1 - rel.imp.sec.avg[i, j] } } } I <- list() for (i in 1:no_classes) { I[[i]] <- vcov(fit[[i]]) } var.logodds <- function(a, b, m, s, i11, i12, i22, n) { var1 <- i11/(1 + (k*s*b)^2) var2 <- 2*i12*(m - (2*a*b*(k*s)^2))/((1+(k*s*b)^2)^2) var3 <- i22*((m - (2*a*b*(k*s)^2))^2)/((1+(k*s*b)^2)^3) var4 <- ((s*b)^2) / (n*(1 + (k*s*b)^2)) var5 <- (2*((k*b*s)^4)*((a + b*m)^2) / (n*((1+(k*s*b)^2)^3))) as.numeric(var1+var2+var3+var4+var5) } var.lo <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(var.lo)[1]) { for (j in 1:dim(var.lo)[2]) { var.lo[i, j] <- var.logodds(parameters$alpha[j], parameters$beta[j], parameters$mu[i], parameters$sigma[i], I[[j]][1,1], I[[j]][1,2], I[[j]][2,2], n[i]) } } se.lo <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(var.lo)[1]) { for (j in 1:dim(var.lo)[2]) { se.lo[i, j] <- sqrt(var.lo[i, j]) } } cov.logodds.ii.ij <- function(a.i, a.j, b.i, b.j, m.i, s.i, n.i) { as.numeric((s.i^2*b.i*b.j/(n.i*sqrt(1+(k*s.i*b.i)^2)*sqrt(1+(k*s.i*b.j)^2)) + (s.i*k)^4*(b.i*b.j)^2*(a.i+b.i*m.i)*(a.j + b.j*m.i)/(2*n.i*((1+(k*s.i*b.i)^2)^(3/2))*((1+(k*s.i*b.j)^2)^(3/2))))) } cov.lo.ii.ij <- matrix(NA, nrow=no_classes, ncol=no_classes) for (i in 1:dim(cov.lo.ii.ij)[1]) { for (j in 1:dim(cov.lo.ii.ij)[2]) { if (i != j) { cov.lo.ii.ij[i, j] <- cov.logodds.ii.ij(parameters$alpha[i], parameters$alpha[j], parameters$beta[i], parameters$beta[j], parameters$mu[i], parameters$sigma[i], n[i]) } } } cov.logodds.ii.ji <- function(a.i, b.i, m.i, s.i, i11, i12, i22, m.j, s.j) { var1 <- i11/sqrt(1 + ((k*s.i*b.i)^2)) + ((m.i-(a.i*b.i*(k*s.i)^2))*i12/((1 + (k*s.i*b.i)^2)^(3/2))) var2 <- i12/sqrt(1 + ((k*s.i*b.i)^2)) + ((m.i-(a.i*b.i*(k*s.i)^2))*i22/((1 + (k*s.i*b.i)^2)^(3/2))) as.numeric((var1/sqrt(1 + (k*s.j*b.i)^2) ) + (var2 * ((m.j-a.i*b.i*(k*s.j)^2)/((1 + (k*s.j*b.i)^2))^(3/2)))) } cov.lo.ii.ji <- matrix(NA, nrow=no_classes, ncol=no_classes) for (i in 1:dim(cov.lo.ii.ji)[1]) { for (j in 1:dim(cov.lo.ii.ji)[2]) { if (i != j) { cov.lo.ii.ji[i, j] <- cov.logodds.ii.ji(parameters$alpha[i], parameters$beta[i], parameters$mu[i], parameters$sigma[i], I[[i]][1, 1], I[[i]][1, 2], I[[i]][2, 2], parameters$mu[j], parameters$sigma[j]) } } } var.relimp.1 <- function(fii, fij, fjj, var.fii, var.fij, var.fjj, cov.fii.fij, cov.fij.fjj) { as.numeric(((fij-fjj)^2*var.fii/((fii-fjj)^4)) + ((fii-fij)^2*var.fjj/((fii-fjj)^4)) + (var.fij/((fii-fjj)^2)) - (2*(fij-fjj)*cov.fii.fij/((fii-fjj)^3)) - (2*(fii-fij)*cov.fij.fjj/((fii-fjj)^3))) } var.ri.1 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(var.ri.1)[1]) { for (j in 1:dim(var.ri.1)[2]) { if (i < j) { var.ri.1[i, j] <- var.relimp.1(logodds[i, i], logodds[i, j], logodds[j, j], var.lo[i, i], var.lo[i, j], var.lo[j, j], cov.lo.ii.ij[i, j], cov.lo.ii.ij[j, i]) } } } var.relimp.2 <- function(fii, fji, fjj, var.fii, var.fji, var.fjj, cov.fii.fji, cov.fji.fjj) { as.numeric(((fji-fjj)^2*var.fii/((fii-fjj)^4)) + ((fii-fji)^2*var.fjj/((fii-fjj)^4)) + (var.fji/((fii-fjj)^2)) - (2*(fji-fjj)*cov.fii.fji/((fii-fjj)^3)) - (2*(fii-fji)*cov.fji.fjj/((fii-fjj)^3))) } var.ri.2 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(var.ri.2)[1]) { for (j in 1:dim(var.ri.2)[2]) { if (i < j) { var.ri.2[i, j] <- var.relimp.2(logodds[i, i], logodds[j, i], logodds[j, j], var.lo[i, i], var.lo[j, i], var.lo[j, j], cov.lo.ii.ji[i, j], cov.lo.ii.ji[j, i]) } } } se.ri.1 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(se.ri.1)[1]) { for (j in 1:dim(se.ri.1)[2]) { if (i < j) { se.ri.1[i, j] <- sqrt(var.ri.1[i, j]) } } } se.ri.2 <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(se.ri.2)[1]) { for (j in 1:dim(se.ri.2)[2]) { if (i < j) { se.ri.2[i, j] <- sqrt(var.ri.2[i, j]) } } } ci.normal <- function(f, se.f) { c(f - (1.96 * se.f), f + (1.96 * se.f)) } ci.lo <- matrix(NA, nrow = no_classes, ncol = 2) for (i in 1:no_classes) { ci.lo[i, 1] <- ci.normal(logodds[i, i], se.lo[i, i])[1] ci.lo[i, 2] <- ci.normal(logodds[i, i], se.lo[i, i])[2] } log.oddsratios <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(log.oddsratios)[1]) { for (j in 1:dim(log.oddsratios)[2]) { if (i < j) { log.oddsratios[i, j] <- logodds[i, i] - logodds[j, j] } } } se.log.oddsratios <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(se.log.oddsratios)[1]) { for (j in 1:dim(se.log.oddsratios)[2]) { if (i < j) { se.log.oddsratios[i, j] <- sqrt(var.lo[i, i] + var.lo[j, j]) } } } ci.log.oddsratios <- matrix(NA, ncol=no_classes, nrow=no_classes) ci.log.oddsratios <- as.data.frame(ci.log.oddsratios) ci.log.oddsratios.lower <- matrix(NA, ncol=no_classes, nrow=no_classes) ci.log.oddsratios.upper <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(ci.log.oddsratios)[1]) { for (j in 1:dim(ci.log.oddsratios)[2]) { if (i < j) { ci.log.oddsratios.lower[i, j] <- ci.normal(log.oddsratios[i, j], se.log.oddsratios[i, j])[1] ci.log.oddsratios.upper[i, j] <- ci.normal(log.oddsratios[i, j], se.log.oddsratios[i, j])[2] ci.log.oddsratios[i, j] <- paste("(", format(ci.log.oddsratios.lower[i, j], digits=5), ", ", format(ci.log.oddsratios.upper[i, j], digits=5), ")", sep="") } } } ci.ri.1 <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.1 <- as.data.frame(ci.ri.1) ci.ri.1.lower <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.1.upper <- matrix(NA, nrow=no_classes, ncol=no_classes) for (i in 1:dim(ci.ri.1)[1]) { for (j in 1:dim(ci.ri.1)[2]) { if (i < j) { ci.ri.1.lower[i, j] <- ci.normal(rel.imp.sec1[i, j], se.ri.1[i, j])[1] ci.ri.1.upper[i, j] <- ci.normal(rel.imp.sec1[i, j], se.ri.1[i, j])[2] ci.ri.1[i, j] <- paste("(", format(ci.ri.1.lower[i, j], digits=5), ", ", format(ci.ri.1.upper[i, j], digits=5), ")", sep="") } } } ci.ri.2 <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.2 <- as.data.frame(ci.ri.2) ci.ri.2.lower <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.2.upper <- matrix(NA, nrow=no_classes, ncol=no_classes) for (i in 1:dim(ci.ri.2)[1]) { for (j in 1:dim(ci.ri.2)[2]) { if (i < j) { ci.ri.2.lower[i, j] <- ci.normal(rel.imp.sec2[i, j], se.ri.2[i, j])[1] ci.ri.2.upper[i, j] <- ci.normal(rel.imp.sec2[i, j], se.ri.2[i, j])[2] ci.ri.2[i, j] <- paste("(", format(ci.ri.2.lower[i, j], digits=5), ", ", format(ci.ri.2.upper[i, j], digits=5), ")", sep="") } } } var.relimp.avg <- function(fji, fij, fii, fjj, var.fji, var.fij, var.fii, var.fjj, cov.fji.fjj, cov.fij.fii, cov.fji.fii, cov.fij.fjj) { as.numeric(((var.fji + var.fij)/(4*((fii-fjj)^2))) + ((fji-fij)^2*(var.fii+var.fjj)/(4*((fii-fjj)^4))) + ((fji-fij)*(cov.fji.fjj+cov.fij.fii-cov.fji.fii-cov.fij.fjj)/(2*((fii-fjj)^3)))) } var.ri.avg <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(var.ri.avg)[1]) { for (j in 1:dim(var.ri.avg)[2]) { if (i < j) { var.ri.avg[i, j] <- var.relimp.avg(logodds[j, i], logodds[i, j], logodds[i, i], logodds[j, j], var.lo[j, i], var.lo[i, j], var.lo[i, i], var.lo[j, j], cov.lo.ii.ij[j, i], cov.lo.ii.ij[i, j], cov.lo.ii.ji[i, j], cov.lo.ii.ji[j, i]) } } } se.ri.avg <- matrix(NA, ncol=no_classes, nrow=no_classes) for (i in 1:dim(se.ri.avg)[1]) { for (j in 1:dim(se.ri.avg)[2]) { if (i < j) { se.ri.avg[i, j] <- sqrt(var.ri.avg[i, j]) } } } ci.ri.avg <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.avg <- as.data.frame(ci.ri.avg) ci.ri.avg.lower <- matrix(NA, nrow=no_classes, ncol=no_classes) ci.ri.avg.upper <- matrix(NA, nrow=no_classes, ncol=no_classes) for (i in 1:dim(ci.ri.avg)[1]) { for (j in 1:dim(ci.ri.avg)[2]) { if (i < j) { ci.ri.avg.lower[i, j] <- ci.normal(rel.imp.sec.avg[i, j], se.ri.avg[i, j])[1] ci.ri.avg.upper[i, j] <- ci.normal(rel.imp.sec.avg[i, j], se.ri.avg[i, j])[2] ci.ri.avg[i, j] <- paste("(", format(ci.ri.avg.lower[i, j], digits=5), ", ", format(ci.ri.avg.upper[i, j], digits=5), ")", sep="") } } } return(list("sample_size"=n.total, "no_classes"=no_classes, "class_size"=n, "percentage_overall"=perc.total, "percentage_class"=perc.class, "fifty_point"=fifty.point, "parameters"=parameters, "transition_prob"=transprob, "log_odds"=logodds, "se_logodds"=se.lo, "ci_logodds"=ci.lo, "odds"=odds, "log_oddsratios"=log.oddsratios, "se_logoddsratios"=se.log.oddsratios, "ci_logoddsratios"=ci.log.oddsratios, "oddsratios"=oddsratios, "rel_imp_prim1"=rel.imp.prim1, "rel_imp_prim2"=rel.imp.prim2, "rel_imp_prim_avg"=rel.imp.prim.avg, "rel_imp_sec1"=rel.imp.sec1, "rel_imp_sec2"=rel.imp.sec2, "rel_imp_sec_avg"=rel.imp.sec.avg, "se.ri.1"=se.ri.1, "ci.ri.1"=ci.ri.1, "se.ri.2"=se.ri.2, "ci.ri.2"=ci.ri.2, "se.ri.avg"=se.ri.avg, "ci.ri.avg"=ci.ri.avg)) }
BB.mod.stab.glm <- function(data, BB.data, s.model, model="linear", maxit.glm=25) { if (model == "binomial") { options(warn=-1) regmod <- glm(s.model, data=BB.data, family = binomial(link="logit"), na.action=na.exclude, control=glm.control(maxit = maxit.glm)) options(warn=0) c.regmod <- glm(s.model, data=data, family = binomial(link="logit"), na.action=na.exclude, control=glm.control(maxit = maxit.glm)) } else if (model == "linear") { regmod <- lm(s.model, data=BB.data, na.action=na.exclude) c.regmod <- lm(s.model, data=data, na.action=na.exclude) } c.namen <- names(c.regmod$coefficients) BB.namen <- names(regmod$coefficients) mislevpos <- !is.element(c.namen, BB.namen) if (any(mislevpos == T)) { help.coeff <- regmod$coefficients regmod$coefficients <- c.regmod$coefficients regmod$coefficients[mislevpos==T] <- 0 regmod$coefficients[mislevpos==F] <- help.coeff regmod$xlevels <- c.regmod$xlevels regmod$rank <- c.regmod$rank regmod$assign <- c.regmod$assign regmod$qr$pivot <- c.regmod$qr$pivot regmod$qr$rank <- c.regmod$qr$rank } x <- list(model=regmod, c.model=c.regmod, mislevpos=mislevpos) return(x) }
GRSin <- function(Species_list,Occurrence_data,Raster_list,Pro_areas=NULL, Gap_Map=FALSE){ par_names <- c("species","latitude","longitude","type") if(missing(Occurrence_data)){ stop("Please add a valid data frame with columns: species, latitude, longitude, type") } if(isFALSE(identical(names(Occurrence_data),par_names))){ stop("Please format the column names in your dataframe as species, latitude, longitude, type") } if (isTRUE("RasterStack" %in% class(Raster_list))) { Raster_list <- raster::unstack(Raster_list) } else { Raster_list <- Raster_list } if(is.null(Gap_Map) | missing(Gap_Map)){ Gap_Map <- FALSE } else if(isTRUE(Gap_Map) | isFALSE(Gap_Map)){ Gap_Map <- Gap_Map } else { stop("Choose a valid option for GapMap (TRUE or FALSE)") } df <- data.frame(matrix(ncol=2, nrow = length(Species_list))) colnames(df) <- c("species", "GRSin") if(is.null(Pro_areas) | missing(Pro_areas)){ if(file.exists(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis"))){ Pro_areas <- raster::raster(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis")) } else { stop("Protected areas file is not available yet. Please run the function GetDatasets() and try again") } } else{ Pro_areas <- Pro_areas } if(isTRUE(Gap_Map)){ GapMapIn_list <- list() } for(i in seq_len(length(Species_list))){ for(j in seq_len(length(Raster_list))){ if(grepl(j, i, ignore.case = TRUE)){ sdm <- Raster_list[[j]] } d1 <- Occurrence_data[Occurrence_data$species == Species_list[i],] test <- GapAnalysis::ParamTest(d1, sdm) if(isTRUE(test[1])){ stop(paste0("No Occurrence data exists, but and SDM was provide. Please check your occurrence data input for ", Species_list[i])) } };rm(j) if(isFALSE(test[2])){ df$species[i] <- as.character(Species_list[i]) df$GRSex[i] <- 0 warning(paste0("Either no occurrence data or SDM was found for species ", as.character(Species_list[i]), " the conservation metric was automatically assigned 0")) }else{ sdm1 <- sdm Pro_areas1 <- raster::crop(x = Pro_areas,y = sdm1) sdm1[sdm1[] != 1] <- NA if(raster::res(Pro_areas1)[1] != raster::res(sdm)[1]){ Pro_areas1 <- raster::resample(x = Pro_areas1, y = sdm) } cell_size <- raster::area(sdm1, na.rm=TRUE, weights=FALSE) cell_size <- cell_size[!is.na(cell_size)] thrshold_area <- length(cell_size)*median(cell_size) Pro_areas1[Pro_areas1[] != 1] <-NA Pro_areas1 <- Pro_areas1 * sdm1 cell_size <- raster::area(Pro_areas1, na.rm=TRUE, weights=FALSE) cell_size <- cell_size[!is.na(cell_size)] protected_area <- length(cell_size)*stats::median(cell_size) if(!is.na(protected_area)){ GRSin <- min(c(100, protected_area/thrshold_area*100)) df$species[i] <- as.character(Species_list[i]) df$GRSin[i] <- GRSin }else{ df$species[i] <- as.character(Species_list[i]) df$GRSin[i] <- 0 } if(isTRUE(Gap_Map)){ message(paste0("Calculating GRSin gap map for ",as.character(Species_list[i])),"\n") Pro_areas1[is.na(Pro_areas1),] <- 0 gap_map <- sdm - Pro_areas1 gap_map[gap_map[] != 1] <- NA GapMapIn_list[[i]] <- gap_map names(GapMapIn_list[[i]] ) <- Species_list[[i]] } } } if(isTRUE(Gap_Map)){ df <- list(GRSin= df,gap_maps=GapMapIn_list) } else { df <- df } return(df) }
probDistance <- function(result, numSimulations = BLCOPOptions("numSimulations")) { monteCarloSample <- rmnorm(numSimulations, result@priorMean, result@priorCovar) mean(abs(dmnorm(monteCarloSample, result@priorMean, result@priorCovar,log=TRUE) - dmnorm(monteCarloSample, result@posteriorMean, result@posteriorCovar, log = TRUE))) } setGeneric("probDistance") probDistance.COPResult <- function(result, numSimulations = BLCOPOptions("numSimulations") ) { show("Not implemented yet...") } setMethod("probDistance", signature(result = "COPResult"), probDistance.COPResult)
get_concentrations_from_NASIS_db <- function(SS=TRUE, stringsAsFactors = default.stringsAsFactors(), dsn = NULL) { q <- "SELECT peiid, phiid, concpct, concsize, conccntrst, conchardness, concshape, conckind, conclocation, concboundary, phconceniid FROM pedon_View_1 INNER JOIN phorizon_View_1 ON pedon_View_1.peiid = phorizon_View_1.peiidref INNER JOIN phconcs_View_1 ON phorizon_View_1.phiid = phconcs_View_1.phiidref ORDER BY phiid, conckind;" q.c <- "SELECT phconceniidref AS phconceniid, colorpct, colorhue, colorvalue, colorchroma, colormoistst FROM phconccolor_View_1 ORDER BY phconceniidref, colormoistst;" channel <- dbConnectNASIS(dsn) if (inherits(channel, 'try-error')) return(data.frame()) if (SS == FALSE) { q <- gsub(pattern = '_View_1', replacement = '', x = q, fixed = TRUE) q.c <- gsub(pattern = '_View_1', replacement = '', x = q.c, fixed = TRUE) } d <- dbQueryNASIS(channel, q, close = FALSE) d.c <- dbQueryNASIS(channel, q.c) d <- uncode(d, stringsAsFactors = stringsAsFactors, dsn = dsn) d.c <- uncode(d.c, stringsAsFactors = stringsAsFactors, dsn = dsn) d.c$colormoistst <- as.character(d.c$colormoistst) d.c$colorhue <- as.character(d.c$colorhue) d.c$colorvalue <- as.numeric(as.character(d.c$colorvalue)) d.c$colorchroma <- as.numeric(as.character(d.c$colorchroma)) return(list(conc = d, conc_colors = d.c)) }
madauni <- function(x, type = "DOR", method = "DSL", suppress = TRUE, ...){ if(suppress){x <- suppressWarnings(madad(x, ...)) }else{ x <- madad(x, ...) } TP <- x$data$TP FP <- x$data$FP FN <- x$data$FN TN <- x$data$TN number.of.pos<-TP+FN number.of.neg<-FP+TN nop <- number.of.pos non <- number.of.neg total <- nop + non naive.tausquared<-function(Q,weights) { k<-length(weights) if(Q<(k-1)){return(0)} else return((Q-k+1)/(sum(weights)-(sum(weights^2)/sum(weights)))) } if(! method %in% c("MH","DSL"))stop("method must be either \"MH\" or \"DSL\"")else nobs <- x$nobs theta <-switch(type, "DOR" = x$DOR$DOR, "posLR" = x$posLR$posLR, "negLR" = x$negLR$negLR) if(method == "MH") { weights<-switch(type, "DOR" = FP*FN/total, "posLR" = FP*nop/total, "negLR" = TN*nop/total) coef <- log(sum(weights*theta)/sum(weights)) CQ<-cochran.Q(theta, weights = weights) tau.squared <- NULL P <- sum((nop*non*(TP+FP) - TP*FP*total)/total^2) U <- sum(TP*non/total) V = sum(FN*nop/total) Uprime = sum(FP*non/total) Vprime = sum(TN*nop/total) R = sum(TP*TN/total) S = sum(FP*FN/total) E = sum((TP+TN)*TP*TN/(total^2)) FF = sum((TP+TN)*FN*FP/(total^2)) G = sum((FP+FN)*TP*TN/(total^2)) H = sum((FP+FN)*FP*FN/(total^2)) vcov <- switch(type, "DOR" = 0.5*(E/(R^2) + (F+G)/(R*S) + H/(S^2)), "posLR" = P/(U*V), "negLR" = P/(Uprime*Vprime)) } if(method == "DSL") { se.lntheta <- switch(type, "DOR" = x$DOR$se.lnDOR, "posLR" = x$posLR$se.lnposLR, "negLR" = x$negLR$se.lnnegLR) lntheta <- log(theta) CQ<-cochran.Q(lntheta, 1/se.lntheta^2) tau.squared<-naive.tausquared(CQ[1],1/(se.lntheta^2)) weights<-1/(se.lntheta^2+tau.squared) CQ<-cochran.Q(lntheta, weights) coef <- sum(weights*lntheta)/sum(weights) vcov <- 1/sum(weights) } names(coef) <- paste("ln", type, collapse ="", sep ="") vcov <- matrix(vcov, nrow = 1, ncol = 1) colnames(vcov) <- paste("ln", type, collapse ="", sep ="") rownames(vcov) <- paste("ln", type, collapse ="", sep ="") output <- list(coefficients = coef, vcov = vcov, tau_sq = tau.squared, weights = weights, type = type, method = method, data = x$data, theta = theta, CQ = CQ, nobs = length(theta), descr = x, call = match.call()) class(output) <- "madauni" output } print.madauni <- function(x, digits = 3, ...){ cat("Call:\n") print(x$call) cat("\n") if(is.null(x$tau_sq)){ ans <- exp(x$coefficients) names(ans) <- x$type print(ans) }else{ ans <- c(exp(x$coefficients),x$tau_sq) names(ans) <- c(x$type, "tau^2") print(round(ans, digits)) } } vcov.madauni <- function(object, ...){object$vcov} summary.madauni <- function(object, level = .95, ...){ x <- object Higgins.Isq<-function(T,df){return(max(0,100*(T-df)/T))} if(object$method == "DSL"){ Isq <- Higgins.Isq(x$CQ[1], x$CQ[3])}else{ Isq <- NULL } CIcoef <- rbind(exp(cbind(coef(x), confint(x, level = level))), cbind(coef(x), confint(x, level = level))) rownames(CIcoef) <- c(x$type,paste("ln",x$type, sep ="", collapse = "")) colnames(CIcoef)[1] <- paste(x$method, "estimate", collapse ="") Q <- function(tau2){sum(((log(x$theta) - coef(x)[1])^2)/(1/x$weights+tau2))} CQ <- ifelse(is.null(x$tau_sq), Q(0), Q(x$tau_sq)) if(!is.null(x$tau_sq)){ kappa_up <- qchisq(1-(1-level)/2, x$nobs - 1) kappa_low <- qchisq((1-level)/2, x$nobs - 1) if(Q(0) < kappa_up){lower <- 0}else{ lower <- uniroot(function(x){Q(x)-kappa_up}, lower = 0, upper = 10^4)$root} if(Q(0) < kappa_low){upper <- 0}else{ upper <- uniroot(function(x){Q(x)-kappa_low}, lower = 0, upper = 10^4)$root} CIcoef <- rbind(CIcoef, c(x$tau_sq, lower, upper), sqrt(c(x$tau_sq, lower, upper))) rownames(CIcoef)[3:4] <- c("tau^2","tau") } output <- list(x=object, Isq = Isq, CIcoef = CIcoef) class(output) <- "summary.madauni" output } print.summary.madauni <- function(x, digits = 3,...){ cat("Call:\n") print(x$x$call) cat("\nEstimates:\n") print(round(x$CIcoef,digits)) cat("\nCochran's Q: ",round(x$x$CQ[1],digits), " (",round(x$x$CQ[3])," df, p = ", round(x$x$CQ[2], digits),")", sep = "") if(!is.null(x$Isq)){cat("\nHiggins' I^2: ",round(x$Isq, digits),"%", sep ="")} }
genMod<-function(sequences, modificationPattern, nModification=2){ R<-list() for (peptideSequence in sequences){ n<-nchar(peptideSequence) m<-length(modificationPattern) idx<-1:n pidx<-1:m acids<-(strsplit(peptideSequence, ''))[[1]] hits<-idx[acids %in% modificationPattern] result<-paste(rep(0,n), collapse="") if (length(hits) < nModification) nModification <- length(hits) if (length(hits) > 1){ for (ii in 1:nModification){ c<-combn(hits, ii) result<-c(result, (apply(c, 2, FUN=function(x){ cand=rep(0,n); cand[x] <- pidx[ modificationPattern %in% acids[x] ] - 1 return(paste(cand, collapse="")) }) )) } }else if (length(hits) == 1){ cand=rep(0,n); cand[hits]<-1 result<-c(result, paste(cand, collapse="")) } R[[length(R)+1]] <- unique(result) } return(R) }
optimizeSubInts = function(f, interval, ..., lower = min(interval), upper = max(interval), maximum = FALSE, tol = .Machine$double.eps^0.25, nsub = 50L) { nsub = asCount(nsub, positive = TRUE) interval = c(lower, upper) best = optimize(f = f, interval = interval, maximum = maximum, tol = tol) if (nsub > 1L) { mult = ifelse(maximum, -1, 1) grid = seq(lower, upper, length.out = nsub - 1L) for (j in seq_len(length(grid)-1L)) { res = optimize(f = f, interval = c(grid[j], grid[j+1L]), maximum = maximum, tol = tol) if (mult * res$objective < mult * best$objective) best = res } } return(best) }
nn.search = function(data, query, k = min(10, nrow(data)), treetype = c("kd", "bd"), searchtype = c("standard", "priority", "radius"), radius = 1.0, eps = 0.0) { dimension = ncol(data) ND = nrow(data) NQ = nrow(query) if (ncol(data) != ncol(query)) { stop("Query and data tables must have same dimensions") } if (k > ND) { stop("Cannot find more nearest neighbours than there are points") } searchtypeInt = pmatch(searchtype[1], c("standard", "priority", "radius")) if (is.na(searchtypeInt)) { stop(paste("Unknown search type", searchtype)) } treetype = match.arg(treetype, c("kd", "bd")) if (is.data.frame(data)) { data = unlist(data, use.names = FALSE) } if (!is.matrix(query)) { query = unlist(query, use.names = FALSE) } results = .Call( "_nonlinearTseries_get_NN_2Set_wrapper", data, query, dimension, ND, NQ, as.integer(k), as.double(eps), as.integer(searchtypeInt), as.integer(treetype == "bd"), as.double(radius * radius), nn.idx = integer(k * NQ), nn = double(k * NQ), PACKAGE = "nonlinearTseries" ) nn.indexes = matrix(results$nn_index, ncol = k, byrow = TRUE) nn.dist = matrix(results$distances, ncol = k, byrow = TRUE) list(nn.idx = nn.indexes, nn.dists = nn.dist ^ 2) }
mcrnonneg <- function(D,C,S,stop.threshold=.0001,max.iter=100) { D[is.na(D)==T] <- 0 C[is.na(C)==T] <- 0 S[is.na(S)==T] <- 0 C <- as.matrix(C) S <- as.matrix(S) RD <- 1 res <- rep(0,nrow(D)) res <- apply(as.matrix(1:nrow(D)),1,function(i) sum((D[i,] - (C[i,] %*% t(S)))^2)) oldrss <- sum(res) Cd <- dim(C) Sd <- dim(S) k <- 0 while(abs(RD)>stop.threshold) { if(is.even(k)==T){ S <- t(apply(as.matrix(1:ncol(D)),1,function(i){nnls(C,D[,i])$x})) if(!all(dim(S)==Sd)) dim(S) <- Sd S <- normalize(S) }else{ C <- t(apply(as.matrix(1:nrow(D)),1,function(i){nnls(S,D[i,])$x})) if(!all(dim(C)==Cd)) dim(C) <- Cd } res <- apply(as.matrix(1:nrow(D)),1,function(i) sum((D[i,] - (C[i,] %*% t(S)))^2)) rss <- sum(res) RD <- ((oldrss - rss)/oldrss) RD[is.na(RD)] <- 0 oldrss <- rss k <- k + 1 if(k>=max.iter) break } return(list(resC=C,resS=S)) }
state <- par("mar", "mfrow") par(mfrow = c(4, 3), mar=c(1,3,3,1)) nms <- names(twelve_from_slant_wide) for (i in seq(1, 23, by = 2)){ nm <- substr(nms[i], 1, nchar(nms[i]) - 2) plot(twelve_from_slant_wide[[nms[i]]], twelve_from_slant_wide[[nms[i+1]]], xlab = "", ylab = "", main = nm) } par(state)
parse.pde <- function(card) { yr = as.numeric(substr(card,9,12)) mo = as.numeric(substr(card, 15,16)) day = as.numeric(substr(card,18, 19 )) hr = as.numeric(substr(card, 21,22)) mi = as.numeric(substr(card, 23,24)) sec = as.numeric(substr(card, 25,29)) lat= as.numeric(substr(card, 30, 36)) lon= as.numeric(substr(card, 37, 44)) depth= as.numeric(substr(card, 46, 48)) if(is.numeric(depth)) { z = depth } else { z = 0 } mag = as.numeric(substr(card, 50, 53)) jd = getjul(yr, mo, day) locdate = list(yr=yr, jd=jd, mo=mo, dom=day, hr=hr, mi=mi, sec=sec, lat=lat, lon=lon, depth=depth, z=z, mag=mag) return(locdate) }
ettersonEq14 <- function(s,f,J){ pr <- 1-s pd <- f q_d <- 1-pd; q_r <- 1-pr; n <- length(J); Svec <- c(q_r,pr,0,0,1,0,0,0,1); S <- matrix( Svec, ncol=3, byrow=TRUE ) Dvec <- c(q_d,0,pd,0,1,0,0,0,1); D <- matrix( Dvec, ncol=3, byrow=TRUE ) gfe <- 0; V1<- matrix( c(1,0,0), ncol=3, byrow=TRUE) V3<- matrix( c(0,0,1), ncol=3, byrow=TRUE) for (k in 1:(n-1)){ dk <- J[k]; A <- diag(3); for (m in (k+1):n){ dm = J[m]; A = A %*% (S %^%dm) %*% D; } for (h in 1:dk){ A1 <- (S %^% h) %*% D; gfe <- gfe + V1 %*% A1 %*% A %*% t(V3); } } dn <- J[n]; for (h in 1:dn){ A1 <- (S %^% h) %*% D; gfe <- gfe + V1 %*% A1 %*% t(V3); } p <- gfe/sum(J) return(p) }
library(testthat) library(photosynthesis) context("Fitting pressure volume curves") df <- data.frame( psi = c( -0.14, -0.8, -1.2, -1.75, -2.15, -2.5, -3, -4 ), mass = c( 3.47, 3.43, 3.39, 3.33, 3.22, 3.15, 3.07, 2.98 ), leaf_mass = c(rep(0.56, 8)), bag_mass = c(rep(1.53, 8)), leaf_area = c(rep(95, 8)) ) model <- fit_PV_curve(df) test_that("Outputs", { expect_is(object = model[[1]], class = "data.frame") expect_is(object = model[2], class = "list") expect_is(object = model[3], class = "list") expect_length(object = model, 3) })
lavaanify.grep.MEASERR <- function( lavmodel ) { lavmodel0 <- lavmodel lavmodel <- gsub( ";", "\n", lavmodel, fixed=TRUE) lavmodel <- gsub( " ", "", lavmodel ) syn <- strsplit( lavmodel, split="\n", fixed=TRUE )[[1]] syn <- syn[ syn !="" ] SS <- length(syn) dfr <- data.frame( "index"=1:SS, "syn"=syn ) dfr$MEASERR <- 1 * ( substring( dfr$syn, 1, 7 )=="MEASERR" ) dfr$MEASERR1 <- 1 * ( substring( dfr$syn, 1, 8 )=="MEASERR1" ) dfr$MEASERR0 <- 1 * ( substring( dfr$syn, 1, 8 )=="MEASERR0" ) dfr$true <- NA dfr$obs <- NA dfr$errvar <- NA ind <- which( dfr$MEASERR==1 ) if ( length(ind) > 0 ){ for (ii in ind ){ l1 <- paste(dfr$syn[ii] ) l1 <- gsub( "MEASERR1(", "", l1, fixed=TRUE ) l1 <- gsub( "MEASERR0(", "", l1, fixed=TRUE ) l1 <- gsub( ")", "", l1, fixed=TRUE ) l2 <- strsplit( l1, "," )[[1]] dfr[ ii, "true" ] <- l2[1] dfr[ ii, "obs" ] <- l2[2] dfr[ ii, "errvar" ] <- as.numeric( l2[3] ) } N1 <- nrow(dfr) lavmodel0 <- "" for (nn in 1:N1){ if ( dfr$MEASERR[nn]==0 ){ lavmodel0 <- paste0( lavmodel0, "\n", dfr[nn,"syn"] ) } if ( dfr$MEASERR[nn]==1 ){ lavmodel0 <- paste0( lavmodel0, "\n", dfr[nn,"true"], "=~1*", dfr[nn,"obs"] ) lavmodel0 <- paste0( lavmodel0, "\n", dfr[nn,"obs"], "~~", dfr[nn,"errvar"], "*", dfr[nn,"obs"] ) } if ( dfr$MEASERR0[nn]==1 ){ lavmodel0 <- paste0( lavmodel0, "\n", dfr[nn,"true"], "~~", dfr[nn,"true"] ) } } } return(lavmodel0) }
ISOScale <- R6Class("ISOScale", inherit = ISOMeasure, private = list( xmlElement = "Scale", xmlNamespacePrefix = "GCO" ), public = list( initialize = function(xml = NULL, value, uom, useUomURI = FALSE){ super$initialize( xml = xml, value = value, uom = uom ) } ) )
"_PACKAGE" NULL
pocrepath<-function(y, x, delta=0.1, maxvar=dim(x)[1]/2, x.nop=NA, maxcmp=10, ptype=c('ebtz','ebt','l1','scad','mcp'), lambda.init=1, maxit=100, tol=1e-6, maxtps=500, gamma=3.7, pval=(dim(y)[2]==1)) { y <- as.matrix(y) x <- as.matrix(x) ptype <- ptype[1] retRes <- vector("list",length = maxtps) eps <- .Machine$double.eps n <- dim(x)[1] p <- dim(x)[2] k <- dim(y)[2] if(n!=dim(y)[1]) stop("x and y should have the same number of rows!") idxM <- 0 lambda <- lambda.init while(idxM <= maxtps){ cat(paste("Tuning Parameter:", lambda)) idxM <- idxM + 1 retRes[[idxM]] <- pocre(y,x,lambda,x.nop,maxvar,maxcmp,ptype,maxit,tol,gamma,pval) if(lambda>=lambda.init){ if((retRes[[idxM]]$nzBeta==0) && (retRes[[idxM]]$bSparse)){ if(retRes[[1]]$bSparse){ lambda <- lambda.init-delta }else{ break } }else{ lambda <- lambda+delta } }else if((lambda<lambda.init) && (retRes[[idxM]]$bSparse)){ lambda <- lambda-delta }else{ break } } lambda <- NULL for(i in 1:idxM){ lambda <- c(lambda,retRes[[i]]$lambda) } tmpL <- sort(lambda, index.return = T)$x idxL <- sort(lambda, index.return = T)$ix retRes <- retRes[idxL] class(retRes) <- c('pocrepath','pocre') return(retRes) }
search_users <- function(q, n = 100, parse = TRUE, token = NULL, verbose = TRUE) { args <- list( q = q, n = n, parse = parse, token = token, verbose = verbose ) do.call("search_users_call", args) } search_users_call <- function(q, n = 20, parse = TRUE, token = NULL, verbose = TRUE) { query <- "users/search" stopifnot(is_n(n), is.atomic(q)) token <- check_token(token) if (n > 1000) { warning( paste0("search only returns up to 1,000 users per ", "unique search. Setting n to 1000...")) n <- 1000 } n.times <- ceiling(n / 20) if (n.times > 50) n.times <- 50 if (n < 20) { count <- n } else { count <- 20 } if (nchar(q) > 500) { stop("q cannot exceed 500 characters.", call. = FALSE) } if (verbose) message("Searching for users...") usr <- vector("list", n.times) k <- 0 nrows <- NULL for (i in seq_len(n.times)) { params <- list( q = q, count = count, page = i, tweet_mode = "extended" ) url <- make_url( query = query, param = params ) r <- tryCatch( TWIT(get = TRUE, url, token), error = function(e) return(NULL)) if (is.null(r)) break usr[[i]] <- from_js(r) if (i > 1L) { if (identical(usr[[i]], usr[[i - 1L]])) { usr <- usr[-i] break } } if (identical(length(usr[[i]]), 0)) break if (isTRUE(is.numeric(NROW(usr[[i]])))) { nrows <- NROW(usr[[i]]) } else { if (identical(nrows, 0)) break nrows <- 0 } k <- k + nrows if (k >= n * 20) break } if (parse) { usr <- tweets_with_users(usr) } if (verbose) { message("Finished collecting users!") } usr }
context("Testing CoBC") source("wine.R") require(caret) test_that( desc = "coBC works", code = { m <- coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3) expect_is(m, "coBC") p <- predict(m, wine$xitest) expect_is(p, "factor") expect_equal(length(p), length(wine$ytrain)) m <- coBC(x = wine$dtrain, y = wine$ytrain, x.inst = FALSE, learner = knn3) expect_is(m, "coBC") p <- predict(m, wine$ditest[, m$instances.index]) expect_is(p, "factor") expect_equal(length(p), length(wine$ytrain)) } ) test_that( desc = "prediction not fail when x is a vector", code = { m <- coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3) p <- predict(m, wine$xitest[1,]) expect_is(p, "factor") expect_equal(length(p), 1) } ) test_that( desc = "the model structure is correct", code = { m <- coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3) expect_equal( names(m), c("model", "model.index", "instances.index", "model.index.map", "classes", "pred", "pred.pars", "x.inst") ) } ) test_that( desc = "x can be a data.frame", code = { expect_is( coBC(x = as.data.frame(wine$xtrain), y = wine$ytrain, learner = knn3), "coBC" ) } ) test_that( desc = "y can be a vector", code = { expect_is( coBC(x = wine$xtrain, y = as.vector(wine$ytrain), learner = knn3), "coBC" ) } ) test_that( desc = "x.inst can be coerced to logical", code = { expect_is( coBC(x = wine$xtrain, y = wine$ytrain, x.inst = TRUE, learner = knn3), "coBC" ) expect_is( coBC(x = wine$xtrain, y = wine$ytrain, x.inst = 1, learner = knn3), "coBC" ) expect_error( coBC(x = wine$xtrain, y = wine$ytrain, x.inst = "a", learner = knn3) ) } ) test_that( desc = "relation between x and y is correct", code = { expect_error( coBC(x = wine$xtrain, y = wine$ytrain[-1], learner = knn3) ) expect_error( coBC(x = wine$xtrain[-1,], y = wine$ytrain, learner = knn3) ) } ) test_that( desc = "y has some labeled instances", code = { expect_error( coBC(x = wine$xtrain, y = rep(NA, length(wine$ytrain)), learner = knn3) ) } ) test_that( desc = "y has some unlabeled instances", code = { expect_error( coBC(x = wine$xtrain, y = rep(1, length(wine$ytrain)), learner = knn3) ) } ) test_that( desc = "x is a square matrix when x.inst is FALSE", code = { expect_error( coBC(x = wine$dtrain[-1,], y = wine$ytrain, x.inst = FALSE, learner = knn3) ) expect_is( coBC(x = wine$dtrain, y = wine$ytrain, x.inst = FALSE, learner = knn3), "coBC" ) } ) test_that( desc = "max.iter is a value greather than 0", code = { expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, max.iter = -1) ) expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, max.iter = 0) ) expect_is( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, max.iter = 80), "coBC" ) } ) test_that( desc = "perc.full is a value between 0 and 1", code = { expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, perc.full = -0.5) ) expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, perc.full = 1.5) ) expect_is( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, perc.full = 0.8), "coBC" ) } ) test_that( desc = "N is a value greather than 0", code = { expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, N = -1) ) expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, N = 0) ) expect_is( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, N = 2), "coBC" ) } ) test_that( desc = "u is a value greather than 0", code = { expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, u = -1) ) expect_error( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, u = 0) ) expect_is( coBC(x = wine$xtrain, y = wine$ytrain, learner = knn3, u = 80), "coBC" ) } )
get_census_api <- function(data_url, key, vars, region, retry = 0) { if(length(vars) > 50){ vars <- vec_to_chunk(vars) get <- lapply(vars, function(x) paste(x, sep='', collapse=",")) data <- lapply(vars, function(x) get_census_api_2(data_url, key, x, region, retry)) } else { get <- paste(vars, sep='', collapse=',') data <- list(get_census_api_2(data_url, key, get, region, retry)) } if(all(sapply(data, is.data.frame))){ colnames <- unlist(lapply(data, names)) data <- do.call(cbind,data) names(data) <- colnames data <- data[,unique(colnames, fromLast=TRUE)] data <- data[,c(which(sapply(data, class)!='numeric'), which(sapply(data, class)=='numeric'))] return(data) } else{ print('Unable to create single data.frame in get_census_api') return(data) } }
library(shiny) library(adegenet) shinyServer(function(input, output) { graphTitle <- reactive({ paste(input$dataset, ": DAPC scatterplot, axes ", input$xax,"-", input$yax, sep="") }) output$caption <- renderText({ graphTitle() }) getData <- reactive({ out <- NULL if(input$datatype=="expl"){ if(input$dataset=="microbov") data("microbov", package="adegenet", envir=environment()) if(input$dataset=="sim2pop") data("sim2pop", package="adegenet", envir=environment()) if(input$dataset=="nancycats") data("nancycats", package="adegenet", envir=environment()) out <- get(input$dataset) } if(input$datatype=="file" && !is.null(input$datafile)){ oldName <- input$datafile$datapath extension <- .readExt(input$datafile$name) newName <- paste(input$datafile$datapath, extension, sep=".") file.rename(oldName, newName) if(extension %in% c("gtx","gen","dat","GTX","GEN","DAT")){ out <- import2genind(newName) } if(extension %in% c("RData","Rdata","Rda","rda")){ out <- get(load(newName)) } if(extension %in% c("fasta","fa","fas","aln","FASTA","FA","FAS","ALN")){ out <- DNAbin2genind(fasta2DNAbin(newName)) } } return(out) }) output$npca <- renderUI({ if(!is.null(x <- getData())) { nmax <- min(dim(x@tab)) def <- min(10, nmax) if(input$useoptimnpca){ xval1 <- xvaldapc() npca <- as.integer(xval1[[6]]) def <- npca} } else { nmax <- 1000 def <- 1 } sliderInput("npca", "Number of PCA axes retained:", min=1, max=nmax, value=def,step=1) }) output$nda <- renderUI({ if(!is.null(x <- getData())) { nmax <- max(length(levels(pop(x)))-1,2) def <- length(levels(pop(x)))-1 } else { nmax <- 100 def <- 1 } sliderInput("nda", "Number of DA axes retained:", min=1, max=nmax, value=def,step=1) }) output$xax <- renderUI({ if(!is.null(x <- getData())) { nmax <- min(dim(x@tab)) } else { nmax <- 1000 } numericInput("xax", "Indicate the x axis", value=1, min=1, max=nmax) }) output$yax <- renderUI({ def <- 1 nda <- 1 if(!is.null(input$nda)) nda <- input$nda if(!is.null(x <- getData())) { nmax <- min(dim(x@tab)) if(nda>1 && length(levels(pop(x)))>1) def <- 2 } else { nmax <- 1000 } numericInput("yax", "Indicate the y axis", value=def, min=1, max=nmax) }) output$doxval <- renderUI({ checkboxInput("doxval", "Perform cross validation (computer intensive)?", input$doxval) }) output$npcaMax <- renderUI({ if(!is.null(x <- getData())) { nmax <- min(dim(x@tab)) def <- nmax } else { nmax <- 1000 def <- 1 } sliderInput("npcaMax", "Maximum number of PCs:", min=1, max=nmax, value=def,step=1) }) xvaldapc <- reactive({ doxval <- FALSE if(!is.null(input$doxval)) doxval <- input$doxval if(input$useoptimnpca || doxval){ x <- getData() mat <- tab(x, NA.method="mean") grp <- pop(x) result <- input$result n.rep <- input$nrep nda <- 1 if(!is.null(input$nda)) nda <- input$nda training.set <- input$trainingset npcaMax <- 1 if(!is.null(input$npcaMax)) npcaMax <- input$npcaMax out <- xvalDapc(mat, grp, n.pca.max=npcaMax, result=result, n.rep=n.rep, n.da=nda, training.set=training.set, xval.plot=FALSE) } else{ out <- NULL } return(out) }) output$xvalPlot <- renderPlot({ xval1 <- xvaldapc() if(!is.null(xval1)){ x <- getData() mat <- tab(x, NA.method="mean") grp <- pop(x) xval2 <- xval1[[1]] successV <-as.vector(xval2$success) random <- replicate(300, mean(tapply(sample(grp)==grp, grp, mean))) q.GRP <- quantile(random, c(0.025,0.5,0.975)) smoothScatter(xval2$n.pca, successV, nrpoints=Inf, pch=20, col=transp("black"), ylim=c(0,1), xlab="Number of PCA axes retained", ylab="Proportion of successful outcome prediction", main="DAPC Cross-Validation") print(abline(h=q.GRP, lty=c(2,1,2))) } }) output$xvalResults1 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[1]]) } }) output$xvalResults2 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[2]]) } }) output$xvalResults3 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[3]]) } }) output$xvalResults4 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[4]]) } }) output$xvalResults5 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[5]]) } }) output$xvalResults6 <-renderPrint({ xval1 <- xvaldapc() if(!is.null(xval1)){ print(xval1[[6]]) } }) getDapc <- reactive({ out <- NULL x <- getData() npca <- nda <- 1 if(input$useoptimnpca){ xval1 <- xvaldapc() npca <- as.integer(xval1[[6]]) } else { if(!is.null(input$npca)) npca <- input$npca } if(!is.null(input$nda)) nda <- input$nda if(!is.null(x)) out <- dapc(x, n.pca=npca, n.da=nda, parallel=FALSE) return(out) }) getPlotParam <- reactive({ col.pal <- get(input$col.pal) return(list(col.pal=col.pal)) }) output$scatterplot <- renderPlot({ dapc1 <- getDapc() if(!is.null(dapc1)){ K <- length(levels(dapc1$grp)) myCol <- get(input$col.pal)(K) scree.pca <- ifelse(input$screepca=="none", FALSE, TRUE) scree.da <- ifelse(input$screeda=="none", FALSE, TRUE) cellipse <- ifelse(input$ellipses, 1.5, 0) cstar <- ifelse(input$stars, 1, 0) scatter(dapc1, xax=input$xax, yax=input$yax, col=myCol, scree.pca=scree.pca, scree.da=scree.da, posi.pca=input$screepca, posi.da=input$screeda, cellipse=cellipse, cstar=cstar, mstree=input$mstree, cex=input$pointsize, clabel=input$labelsize, solid=1-input$alpha) } else { NULL } }) output$summary <- renderPrint({ dapc1 <- getDapc() if(!is.null(dapc1)){ summary(dapc1) } }) output$compoplot <- renderPlot({ dapc1 <- getDapc() if(!is.null(dapc1)){ K <- length(levels(dapc1$grp)) myCol <- get(input$col.pal)(K) compoplot(dapc1, col=myCol, lab=input$compo.lab, legend=input$compo.legend) } }) output$LPax <- renderUI({ def <- 1 nda <- 1 nmax <- 2 if(!is.null(x <- getData())) { if(!is.null(input$nda)) nda <- input$nda nmax <- nda if(!is.null(input$LPax)) def <- input$LPax } numericInput("LPax", "Select discriminant axis", value=def, min=1, max=nmax) }) selector <- reactive({ dimension <- 1 dapc1 <- getDapc() if(!is.null(dapc1)){ if(!is.null(input$thresholdMethod)) method <- input$thresholdMethod if(!is.null(input$LPaxis)) dimension <- input$LPaxis x <- getData() mat <- tab(x, NA.method="mean") } if(method=="quartile"){ x <- dapc1$var.contr[,dimension] thresh <- quantile(x,0.75) maximus <- which(x > thresh) n.snp.selected <- length(maximus) sel.snps <- mat[,maximus] } else{ z <- dapc1$var.contr[,dimension] xTotal <- dapc1$var.contr[,dimension] toto <- which(xTotal%in%tail(sort(xTotal), 2000)) z <- sapply(toto, function(e) xTotal[e]) D <- dist(z) clust <- hclust(D,method) pop <- factor(cutree(clust,k=2,h=NULL)) m <- which.max(tapply(z,pop,mean)) maximus <- which(pop==m) maximus <- as.vector(unlist(sapply(maximus, function(e) toto[e]))) popvect <- as.vector(unclass(pop)) n.snp.selected <- sum(popvect==m) sel.snps <- mat[,maximus] } selection <- c((ncol(mat)-ncol(mat[,-maximus])), ncol(mat[,-maximus])) resultat <- list(selection, maximus, dimnames(sel.snps)[[2]], dapc1$var.contr[maximus, dimension]) return(resultat) }) output$loadingplot <- renderPlot({ dapc1 <- getDapc() LPaxis <- 1 if(!is.null(dapc1)){ LPaxis <- 1 if(!is.null(input$LPax)) LPaxis <- input$LPax if(input$threshold){ if(input$thresholdMethod=="quartile"){ x <- dapc1$var.contr[,LPaxis] def <- quantile(x,0.75) }else{ select <- selector() thresh <- select[[2]] def <- abs(dapc1$var.contr[thresh][(which.min(dapc1$var.contr[thresh]))])-0.000001} } else{ def <- NULL} loadingplot(dapc1$var.contr[,LPaxis], threshold=def) } }) output$FS1 <-renderPrint({ if(input$FS){ fs1 <- selector() if(!is.null(fs1)){ print(fs1[[1]]) } } }) output$FS2 <-renderPrint({ if(input$FS){ fs1 <- selector() if(!is.null(fs1)){ print(fs1[[2]]) } } }) output$FS3 <-renderPrint({ if(input$FS){ fs1 <- selector() if(!is.null(fs1)){ print(fs1[[3]]) } } }) output$FS4 <-renderPrint({ if(input$FS){ fs1 <- selector() if(!is.null(fs1)){ print(fs1[[4]]) } } }) output$systeminfo <- renderPrint({ cat("\n== R version ==\n") print(R.version) cat("\n== Date ==\n") print(date()) cat("\n== adegenet version ==\n") print(packageDescription("adegenet", fields=c("Package", "Version", "Date", "Built"))) cat("\n== shiny version ==\n") print(packageDescription("adegenet", fields=c("Package", "Version", "Date", "Built"))) cat("\n== attached packages ==\n") print(search()) }) })
uscores <- function(dat.frame, paired = TRUE, rnk=TRUE) { cols <- ncol(dat.frame) if (cols >2) { half <- cols/2 dat.orig <- as.matrix(na.omit (dat.frame)) j=0; uscr=0; DLmax=0; data.1 <- dat.orig; data.0 <- dat.orig if (paired) { for (i in seq(1, to=(cols-1), by=2)) {j = j+1 data.0[,j] <- dat.orig[,i] data.0[,j+half] <- dat.orig[,i+1] nvec <- colnames(data.0) nvec <- nvec[seq(1, (cols-1), 2)] nvec <- paste("usc.", nvec, sep="") } } else {data.0 <- dat.orig nvec <- colnames(data.0) nvec <- nvec[1:half] nvec <- paste("usc.", nvec, sep="") } u.out <- data.0[,1:half] for (i in 1:half) {u <- Usc(data.0[,i], data.0[,i+half], rnk=rnk) if (i==1) {u.out <- u} else {u.out <- cbind(u.out, u)} } colnames(u.out) <- nvec return(u.out) } else { x <- na.omit(dat.frame) names(x) <- c("y", "ind") n=length(x$y) ylo=(1-as.integer(x$ind))*x$y yadj=x$y-(sign(x$y-ylo)*0.001*x$y) overlap=x$y Score=overlap for (j in 1:n) { for (i in 1:n ){ overlap[i]=sign(sign(yadj[i]-ylo[j])+sign(ylo[i]-yadj[j])) } Score[j] = -1*sum(overlap) } if (rnk) {uscore=rank(Score)} else {uscore = Score} return(uscore) } }
defaultIon<-function(b, y){ Hydrogen <- 1.007825 Oxygen <- 15.994915 Nitrogen <- 14.003074 c <- b + (Nitrogen + (3 * Hydrogen)) z <- y - (Nitrogen + (3 * Hydrogen)) return(cbind(b, y, c ,z)) } fragmentIon <- function(sequence, FUN=defaultIon, modified=numeric(), modification=numeric(), N_term=1.007825, C_term=17.002740) { if (!is.character(sequence)) { R <- list() input.n <- length(sequence) out <- .C("_computeFragmentIons", n=input.n, W_=as.double(sequence), b_=as.double(rep(0,input.n)), y_=as.double(rep(0,input.n))) R[[1]] <- as.data.frame(FUN(out$b, out$y)) }else if (length(modification) > 1) { FUN <- match.fun(FUN) R <- list() pim <- parentIonMass(sequence) Oxygen <- 15.994915 Carbon <- 12.000000 Hydrogen <- 1.007825 Nitrogen <- 14.003074 Electron <- 0.000549 for (i in 1:length(sequence)){ input.sequence <- sequence[i] input.n <- nchar(input.sequence) input.modified <- as.integer(strsplit(modified[i], '')[[1]]) input.pim <- pim[i] + (sum(as.double(as.character(modification[input.modified + 1])))) if (input.n != length(input.modified)) stop (paste("unvalid argument",i,"- number of AA and modification config differ! stop.")) out <- .C("computeFragmentIonsModification", n=as.integer(input.n), pepSeq=as.character(input.sequence), pim=as.double(input.pim), b=as.double(rep(0.0, input.n)), y=as.double(rep(0.0, input.n)), modified=input.modified, modification=as.double(as.character(modification))) R[[length(R)+1]] <- as.data.frame(FUN(out$b, out$y)) attributes(R[[length(R)]])$sequence <- sequence[i] class(R[[length(R)]]) <- c('fragmentIon', class(R[[length(R)]])) } } else{ FUN<-match.fun(FUN) R <- list() pim <- parentIonMass(sequence) Oxygen <- 15.994915 Carbon <- 12.000000 Hydrogen <- 1.007825 Nitrogen <- 14.003074 Electron <- 0.000549 for (i in 1:length(sequence)){ pepseq<-sequence[i] pepseq.pim<-pim[i] out <- .C("computeFragmentIons", n=as.integer(nchar(pepseq)), pepSeq=as.character(pepseq), pim=as.double(pepseq.pim), b=as.double(rep(0.0,nchar(pepseq))), y=as.double(rep(0.0,nchar(pepseq)))) R[[length(R)+1]] <- as.data.frame(FUN(out$b, out$y)) attributes(R[[length(R)]])$sequence <- sequence[i] class(R[[length(R)]]) <- c('fragmentIon', class(R[[length(R)]])) } } class(R) <- c('fragmentIonSet', class(R)) return(R) } as.data.frame.fragmentIon <- function(x, ...){ long <- reshape(x, idvar = "pos", ids = row.names(x), times = names(x), timevar = "type", varying = list(names(x)), direction = "long") long$pos <- as.numeric(long$pos) names(long)[2] <- "mass" long <- long[order(long$mass), ] if ('sequence' %in% names(attributes(x))){ attr(long, 'sequence') <- attr(x, 'sequence') sequence <- attributes(long)$sequence sequence.n <- nchar(sequence) abc.idx <- grep("[abc]", long$type) xyz.idx <- grep("[xyz]", long$type) long$fragment <- NA long$sequence <- sequence long$fragment[abc.idx] <- substr(rep(sequence, length(abc.idx)), 1, long$pos[abc.idx]) long$fragment[xyz.idx] <- substr(rep(sequence, length(xyz.idx)), sequence.n - long$pos[xyz.idx] + 1, sequence.n) } row.names(long) <- paste(long$type, long$pos, sep='') long[long$pos != max(long$pos),] } as.data.frame.fragmentIonSet <- function(x, ...){ do.call('rbind', lapply(x, as.data.frame.fragmentIon)) }
"hmmer" <- function(seq, type='phmmer', db=NULL, verbose=TRUE, timeout=90) { cl <- match.call() oopsa <- requireNamespace("XML", quietly = TRUE) oopsb <- requireNamespace("RCurl", quietly = TRUE) if(!all(c(oopsa, oopsb))) stop("Please install the XML and RCurl package from CRAN") seqToStr <- function(seq) { if(inherits(seq, "fasta")) seq <- seq$ali if(is.matrix(seq)) { if(nrow(seq)>1) warning(paste("Alignment with multiple sequences detected. Using only the first sequence")) seq <- as.vector(seq[1,!is.gap(seq[1,])]) } else seq <- as.vector(seq[!is.gap(seq)]) return(paste(seq, collapse="")) } alnToStr <- function(seq) { if(!inherits(seq, "fasta")) stop("seq must be of type 'fasta'") tmpfile <- tempfile() write.fasta(seq, file=tmpfile) rawlines <- paste(readLines(tmpfile), collapse="\n") unlink(tmpfile) return(rawlines) } types.allowed <- c("phmmer", "hmmscan", "hmmsearch", "jackhmmer") if(! type%in%types.allowed ) stop(paste("Input type should be either of:", paste(types.allowed, collapse=", "))) if(type=="phmmer") { seq <- seqToStr(seq) if(is.null(db)) db="pdb" db.allowed <- c("env_nr", "nr", "refseq", "pdb", "rp15", "rp35", "rp55", "rp75", "swissprot", "unimes", "uniprotkb", "uniprotrefprot", "pfamseq") db <- tolower(db) if(!db%in%db.allowed) stop(paste("db must be either:", paste(db.allowed, collapse=", "))) seqdb <- db hmmdb <- NULL iter <- NULL rcurl <- TRUE } if(type=="hmmscan") { seq <- seqToStr(seq) if(is.null(db)) db="pfam" db.allowed <- tolower(c("pfam", "gene3d", "superfamily", "tigrfam")) db <- tolower(db) if(!db%in%db.allowed) stop(paste("db must be either:", paste(db.allowed, collapse=", "))) seqdb <- NULL hmmdb <- db iter <- NULL rcurl <- TRUE } if(type=="hmmsearch") { if(!inherits(seq, "fasta")) stop("please provide 'seq' as a 'fasta' object") seq <- alnToStr(seq) if(is.null(db)) db="pdb" db.allowed <- tolower(c("pdb", "swissprot")) db <- tolower(db) if(!db%in%db.allowed) stop(paste("db must be either:", paste(db.allowed, collapse=", "))) seqdb <- db hmmdb <- NULL iter <- NULL rcurl <- TRUE } if(type=="jackhmmer") { if(!inherits(seq, "fasta")) stop("please provide 'seq' as a 'fasta' object") seq <- alnToStr(seq) if(is.null(db)) db="pdb" db.allowed <- tolower(c("pdb", "swissprot")) db.allowed <- c("env_nr", "nr", "refseq", "pdb", "rp15", "rp35", "rp55", "rp75", "swissprot", "unimes", "uniprotkb", "uniprotrefprot", "pfamseq") db <- tolower(db) if(!db%in%db.allowed) stop(paste("db must be either:", paste(db.allowed, collapse=", "))) seqdb <- db hmmdb <- NULL iter <- NULL rcurl <- TRUE } url <- paste("https://www.ebi.ac.uk/Tools/hmmer/search/", type, sep="") curl.opts <- list(httpheader = "Expect:", httpheader = "Accept:text/xml", verbose = verbose, followlocation = TRUE ) hmm <- RCurl::postForm(url, hmmdb=hmmdb, seqdb=seqdb, seq=seq, style = "POST", .opts = curl.opts, .contentEncodeFun=RCurl::curlPercentEncode, .checkParams=TRUE ) if(!grepl("results", hmm)) { if(verbose) { message("Content from HMMER server:") message(" ", hmm) } stop("Request to HMMER server failed") } add.pdbs <- function(x, ...) { hit <- XML::xpathSApply(x, '@*') pdbs <- unique(XML::xpathSApply(x, 'pdbs', XML::xmlToList)) new <- as.matrix(hit, ncol=1) if(length(pdbs) > 1) { for(i in 1:length(pdbs)) { hit["acc"]=pdbs[i] new=cbind(new, hit) } colnames(new)=NULL } return(new) } if(grepl("act_site", hmm)) { lines <- unlist(strsplit(hmm, "\n")) actsite.inds <- grep("act_site", lines) actlen <- length(actsite.inds) if(actlen>2) { if(actlen%%2 != 0) { stop("Bad XML format") } rm.inds <- NULL for(i in seq(1, actlen, 2)) { rm.inds <- c(rm.inds, seq(actsite.inds[i], actsite.inds[i+1])) } hmm <- paste(lines[-rm.inds], collapse="\n") } else { hmm <- paste(lines[-seq(actsite.inds[1], actsite.inds[2])], collapse="\n") } } xml <- XML::xmlParse(hmm) resurl <- XML::xpathSApply(xml, '//data', XML::xpathSApply, '@*') resurl <- paste0("http://www.ebi.ac.uk/Tools/hmmer/results/", resurl["uuid", 1]) data <- XML::xpathSApply(xml, '///hits', XML::xpathSApply, '@*') pdb.ids <- NULL if(db=="pdb") { tmp <- XML::xpathSApply(xml, '///hits', add.pdbs) data <- as.data.frame(tmp, stringsAsFactors=FALSE) colnames(data) <- NULL } data <- as.data.frame(t(data), stringsAsFactors=FALSE) data <- data[!duplicated(data$acc), ] fieldsToNumeric <- c("evalue", "pvalue", "score", "archScore", "ndom", "nincluded", "niseqs", "nregions", "nreported", "bias", "dcl", "hindex") inds <- which(names(data) %in% fieldsToNumeric) for(i in 1:length(inds)) { tryCatch({ data[[inds[i]]] = as.numeric(data[[inds[i]]]) }, warning = function(w) { return(data[[inds[i]]]) }, error = function(e) { return(data[[inds[i]]]) } ) } data$pdb.id <- data$acc data$bitscore <- data$score data$mlog.evalue <- -log(data$evalue) data$mlog.evalue[is.infinite(data$mlog.evalue)] <- -log(.Machine$double.xmin) out <- list(hit.tbl = data, url = resurl) class(out) <- c("hmmer", type) return(out) }
library(MetaLandSim) data(occ.landscape) data(occ.landscape2) param1 <- parameter.estimate (occ.landscape, method='Rsnap_1') param1 param2 <- parameter.estimate (occ.landscape2, method='Rsnap_x', nsnap=10) param2
context("WellSVM") data(diabetes) test_that("Implementation gives same result as Matlab implementation",{ acc <- RSSL:::wellsvm_direct(rbind(diabetes$data[diabetes$idxLabs[1,],],diabetes$data[diabetes$idxUnls[1,],]), rbind(diabetes$target[diabetes$idxLabs[1,],,drop=FALSE],matrix(0,length(diabetes$idxUnls[1,]),1)), diabetes$data[diabetes$idxTest[1,],], diabetes$target[diabetes$idxTest[1,],,drop=FALSE], C = 1,C2=0.1,gamma=1)$accuracy expect_equal(acc, 0.7864583,tolerance=10e-6) }) test_that("svmd does not throw an error",{ library(RSSL) library(kernlab) K <- kernelMatrix(rbfdot(),as.matrix(iris[1:100,1:2])) RSSL:::svmd(iris[1:100,1:2],y=iris$Species[1:100],fitted=FALSE) expect_silent(RSSL:::svmd(K,y=iris$Species[1:100],type="one-classification")) }) test_that("WellSVM interface result equal to direct result",{ data <- iris[1:100,] x <- as.matrix(data[,1:3]) y <- model.matrix(~Species,data)[,2]*2-1 g_train <- WellSVM(x,factor(y),x,gamma=1,x_center=TRUE) expect_equal(predict(g_train,x), factor(RSSL:::wellsvm_direct(rbind(x,x), rbind(matrix(y,ncol=1), matrix(0,nrow=nrow(x))), x,y,gamma=1)$prediction)) })
if (!at_home() || !bspm:::root()) exit_file("not in a CI environment") sudo.avail <- unname(nchar(Sys.which("sudo")) > 0) in.toolbox <- file.exists("/run/.toolboxenv") if (sudo.avail || in.toolbox) { expect_true(bspm:::sudo_available()) } else { expect_false(bspm:::sudo_available()) file.create("/run/.toolboxenv") expect_true(bspm:::sudo_available()) } if (requireNamespace("Rcpp", quietly=TRUE)) exit_file("not in a clean environment") bspm.pref <- system.file("service/bspm.pref", package="bspm") bspm.excl <- system.file("service/bspm.excl", package="bspm") expect_true(all(c(bspm.pref, bspm.excl) == "")) discover() bspm.pref <- system.file("service/bspm.pref", package="bspm") bspm.excl <- system.file("service/bspm.excl", package="bspm") expect_true(all(c(bspm.pref, bspm.excl) != "")) pkgs <- install_sys(c("Rcpp", "NOTAPACKAGE")) expect_true(requireNamespace("Rcpp", quietly=TRUE)) expect_equal(pkgs, "NOTAPACKAGE") unloadNamespace("Rcpp") pkgs <- remove_sys(c("Rcpp", "NOTAPACKAGE")) expect_false(requireNamespace("Rcpp", quietly=TRUE)) expect_equal(pkgs, "NOTAPACKAGE")
MAPE_P_gene_KS <- function(study,label,censoring.status,DB.matrix,size.min=15,size.max=500,nperm=500,stat=NULL,rth.value=NULL,resp.type){ if (is.null(names(study))) names(study)=paste('study.',1:length(study),sep="") out=list() for(t1 in 1:length(study)){ madata=study[[t1]] testlabel=madata[[label]] out[[t1]]=list() if (resp.type=="survival") { censoring=madata[[censoring.status]] } out[[t1]]=Enrichment_KS_gene(madata=madata,label=testlabel,censoring=censoring,DB.matrix=DB.matrix,size.min=size.min,size.max=size.max,nperm=nperm,resp.type=resp.type) } set.common=rownames(out[[1]]$pvalue.set.0) for(t1 in 2:length(study)){ set.common=intersect(set.common,rownames(out[[t1]]$pvalue.set.0)) } if (is.null(names(study))) names(study)=paste('study.',1:length(study),sep="") pvalue.B.array=array(data=NA,dim=c(length(set.common),nperm,length(study)),dimnames=names(study)) pvalue.0.mtx=matrix(NA,length(set.common),length(study)) qvalue.0.mtx=matrix(NA,length(set.common),length(study)) for(t1 in 1:length(study)){ pvalue.B.array[,,t1]=out[[t1]]$pvalue.set.B[set.common,] pvalue.0.mtx[,t1]=out[[t1]]$pvalue.set.0[set.common,] qvalue.0.mtx[,t1]=out[[t1]]$qvalue.set.0[set.common,] } rownames(qvalue.0.mtx)=set.common rownames(pvalue.0.mtx)=set.common rm(out) if(stat=='maxP'){ P.0=as.matrix(apply(pvalue.0.mtx,1,max)) rownames(P.0)=rownames(qvalue.0.mtx) P.B=apply(pvalue.B.array,c(1,2),max) rownames(P.B)=rownames(qvalue.0.mtx) } else if (stat=='minP'){ P.0=as.matrix(apply(pvalue.0.mtx,1,min)) rownames(P.0)=rownames(qvalue.0.mtx) P.B=apply(pvalue.B.array,c(1,2),min) rownames(P.B)=rownames(qvalue.0.mtx) } else if (stat=='rth'){ P.0=as.matrix(apply(pvalue.0.mtx,1,function(x) sort(x)[ceiling(rth.value*ncol(pvalue.0.mtx))])) rownames(P.0)=rownames(qvalue.0.mtx) P.B=apply(pvalue.B.array,c(1,2),function(x) sort(x)[ceiling(rth.value*dim(pvalue.B.array)[3])]) rownames(P.B)=rownames(qvalue.0.mtx) } else if (stat=='Fisher'){ DF=2*length(study) P.0=as.matrix(apply(pvalue.0.mtx,1,function(x) pchisq(-2*sum(log(x)),DF,lower.tail=T) )) rownames(P.0)=rownames(qvalue.0.mtx) P.B=apply(pvalue.B.array,c(1,2),function(x) pchisq(-2*sum(log(x)),DF,lower.tail=T) ) rownames(P.B)=rownames(qvalue.0.mtx) } else { stop("Please check: the selection of stat should be one of the following options: maxP,minP,rth and Fisher") } meta.out=pqvalues.compute(P.0,P.B,Stat.type='Pvalue') return(list(pvalue.meta=meta.out$pvalue.0, qvalue.meta=meta.out$qvalue.0, pvalue.meta.B=meta.out$pvalue.B,qvalue.set.study=qvalue.0.mtx,pvalue.set.study=pvalue.0.mtx)) }
if (requiet("testthat") && requiet("parameters")) { data(iris) dat <- iris m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type default contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "versicolor", "virginica")) }) data(iris) dat <- iris dat$Species <- as.ordered(dat$Species) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type ordered factor", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "ordered", "ordered")) expect_equal(p_type$Level, c(NA, "[linear]", "[quadratic]")) }) data(iris) dat <- iris dat$Species <- as.ordered(dat$Species) contrasts(dat$Species) <- contr.treatment(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type ordered factor", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "2", "3")) }) data(iris) dat <- iris contrasts(dat$Species) <- contr.poly(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type poly contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, ".L", ".Q")) }) data(iris) dat <- iris contrasts(dat$Species) <- contr.treatment(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type treatment contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "2", "3")) }) data(iris) dat <- iris contrasts(dat$Species) <- contr.sum(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type sum contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "1", "2")) }) data(iris) dat <- iris contrasts(dat$Species) <- contr.helmert(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type helmert contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "1", "2")) }) data(iris) dat <- iris contrasts(dat$Species) <- contr.SAS(3) m <- lm(Sepal.Length ~ Species, data = dat) test_that("parameters_type SAS contrasts", { p_type <- parameters_type(m) expect_equal(p_type$Type, c("intercept", "factor", "factor")) expect_equal(p_type$Level, c(NA, "1", "2")) }) }
fusco.test <- function(phy, data , names.col , rich , tipsAsSpecies=FALSE, randomise.Iprime=TRUE, reps=1000, conf.int = 0.95){ if(inherits(phy, 'phylo') & missing(data)){ tipsAsSpecies <- TRUE data <- data.frame(nSpp = rep(1, length(phy$tip.label)), tips=phy$tip.label) phy <- comparative.data(phy = phy, data = data, names.col = 'tips') } else if(inherits(phy, "phylo" ) & ! missing(data)){ if(missing(names.col)) stop('Names column not specified') names.col <- deparse(substitute(names.col)) phy <- eval(substitute(comparative.data(phy = phy, data = data, names.col = XXX), list(XXX=names.col))) } else if(! inherits(phy, 'comparative.data')) { stop('phy must be a phylo or comparative.data object.') } if( ! tipsAsSpecies){ if(missing(rich)) { stop('The name of a column of richness values must be provided') } else { rich <- deparse(substitute(rich)) if(! rich %in% names(phy$data)) stop("The column '", rich, "' was not found in the data from '", phy$data.name,"'.") } } phy <- reorder(phy, "pruningwise") if(tipsAsSpecies){ rich <- rep(1, length(phy$phy$tip.label)) } else { rich <- phy$data[,rich,drop=TRUE] } nSpecies <- sum(rich) nTips <- length(rich) intNodes <- unique(phy$phy$edge[,1]) nTip <- length(phy$phy$tip.label) nNode <- phy$phy$Nnode rich <- c(rich, rep(NA, nNode)) observed <- data.frame(polytomy=logical(nNode), N1 = numeric(nNode), N2 = numeric(nNode), row.names=intNodes) for(ind in seq(along=intNodes)){ daughters <- phy$phy$edge[,2][phy$phy$edge[,1] == intNodes[ind]] richD <- rich[daughters] if(length(daughters) > 2){ observed$polytomy[ind] <- TRUE } else { observed[ind, 2:3] <- richD } rich[intNodes[ind]] <- sum(richD) } observed$S <- with(observed, N1 + N2) observed <- observed[! observed$polytomy & observed$S > 3, names(observed) != 'polytomy'] observed$B <- with(observed, pmax(N1, N2)) observed$M <- observed$S - 1 observed$m <- ceiling(observed$S/2) observed$I <- with(observed, (B - m)/(M - m)) observed$S.odd <- (observed$S %% 2) == 1 observed$w <- with(observed, ifelse(S.odd, 1, ifelse(I > 0, M/S, 2*M/S))) observed$I.w <- with(observed, (I*w)/mean(w)) observed$I.prime <- with(observed, ifelse(S.odd, I, I * M/S)) if(! is.null(phy$phy$node.label)){ observed$node <- phy$phy$node.label[as.numeric(rownames(observed)) - nTip] } obsStats <- with(observed, c(median(I), IQR(I)/2)) ret <- list(observed=observed, median.I=median(observed$I), mean.Iprime=mean(observed$I.prime), qd=IQR(observed$I)/2, tipsAsSpecies=tipsAsSpecies, nInformative=dim(observed)[1], nSpecies=nSpecies, nTips=nTips) class(ret) <- "fusco" if(randomise.Iprime){ expFun <- function(x){ y <- runif(length(x)) rand.I.prime <- ifelse(y>0.5,x,1-x) ret <- mean(rand.I.prime) return(ret) } randomised <- with(ret, replicate(reps, expFun(observed$I.prime))) randomised <- as.data.frame(randomised) names(randomised) <- "mean" rand.twotail <- c((1 - conf.int)/2, 1 - (1 - conf.int)/2) rand.mean <- quantile(randomised$mean, rand.twotail) ret <- c(ret, list(randomised=randomised, rand.mean=rand.mean, reps=reps, conf.int=conf.int)) } class(ret) <- "fusco" return(ret) } print.fusco <- function(x, ...){ print(x$observed) } summary.fusco <- function(object, ...){ cat("Fusco test for phylogenetic imbalance\n\n") cat(" Tree with", object$nInformative, "informative nodes and", object$nTips, "tips.\n") if(object$tipsAsSpecies){ cat(" Tips are treated as species.\n\n") } else { cat(" Tips are higher taxa containing", object$nSpecies, "species.\n") } if(! is.null(object$randomised) | ! is.null(object$simulated)){ cat(" ", sprintf("%2.1f%%", object$conf.int*100), "confidence intervals around 0.5 randomised using", object$reps, "replicates.\n" ) } cat("\n") cat(" Mean I prime:", round(object$mean.Iprime,3)) if(! is.null(object$randomised)){ cat(sprintf(" [%1.3f,%1.3f]", object$rand.mean[1],object$rand.mean[2])) } cat("\n") cat(" Median I:", round(object$median.I,3)) if(! is.null(object$simulated)){ cat(sprintf(" [%1.3f,%1.3f]", object$sim.median[1],object$sim.median[2])) } cat("\n") cat(" Quartile deviation in I:", round(object$qd,3)) if(! is.null(object$simulated)){ cat(sprintf(" [%1.3f,%1.3f]", object$sim.qd[1],object$sim.qd[2])) } cat("\n") print(wilcox.test(object$observed$I.prime, mu=0.5)) } plot.fusco <- function(x, correction=TRUE, nBins=10, right=FALSE, I.prime=TRUE, plot=TRUE, ...){ breaks <- seq(0,1,length=nBins+1) if(I.prime){ fuscoDist <- hist(x$observed$I.prime, breaks=breaks, plot=FALSE, right=right) xLab <- "Nodal imbalance score (I')" } else { fuscoDist <- hist(x$observed$I, breaks=breaks, plot=FALSE, right=right) xLab <- "Nodal imbalance score (I)" } interv <- levels(cut(0.5, breaks=breaks, right=right)) RET <- data.frame(imbalance=interv, observedFrequency=fuscoDist$density/nBins) if(correction==TRUE){ allPossI <- function(S, I.prime){ m <- ceiling(S/2) RET <- (seq(from=m, to=S-1) - m)/((S - 1) - m) if(I.prime & (S%%2) == 1) RET <- RET * (S-1) / S return(RET) } distrib <- sapply(x$observed$S, FUN=allPossI, I.prime=I.prime) distrib <- sapply(distrib, function(x) hist(x, breaks=breaks, plot=FALSE, right=right)$density) distrib <- distrib/nBins correction <- 1/nBins - distrib correction <- rowMeans(correction) RET$correction <- correction RET$correctedFrequency <- with(RET, observedFrequency + correction) if(plot){ plot(structure(list(density=RET$correctedFrequency, breaks=breaks), class="histogram"), freq=FALSE, ylab="Corrected Frequency", main="", xlab=xLab)} } else { if(plot){ plot(structure(list(density=RET$observedFrequency, breaks=breaks), class="histogram"), freq=FALSE, ylab="Observed Frequency", main="", xlab=xLab)} } if(plot){ if(I.prime){ abline(v=x$mean.Iprime) if(! is.null(x$rand.mean)) abline(v=x$rand.mean, col="red") } else { abline(v=median(x$observed$I)) if(! is.null(x$sim.median)) abline(v=x$sim.median, col="red") }} invisible(RET) }
spflow_mle <- function( ZZ, ZY, TSS, N, n_d, n_o, DW_traces, OW_traces, flow_control) { model <- flow_control$model hessian_method <- flow_control$mle_hessian_method delta_t <- solve(ZZ,ZY) RSS <- TSS - crossprod(ZY,delta_t) calc_log_det <- derive_log_det_calculator(OW_traces, DW_traces, n_o, n_d, model) optim_part_LL <- function(rho) { tau <- c(1, -rho) rss_part <- N * log(tau %*% RSS %*% tau) / 2 return(rss_part - calc_log_det(rho)) } nb_rho <- ncol(ZY) - 1 rho_tmp <- draw_initial_guess(nb_rho) optim_results <- structure(rho_tmp,class = "try-error") optim_count <- 1 optim_limit <- flow_control[["mle_optim_limit"]] while (is(optim_results,"try-error") & (optim_count < optim_limit)) { optim_results <- try(silent = TRUE, expr = { optim(rho_tmp, optim_part_LL, gr = NULL, method = "L-BFGS-B", lower = rep(-0.99, nb_rho), upper = rep(0.99, nb_rho), hessian = TRUE)}) optim_count <- optim_count + 1 rho_tmp <- draw_initial_guess(nb_rho) } assert(optim_count < optim_limit, "Optimization of the likelihood failed to converge within %s tries.", optim_limit) rho <- lookup(optim_results$par, define_spatial_lag_params(model)) tau <- c(1, -rho) delta <- (delta_t %*% tau)[,1] sigma2 <- as.numeric(1 / N * (tau %*% RSS %*% tau)) hessian_inputs <- collect(c("ZZ","ZY","TSS","rho","delta","sigma2","N")) if ( hessian_method == "mixed" ) { mixed_specific <- list("numerical_hess" = -optim_results$hessian) hessian_inputs <- c(hessian_inputs,mixed_specific) } if ( hessian_method == "f2" ) { f2_specific <- list("delta_t" = delta_t, "calc_log_det" = calc_log_det) hessian_inputs <- c(hessian_inputs,f2_specific) } hessian <- spflow_hessian(hessian_method, hessian_inputs) mu <- c(rho, delta) varcov <- -solve(hessian) sd_mu <- sqrt(diag(varcov)) ll_const_part <- -(N/2)*log(2*pi) + (N/2)*log(N) - N/2 ll_partial <- -optim_results$value loglik_value <- ll_partial + ll_const_part drop_sigma <- length(sd_mu) results_df <- data.frame( "est" = mu, "sd" = sd_mu[-drop_sigma]) estimation_results <- spflow_model( varcov = varcov, ll = loglik_value, estimation_results = results_df, estimation_control = flow_control, sd_error = sqrt(sigma2), N = N) return(estimation_results) }
source("ESEUR_config.r") pooled_mean=function(df) { return(sum(df$s_n*df$s_mean)/sum(df$s_mean)) } pooled_sd=function(df) { return(sqrt(sum(df$s_sd^2*(df$s_n-1))/sum(df$s_n-1))) } studies=data.frame(s_n=c(5, 10, 20), s_mean=c(30, 31, 32), s_sd=c(5, 4, 3)) pooled_mean(studies) pooled_sd(studies)
bp_maxmin <- function(x, probs = c(0,0,.5,1,1)) { r <- quantile(x, probs = probs, na.rm = TRUE) names(r) <- c("ymin","lower","middle","upper","ymax") r }
"amnesia"
"metadata_uk_2010"
plan(multisession) x <- rnorm(100) y <- 2 * x + 0.2 + rnorm(100) w <- 1 + x ^ 2 fitA <- lm(y ~ x, weights = w) fitB <- lm(y ~ x - 1, weights = w) fitC <- { w <- 1 + abs(x) lm(y ~ x, weights = w) } print(fitA) print(fitB) print(fitC) fitA %<-% lm(y ~ x, weights = w) fitB %<-% lm(y ~ x - 1, weights = w) fitC %<-% { w <- 1 + abs(x) lm(y ~ x, weights = w) } print(fitA) print(fitB) print(fitC) fA <- future( lm(y ~ x, weights = w) ) fB <- future( lm(y ~ x - 1, weights = w) ) fC <- future({ w <- 1 + abs(x) lm(y ~ x, weights = w) }) fitA <- value(fA) fitB <- value(fB) fitC <- value(fC) print(fitA) print(fitB) print(fitC) \dontshow{ plan(sequential) }
openbugs <- function(data, inits, parameters.to.save, model.file="model.txt", n.chains = 3, n.iter = 2000, n.burnin = floor(n.iter/2), n.thin = max(1, floor(n.chains *(n.iter - n.burnin) / n.sims)), n.sims = 1000, DIC = TRUE, bugs.directory = "c:/Program Files/OpenBUGS/", working.directory=NULL, digits = 5, over.relax = FALSE, seed=NULL) { if(!is.R()) stop("OpenBUGS is not yet available in S-PLUS") if(!requireNamespace("BRugs")) stop("BRugs is required") modelFile <- model.file numChains <- n.chains nBurnin <- n.burnin nIter <- n.iter - n.burnin nThin <- n.thin if(DIC) parameters.to.save <- c(parameters.to.save, "deviance") parametersToSave <- parameters.to.save inTempDir <- FALSE if(is.null(working.directory)) { working.directory <- tempdir() inTempDir <- TRUE } savedWD <- getwd() setwd(working.directory) on.exit(setwd(savedWD)) if(inTempDir && basename(model.file) == model.file) try(file.copy(file.path(savedWD, model.file), model.file, overwrite = TRUE)) if(!file.exists(modelFile)) { stop(modelFile, " does not exist") } if(file.info(modelFile)$isdir) { stop(modelFile, " is a directory, but a file is required") } if(!length(grep("\r\n", readChar(modelFile, 10^3)))) { message("Carriage returns added to model file ", modelFile) model <- readLines(modelFile) try(writeLines(model, modelFile)) } BRugs::modelCheck(modelFile) if(!(is.vector(data) && is.character(data) && all(file.exists(data)))) { data <- BRugs::bugsData(data, digits = digits) } if(inTempDir && all(basename(data) == data)) try(file.copy(file.path(savedWD, data), data, overwrite = TRUE)) BRugs::modelData(data) BRugs::modelCompile(numChains) if(!is.null(seed)) BRugs::modelSetRN(seed) if(missing(inits) || is.null(inits)) { BRugs::modelGenInits() } else { if(is.list(inits) || is.function(inits) || (is.character(inits) && !any(file.exists(inits)))) { inits <- BRugs::bugsInits(inits = inits, numChains = numChains, digits = digits) } if(inTempDir && all(basename(inits) == inits)) try(file.copy(file.path(savedWD, inits), inits, overwrite = TRUE)) BRugs::modelInits(inits) BRugs::modelGenInits() } BRugs::samplesSetThin(nThin) if(getOption("BRugsVerbose")){ cat("Sampling has been started ...\n") flush.console() } BRugs::modelUpdate(nBurnin, overRelax = over.relax) if(DIC) { BRugs::dicSet() on.exit(BRugs::dicClear(), add = TRUE) } BRugs::samplesSet(parametersToSave) BRugs::modelUpdate(nIter, overRelax = over.relax) params <- sort.name(BRugs::samplesMonitors("*"), parametersToSave) samples <- sapply(params, BRugs::samplesSample) n.saved.per.chain <- nrow(samples)/numChains samples.array <- array(samples, c(n.saved.per.chain, numChains, ncol(samples))) dimnames(samples.array)[[3]] <- dimnames(samples)[[2]] if(DIC) { DICOutput <- BRugs::dicStats() } else { DICOutput <- NULL } bugs.output <- as.bugs.array(sims.array=samples.array, model.file=modelFile, program="OpenBUGS", DIC=DIC, DICOutput=DICOutput, n.iter=n.iter, n.burnin=n.burnin, n.thin=n.thin) bugs.output } sort.name <- function(a, b){ bracket.pos <- regexpr("\\[", a) a.stem <- substr(a, 1, ifelse(bracket.pos>0, bracket.pos-1, nchar(a))) a[order(match(a.stem, b))] }
"find.ab" <- function(n=100000,ALPHA=.05,BETA=.2,higha=100){ higha<-100 H<-function(x,alpha=.05,beta=.2){ 1-pnorm( qnorm(1-x)-qnorm(1-alpha) - qnorm(1-beta) ) } x<-(0:n)/n Hx<- H(x,alpha=ALPHA,beta=BETA) ex0<-sum( x[-(n+1)]*( Hx[-1] - Hx[-(n+1)] ) ) ex1<-sum( x[-1]*( Hx[-1] - Hx[-(n+1)] ) ) EH<-(ex0+ex1)/2 rootfunc<-function(x,beta,alpha,EH){ 1-beta - pbeta(alpha,x,x*(1-EH)/EH) } x<-c((1:higha),1/(1:higha)) px<-pbeta(ALPHA,x,x*(1-EH)/EH) if (sign(rootfunc(higha,beta=BETA,alpha=ALPHA,EH=EH))== sign(rootfunc(1/higha,beta=BETA,alpha=ALPHA,EH=EH)) ){ mina<- x[px==min(px)] uroot1<-uniroot(rootfunc,c(1/higha,mina),beta=BETA, alpha=ALPHA,EH=EH) a1<-uroot1$root b1<- a1*(1-EH)/EH uroot2<-uniroot(rootfunc,c(mina,higha),beta=BETA,alpha=ALPHA,EH=EH) a2<-uroot2$root b2<- a2*(1-EH)/EH x<-(0:n)/n var1<- var(Hx-pbeta(x,a1,b1)) var2<-var(Hx-pbeta(x,a2,b2)) if (var1<var2){ a<-a1 ; b<-b1 } else { a<-a2 ; b<-b2 } } else { uroot<-uniroot(rootfunc,c(1/higha,higha),beta=BETA, alpha=ALPHA,EH=EH) a<-uroot$root b<- a*(1-EH)/EH } out<-list(a=a,b=b) out }
generalAxis <- function(x, maxVal, minVal, units = NA, logScale = FALSE, tinyPlot = FALSE, padPercent = 5, concentration = TRUE, usgsStyle = FALSE, prettyDate = TRUE) { nTicks<-if(tinyPlot) 5 else 8 upperMagnification <- 1 + (padPercent / 100) lowerMagnification <- 1 - (padPercent / 100) if (max(x,na.rm=TRUE) > 0){ high <- if(is.na(maxVal)) {upperMagnification*max(x,na.rm=TRUE)} else {maxVal} } else { high <- if(is.na(maxVal)) {lowerMagnification*max(x,na.rm=TRUE)} else {maxVal} } if (min(x,na.rm=TRUE) > 0){ low <- if(is.na(minVal)) {lowerMagnification*min(x,na.rm=TRUE)} else {minVal} } else { low <- if(is.na(minVal)) {upperMagnification*min(x,na.rm=TRUE)} else {minVal} } if(concentration){ if (tinyPlot){ label <- paste("Conc. (",units,")",sep="") } else { if(usgsStyle){ localUnits <- toupper(units) possibleGoodUnits <- c("mg/l","mg/l as N", "mg/l as NO2", "mg/l as NO3","mg/l as P","mg/l as PO3","mg/l as PO4","mg/l as CaCO3", "mg/l as Na","mg/l as H","mg/l as S","mg/l NH4" ) allCaps <- toupper(possibleGoodUnits) if(localUnits %in% allCaps){ label <- "Concentration, in milligrams per liter" } else { label <- paste("Concentration, in",units) } } else { label <- paste("Concentration in", units) } } } else { label <- "" } span <- c(low, high) ticks <- if (logScale) { if (tinyPlot) { logPretty1(low, high) } else { logPretty3(low, high) } } else { pretty(span, n = nTicks) } numTicks <- length(ticks) bottom <- ticks[1] top <- ticks[numTicks] if(!prettyDate){ bottom <- minVal top <- maxVal ticks[1] <- minVal ticks[length(ticks)] <- maxVal } return(list(ticks=ticks, bottom=bottom, top=top, label=label)) }
context("docker_available") test_that("invalid url", { expect_false(docker_available(host = "~", http_client_type = "null")) expect_silent(docker_available(host = "~", http_client_type = "null")) expect_message( docker_available(host = "~", http_client_type = "null", verbose = TRUE), "Failed to create docker client") }) test_that("Nonexistent socket", { skip_on_windows() tmp <- tempfile_test() expect_false(docker_available(host = tmp, http_client_type = "null")) expect_silent(docker_available(host = tmp, http_client_type = "null")) expect_message( docker_available(host = tmp, http_client_type = "null", verbose = TRUE), "Failed to connect to docker daemon") })
context("testing openmp parallelization") test_that("gbm refuses to work with insane numbers of threads", { N <- 1000 X1 <- runif(N) X2 <- 2*runif(N) X3 <- factor(sample(letters[1:4],N,replace=T)) X4 <- ordered(sample(letters[1:6],N,replace=T)) X5 <- factor(sample(letters[1:3],N,replace=T)) X6 <- 3*runif(N) mu <- c(-1,0,1,2)[as.numeric(X3)] SNR <- 10 Y <- X1**1.5 + 2 * (X2**.5) + mu sigma <- sqrt(var(Y)/SNR) Y <- Y + rnorm(N, 0, sigma) X1[sample(1:N,size=100)] <- NA X3[sample(1:N,size=300)] <- NA w <- rep(1,N) data <- data.frame(Y=Y,X1=X1,X2=X2,X3=X3,X4=X4,X5=X5,X6=X6) expect_error(gbmt(Y~X1+X2+X3+X4+X5+X6, data=data, var_monotone=c(0,0,0,0,0,0), keep_gbm_data=TRUE, cv_folds=10, par_details=gbmParallel(num_threads=-1)), "number of threads must be strictly positive", fixed=TRUE) }) test_that("gbm refuses to work with insane array chunk size - old api", { N <- 1000 X1 <- runif(N) X2 <- 2*runif(N) X3 <- factor(sample(letters[1:4],N,replace=T)) X4 <- ordered(sample(letters[1:6],N,replace=T)) X5 <- factor(sample(letters[1:3],N,replace=T)) X6 <- 3*runif(N) mu <- c(-1,0,1,2)[as.numeric(X3)] SNR <- 10 Y <- X1**1.5 + 2 * (X2**.5) + mu sigma <- sqrt(var(Y)/SNR) Y <- Y + rnorm(N,0,sigma) X1[sample(1:N,size=100)] <- NA X3[sample(1:N,size=300)] <- NA w <- rep(1,N) data <- data.frame(Y=Y,X1=X1,X2=X2,X3=X3,X4=X4,X5=X5,X6=X6) expect_error(gbmt(Y~X1+X2+X3+X4+X5+X6, data=data, var_monotone=c(0,0,0,0,0,0), keep_gbm_data=TRUE, cv_folds=10, par_details=gbmParallel(num_threads=1, array_chunk_size=0)), "array chunk size must be strictly positive", fixed=TRUE) }) test_that("gbm refuses to work with insane numbers of threads - old API", { N <- 1000 X1 <- runif(N) X2 <- 2*runif(N) X3 <- factor(sample(letters[1:4],N,replace=T)) X4 <- ordered(sample(letters[1:6],N,replace=T)) X5 <- factor(sample(letters[1:3],N,replace=T)) X6 <- 3*runif(N) mu <- c(-1,0,1,2)[as.numeric(X3)] SNR <- 10 Y <- X1**1.5 + 2 * (X2**.5) + mu sigma <- sqrt(var(Y)/SNR) Y <- Y + rnorm(N,0,sigma) X1[sample(1:N,size=100)] <- NA X3[sample(1:N,size=300)] <- NA w <- rep(1,N) data <- data.frame(Y=Y,X1=X1,X2=X2,X3=X3,X4=X4,X5=X5,X6=X6) expect_error(gbm(Y~X1+X2+X3+X4+X5+X6, data=data, var.monotone=c(0,0,0,0,0,0), distribution="Gaussian", n.trees=2000, shrinkage=0.005, interaction.depth=3, bag.fraction = 0.5, train.fraction = 0.5, n.minobsinnode = 10, keep.data=TRUE, cv.folds=10, par.details=gbmParallel(num_threads=-1)), "number of threads must be strictly positive", fixed=TRUE) }) test_that("gbm refuses to work with insane array chunk size - old api", { N <- 1000 X1 <- runif(N) X2 <- 2*runif(N) X3 <- factor(sample(letters[1:4],N,replace=T)) X4 <- ordered(sample(letters[1:6],N,replace=T)) X5 <- factor(sample(letters[1:3],N,replace=T)) X6 <- 3*runif(N) mu <- c(-1,0,1,2)[as.numeric(X3)] SNR <- 10 Y <- X1**1.5 + 2 * (X2**.5) + mu sigma <- sqrt(var(Y)/SNR) Y <- Y + rnorm(N,0,sigma) X1[sample(1:N,size=100)] <- NA X3[sample(1:N,size=300)] <- NA w <- rep(1,N) data <- data.frame(Y=Y,X1=X1,X2=X2,X3=X3,X4=X4,X5=X5,X6=X6) expect_error(gbm(Y~X1+X2+X3+X4+X5+X6, data=data, var.monotone=c(0,0,0,0,0,0), distribution="Gaussian", n.trees=2000, shrinkage=0.005, interaction.depth=3, bag.fraction = 0.5, train.fraction = 0.5, n.minobsinnode = 10, keep.data=TRUE, cv.folds=10, par.details=gbmParallel(num_threads=2, array_chunk_size=0)), "array chunk size must be strictly positive", fixed=TRUE) })
CCorDistance <- function(x, y, lag.max=(min(length(x), length(y)) - 1)){ if (class(try(CCInitialCheck(x, y, lag.max))) == "try-error") { return(NA) } cc <- ccf(x, y, lag.max=lag.max, type="correlation", plot="FALSE") d <- sqrt((1 - round(cc$acf[, , 1][which(cc$lag == 0)] ^ 2, digits=5)) / sum(cc$acf[, , 1][which(cc$lag < 0)] ^ 2)) return(d) } CCInitialCheck <- function(x, y, lag.max){ if (! is.numeric(x) | ! is.numeric(y)) { stop('The series must be numeric', call.=FALSE) } if (! is.vector(x) | ! is.vector(y)) { stop('The series must be univariate vectors', call.=FALSE) } if (length(x) <= 1 | length(y) <= 1) { stop('The series must have more than one point', call.=FALSE) } if (lag.max < 0) { stop ('The maximum lag value must be positive', call.=FALSE) } if (lag.max >= length(x)) { stop ('The maximum lag value exceeds the length of the first series', call.=FALSE) } if (lag.max >= length(y)) { stop ('The maximum lag value exceeds the length of the second series', call.=FALSE) } if (any(is.na(x)) | any(is.na(y))) { stop('There are missing values in the series', call.=FALSE) } }
isNumberOrInfVectorOrNull <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) { checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = NA, zeroAllowed = TRUE, negativeAllowed = TRUE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = FALSE, nanAllowed = FALSE, infAllowed = TRUE, message = message, argumentName = argumentName) }
context("writeNetworkModel") Net <- HydeNetwork(~ wells + pe | wells + d.dimer | pregnant*pe + angio | pe + treat | d.dimer*angio + death | pe*treat, data = PE) test_that("writeNetworkModel with pretty output succeeds", { expect_output(writeNetworkModel(Net, pretty = TRUE)) }) test_that("writeNetworkModel with non-pretty output succeeds", { expect_silent(writeNetworkModel(Net, pretty = FALSE)) })
soilStrength5 <- function(bulk.density, water.content, clay.content) { out <- -566.8 + 443* bulk.density + 4.34*clay.content - 773*water.content for (j in 1: length(out)) { if (out[j] < 0) {out[j] <- 0} } return(out) }
context("status") make_testdir <- function() { td <- tempfile() dir.create(td) teardown(unlink(td, recursive = TRUE, force = TRUE)) td } test_that("status functions accept explicit filename", { d <- make_testdir() f <- file.path(d, "MY_STATUS") expect_silent(status.start("TRAITS", f)) expect_silent(status.end("DONE", f)) expect_silent(status.skip("MET", f)) expect_silent(status.start("ENSEMBLE", f)) expect_silent(status.end("ERROR", f)) res <- readLines(f) expect_length(res, 3) expect_match(res[[1]], "^TRAITS.*DONE\\s*$") expect_match(res[[2]], "^MET.*SKIPPED\\s*$") expect_match(res[[3]], "^ENSEMBLE.*ERROR\\s*$") expect_equal(status.check("TRAITS", f), 1L) expect_equal(status.check("MET", f), 0L) expect_equal(status.check("ENSEMBLE", f), -1L) }) test_that("status handles file = dir/", { d <- make_testdir() status.start("NONE", d) status.end("DONE", d) expect_equal(status.check("NONE", file.path(d, "STATUS")), 1L) }) test_that("status functions read from local settings", { settings <- list(outdir = make_testdir()) expect_silent(status.skip("auto")) expect_match( readLines(file.path(settings$outdir, "STATUS"))[[1]], "^auto.*SKIPPED\\s*$") }) test_that("status finds settings defined outside immediate calling scope", { settings <- list(outdir = make_testdir()) f <- function(name) { status.start(name) status.end() } g <- function(name) { f(name) } expect_silent(g("WRAPPED")) expect_equal( status.check("WRAPPED", file.path(settings$outdir, "STATUS")), 1L) }) test_that("status writes to stdout on bad filename", { expect_output(status.start("NOFILE"), "NOFILE") settings <- list(outdir = file.path(make_testdir(), "fake", "path")) expect_output(status.end(), "\\d{4}-\\d{2}-\\d{2}.*DONE") }) test_that("status.check returns 0 on bad filename", { expect_equal(status.check("NOFILE"), 0L) expect_equal(status.check("NOFILE", file.path(make_testdir(), "fake")), 0L) })
github_api_get_user = function(user) { arg_is_chr_scalar(user) ghclass_api_v3_req( endpoint = "/users/:username", username = user ) } user_exists = function(user) { arg_is_chr(user) res = purrr::map(user, purrr::safely(github_api_get_user)) purrr::map_lgl(res, succeeded) }
NULL setClass( "spect_match_objfun", contains="function", slots=c( env="environment", est="character" ) ) setGeneric( "spect_objfun", function (data, ...) standardGeneric("spect_objfun") ) setMethod( "spect_objfun", signature=signature(data="missing"), definition=function (...) { reqd_arg("spect_objfun","data") } ) setMethod( "spect_objfun", signature=signature(data="ANY"), definition=function (data, ...) { undef_method("spect_objfun",data) } ) setMethod( "spect_objfun", signature=signature(data="data.frame"), definition=function(data, est = character(0), weights = 1, fail.value = NA, vars, kernel.width, nsim, seed = NULL, transform.data = identity, detrend = c("none","mean","linear","quadratic"), params, rinit, rprocess, rmeasure, partrans, ..., verbose = getOption("verbose", FALSE)) { tryCatch( smof.internal( data, est=est, weights=weights, fail.value=fail.value, vars=vars, kernel.width=kernel.width, nsim=nsim, seed=seed, transform.data=transform.data, detrend=detrend, params=params, rinit=rinit, rprocess=rprocess, rmeasure=rmeasure, partrans=partrans, ..., verbose=verbose ), error = function (e) pStop("spect_objfun",conditionMessage(e)) ) } ) setMethod( "spect_objfun", signature=signature(data="pomp"), definition=function(data, est = character(0), weights = 1, fail.value = NA, vars, kernel.width, nsim, seed = NULL, transform.data = identity, detrend = c("none","mean","linear","quadratic"), ..., verbose = getOption("verbose", FALSE)) { tryCatch( smof.internal( data, est=est, weights=weights, fail.value=fail.value, vars=vars, kernel.width=kernel.width, nsim=nsim, seed=seed, transform.data=transform.data, detrend=detrend, ..., verbose=verbose ), error = function (e) pStop("spect_objfun",conditionMessage(e)) ) } ) setMethod( "spect_objfun", signature=signature(data="spectd_pomp"), definition=function(data, est = character(0), weights = 1, fail.value = NA, vars, kernel.width, nsim, seed = NULL, transform.data = identity, detrend, ..., verbose = getOption("verbose", FALSE)) { if (missing(vars)) vars <- data@vars if (missing(kernel.width)) kernel.width <- [email protected] if (missing(nsim)) nsim <- data@nsim if (missing(transform.data)) transform.data <- [email protected] if (missing(detrend)) detrend <- data@detrend spect_objfun( as(data,"pomp"), est=est, weights=weights, fail.value=fail.value, vars=vars, kernel.width=kernel.width, nsim=nsim, seed=seed, transform.data=transform.data, detrend=detrend, ..., verbose=verbose ) } ) setMethod( "spect_objfun", signature=signature(data="spect_match_objfun"), definition=function(data, est, weights, fail.value, seed = NULL, ..., verbose = getOption("verbose", FALSE)) { if (missing(est)) est <- data@est if (missing(weights)) weights <-data@env$weights if (missing(fail.value)) fail.value <- data@env$fail.value spect_objfun( data@env$object, est=est, weights=weights, fail.value=fail.value, seed=seed, ..., verbose=verbose ) } ) smof.internal <- function (object, est, weights, fail.value, vars, kernel.width, nsim, seed, transform.data, detrend, ..., verbose) { verbose <- as.logical(verbose) object <- spect(object,vars=vars,kernel.width=kernel.width, nsim=nsim,seed=seed, transform.data=transform.data,detrend=detrend, ...,verbose=verbose) fail.value <- as.numeric(fail.value) if (is.numeric(weights)) { if (length(weights)==1) { weights <- rep(weights,length(object@freq)) } else if ((length(weights) != length(object@freq))) pStop_("if ",sQuote("weights"), " is provided as a vector, it must have length ", length(object@freq)) } else if (is.function(weights)) { weights <- tryCatch( vapply(object@freq,weights,numeric(1)), error = function (e) pStop_(sQuote("weights")," function: ",conditionMessage(e)) ) } else { pStop_(sQuote("weights"), " must be specified as a vector or as a function") } if (any(!is.finite(weights) | weights<0)) pStop_(sQuote("weights")," should be nonnegative and finite") weights <- weights/mean(weights) params <- coef(object,transform=TRUE) est <- as.character(est) est <- est[nzchar(est)] idx <- match(est,names(params)) if (any(is.na(idx))) { missing <- est[is.na(idx)] pStop_(ngettext(length(missing),"parameter","parameters")," ", paste(sQuote(missing),collapse=","), " not found in ",sQuote("params")) } pompLoad(object) ker <- reuman.kernel(kernel.width) discrep <- spect.discrep(object,ker=ker,weights=weights) ofun <- function (par = numeric(0)) { params[idx] <- par coef(object,transform=TRUE) <<- params object@simspec <- compute.spect.sim( object, vars=object@vars, params=object@params, nsim=object@nsim, seed=object@seed, [email protected], detrend=object@detrend, ker=ker ) discrep <<- spect.discrep(object,ker=ker,weights=weights) if (is.finite(discrep) || is.na(fail.value)) discrep else fail.value } environment(ofun) <- list2env( list(object=object,fail.value=fail.value, params=params,idx=idx,discrep=discrep,seed=seed,ker=ker, weights=weights), parent=parent.frame(2) ) new("spect_match_objfun",ofun,env=environment(ofun),est=est) } spect.discrep <- function (object, ker, weights) { discrep <- array(dim=c(length(object@freq),length(object@vars))) sim.means <- colMeans(object@simspec) for (j in seq_along(object@freq)) { for (k in seq_along(object@vars)) { discrep[j,k] <- ((object@datspec[j,k]-sim.means[j,k])^2)/ mean((object@simspec[,j,k]-sim.means[j,k])^2) } discrep[j,] <- weights[j]*discrep[j,] } sum(discrep) } setMethod( "spect", signature=signature(data="spect_match_objfun"), definition=function (data, seed, ..., verbose=getOption("verbose", FALSE)) { if (missing(seed)) seed <- data@env$seed spect( data@env$object, seed=seed, ..., verbose=verbose ) } ) setAs( from="spect_match_objfun", to="spectd_pomp", def = function (from) { from@env$object } ) setMethod( "plot", signature=signature(x="spect_match_objfun"), definition=function (x, ...) { plot(as(x,"spectd_pomp"),...) } )
test_that("Columns are of correct type in character data", { expect_type(qualtrics_text$Status, "character") expect_type(qualtrics_text$Finished, "logical") }) test_that("Data sets include exclusion criteria", { expect_true(any(qualtrics_raw$Status == "Survey Preview")) expect_true(any(qualtrics_raw$Finished == FALSE)) suppressWarnings( expect_true(any(as.numeric(qualtrics_raw$`Duration (in seconds)`) < 100)) ) suppressWarnings( expect_true(any(as.numeric(stringr::str_split( qualtrics_raw$Resolution, "x", simplify = TRUE )[, 1]) < 1000)) ) expect_true(nrow(janitor::get_dupes(qualtrics_raw, IPAddress)) > 0) expect_true( nrow(janitor::get_dupes( qualtrics_raw, dplyr::any_of( c("LocationLatitude", "LocationLongitude") ) )) > 0 ) }) test_that("Columns are of correct type in numeric data", { expect_type(qualtrics_numeric$Status, "double") expect_type(qualtrics_numeric$Finished, "double") }) test_that("Data sets include exclusion criteria", { expect_true(any(qualtrics_numeric$Status == 1)) expect_true(any(qualtrics_numeric$Finished == 0)) expect_true(any(qualtrics_numeric$`Duration (in seconds)` < 100)) expect_true(any(as.numeric(stringr::str_split(qualtrics_numeric$Resolution, "x", simplify = TRUE )[, 1]) < 1000)) expect_true(nrow(janitor::get_dupes(qualtrics_numeric, IPAddress)) > 0) expect_true( nrow(janitor::get_dupes( qualtrics_numeric, dplyr::any_of( c("LocationLatitude", "LocationLongitude") ) )) > 0 ) }) test_that("Columns are of correct type in character data", { expect_type(qualtrics_text$Status, "character") expect_type(qualtrics_text$Finished, "logical") }) test_that("Data sets include exclusion criteria", { expect_true(any(qualtrics_text$Status == "Survey Preview")) expect_true(any(qualtrics_text$Finished == FALSE)) expect_true(any(qualtrics_text$`Duration (in seconds)` < 100)) expect_true(any(as.numeric(stringr::str_split(qualtrics_text$Resolution, "x", simplify = TRUE )[, 1]) < 1000)) expect_true(nrow(janitor::get_dupes(qualtrics_text, IPAddress)) > 0) expect_true( nrow(janitor::get_dupes( qualtrics_text, dplyr::any_of( c("LocationLatitude", "LocationLongitude") ) )) > 0 ) })
pt.btavg <- function(ar,br){ n <- length(ar) dirt <- ar - br outperform <- length(dirt[dirt > 0]) bta <- outperform/n return(bta) }
NestedRegression <- function(response, predictors, group.id, residual.precision.prior = NULL, coefficient.prior = NULL, coefficient.mean.hyperprior = NULL, coefficient.variance.hyperprior = NULL, suf = NULL, niter, ping = niter / 10, sampling.method = c("ASIS", "DA"), seed = NULL) { if (is.null(suf)) { if (missing(response) || missing(predictors) || missing(group.id)) { stop("NestedRegression either needs a list of sufficient statistics,", " or a predictor matrix, response vector, and group indicators.") } suf <- .RegressionSufList(predictors, response, group.id) } stopifnot(is.list(suf)) stopifnot(length(suf) > 0) stopifnot(all(sapply(suf, inherits, "RegressionSuf"))) if (length(unique(sapply(suf, function(x) ncol(x$xtx)))) != 1) { stop("All RegressionSuf objects must have the same dimensions.") } xdim <- ncol(suf[[1]]$xtx) sampling.method <- match.arg(sampling.method) if (is.null(residual.precision.prior)) { residual.precision.prior <- .DefaultNestedRegressionResidualSdPrior(suf) } stopifnot(inherits(residual.precision.prior, "SdPrior")) if (is.logical(coefficient.mean.hyperprior) && coefficient.mean.hyperprior == FALSE) { sampling.method <- "DA" coefficient.mean.hyperprior <- NULL } else { if (is.null(coefficient.mean.hyperprior)) { coefficient.mean.hyperprior <- .DefaultNestedRegressionMeanHyperprior(suf) } stopifnot(inherits(coefficient.mean.hyperprior, "MvnPrior")) stopifnot(length(coefficient.mean.hyperprior$mean) == xdim) } if (is.logical(coefficient.variance.hyperprior) && coefficient.variance.hyperprior == FALSE) { coefficient.variance.hyperprior <- NULL sampling.method <- "DA" } else if (is.null(coefficient.variance.hyperprior)) { coefficient.variance.hyperprior <- .DefaultNestedRegressionVarianceHyperprior(suf) stopifnot(inherits(coefficient.variance.hyperprior, "InverseWishartPrior"), ncol(coefficient.variance.hyperprior$variance.guess) == xdim) } if (!is.null(coefficient.mean.hyperprior) && !is.null(coefficient.variance.hyperprior)) { if (is.null(coefficient.prior)) { coefficient.prior <- MvnPrior(rep(0, xdim), diag(rep(1, xdim))) } } stopifnot(inherits(coefficient.prior, "MvnPrior")) stopifnot(is.numeric(niter), length(niter) == 1, niter > 0) stopifnot(is.numeric(ping), length(ping) == 1) if (!is.null(seed)) { seed <- as.integer(seed) } ans <- .Call("boom_nested_regression_wrapper", suf, coefficient.prior, coefficient.mean.hyperprior, coefficient.variance.hyperprior, residual.precision.prior, as.integer(niter), as.integer(ping), sampling.method, seed) ans$priors <- list( coefficient.prior = coefficient.prior, coefficient.mean.hyperprior = coefficient.mean.hyperprior, coefficient.variance.hyperprior = coefficient.variance.hyperprior, residual.precision.prior = residual.precision.prior) class(ans) <- "NestedRegression" return(ans) } .RegressionSufList <- function(predictors, response, group.id) { stopifnot(is.numeric(response)) stopifnot(is.matrix(predictors), nrow(predictors) == length(response)) group.id <- as.factor(group.id) stopifnot(length(group.id) == length(response)) MakeRegSuf <- function(data) { return(RegressionSuf(X = as.matrix(data[,-1]), y = as.numeric(data[,1]))) } return(by(as.data.frame(cbind(response, predictors)), group.id, MakeRegSuf)) } .CollapseRegressionSuf <- function(reg.suf.list) { stopifnot(is.list(reg.suf.list), length(reg.suf.list) > 0, all(sapply(reg.suf.list, inherits, "RegressionSuf"))) if (length(reg.suf.list) == 1){ return(reg.suf.list[[1]]) } xtx <- reg.suf.list[[1]]$xtx xty <- reg.suf.list[[1]]$xty yty <- reg.suf.list[[1]]$yty n <- reg.suf.list[[1]]$n xsum <- reg.suf.list[[1]]$xbar * n for (i in 2:length(reg.suf.list)) { xtx <- xtx + reg.suf.list[[i]]$xtx xty <- xty + reg.suf.list[[i]]$xty yty <- yty + reg.suf.list[[i]]$yty n <- n + reg.suf.list[[i]]$n xsum <- xsum + reg.suf.list[[i]]$xbar * reg.suf.list[[i]]$n } xbar <- xsum / n return(RegressionSuf(xtx = xtx, xty = xty, yty = yty, n = n, xbar = xbar)) } .ResidualVariance <- function(suf) { stopifnot(inherits(suf, "RegressionSuf")) sse <- as.numeric(suf$yty - t(suf$xty) %*% solve(suf$xtx, suf$xty)) df.model <- ncol(suf$xtx) return(sse / (suf$n - df.model)) } .DefaultNestedRegressionMeanHyperprior <- function(suf) { suf <- .CollapseRegressionSuf(suf) beta.hat <- tryCatch(solve(suf$xtx, suf$xty)) if (is.numeric(beta.hat)) { return(MvnPrior(beta.hat, .ResidualVariance(suf) * solve(suf$xtx / suf$n))) } else { xdim <- length(suf$xty) zero <- rep(0, xdim); V <- diag(rep(1000), xdim) return(MvnPrior(zero, V)) } } .DefaultNestedRegressionVarianceHyperprior <- function(suf) { number.of.groups <- length(suf) suf <- .CollapseRegressionSuf(suf) variance.guess <- .ResidualVariance(suf) * number.of.groups * solve(suf$xtx) variance.guess.weight <- ncol(variance.guess) + 1 return(InverseWishartPrior(variance.guess, variance.guess.weight)) } .DefaultNestedRegressionResidualSdPrior <- function(suf) { suf <- .CollapseRegressionSuf(suf) variance.guess <- .ResidualVariance(suf) return(SdPrior(sqrt(variance.guess), 1)) }
smosaic <- function(data, xvar=character(0), yvar=character(0), ...) { main <- paste(deparse(substitute(data), 500), collapse = "\n") obj <- c("matrix", "data.frame", "table") %in% class(data) stopifnot(any(obj)) totab <- main if (!obj[3]) { if (!obj[2]) { totab <- sprintf("as.data.frame(%s)", totab) data <- as.data.frame(data) } totab <- sprintf("table(%s)", totab) data <- table(data) } if (is.null(dimnames(data))) dimnames(data) <- sapply(dim(data), seq) if (is.null(names(dimnames(data)))) names(dimnames(data)) <- sprintf("%s[,%.0f]", main, seq(length(dim(data)))) dvar <- names(dimnames(data)) stopifnot(length(dvar)>1) ivar <- intersect(xvar, yvar) xvar <- setdiff(xvar, ivar) yvar <- setdiff(yvar, ivar) xvar <- xvar[xvar %in% dvar] if (length(xvar)==0) xvar <- setdiff(dvar, yvar)[1] yvar <- yvar[yvar %in% dvar] if (length(yvar)==0) yvar <- setdiff(dvar, xvar)[1] dvar <- setdiff(dvar, c(xvar, yvar)) shinyApp( ui = dashboardPage( dashboardHeader(title="Mosaicplot"), dashboardSidebar( tags$style( HTML(".black-text .rank-list-item { color: bucket_list( header = NULL, group_name = "bucket_var_group", orientation = "vertical", class = c("default-sortable", "black-text"), add_rank_list( text = "Variable(s)", labels = dvar, input_id = "dvar" ), add_rank_list( text = "X", labels = xvar, input_id = "xvar" ), add_rank_list( text = "Y", labels = yvar, input_id = "yvar" ) ) ), dashboardBody( fluidRow( box(plotOutput("mosaic")), box(verbatimTextOutput("command"), title="Basic R code") )) ), server = function(input, output, session) { output$mosaic <- renderPlot({ if ((length(input$xvar)>0) && (length(input$yvar)>0)) { args <- list(...) args$x <- apply(data, c(input$xvar, input$yvar), sum) args$dir <- c(rep("v", length(input$xvar)), rep("h", length(input$yvar))) if (is.null(args$main)) args$main <- main do.call("mosaicplot", args) } }) output$command <- renderText({ txt <- "At least two variables are required for a plot!" if ((length(input$xvar)>0) && (length(input$yvar)>0)) { txt <- c(paste0(" tab <- ", totab, "\n"), paste0("x <- c(", paste0('"', input$xvar, '"', collapse=", "), ")\n"), paste0("y <- c(", paste0('"', input$yvar, '"', collapse=", "), ")\n"), "tab <- apply(tab, c(x, y), sum)\n", "dir <- c(rep(\"v\", length(x)), rep(\"h\", length(y)))\n", "mosaicplot(tab, dir=dir)\n") } txt }) } ) }
cima <- function(y, se, v = NULL, alpha = 0.05, method = c("boot", "DL", "HK", "SJ", "KR", "APX", "PL", "BC"), B = 25000, parallel = FALSE, seed = NULL, maxit1 = 100000, eps = 10^(-10), lower = 0, upper = 1000, maxit2 = 1000, tol = .Machine$double.eps^0.25, rnd = NULL, maxiter = 100) { lstm <- c("boot", "DL", "HK", "SJ", "KR", "APX", "PL", "BC") method <- match.arg(method) if (missing(se) & missing(v)) { stop("Either 'se' or 'v' must be specified.") } else if (missing(se)) { se <- sqrt(v) } util_check_num(y) util_check_nonneg(se) util_check_inrange(alpha, 0.0, 1.0) util_check_gt(B, 1) util_check_gt(maxit1, 1) util_check_gt(eps, 0) util_check_ge(lower, 0) util_check_gt(upper, 0) util_check_gt(maxit2, 1) util_check_gt(tol, 0) util_check_gt(maxiter, 1) if (length(se) != length(y)) { stop("'y' and 'se' should have the same length.") } else if (!is.element(method, lstm)) { stop("Unknown 'method' specified.") } else if (lower >= upper) { stop("'upper' should be greater than 'lower'.") } if (method == "boot") { res <- pima_boot(y = y, sigma = se, alpha = alpha, B = B, maxit1 = maxit1, eps = eps, lower = lower, upper = upper, maxit2 = maxit2, rnd = rnd, parallel = parallel, seed = seed) } else if (method == "DL") { res <- pima_hts(y = y, sigma = se, alpha = alpha) } else if (method == "HK") { res <- pima_htsreml(y = y, sigma = se, alpha = alpha, vartype = "HK", maxiter = maxiter) } else if (method == "SJ") { res <- pima_htsreml(y = y, sigma = se, alpha = alpha, vartype = "SJBC", maxiter = maxiter) } else if (method == "KR") { res <- pima_htsreml(y = y, sigma = se, alpha = alpha, vartype = "KR", maxiter = maxiter) } else if (method == "APX") { res <- pima_htsreml(y = y, sigma = se, alpha = alpha, vartype = "APX", maxiter = maxiter) } else if (method == "PL") { res <- cima_pl(y = y, se = se, alpha = alpha) } else if (method == "BC") { res <- cima_bc(y = y, se = se, alpha = alpha) } res <- append(list(K = length(y)), res) res <- append(res, list(i2h = i2h(se, res$tau2h))) class(res) <- "cima" return(res) } print.cima <- function(x, digits = 4, trans = c("identity", "exp"), ...) { lstt <- c("identity", "exp") trans <- match.arg(trans) if (!is.element(trans, lstt)) { stop("Unknown 'trans' specified.") } nuc <- x$nuc cat("\nConfidence Interval for Random-Effects Meta-Analysis\n\n") if (x$method == "boot") { cat(paste0("A parametric bootstrap confidence interval\n", " Heterogeneity variance: DerSimonian-Laird\n", " Variance for average treatment effect: Hartung\n\n")) } else if (x$method == "DL") { cat(paste0("A Wald-type confidence interval\n", " Heterogeneity variance: DerSimonian-Laird\n", " Variance for average treatment effect: approximate\n\n")) } else if (x$method == "HK") { cat(paste0("A Wald-type t-distribution confidence interval\n", " Heterogeneity variance: REML\n", " Variance for average treatment effect: Hartung-Knapp\n\n")) } else if (x$method == "SJ") { cat(paste0("A Wald-type t-distribution confidence interval\n", " Heterogeneity variance: REML\n", " Variance for average treatment effect: bias corrected Sidik-Jonkman\n\n")) } else if (x$method == "KR") { cat(paste0("A Wald-type t-distribution confidence interval\n", " Heterogeneity variance: REML\n", " Variance for average treatment effect: Kenward-Roger\n\n")) nuc <- format(round(nuc, digits)) } else if (x$method == "PL") { cat(paste0("A profile likelihood confidence interval\n", " Heterogeneity variance: ML\n", " Variance for average treatment effect: ML\n\n")) } else if (x$method == "BC") { cat(paste0("A profile likelihood confidence interval with a Bartlett-type correction\n", " Heterogeneity variance: ML\n", " Variance for average treatment effect: ML\n\n")) } cat(paste0("No. of studies: ", length(x$y), "\n\n")) ftrans <- function(x) { if (trans == "identity") { return(x) } else if (trans == "exp") { return(exp(x)) } } cat(paste0("Average treatment effect [", (1 - x$alpha)*100, "% confidence interval]:\n")) cat(paste0(" ", format(round(ftrans(x$muhat), digits), nsmall = digits), " [", format(round(ftrans(x$lci), digits), nsmall = digits), ", ", format(round(ftrans(x$uci), digits), nsmall = digits), "]\n")) if (!is.na(nuc)) { cat(paste0(" d.f.: ", nuc, "\n")) } if (trans == "exp") { cat(paste0(" Scale: exponential transformed\n")) } cat("\n") cat(paste0("Heterogeneity measure\n")) cat(paste0(" tau-squared: ", format(round(x$tau2, digits), nsmall = digits), "\n")) cat(paste0(" I-squared: ", format(round(x$i2h, 1), nsmall = 1), "%\n\n")) invisible(x) } plot.cima <- function(x, y = NULL, title = "Forest plot", base_size = 16, base_family = "", digits = 3, studylabel = NULL, ntick = NULL, trans = c("identity", "exp"), ...) { lstt <- c("identity", "exp") trans <- match.arg(trans) if (!is.element(trans, lstt)) { stop("Unknown 'trans' specified.") } ftrans <- function(x) { if (trans == "identity") { return(x) } else if (trans == "exp") { return(exp(x)) } } idodr <- lcl <- limits <- lx <- shape <- size <- ucl <- ymax <- ymin <- NULL k <- length(x$y) if (is.null(studylabel)) { studylabel <- 1:k } else { if (k != length(studylabel)) { stop("`studylabel` and the number of studies must have the same length.") } } id <- c( paste0(" ", studylabel), paste0(" 95%CI") ) df1 <- data.frame( id = id, idodr = c((k + 2):3, 1), y = c(x$y, NA), lcl = c(x$y + stats::qnorm(x$alpha*0.5)*x$se, NA), ucl = c(x$y + stats::qnorm(1 - x$alpha*0.5)*x$se, NA), shape = c(rep(15, k), 18), swidth = c(rep(1, k), 3) ) xmin <- min(ftrans(df1$lcl[1:k])) xmax <- max(ftrans(df1$ucl[1:k])) df1 <- data.frame( df1, size = c(1/x$se, 1), limits = c(paste0(format(round(ftrans(df1$y[1:k]), digits), nsmall = digits), " (", format(round(ftrans(df1$lcl[1:k]), digits), nsmall = digits), ", ", format(round(ftrans(df1$ucl[1:k]), digits), nsmall = digits), ")"), paste0(format(round(ftrans(x$muhat), digits), nsmall = digits), " (", format(round(ftrans(x$lci), digits), nsmall = digits), ", ", format(round(ftrans(x$uci), digits), nsmall = digits), ")") ) ) df2 <- data.frame(id = "Study", idodr = k + 3, y = NA, lcl = NA, ucl = NA, shape = NA, swidth = NA, size = NA, limits = NA) df3 <- data.frame(id = "Overall", idodr = 2, y = NA, lcl = NA, ucl = NA, shape = NA, swidth = NA, size = NA, limits = NA) df4 <- data.frame(x = c(x$lci, x$muhat, x$uci), ymax = c(1, 1 + 0.25, 1), ymin = c(1, 1 - 0.25, 1), y = c(1, 1, 1)) df1 <- rbind(df3, df2, df1) ggplot <- ggplot2::ggplot aes <- ggplot2::aes geom_errorbarh <- ggplot2::geom_errorbarh geom_point <- ggplot2::geom_point geom_ribbon <- ggplot2::geom_ribbon geom_vline <- ggplot2::geom_vline scale_y_continuous <- ggplot2::scale_y_continuous scale_x_continuous <- ggplot2::scale_x_continuous scale_shape_identity <- ggplot2::scale_shape_identity ylab <- ggplot2::ylab xlab <- ggplot2::xlab ggtitle <- ggplot2::ggtitle theme_classic <- ggplot2::theme_classic theme <- ggplot2::theme element_text <- ggplot2::element_text element_line <- ggplot2::element_line element_blank <- ggplot2::element_blank element_blank <- ggplot2::element_blank rel <- ggplot2::rel labs <- ggplot2::labs sec_axis <- ggplot2::sec_axis y1labels <- df1[order(df1$idodr),]$id y2labels <- df1[order(df1$idodr),]$limits y2labels[is.na(y2labels)] <- "" if (trans == "exp") { if (is.null(ntick)) { ntick <- 6 } breaks <- log(2^seq.int(ceiling(log2(xmin)), ceiling(log2(xmax)), length.out = ntick)) scalex <- scale_x_continuous( labels = scales::trans_format("exp", format = scales::number_format(big.mark = "", accuracy = 10^(-digits))), breaks = breaks) } else if (trans == "identity") { if (is.null(ntick)) { scalex <- scale_x_continuous() } else { scalex <- scale_x_continuous(breaks = scales::pretty_breaks(n = ntick)) } } suppressWarnings( print( p <- ggplot(df1, aes(x = y, y = idodr)) + geom_errorbarh(aes(xmin = lcl, xmax = ucl), height = 0, size = 1) + geom_point(aes(size = size, shape = shape), fill = "black", show.legend = FALSE) + geom_ribbon(data = df4, aes(x = x, y = y, ymin = ymin, ymax = ymax), alpha = 1, colour = "black", fill = "black") + geom_vline(xintercept = x$muhat, lty = 2) + geom_vline(xintercept = 0, lty = 1) + scale_y_continuous(breaks = 1:length(y1labels), labels = y1labels, sec.axis = sec_axis( ~ ., breaks = 1:length(y2labels), labels = y2labels)) + scalex + scale_shape_identity() + ylab(NULL) + xlab(" ") + labs(caption = parse( text = sprintf('list(hat(tau)^{2}=="%s", I^{2}=="%s"*"%%")', format(round(x$tau2h, digits), nsmall = digits), format(round(x$i2h, 1), nsmall = 1))) ) + ggtitle(title) + theme_classic(base_size = base_size, base_family = base_family) + theme(axis.text.y = element_text(hjust = 0), axis.ticks.y = element_blank()) + theme(axis.line.x = element_line(), axis.line.y = element_blank(), plot.title = element_text(hjust = 0.5, size = rel(0.8))) ) ) }
context("Convert Vietnamese Unicode to ASCII") test_that("Converts Unicode to ASCII", { expect_equal(convert_unicode_to_ascii("\u00C0"), "A") expect_equal(convert_unicode_to_ascii("\u1EF9"), "y") expect_equal(convert_unicode_to_ascii("\u00d0"), "D") })
qacf <- function(x, conf_level = 0.95, show_sig = FALSE, ...) { UseMethod("qacf") } qacf.default <- function(x, conf_level = 0.95, show_sig = FALSE, ...) { do.call(qacf.data.frame, list(x = data.frame(x), conf_level = conf_level, show_sig = show_sig, ...)) } qacf.data.frame <- function(x, conf_level = 0.95, show_sig = FALSE, ...) { acf_data <- stats::acf(x, plot = FALSE, ...) ciline <- stats::qnorm((1 - conf_level) / 2) / sqrt(acf_data$n.used) lags <- as.data.frame(acf_data$lag) acfs <- as.data.frame(acf_data$acf) lags <- utils::stack(lags) acfs <- utils::stack(acfs) names(lags) <- c("lag", "variable") names(acfs) <- c("value", "variable") acf_df <- cbind(lags, value = acfs[["value"]]) acf_df$significant <- factor(abs(acf_df$value) > abs(ciline)) g <- ggplot2::ggplot() + ggplot2::aes_string(x = "lag", y = "value") + ggplot2::geom_bar(stat = "identity", position = "identity") + ggplot2::ylab(acf_data$type) if (ncol(x) > 1) { facets <- rep(apply(expand.grid(acf_data$snames, acf_data$snames), 1, function(x) {if(x[1] == x[2]) x[1] else paste(x, collapse = " & ")}), each = dim(acf_data$acf)[1]) facets_levels <- apply(expand.grid(acf_data$snames, acf_data$snames)[, 2:1], 1, function(x) {if(x[1] == x[2]) x[1] else paste(x, collapse = " & ")}) acf_df$facets <- factor(facets, levels = facets_levels) g <- g + ggplot2::facet_wrap( ~ facets, scales = "free_x") } if(show_sig) { if (ncol(x) > 1) { g <- g + ggplot2::geom_hline(yintercept = ciline) + ggplot2::geom_hline(yintercept = -ciline) + ggplot2::aes_string(fill = "significant") } else { g <- g + ggplot2::geom_hline(yintercept = -ciline) + ggplot2::aes_string(fill = "significant") } } g <- ggplot2::`%+%`(g, acf_df) g }
.Random.seed <- c(403L, 105L, -1687518201L, -1894374947L, -1902051628L, 1300177402L, -762966715L, -1801504353L, 1500850982L, -1023028304L, -1414291373L, -1976624271L, 133466784L, -1286021570L, -1526819511L, -1194603525L, 573321162L, -730840788L, 516545839L, -99646491L, 942619292L, -469418254L, 1271041901L, 1551427751L, 389475022L, -1423181784L, -1943837653L, -325892535L, 427880280L, 1512327686L, -1634896927L, -222867085L, -581787166L, 2141312340L, 1934175319L, 113578061L, -1410919452L, 1421889994L, 861198389L, -986368369L, 1914873750L, 781880128L, 486729219L, -1646797791L, 360992528L, 1410409710L, 323841177L, 1858840875L, -1249230822L, -1308034340L, 1746528991L, 1805661365L, -1969233332L, 403377826L, 832558589L, -649986313L, -2087880674L, -859374888L, 1743826491L, 309296089L, -1284593304L, -1158020970L, 1519771153L, 1338677187L, -529495086L, -1791666588L, -119290457L, -1798612227L, -2103558412L, 686422490L, 2012962085L, -344978369L, -1702437946L, 1690163280L, 2020627571L, -957187951L, -1794438976L, 989176478L, -1813053847L, -1786466661L, -1873607766L, -1954764852L, 96107151L, 1623773893L, -710116740L, -1010968878L, 689349197L, -2050429177L, -745082130L, 1992574920L, 1642121419L, 1714788649L, 1960231288L, -691550554L, -1711599423L, -1402734253L, -1534040574L, -1036476620L, -694596425L, 1287855277L, 268700100L, 673507818L, 1219221077L, 1309181935L, 837507062L, 102191392L, 2113642211L, 1618495361L, 1522401776L, 1343946894L, -1564596231L, 836173195L, 801352122L, 811722940L, -1228420097L, 1059731797L, -71499156L, 1219585730L, -1251577571L, 1568262039L, -88964354L, -253683528L, 716112539L, 349868281L, 706081352L, -1265246858L, -317862735L, 922427619L, -1524858958L, -882819068L, 1844605767L, 1600432669L, 1668497556L, -446255046L, -1577717115L, -424103073L, -1503736858L, 1433683568L, -1802425965L, 1119129137L, -75029280L, 175281534L, 1398638601L, 682780731L, -46811638L, -1785010708L, 812755567L, 1790829989L, -1089088164L, 532564274L, 2093324333L, 876672743L, 1720507406L, 347817448L, -1536446485L, 275583113L, 1034224664L, 841732934L, 108581281L, -67141581L, 195120546L, -1093338988L, -1215353065L, 1699383565L, 194355236L, -1356374006L, -2128247435L, -1796438833L, 686991318L, -1343821952L, 2078882755L, -1409847967L, -187124784L, -1712323794L, 681926361L, -1668928277L, -1812124326L, 1971633948L, -506168801L, -1515058571L, 1081788172L, -797287710L, 731652029L, 678996023L, -859757858L, 159366680L, 670450043L, -1348708071L, 1400169896L, 1618331990L, 1847810513L, 253974915L, -1672656878L, 1625754532L, 155523943L, 1650475197L, 42686516L, 137386906L, -1508419611L, 26674047L, 1921073926L, -1358140272L, -693166797L, 475167441L, 771104896L, -1902413474L, 1878060713L, 1724135771L, 1163694954L, 1526389260L, -3470769L, 1483122437L, 1143566268L, -2103489902L, -225586803L, -612189753L, 1545013934L, -2073574648L, -1511112437L, -100646935L, -615176008L, -1262510234L, -1663685631L, -120391021L, 837619010L, 1768620788L, -1122750729L, -746115347L, -1716659836L, 1831373624L, -1519604582L, 1564406480L, 1381548220L, 288050836L, -1546197374L, -437995328L, -2036239556L, 1933360272L, -1018044894L, -1860173816L, -275596020L, 1169874076L, -812073454L, -1147150464L, -859861484L, -51926488L, -1543305926L, -655894064L, -1294871444L, -775038668L, 1727399570L, -1694749856L, -1681726644L, 1230559200L, -1899673694L, -563402840L, 1532325260L, 1236101308L, -1602344590L, 976499952L, 72147012L, -1745563304L, 1781954106L, 863746928L, 903780412L, -1249681644L, -1767672382L, -1088300320L, 1511278460L, -1493250352L, -1670039390L, -1258136536L, 761439500L, -1430476868L, 566569266L, 1739860416L, -1359058380L, -156988472L, 296261818L, 1177213328L, 1272050156L, -332135852L, -1278173038L, 203259680L, -1656370740L, -1673267744L, 335648450L, 1604265000L, -458427732L, -1413774148L, 72260082L, 47243568L, -1497615196L, 1076668088L, -1840345766L, 123643280L, 1255601020L, -1000859372L, -144592062L, 1675811584L, 145627068L, -1138712752L, -1127095518L, 891125064L, 1777687052L, 1981691996L, -227603246L, 409737728L, -1914729132L, -656926232L, 1791802362L, 616280272L, -1218593492L, -651267340L, -725612142L, 1962243168L, 355099916L, -1194216736L, 247458146L, -1023096152L, -1921985972L, 308674940L, -1341831886L, 263065712L, -962988220L, 7319000L, 1186921594L, -1526575568L, 697322172L, -51687596L, 1489032258L, -1766576736L, 705231548L, -128157232L, 1471458658L, -1034014744L, 1711654860L, 1437826812L, 1621107186L, -686643072L, 723547380L, 1796126344L, 190940986L, 360158032L, 1822447212L, 495194260L, 712524114L, 91217632L, -1812663604L, -1404104544L, 346954626L, -1593920792L, -978824468L, 1781902396L, 17212018L, 1143415920L, -2067790300L, -1909586888L, 1833117722L, -683701552L, -775084996L, 252875924L, -1451406206L, 272590784L, 2146048316L, 1198305936L, 668884002L, 1472701448L, 252344460L, -108467172L, 1234060946L, 1040577664L, -2086207468L, -212884184L, 1872186938L, 530375888L, 2116486252L, -1681681740L, 533186578L, -940525600L, 1801310156L, 396848608L, 2073308706L, -102930136L, 1589489932L, -423356868L, -1389633294L, -1558856976L, -736099516L, 2084612696L, 2038706746L, -556161296L, -1452753732L, 552848916L, -839237438L, -1295601568L, -1130558084L, -1295745840L, -1203880926L, 256473768L, -1605668980L, -577644100L, -297683918L, 1870985024L, 1551939764L, 1821991752L, -1956693318L, -1991512304L, -740386580L, -1202932652L, 736012050L, 1009619872L, 674480076L, -1187525792L, -2122788670L, -73279960L, 1360545196L, -956858564L, 945033074L, 363733808L, 66028068L, -1776537544L, 1843383514L, -110607984L, 536684284L, 55476116L, 1263641410L, -1125672448L, -1482153412L, 496637520L, 1709576866L, -1278809272L, -284607988L, -1541059364L, 23142994L, -523552640L, 1643830100L, 1722364392L, 297396986L, -773343408L, -1262435284L, 1476892020L, -2115285358L, -90121632L, -531262836L, 1729366880L, -922594590L, 1742239912L, -841969460L, 1958457852L, -1499422798L, -1120201232L, 1395453380L, 1710450520L, -440214662L, 967851440L, 226032942L, 1357361627L, 1608476349L, -590736342L, 1932051656L, 1340482033L, -702763165L, 1361639268L, 1385549458L, 455412583L, -163531471L, 1346637430L, 1814499220L, 1018260389L, -271393617L, 2075447656L, -955115194L, 1279324403L, -2009518507L, 1736151602L, -901210112L, -1245510423L, -1830632613L, 940549548L, 488521146L, 1455934319L, -935678727L, -856854130L, 1622295644L, 1231607501L, 1536803383L, -1713772352L, -84928610L, -493880213L, 369630189L, -779436454L, -1744387816L, 1421471361L, -1170111437L, -1831644588L, -766364062L, 715897079L, -360432831L, -1927269946L, -487204092L, -1574195531L, 355891615L, 389608952L, -1707623466L, -1815271837L, 138139173L, -1544321598L, -1140491600L, 427651801L, 1746437195L, 1706343100L, -69015318L, -896604897L, 809495977L, 718908222L, -163461588L, -467749763L, 194211527L, 383014832L, 557500878L, 424674043L, 467034461L, -2087763318L, -1420914520L, 229626897L, 1968956675L, -1982240764L, -681031630L, 377430151L, 918506705L, -1509779882L, 1450231348L, 827505989L, 1990668175L, 1423317768L, -1363403482L, -1797241389L, 1538756405L, 900187794L, -1744035232L, 988722121L, 1450627835L, -1252025140L, -671607462L, -567371697L, -2081893095L, 236601134L, 1864577340L, 756487853L, 1174196567L, 648798368L, 1977540094L, -296161077L, -47231283L, -1769252358L, -599195080L, -325443615L, -1602578285L, -454165836L, -1804240958L, -837471273L, -820102111L, -1911063578L, 1690904292L, -736013803L, -295626177L, -1504701992L, 1989838838L, -171692029L, 61545285L, -62918814L, 1052774608L, -1026860039L, 1074542379L, 1196475548L, -1866229046L, -1537567809L, -2042544375L, 1406855198L, 190732748L, -319868003L, 738242087L, 701465680L, -1271935762L, -415422053L, -1722556419L, 1787161322L, 2097577352L, 1673849649L, 1246995363L, -711466076L, 882191954L, -1773367897L, 741059057L, -793305802L, -1990236716L, -924415131L, 381825903L, 1337888168L, -1895820538L, -119749069L, 286330005L, -476302094L, -96398016L, -1196606807L, -1283296485L, -1430911764L, 1624418554L, -872957649L, -92635847L, -1151996082L, -65108580L, 436471565L, -1357360777L, 176866688L, 1869861854L, -1771660117L, -443848787L, 1175690266L, 698979032L, 1680628545L, -291906573L, 1508320788L, -1482489950L, 1820577534L )
semdiag.combinations<- function (n, r) { v<-1:n v0 <- vector(mode(v), 0) sub <- function(n, r, v) { if (r == 0) v0 else if (r == 1) matrix(v, n, 1) else if (n == 1) matrix(v, 1, r) else rbind(cbind(v[1], Recall(n, r - 1, v)), Recall(n - 1, r, v[-1])) } sub(n, r, v[1:n]) } semdiag.read.eqs<-function (file) { file.ets <- file file.split <- strsplit(file.ets, "\\.") if (length(file.split[[1]]) > 2) stop("File name or folders should not contain '.'") if (file.split[[1]][2] != "ets") stop("File should be of the form 'xxxxxx.ets'") file.cbk <- paste(file.split[[1]][1], ".CBK", sep = "") file.etp <- paste(file.split[[1]][1], ".ETP", sep = "") cbk.info1 <- scan(file.cbk, skip = 2, nlines = 2, quiet = TRUE) cbk.info2 <- scan(file.cbk, skip = 4, nlines = 2, quiet = TRUE) endfile <- scan(file.cbk, nlines = 1, quiet = TRUE) cbk.info.mat <- cbind(cbk.info2, cbk.info1) rownames(cbk.info.mat) <- c("Parameter estimates", "Standard errors", "Robust standard errors", "Corrected standard errors", "Gradients", "Sample covariance matrix", "Model Covariance Matrix (Sigma hat)", "Inverted Information matrix", "Robust inverted information matrix", "Corrected inverted information matrix", "First derivatives", "4th Moment weight matrix", "Standardized Elements", "R-squares", "Factor means", "Univariate statistics (means)", "Univariate statistics (standard deviations)", "Univariate statistics (skewness)", "Univariate statistics (kurtosis)", "Univariate statistics (sample size)", "Dependent variable standardization vector", "Independent variable standardization vector") colnames(cbk.info.mat) <- c("Line Number", "Number of Elements") cbk.base <- read.fwf(file.cbk, widths = c(13, 3), skip = 6, col.names = c("variable", "line"), buffersize = 1, n = 98) nminfo <- length(which(cbk.base[, 2] == 2)) minfo.val <- scan(file.ets, skip = 1, nlines = 1, quiet = TRUE) minfo.dframe <- data.frame(minfo.val) colnames(minfo.dframe) <- "values" rownames(minfo.dframe) <- cbk.base[1:nminfo, 1] start.cbk <- nminfo + 1 ntprobs <- length(c(which(cbk.base[, 2] == 3), which(cbk.base[, 2] == 4))) probs.val <- scan(file.ets, skip = 2, nlines = 2, quiet = TRUE) probs.val[which(probs.val == -1)] <- NA probs.dframe <- data.frame(probs.val, row.names = cbk.base[start.cbk:(start.cbk + ntprobs - 1), 1]) colnames(probs.dframe) <- "p-values" start.cbk <- start.cbk + ntprobs nfit <- 60 fit.val <- scan(file.ets, skip = 4, nlines = 6, quiet = TRUE) fit.val[which(fit.val == -9)] <- NA fit.dframe <- data.frame(fit.val, row.names = cbk.base[start.cbk:(start.cbk + nfit - 1), 1]) colnames(fit.dframe) <- "fit values" start.cbk <- start.cbk + nfit ndesc <- 9 desc.val <- scan(file.ets, skip = 11 - 1, nlines = 1, quiet = TRUE) desc.dframe <- data.frame(desc.val, row.names = cbk.base[start.cbk:(start.cbk + ndesc - 1), 1]) colnames(desc.dframe) <- "values" n.ind <- desc.dframe[8, 1] n.dep <- desc.dframe[9, 1] n.fac <- desc.dframe[3, 1] n.tot <- n.ind + n.dep if (n.ind%%32 == 0) { skiplines <- n.ind/32 }else { skiplines <- trunc(n.ind/32) + 1 } if (n.dep%%32 == 0) { skiplines <- skiplines + n.dep/32 }else { skiplines <- skiplines + trunc(n.dep/32) + 1 } parindvec <- scan(file.etp, skip = skiplines, quiet = TRUE) varnames.string <- readLines(file.etp, n = skiplines, warn=FALSE) varnames.chvec <- unlist(strsplit(varnames.string, split = " ")) varnames.vec <- varnames.chvec[which(varnames.chvec != "")] nout <- dim(cbk.info.mat)[1] model.list <- as.list(rep(NA, nout)) for (i in 1:nout) { startline <- cbk.info.mat[i, 1] if (i != nout) { endlinevec <- cbk.info.mat[(i + 1):nout, 1] endline <- (endlinevec[endlinevec > 0])[1] nlines <- endline - startline }else { if ((cbk.info.mat[i, 2]) > 0) nlines <- endfile - startline else nlines <- 0 } if (startline != 0) { vals <- scan(file.ets, skip = startline - 1, nlines = nlines, quiet = TRUE) }else { vals <- NA } model.list[[i]] <- vals } par.val <- model.list[[1]] par.pos <- which(parindvec > 0) phi.dim <- n.ind * n.ind gamma.dim <- n.dep * n.ind indpos1 <- (par.pos > (phi.dim)) + (par.pos < (phi.dim + gamma.dim)) cumpos1 <- par.pos[indpos1 == 2] cumpos2 <- par.pos[par.pos > (phi.dim + gamma.dim)] if (length(cumpos1) > 0) parindvec[cumpos1] <- parindvec[cumpos1] + max(parindvec) if (length(cumpos2) > 0) parindvec[cumpos2] <- parindvec[cumpos2] + max(parindvec) negpos <- which(parindvec == -1) parindvec[parindvec <= 0] <- NA parvec <- par.val[parindvec] parvec[negpos] <- -1 parvec[is.na(parvec)] <- 0 cuts <- c(n.ind * n.ind, n.dep * n.ind, n.dep * n.dep) dimlist <- list(c(n.ind, n.ind), c(n.dep, n.ind), c(n.dep, n.dep)) cutfac <- rep(1:3, cuts) parlist <- split(parvec, cutfac) parmat <- mapply(function(xx, dd) { matrix(xx, nrow = dd[1], ncol = dd[2], byrow = TRUE) }, parlist, dimlist) names(parmat) <- c("Phi", "Gamma", "Beta") colnames(parmat$Phi) <- rownames(parmat$Phi) <- colnames(parmat$Gamma) <- varnames.vec[1:n.ind] rownames(parmat$Gamma) <- rownames(parmat$Beta) <- colnames(parmat$Beta) <- varnames.vec[(n.ind + 1):length(varnames.vec)] parse.mat <- NULL for (i in 1:5) parse.mat <- cbind(parse.mat, model.list[[i]]) colnames(parse.mat) <- c("Parameter", "SE", "RSE", "CSE", "Gradient") npar <- dim(parse.mat)[1] namesvec <- NULL partable<-NULL for (i in 1:3) { if (i == 1) { combmat <- semdiag.combinations(dim(parmat[[i]])[1], 2) comb.names <- apply(combmat, 2, function(rn) rownames(parmat[[i]])[rn]) par.val0 <- parmat[[i]][lower.tri(parmat[[i]], diag = TRUE)] partable<-rbind(partable, cbind(comb.names, par.val0)) } if (i==2) { comb.names <- as.matrix(expand.grid(rownames(parmat[[i]]), colnames(parmat[[i]]))) par.val0 <- as.vector(parmat[[i]]) partable<-rbind(partable, cbind(comb.names, par.val0)) } if (i ==3){ comb.names <- as.matrix(expand.grid(rownames(parmat[[i]]), colnames(parmat[[i]]))) par.val0 <- as.vector(t(parmat[[i]])) partable<-rbind(partable, cbind(comb.names, par.val0)) } par.val.ind <- which(((par.val0 != 0) + (par.val0 != -1)) == 2) names.mat <- rbind(comb.names[par.val.ind, ]) if (i==3) {names <- apply(names.mat, 1, function(ss) paste("(", ss[2], ",", ss[1], ")", sep = "")) }else{ names <- apply(names.mat, 1, function(ss) paste("(", ss[1], ",", ss[2], ")", sep = "")) } namesvec <- c(namesvec, names) } if ((dim(parse.mat)[1]) != (length(namesvec))) { parse.mat <- parse.mat[parse.mat[, 1] != 0, ] if ((dim(parse.mat)[1]) == (length(namesvec))) rownames(parse.mat) <- namesvec }else { rownames(parse.mat) <- namesvec } meanjn <- scan(file.cbk, skip = 1, nlines = 1, quiet = TRUE)[3] Vcheckstr <- colnames(parmat$Phi) compstr <- paste("V", 1:999, sep = "") TFVcheck <- Vcheckstr %in% compstr if (any(TFVcheck)) depnames.add <- Vcheckstr[TFVcheck] else depnames.add <- NULL VBcheckstr <- colnames(parmat$Beta) TFVBcheck <- VBcheckstr %in% compstr if (any(TFVBcheck)) depnames.addB <- VBcheckstr[TFVBcheck] else depnames.addB <- NULL depnames <- c(depnames.addB, depnames.add) rm(compstr) if (meanjn == 0) p <- n.dep else p <- n.dep + 1 cov.list <- as.list(rep(NA, 5)) names(cov.list) <- c("sample.cov", "sigma.hat", "inv.infmat", "rinv.infmat", "cinv.infmat") for (i in 6:10) { if (length(model.list[[i]]) > 1) { cov.list[[i - 5]] <- matrix(model.list[[i]], nrow = sqrt(length(model.list[[i]]))) if (i <= 7) { dimnames(cov.list[[i - 5]]) <- list(depnames[1:dim(cov.list[[i - 5]])[1]], depnames[1:dim(cov.list[[i - 5]])[2]]) order.V <- order(depnames) cov.list[[i - 5]] <- cov.list[[i - 5]][order.V, order.V] } if (i >= 8) dimnames(cov.list[[i - 5]]) <- list(namesvec, namesvec) } } pstar <- p * (p + 1)/2 if (length(model.list[[11]]) > 1) { deriv1 <- matrix(model.list[[11]], nrow = npar, ncol = pstar) } else { deriv1 <- NA } if (length(model.list[[12]]) > 1) { moment4 <- matrix(model.list[[12]], nrow = pstar, ncol = pstar) } else { moment4 <- NA } ustatmat <- cbind(model.list[[16]], model.list[[17]], model.list[[18]], model.list[[19]], model.list[[20]]) if (dim(ustatmat)[1] == 1) ustatmat <- NA else colnames(ustatmat) <- c("means", "sd", "skewness", "kurtosis", "n") result <- c(list(model.info = minfo.dframe), list(pval = probs.dframe), list(fit.indices = fit.dframe), list(model.desc = desc.dframe), parmat, list(par.table = parse.mat), cov.list, list(derivatives = deriv1), list(moment4 = moment4), list(ssolution = model.list[[13]]), list(Rsquared = model.list[[14]]), list(fac.means = model.list[[15]]), list(var.desc = ustatmat), list(depstd = model.list[[21]]), list(indstd = model.list[[22]])) result } semdiag.run.eqs<-function (EQSpgm, EQSmodel, serial, Rmatrix = NA, datname = NA, LEN = 2e+06) { res <- semdiag.call.eqs(EQSpgm = EQSpgm, EQSmodel = EQSmodel, serial = serial, Rmatrix = Rmatrix, datname = datname, LEN = LEN) if (!res) warning("EQS estimation not successful!") filedir.split <- strsplit(EQSmodel, "/")[[1]] n <- length(filedir.split) etsname <- strsplit(filedir.split[n], "\\.")[[1]][1] etsfile <- paste(etsname, ".ets", sep = "") reslist <- semdiag.read.eqs(etsfile) return(c(list(success = res), reslist)) } semdiag.call.eqs<-function (EQSpgm, EQSmodel, serial, Rmatrix = NA, datname = NA, LEN = 2e+06) { if (!file.exists(EQSmodel)) stop("The .eqs file not found in the current folder!") filedir.split <- strsplit(EQSmodel, "/")[[1]] n <- length(filedir.split) filedir <- paste(filedir.split[1:(n - 1)], collapse = "/") if (n > 1) setwd(filedir) outname <- strsplit(filedir.split[n], "\\.")[[1]][1] file.out <- paste(outname, ".out", sep = "") lenstring <- paste("LEN=", as.integer(LEN), sep = "") filepathin <- paste("IN=", EQSmodel, sep = "") fileout <- paste("OUT=", file.out, sep = "") serstring <- paste("SER=", serial, "\n", sep = "") if (length(Rmatrix) > 1) { if (is.na(datname)) { warning(paste("No filename for data specified! ", outname, ".dat is used", sep = "")) datname <- paste(outname, ".dat", sep = "") } write.table(as.matrix(Rmatrix), file = datname, col.names = FALSE, row.names = FALSE) } EQScmd <- paste(deparse(EQSpgm), filepathin, fileout, lenstring, serstring) RetCode <- system(EQScmd, intern = FALSE, ignore.stderr = TRUE, wait = TRUE, input = NULL) if (RetCode == 0) { success <- TRUE } else { success <- FALSE } return(success = success) } rsem.pattern<-function(x,print=FALSE){ if (missing(x)) stop("A data set has to be provided!") if (!is.matrix(x)) x<-as.matrix(x) y<-x M<-is.na(x) nM<-max(apply(M,1,sum)) n<-dim(x)[1] p<-dim(x)[2] if (nM==p) stop("Some cases have missing data on all variables. Please delete them first.") misorder<-rep(0,n) for (i in 1:n){ misorderj<-0 for (j in 1:p){ if (is.na(x[i,j])) misorderj<-misorderj+2^(j-1) } misorder[i]<-misorderj } temp<-order(misorder) x<-x[temp,] misn<-misorder[temp] mi<-0; nmi<-0;oi<-0; noi<-0; for (j in 1:p){ if (is.na(x[1,j])){ mi<-c(mi,j) nmi<-nmi+1 }else{ oi<-c(oi,j) noi<-noi+1 } } oi<-oi[2:(noi+1)] if (nmi==0){ misinfo_0 = c(noi, oi) }else{ mi<-mi[2:(nmi+1)] misinfo_0<-c(noi,oi,mi) } patnobs <- 0 totpat<-1; ncount<-1; t1<-misn[1] for (i in 2:n){ if (misn[i]==t1){ ncount<-ncount+1 }else{ patnobs<-c(patnobs,ncount) t1<-misn[i] ncount<-1 totpat<-totpat+1 mi<-0; nmi<-0;oi<-0; noi<-0; for (j in 1:p){ if (is.na(x[i,j])){ mi<-c(mi,j) nmi<-nmi+1 }else{ oi<-c(oi,j) noi<-noi+1 } } oi<-oi[2:(noi+1)] mi<-mi[2:(nmi+1)] misinfo_0 <- rbind(misinfo_0, c(noi,oi,mi)) } } patnobs<-c(patnobs, ncount) patnobs<-patnobs[2:(totpat+1)] if (is.vector(misinfo_0)){ misinfo<-c(patnobs, misinfo_0) }else{ misinfo<-cbind(patnobs, misinfo_0) } if (!is.matrix(misinfo)){ misinfo<-matrix(misinfo, nrow=1) } nr<-nrow(misinfo) mispat<-matrix(1, nrow=nr, ncol=p) for (i in 1:nr){ if (misinfo[i,2]<p){ ind<-misinfo[i, (misinfo[i,2]+3):(p+2)] mispat[i, ind]<-0 } } mispat<-cbind(misinfo[,1:2, drop=FALSE], mispat) rownames(mispat)<-paste('Pattern ', 1:nr, sep="") colnames(mispat)<-c('n','nvar',colnames(x)) if (print) print(mispat) invisible(list(misinfo=misinfo, mispat=mispat, x=x, y=y)) } rsem.weight<-function(x, varphi, mu0, sig0){ if (!is.matrix(x)) x<-as.matrix(x) n<-dim(x)[1] p<-dim(x)[2] prob<-1-varphi wi1all<-wi2all<-NULL if (varphi==0){ wi1all<-wi2all<-rep(1, n) }else{ for (i in 1:n){ xi<-x[i, ] xid<-which(!is.na(xi)) xic<-xi[xid] ximu<-mu0[xid] xisig<-as.matrix(sig0[xid, xid]) xidiff<-as.matrix(xic-ximu) di2<-t(xidiff)%*%solve(xisig)%*%xidiff di<-sqrt(di2) pi<-length(xic) chip<-qchisq(prob, pi) ck<-sqrt(chip) cbeta<-( pi*pchisq(chip,pi+2) + chip*(1-prob) )/pi if (di <= ck){ wi1all<-c(wi1all, 1) wi2all<-c(wi2all, 1/cbeta) }else{ wi1<-ck/di wi1all<-c(wi1all, wi1) wi2all<-c(wi2all, wi1*wi1/cbeta) } } } return(list(w1=wi1all, w2=wi2all)) } rsem.ssq<-function(x){ sum(x^2) } rsem.emmusig<-function(xpattern, varphi=.1, max.it=1000, st='i'){ if (is.null(xpattern$mispat)) stop("The output from the function rsem.pattern is required") x<-xpattern$x misinfo<-xpattern$misinfo ep <- 1e-6 n<-dim(x)[1] p<-dim(x)[2] mu0<-rep(0,p) sig0<-diag(p) if (st=='mcd'){ y<-na.omit(x) ny<-nrow(y) par.st<-cov.rob(y, method='mcd') mu0<-par.st$center sig0<-par.st$cov } n_it<-0; dt<-1; if (varphi==0){ ck<-10e+10 cbeta<-1 }else{ prob<-1-varphi chip<-qchisq(prob, p) ck<-sqrt(chip) cbeta<-( p*pchisq(chip, p+2) + chip*(1-prob) )/p } while (dt>ep && n_it <= max.it){ sumx<-rep(0,p); sumxx<-array(0,dim=c(p,p)); sumw1<-0; sumw2<-0; npat<-dim(misinfo)[1] p1<-misinfo[1,2] n1<-misinfo[1,1] if (p1==p){ sigin <- solve(sig0) for (i in 1:n1){ xi<-x[i,] xi0<-xi-mu0 di2<-as.numeric(xi0%*%sigin%*%xi0) di<-sqrt(di2) if (di<=ck){ wi1<-1 wi2<-1/cbeta }else{ wi1<-ck/di wi2<-wi1*wi1/cbeta } sumw1<-sumw1+wi1; xxi0<-xi0%*%t(xi0) sumx<-sumx+wi1*c(xi) sumxx<-sumxx+c(wi2)*xxi0 sumw2<-sumw2+wi2 } }else{ if (varphi==0){ ck1<-1e+10 cbeta1<-1 }else{ chip1<-qchisq(prob, p1) ck1<-sqrt(chip1) cbeta1<-( p1*pchisq(chip1,p1+2) + chip1*(1-prob) )/p1 } o1<-misinfo[1,3:(2+p1)] m1<-misinfo[1,(2+p1+1):(p+2)] mu_o<-mu0[o1]; mu_m<-mu0[m1] sig_oo<-sig0[o1,o1]; sig_om<-sig0[o1,m1]; if (p1==1) {sig_mo<-sig_om}else{sig_mo<-t(sig_om)} sig_mm<-sig0[m1,m1]; sigin_oo<-solve(sig_oo) beta_mo<-sig_mo%*%sigin_oo delt <- array(0, dim=c(p,p)) delt[m1,m1]<-sig_mm - beta_mo%*%sig_om for (i in 1:n1){ xi<-x[i,] xi_o<-xi[o1] xi0_o<-xi_o-mu_o stdxi_o<-sigin_oo%*%xi0_o di2<-as.numeric(xi0_o%*%stdxi_o) di<-sqrt(di2) if (di<=ck1){ wi1<-1 wi2<-1/cbeta1 }else{ wi1<-ck1/di wi2<-wi1*wi1/cbeta1 } sumw1<-sumw1+wi1 xm1<-mu_m+sig_mo%*%stdxi_o xi[m1]<-xm1 xi0<-xi-mu0 xxi0<-xi0%*%t(xi0) sumx<-sumx+wi1*c(xi) sumxx<-sumxx+c(wi2)*xxi0+delt sumw2<-sumw2+wi2 } } if (npat>1){ snj<-n1 for (j in 2:npat){ nj<-misinfo[j,1]; pj<-misinfo[j,2]; oj<-misinfo[j, 3:(2+pj)]; mj<-misinfo[j, (2+pj+1):(p+2)]; mu_o<-mu0[oj]; mu_m<-mu0[mj]; sig_oo<-sig0[oj,oj]; sig_om<-sig0[oj,mj]; if (pj==1) {sig_mo<-sig_om}else{sig_mo<-t(sig_om)} sig_mm<-sig0[mj,mj]; sigin_oo<-solve(sig_oo) beta_mo<-sig_mo%*%sigin_oo delt <- array(0, dim=c(p,p)) delt[mj,mj]<-sig_mm - beta_mo%*%sig_om if (varphi==0){ ckj<-10e+10 cbetaj<-1 }else{ chipj<-qchisq(prob,pj) ckj<-sqrt(chipj) cbetaj<- ( pj*pchisq(chipj, pj+2) + chipj*(1-prob) )/pj } for (i in ((snj+1):(snj+nj))){ xi<-x[i,] xi_o<-xi[oj] xi0_o<-xi_o - mu_o stdxi_o<-sigin_oo%*%xi0_o di2<-as.numeric(xi0_o%*%stdxi_o) di<-sqrt(di2) if (di<=ckj){ wi1<-1 wi2<-1/cbetaj }else{ wi1<-ckj/di wi2<-wi1*wi1/cbetaj } sumw1<-sumw1+wi1 xmj<-mu_m+sig_mo%*%stdxi_o xi[mj]<-xmj xi0<-xi-mu0 xxi0<-xi0%*%t(xi0) sumx<-sumx+wi1*c(xi) sumxx<-sumxx+c(wi2)*xxi0+delt sumw2<-sumw2+wi2 } snj<-snj+nj } } mu1<-sumx/sumw1 sig1<-sumxx/n dt<-max(c(max(abs(mu1-mu0)), max(abs(sig1-sig0)))); mu0<-mu1; sig0<-sig1; n_it<-n_it+1; } if (n_it>=max.it) warning("The maximum number of iteration was exceeded. Please increase max.it in the input.") rownames(sig1)<-colnames(sig1) names(mu1)<-colnames(sig1) weight<-rsem.weight(xpattern$y, varphi, mu1, sig1) list(mu=mu1, sigma=sig1, max.it=n_it, weight=weight) } rsem.vec<-function(x){ t(t(as.vector(x))) } rsem.vech<-function(x){ t(x[!upper.tri(x)]) } rsem.DP <- function(x){ mat <- diag(x) index <- seq(x*(x+1)/2) mat[ lower.tri( mat , TRUE ) ] <- index mat[ upper.tri( mat ) ] <- t( mat )[ upper.tri( mat ) ] outer(c(mat), index , function( x , y ) ifelse(x==y, 1, 0 ) ) } rsem.index<-function(p,oj){ temp<-1:(p*p) index<-array(temp, dim=c(p,p)) indexoj<-index[oj,oj] nj<-length(oj) rsem.vec(indexoj) } rsem.indexv<-function(p, select){ pv<-length(select) pvs<-pv*(pv+1)/2 index_s<-rep(0,pvs) count<-p countv<-0 for (i in 1:p){ for (j in i:p){ count<-count+1 for (iv in 1:pv){ for (jv in iv:pv){ if (i==select[iv] && j==select[jv]){ countv<-countv+1 index_s[countv]<-count } } } } } c(select, index_s) } rsem.indexvc<-function(p, select){ pv<-length(select) pvs<-pv*(pv+1)/2 index_s<-rep(0,pvs) count<-0 countv<-0 for (i in 1:p){ for (j in i:p){ count<-count+1 for (iv in 1:pv){ for (jv in iv:pv){ if (i==select[iv] && j==select[jv]){ countv<-countv+1 index_s[countv]<-count } } } } } index_s + rep(p,pvs) } rsem.switch<-function(p){ ps<-p*(p+1)/2 bmat<-array(0,c(p,p)) nb<-0 for (i in 1:p){ for (j in 1:i){ nb<-nb+1 bmat[i,j]<-nb } } vb<-rsem.vech(bmat) Imatc<-diag(ps) permuc<-Imatc[,vb] iMat<-diag(p+ps) vp<-1:p vs<-c(vp, (vb+rep(p,ps))) permu<-iMat[,vs] permu<-rbind(permu[(p+1):(p+ps), ], permu[1:p, ]) list(mu=permu, sigma=permuc) } rsem.gname<-function(name){ temp.name<-NULL k<-length(name) for (i in 1:k){ for (j in i:k){ temp.name<-c(temp.name, paste(name[i], ".", name[j], sep="")) } } temp.name } rsem.Ascov<-function(xpattern, musig, varphi=.1){ if (is.null(xpattern$mispat)) stop("The output from the function rsem.pattern is required") x<-xpattern$x misinfo<-xpattern$misinfo mu0<-musig$mu sig0<-musig$sig n<-dim(x)[1]; p<-dim(x)[2]; ps<-p*(p+1)/2; pps<-p+ps; dup<-rsem.DP(p) dupt<-t(dup) i_p<-diag(p) B11<-array(0, c(p,p)); B12<-array(0,c(p,ps)); B22<-array(0,c(ps,ps)); ddl11<-array(0,c(p,p)); ddl12<-array(0,c(p,ps)); ddl21<-array(0,c(ps,p)); ddl22<-array(0,c(ps,ps)); if (varphi==0){ ck<-1e+10 cbeta<-1 }else{ prob<-1-varphi chip<-qchisq(prob,p); ck<-sqrt(chip); cbeta<-( p*pchisq(chip,p+2)+ chip*(1-prob) )/p; } dl<-rep(0,pps) npat<-dim(misinfo)[1] n1<-misinfo[1,1]; p1<-misinfo[1,2]; if (p1==p){ sigin<-solve(sig0) vecsig<-rsem.vec(sig0) Wmat<-kronecker(sigin,sigin)/2 for (i in 1:n1){ xi<-x[i,] xi0<-xi-mu0; stdxi<-sigin%*%xi0 stdxit<-t(stdxi) di2<-xi0%*%stdxi di<-sqrt(di2) if (di<=ck){ wi1<-1 wi2<-1/cbeta dwi1<-0 dwi2<-0 }else{ wi1<-ck/di wi2<-wi1*wi1/cbeta dwi1<-wi1/di2 dwi2<-wi2/di2 } dlimu<-c(wi1)*stdxi xixi0<-xi0%*%t(xi0) vecyi<-rsem.vec(xixi0) wvecyi<-c(wi2)*vecyi dlisig<-dupt%*%Wmat%*%(wvecyi-vecsig) B11<-B11+dlimu%*%t(dlimu) B12<-B12+dlimu%*%t(dlisig) B22<-B22+dlisig%*%t(dlisig) dl_i<-c(dlimu, dlisig) dl<-dl+dl_i Hi<-stdxi%*%stdxit tti<-c(wi1)*sigin uui<-c(wi2)*sigin ddl11<-ddl11 + (-tti+c(dwi1)*Hi) ddl22<-ddl22 + dupt%*%( Wmat - kronecker(Hi, (uui-.5*c(dwi2)*Hi) ) )%*%dup ddl12<-ddl12 + kronecker( (-tti+.5*c(dwi1)*Hi) ,stdxit)%*%dup ddl21<-ddl21 + dupt%*%kronecker( (-uui+c(dwi2)*Hi), stdxi ) } }else{ if (varphi==0){ ck1<-1e+10 cbeta1<-1 }else{ chip1<-qchisq(prob,p1) ck1<-sqrt(chip1) cbeta1<-( p1*pchisq(chip1,p1+2) + chip1*(1-prob) )/p1 } o1<-misinfo[1,3:(2+p1)] mu_o<-mu0[o1] sig_oo<-sig0[o1,o1] vecsig_oo<-rsem.vec(sig_oo) sigin_oo<-solve(sig_oo) E1<-i_p[o1,]; if (o1==1){Et1=E1}else{Et1<-t(E1)} F1<-kronecker(E1, E1)%*%dup; Ft1<-t(F1) Wmat1<-.5*kronecker(sigin_oo, sigin_oo) for (i in 1:n1){ xi<-x[i,] xi_o<-xi[o1] xi0_o<-xi_o-mu_o xi0_ot<-t(xi0_o) stdxi_o<-sigin_oo%*%xi0_o stdxit_o<-t(stdxi_o) di2<-xi0_o%*%stdxi_o di<-sqrt(di2) if (di<=ck){ wi1<-1 wi2<-1/cbeta dwi1<-0 dwi2<-0 }else{ wi1<-ck/di wi2<-wi1*wi1/cbeta dwi1<-wi1/di2 dwi2<-wi2/di2 } dlimu<-c(wi1)*Et1%*%stdxi_o xixi0_o<-xi0_o%*%t(xi0_o) vecyi<-rsem.vec(xixi0_o) wvecyi<-c(wi2)*vecyi dlisig<-Ft1%*%Wmat1%*%(wvecyi-vecsig_oo) B11<-B11+dlimu%*%t(dlimu) B12<-B12+dlimu%*%t(dlisig) B22<-B22+dlisig%*%t(dlisig) dl_i<-c(dlimu, dlisig) dl<-dl+dl_i Hi<-stdxi_o%*%stdxit_o tti<-c(wi1)*sigin_oo uui<-c(wi2)*sigin_oo ddl11<-ddl11 + Et1%*%(-tti+c(dwi1)*Hi)%*%E1 ddl22<-ddl22 + Ft1%*%( Wmat1 - kronecker(Hi, (uui-.5*c(dwi2)*Hi) ) )%*%F1 ddl12<-ddl12 + Et1%*%kronecker( (-tti+.5*c(dwi1)*Hi) ,stdxit_o)%*%F1 ddl21<-ddl21 + Ft1%*%kronecker( (-uui+c(dwi2)*Hi), stdxi_o )%*%E1 } } if (npat>1){ snj<-n1 for (j in 2:npat){ nj<-misinfo[j,1] pj<-misinfo[j,2] if (varphi==0){ ckj<-1e+10 cbetaj<-1 }else{ chipj<-qchisq(prob, pj) ckj<-sqrt(chipj) cbetaj<-( pj*pchisq(chipj,pj+2) + chipj*(1-prob) )/pj } oj<-misinfo[j, 3:(2+pj)] mu_o<-mu0[oj] sig_oo<-sig0[oj,oj] sigin_oo<-solve(sig_oo) vecsig_oo<-rsem.vec(sig_oo) Ej<-i_p[oj, ] if (pj==1){Etj<-Ej}else{Etj<-t(Ej)} Fj<-kronecker(Ej, Ej)%*%dup Ftj<-t(Fj) Wmati<-0.5*kronecker(sigin_oo, sigin_oo) for (i in (snj+1):(snj+nj)){ xi<-x[i,] xi_o<-xi[oj] xi0_o<-xi_o-mu_o xi0_ot<-t(xi0_o) stdxi_o<-sigin_oo%*%xi0_o stdxit_o<-t(stdxi_o) di2<-xi0_o%*%stdxi_o di<-sqrt(di2) if (di<=ckj){ wi1<-1 wi2<-1/cbetaj dwi1<-0 dwi2<-0 }else{ wi1<-ckj/di wi2<-wi1*wi1/cbetaj dwi1<-wi1/di2 dwi2<-wi2/di2 } dlimu<-c(wi1)*Etj%*%stdxi_o xixi0_o<-xi0_o%*%t(xi0_o) vecyi<-rsem.vec(xixi0_o) wvecyi<-c(wi2)*vecyi dlisig<-Ftj%*%Wmati%*%(wvecyi-vecsig_oo) B11<-B11+dlimu%*%t(dlimu) B12<-B12+dlimu%*%t(dlisig) B22<-B22+dlisig%*%t(dlisig) dl_i<-c(dlimu, dlisig) dl<-dl+dl_i Hi<-stdxi_o%*%stdxit_o tti<-c(wi1)*sigin_oo uui<-c(wi2)*sigin_oo ddl11<-ddl11 + Etj%*%(-tti+c(dwi1)*Hi)%*%Ej ddl22<-ddl22 + Ftj%*%( Wmati - kronecker(Hi, (uui-.5*c(dwi2)*Hi) ) )%*%Fj ddl12<-ddl12 + Etj%*%kronecker( (-tti+.5*c(dwi1)*Hi) ,stdxit_o)%*%Fj ddl21<-ddl21 + Ftj%*%kronecker( (-uui+c(dwi2)*Hi), stdxi_o )%*%Ej } snj<-snj+nj } } Bbeta<-rbind( cbind(B11, B12), cbind(t(B12), B22) ) Abeta<-rbind( cbind(ddl11, ddl12), cbind(ddl21, ddl22) ) Abin<-solve(Abeta) Omega<-n*Abin%*%Bbeta%*%t(Abin) Gamma<-Omega xnames<-colnames(x) if (is.null(xnames)) xnames<-paste('V', 1:p) mnames<-rsem.gname(xnames) colnames(Abeta)<-colnames(Bbeta)<-colnames(Gamma)<-rownames(Abeta)<-rownames(Bbeta)<-rownames(Gamma)<-c(xnames, mnames) list(Abeta=Abeta, Bbeta=Bbeta, Gamma=Gamma) } rsem<-function(dset, select, EQSmodel, moment=TRUE, varphi=.1, st='i', max.it=1000, eqsdata='data.txt', eqsweight='weight.txt', EQSpgm="C:/Progra~1/EQS61/WINEQS.EXE", serial="1234"){ if (missing(dset)) stop("A data set is needed!") if (!is.matrix(dset)) dset<-data.matrix(dset) n<-dim(dset)[1] p<-dim(dset)[2] cat("Sample size n =", n, "\n") cat("Total number of variables q =", p, "\n\n") if (missing(select)) select<-c(1:p) cat("The following",length(select),"variables are selected for SEM models \n") cat(colnames(dset)[select], "\n\n") p_v<-length(select) pvs<-p_v+p_v*(p_v+1)/2 miss_pattern<-rsem.pattern(dset) x<-miss_pattern$x misinfo<-miss_pattern$misinfo totpat<-dim(misinfo)[1] cat("There are", totpat, "missing data patterns. They are \n") print(misinfo) cat("\n") em_results<-rsem.emmusig(miss_pattern, varphi=varphi) if (em_results$max.it >= max.it){ warning("\nMaximum iteration for EM is exceeded and the results may not be trusted. Change max.it to a greater number.\n") } hmu1<-em_results$mu hsigma1<-em_results$sigma ascov_results<-rsem.Ascov(miss_pattern, em_results, varphi=varphi) Abeta<-ascov_results$Abeta Bbeta<-ascov_results$Bbeta hupsilon<-ascov_results$Gamma index_beta<-rsem.indexv(p, select) index_sig<-rsem.indexvc(p,select) index_other<-c(select, index_sig) gamma_other<-hupsilon[index_other,index_other] hmu<-hmu1[select] hsigma<-hsigma1[select, select] cat("Estimated means: \n") print(hmu) if (missing(EQSmodel)){ se.hup<-sqrt(diag(hupsilon/n)) se.hmu1<-se.hup[1:p] se.hsig1<-se.hup[(p+1):(p*(p+3)/2)] se.matrix.hsig1<-array(0, c(p,p)) se.matrix.hsig1[lower.tri(se.matrix.hsig1,TRUE)]<-se.hsig1 se.matrix.hsig1[upper.tri(se.matrix.hsig1)]<-se.matrix.hsig1[lower.tri(se.matrix.hsig1)] se.hmu<-se.hmu1[select] se.matrix.hsig<-se.matrix.hsig1[select,select] cat("Standard errors for estimated means:\n"); print(se.hmu) } cat("\nEstimated covariance matrix: \n") print(hsigma) if (missing(EQSmodel)){ cat("Standard errors for estimated covariance matrix: \n") print(se.matrix.hsig) } cat("\n") if (!missing(EQSmodel)){ permu_sig<-rsem.switch(p_v)$sigma permu_beta<-rsem.switch(p_v)$mu hgamma_sig<-hupsilon[index_sig,index_sig] hgamma_sig<-permu_sig%*%hgamma_sig%*%t(permu_sig) hgamma_beta<-hupsilon[index_beta,index_beta] hgamma_beta_eqs<-rbind( cbind(permu_beta%*%hgamma_beta%*%t(permu_beta), rep(0,pvs)), c(rep(0,pvs), 1) ) hgamma_beta<-permu_beta%*%hgamma_beta%*%t(permu_beta) if (moment){ write.table(rbind(hsigma,hmu), 'data.txt', row.names=FALSE,col.names=FALSE) write.table(hgamma_beta_eqs, 'weight.txt', row.names=FALSE,col.names=FALSE) }else{ write.table(rbind(hsigma), 'data.txt', row.names=FALSE,col.names=FALSE) write.table(hgamma_sig, 'weight.txt', row.names=FALSE,col.names=FALSE) } res <- semdiag.run.eqs(EQSpgm = EQSpgm, EQSmodel = EQSmodel, serial = serial) fit<-res$fit.indices pval<-res$pval fit.stat<-rbind( c(fit[sub(' +','',row.names(fit))=='SBCHI',1], pval[sub(' +','',row.names(pval))=='SBPVAL',1]), c(fit[sub(' +','',row.names(fit))=='MVADJCHI',1], pval[sub(' +','',row.names(pval))=='TPADJCHI',1]), c(fit[sub(' +','',row.names(fit))=='YBRESTST',1], pval[sub(' +','',row.names(pval))=='TPYBRTST',1]), c(fit[sub(' +','',row.names(fit))=='YBRESF',1], pval[sub(' +','',row.names(pval))=='TPYBRESF',1]) ) colnames(fit.stat)<-c('T','p') rownames(fit.stat)<-c('RML','AML','CRADF','RF') cat('Test statistics:\n') print(fit.stat) cat('\nParameter estimates:\n') z<-res$par.table[,1]/res$par.table[,3] par.est<-cbind(res$par.table[,c(1,3)], z) colnames(par.est)<-c('Parameter', 'SE', 'z-score') print(par.est) invisible(list(fit.stat=fit.stat, para=par.est, sem=list(mu=hmu, sigma=hsigma, gamma_eqs_cov=hgamma_sig, gammam_eqs_mcov=hgamma_beta_eqs), misinfo=miss_pattern, em=em_results, ascov=ascov_results, eqs=res)) }else{ invisible(list(sem=list(mu=hmu, sigma=hsigma, gamma=gamma_other), misinfo=miss_pattern, em=em_results, ascov=ascov_results)) } } rsem.print<-function(object, robust.se, robust.fit, estimates=TRUE, fit.measures=FALSE, standardized=FALSE, rsquare=FALSE, std.nox=FALSE, modindices=FALSE) { test <- lavInspect(object, "test") lavpartable <- parTable(object) lavoptions <- lavInspect(object, "options") t0.txt <- sprintf(" %-40s", "Statistic") t1.txt <- sprintf(" %10s", "ML") cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Value") t1.txt <- sprintf(" %10.3f", test[[1]]$stat) cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom") t1.txt <- sprintf(" %10i", test[[1]]$df); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "P-value") t1.txt <- sprintf(" %10.3f", test[[1]]$pvalue) cat(t0.txt, t1.txt, "\n\n", sep="") t0.txt <- sprintf(" %-40s", "Statistic") t1.txt <- sprintf(" %10s", "RML") cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Value") t1.txt <- sprintf(" %10.3f", robust.fit$TRML[[1]][1]) cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom") t1.txt <- sprintf(" %10i", robust.fit$TRML[[1]][2]); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "P-value") t1.txt <- sprintf(" %10.3f", robust.fit$TRML[[1]][3]) cat(t0.txt, t1.txt, "\n\n", sep="") t0.txt <- sprintf(" %-40s", "Statistic") t1.txt <- sprintf(" %10s", "AML") cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Value") t1.txt <- sprintf(" %10.3f", robust.fit$TAML[[1]][1]) cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom") t1.txt <- sprintf(" %10.3f", robust.fit$TAML[[1]][2]); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "P-value") t1.txt <- sprintf(" %10.3f", robust.fit$TAML[[1]][3]) cat(t0.txt, t1.txt, "\n\n", sep="") t0.txt <- sprintf(" %-40s", "Statistic") t1.txt <- sprintf(" %10s", "CRADF") cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Value") t1.txt <- sprintf(" %10.3f", robust.fit$TCRADF[[1]][1]) cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom") t1.txt <- sprintf(" %10i", robust.fit$TCRADF[[1]][2]); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "P-value") t1.txt <- sprintf(" %10.3f", robust.fit$TCRADF[[1]][3]) cat(t0.txt, t1.txt, "\n\n", sep="") t0.txt <- sprintf(" %-40s", "Statistic") t1.txt <- sprintf(" %10s", "RF") cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Value") t1.txt <- sprintf(" %10.3f", robust.fit$TRF[[1]][1]) cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom 1") t1.txt <- sprintf(" %10.3f", robust.fit$TRF[[1]][2]); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "Degrees of freedom 2") t1.txt <- sprintf(" %10.3f", robust.fit$TRF[[1]][3]); cat(t0.txt, t1.txt, "\n", sep="") t0.txt <- sprintf(" %-40s", "P-value") t1.txt <- sprintf(" %10.3f", robust.fit$TRF[[1]][4]) cat(t0.txt, t1.txt, "\n\n", sep="") if(std.nox) standardized <- TRUE if(estimates) { print.estimate <- function(name="ERROR", i=1, z.stat=TRUE) { name <- substr(name, 1, 13) if(!standardized) { if(is.na(se[i])) { txt <- sprintf(" %-13s %9.3f %8.3f\n", name, est[i], se[i]) } else if(se[i] == 0) { txt <- sprintf(" %-13s %9.3f\n", name, est[i]) } else if(est[i]/se[i] > 9999.999) { txt <- sprintf(" %-13s %9.3f %8.3f\n", name, est[i], se[i]) } else if(!z.stat) { txt <- sprintf(" %-13s %9.3f %8.3f\n", name, est[i], se[i]) } else { z <- est[i]/se[i] pval <- 2 * (1 - pnorm( abs(z) )) txt <- sprintf(" %-13s %9.3f %8.3f %8.3f %8.3f\n", name, est[i], se[i], z, pval) } } cat(txt) } est <- lavpartable$est se <- lavpartable$se se[lavpartable$free != 0] <- robust.se$se[[1]] ngroups <- lavInspect(object, "ngroups") group.label <- lavInspect(object, "group.label") for(g in 1:ngroups) { ov.names <- lavNames(object, "ov", group=g) lv.names <- lavNames(object, "lv", group=g) if(ngroups > 1) { if(g > 1) cat("\n\n") cat("Group ", g, " [", group.label[[g]], "]:\n\n", sep="") } if(!standardized) { cat(" Estimate SE Z-value P-value\n") } else { if(std.nox) { cat(" Estimate Std.err Z-value P(>|z|) Std.lv Std.nox\n") } else { cat(" Estimate Std.err Z-value P(>|z|) Std.lv Std.all\n") } } makeNames <- function(NAMES, LABELS) { l.idx <- which(nchar(LABELS) > 0L) if(length(l.idx) > 0L) { LABELS <- abbreviate(LABELS, 4) LABELS[l.idx] <- paste(" (", LABELS[l.idx], ")", sep="") MAX.L <- max(nchar(LABELS)) NAMES <- abbreviate(NAMES, minlength = (13 - MAX.L), strict = TRUE) NAMES <- sprintf(paste("%-", (13 - MAX.L), "s%", MAX.L, "s", sep=""), NAMES, LABELS) } else { NAMES <- abbreviate(NAMES, minlength = 13, strict = TRUE) } } NAMES <- lavpartable$rhs mm.idx <- which( lavpartable$op == "=~" & !lavpartable$lhs %in% ov.names & lavpartable$group == g) if(length(mm.idx)) { cat("Latent variables:\n") lhs.old <- "" NAMES[mm.idx] <- makeNames( lavpartable$rhs[mm.idx], lavpartable$label[mm.idx] ) for(i in mm.idx) { lhs <- lavpartable$lhs[i] if(lhs != lhs.old) cat(" ", lhs, " =~\n", sep="") print.estimate(name=NAMES[i], i) lhs.old <- lhs } cat("\n") } fm.idx <- which( lavpartable$op == "<~" & lavpartable$group == g) if(length(fm.idx)) { cat("Composites:\n") lhs.old <- "" NAMES[fm.idx] <- makeNames( lavpartable$rhs[fm.idx], lavpartable$label[fm.idx]) for(i in fm.idx) { lhs <- lavpartable$lhs[i] if(lhs != lhs.old) cat(" ", lhs, " <~\n", sep="") print.estimate(name=NAMES[i], i) lhs.old <- lhs } cat("\n") } eqs.idx <- which(lavpartable$op == "~" & lavpartable$group == g) if(length(eqs.idx) > 0) { cat("Regressions:\n") lhs.old <- "" NAMES[eqs.idx] <- makeNames( lavpartable$rhs[eqs.idx], lavpartable$label[eqs.idx]) for(i in eqs.idx) { lhs <- lavpartable$lhs[i] if(lhs != lhs.old) cat(" ", lhs, " ~\n", sep="") print.estimate(name=NAMES[i], i) lhs.old <- lhs } cat("\n") } cov.idx <- which(lavpartable$op == "~~" & !lavpartable$exo & lavpartable$lhs != lavpartable$rhs & lavpartable$group == g) if(length(cov.idx) > 0) { cat("Covariances:\n") lhs.old <- "" NAMES[cov.idx] <- makeNames( lavpartable$rhs[cov.idx], lavpartable$label[cov.idx]) for(i in cov.idx) { lhs <- lavpartable$lhs[i] if(lhs != lhs.old) cat(" ", lhs, " ~~\n", sep="") print.estimate(name=NAMES[i], i) lhs.old <- lhs } cat("\n") } int.idx <- which(lavpartable$op == "~1" & !lavpartable$exo & lavpartable$group == g) if(length(int.idx) > 0) { cat("Intercepts:\n") NAMES[int.idx] <- makeNames( lavpartable$lhs[int.idx], lavpartable$label[int.idx]) for(i in int.idx) { print.estimate(name=NAMES[i], i) } cat("\n") } var.idx <- which(lavpartable$op == "~~" & !lavpartable$exo & lavpartable$lhs == lavpartable$rhs & lavpartable$group == g) if(length(var.idx) > 0) { cat("Variances:\n") NAMES[var.idx] <- makeNames( lavpartable$rhs[var.idx], lavpartable$label[var.idx]) for(i in var.idx) { if(lavoptions$mimic == "lavaan") { print.estimate(name=NAMES[i], i, z.stat=TRUE) } else { print.estimate(name=NAMES[i], i, z.stat=TRUE) } } cat("\n") } } def.idx <- which(lavpartable$op == ":=") if(length(def.idx) > 0) { if(ngroups > 1) cat("\n") cat("Defined parameters:\n") NAMES[def.idx] <- makeNames( lavpartable$lhs[def.idx], "") for(i in def.idx) { print.estimate(name=NAMES[i], i) } cat("\n") } cin.idx <- which((lavpartable$op == "<" | lavpartable$op == ">")) ceq.idx <- which(lavpartable$op == "==") if(length(cin.idx) > 0L || length(ceq.idx) > 0L) { slack <- ifelse(abs(est) < 1e-5, 0, est) if(ngroups > 1 && length(def.idx) == 0L) cat("\n") cat("Constraints: Slack (>=0)\n") for(i in c(cin.idx,ceq.idx)) { lhs <- lavpartable$lhs[i] op <- lavpartable$op[i] rhs <- lavpartable$rhs[i] if(rhs == "0" && op == ">") { con.string <- paste(lhs, " - 0", sep="") } else if(rhs == "0" && op == "<") { con.string <- paste(rhs, " - (", lhs, ")", sep="") } else if(rhs != "0" && op == ">") { con.string <- paste(lhs, " - (", rhs, ")", sep="") } else if(rhs != "0" && op == "<") { con.string <- paste(rhs, " - (", lhs, ")", sep="") } else if(rhs == "0" && op == "==") { con.string <- paste(lhs, " - 0", sep="") } else if(rhs != "0" && op == "==") { con.string <- paste(lhs, " - (", rhs, ")", sep="") } con.string <- abbreviate(con.string, 41, strict = TRUE) txt <- sprintf(" %-41s %8.3f\n", con.string, slack[i]) cat(txt) } cat("\n") } } if(modindices) { cat("Modification Indices:\n\n") print( modificationIndices(object, standardized=TRUE) ) } } rsem.switch.gamma<-function(gamma, ov.names){ gamma.old.names<-rownames(gamma) gamma.new.name<-ov.names k<-length(ov.names) for (i in 1:k){ for (j in i:k){ temp.name<-paste(ov.names[i], ".", ov.names[j], sep="") if (temp.name %in% gamma.old.names){ gamma.new.name <- c(gamma.new.name, temp.name) }else{ gamma.new.name <- c(gamma.new.name, paste(ov.names[j], ".", ov.names[i], sep="")) } } } gamma.new<-gamma[gamma.new.name, gamma.new.name] gamma.new } rsem.se<-function(object, gamma){ if (!is.list(gamma)){ temp<-gamma gamma<-NULL gamma[[1]]<-temp } Delta <- lavTech(object, "delta") WLS.V <- lavTech(object, "wls.v") ngroups <- lavInspect(object, "ngroups") nobs <- lavInspect(object, "nobs") vcov <- vector("list", length=ngroups) se <- vector("list", length=ngroups) for(g in 1:ngroups) { OV.NAMES <- lavNames(object, "ov", group = g) gamma[[g]]<-rsem.switch.gamma(gamma[[g]], OV.NAMES) A<-t(Delta[[g]])%*%WLS.V[[g]]%*%Delta[[g]] B<-t(Delta[[g]])%*%WLS.V[[g]]%*%gamma[[g]]%*%WLS.V[[g]]%*%Delta[[g]] D<-solve(A) vcov[[g]] <- D%*%B%*%D se[[g]]<-sqrt(diag(vcov[[g]])/(nobs[g]-1)) } list(se=se, vcov=vcov, delta=Delta, W=WLS.V) } rsem.fit<-function(object, gamma, musig){ if (!is.list(gamma)){ temp<-gamma gamma<-NULL gamma[[1]]<-temp } ngroups <- lavInspect(object, "ngroups") nobs <- lavInspect(object, "nobs") test <- lavInspect(object, "test") meanstructure <- lavInspect(object, "meanstructure") lavimplied <- lavTech(object, "implied") for(g in 1:ngroups) { OV.NAMES <- lavNames(object, "ov", group = g) gamma[[g]]<-rsem.switch.gamma(gamma[[g]], OV.NAMES) } Delta <- lavTech(object, "delta") WLS.V <- lavTech(object, "wls.v") TRML<-TAML<-TCRADF<-TRF <- vector("list", length=ngroups) for (g in 1:ngroups){ A<-t(Delta[[g]])%*%WLS.V[[g]]%*%Delta[[g]] D<-solve(A) U<-WLS.V[[g]] - WLS.V[[g]]%*%Delta[[g]]%*%D%*%t(Delta[[g]])%*%WLS.V[[g]] df<-test[[g]]$df n<-nobs[g] n1<-n-1 trUT<-sum(diag(U%*%gamma[[g]])) m<-df/trUT trml<-m*test[[g]]$stat df.rml<-df p.rml<-1-pchisq(trml, df) temp<-c(trml, df.rml, p.rml) names(temp)<-c('Statistic','df','p-value') TRML[[g]]<-temp trUT2<-sum(diag(U%*%gamma[[g]]%*%U%*%gamma[[g]])) m1<-trUT/trUT2 m2<-(trUT)^2/trUT2 taml<-m1*test[[g]]$stat p.aml<-1-pchisq(taml, m2) temp<-c(taml, m2, p.aml) names(temp)<-c('Statistic','df','p-value') TAML[[g]]<-temp } for (g in 1:ngroups){ D<-solve(gamma[[g]]) B<-solve(t(Delta[[g]])%*%D%*%Delta[[g]]) Q<-D - D%*%Delta[[g]]%*%B%*%t(Delta[[g]])%*%D ovnames<-lavNames(object, "ov", group = g) sigmahat<-musig$sigma[ovnames,ovnames] muhat<-musig$mu[ovnames] if (meanstructure){ r<-c(muhat-lavimplied[[g]]$mean, lav_matrix_vech(sigmahat-lavimplied[[g]]$cov)) }else{ r<-lav_matrix_vech(sigmahat-lavimplied[[g]]$cov) } r<-matrix(r, length(r), 1) radf<-t(r)%*%Q%*%r n<-nobs[g] tcradf<-radf*n1/(1+radf) df<-test[[g]]$df p.cradf<-1-pchisq(tcradf, df) temp<-c(tcradf, df, p.cradf) names(temp)<-c('Statistic','df','p-value') TCRADF[[g]]<-temp trf<-(n-df)*n1*radf/(n1*df) p.rf<-1-pf(trf, df, n-df) temp<-c(trf, df, n-df, p.rf) names(temp)<-c('Statistic','df1','df2','p-value') TRF[[g]]<-temp } return(list(TRML=TRML, TAML=TAML, TCRADF=TCRADF, TRF=TRF)) } rsem.lavaan<-function(dset, model, select, varphi=.1, max.it=1000){ if (missing(dset)) stop("A data set is needed!") if (!is.matrix(dset)) dset<-data.matrix(dset) n<-dim(dset)[1] p<-dim(dset)[2] cat("Sample size n =", n, "\n") cat("Total number of variables q =", p, "\n\n") if (missing(select)) select<-c(1:p) cat("The following",length(select),"variables are selected for SEM models \n") cat(colnames(dset)[select], "\n\n") p_v<-length(select) pvs<-p_v+p_v*(p_v+1)/2 miss_pattern<-rsem.pattern(dset) x<-miss_pattern$x misinfo<-miss_pattern$misinfo totpat<-dim(misinfo)[1] cat("There are", totpat, "missing data patterns. They are \n") print(misinfo) cat("\n") musig<-rsem.emmusig(miss_pattern, varphi=varphi) if (musig$max.it >= max.it){ warning("\nMaximum iteration for EM is exceeded and the results may not be trusted. Change max.it to a greater number.\n") } res.lavaan<-sem(model, sample.cov=musig$sigma, sample.mean=musig$mu, sample.nobs=n,mimic='EQS') ascov<-rsem.Ascov(miss_pattern, musig, varphi=varphi) robust.se<-rsem.se(res.lavaan, ascov$Gamma) robust.fit <- rsem.fit(res.lavaan, ascov$Gamma, musig) cat("\nFit statistics\n") rsem.print(res.lavaan, robust.se, robust.fit) invisible(list(musig=musig, lavaan=res.lavaan, ascov=ascov, se=robust.se, fit=robust.fit)) }
setMethod("as.matrix", "dcmle", function(x, ...) as.matrix(as(x, "MCMClist"), ...)) setMethod("as.matrix", "codaMCMC", function(x, ...) as.matrix(as(x, "MCMClist"), ...)) setMethod("as.array", "dcmle", function(x, ...) array(x@details@values, dim=c(x@details@niter, x@details@nvar, x@details@nchains), dimnames=list(NULL, x@details@varnames, NULL))) setMethod("as.array", "codaMCMC", function(x, ...) array(x@values, dim=c(x@niter, x@nvar, x@nchains), dimnames=list(NULL, x@varnames, NULL))) setMethod("dcdiag", "dcmle", function(x, ...) x@details@dcdiag) setMethod("dcdiag", "dcCodaMCMC", function(x, ...) x@dcdiag) setMethod("dcdiag", "codaMCMC", function(x, ...) { dcdiag(as(x, "MCMClist"), ...) }) setMethod("dctable", "dcmle", function(x, ...) x@details@dctable) setMethod("dctable", "dcCodaMCMC", function(x, ...) x@dctable) setMethod("dctable", "codaMCMC", function(x, ...) { dctable(as(x, "MCMClist"), ...) }) setMethod("dcsd", "dcmle", function(object, ...) { sqrt(diag(vcov(object))) }) setMethod("dcsd", "codaMCMC", function(object, ...) { dcsd(as(object, "MCMClist"), ...) }) setMethod("nclones", "dcmle", function(x, ...) x@details@nclones) setMethod("nclones", "dcCodaMCMC", function(x, ...) x@nclones) setMethod("nclones", "codaMCMC", function(x, ...) NULL) setGeneric("nvar", function(x) standardGeneric("nvar")) setGeneric("varnames", function(x, ...) standardGeneric("varnames")) setGeneric("chanames", function(x, ...) standardGeneric("chanames")) setGeneric("nchain", function(x) standardGeneric("nchain")) setGeneric("niter", function(x) standardGeneric("niter")) setGeneric("crosscorr", function(x) standardGeneric("crosscorr")) setGeneric("mcpar", function(x) standardGeneric("mcpar")) setMethod("nvar", "dcmle", function(x) x@details@nvar) setMethod("varnames", "dcmle", function(x, ...) x@details@varnames) setMethod("chanames", "dcmle", function(x, ...) chanames(as(x, "MCMClist"), ...)) setMethod("nchain", "dcmle", function(x) x@details@nchains) setMethod("niter", "dcmle", function(x) x@details@niter) setMethod("thin", "dcmle", function(x) x@details@thin) setMethod("crosscorr", "dcmle", function(x) crosscorr(as(x, "MCMClist"))) setMethod("mcpar", "dcmle", function(x) c(start(x), end(x), thin(x))) setMethod("nvar", "codaMCMC", function(x) x@nvar) setMethod("varnames", "codaMCMC", function(x, ...) x@varnames) setMethod("chanames", "codaMCMC", function(x, ...) chanames(as(x, "MCMClist"), ...)) setMethod("nchain", "codaMCMC", function(x) x@nchains) setMethod("niter", "codaMCMC", function(x) x@niter) setMethod("thin", "codaMCMC", function(x) x@thin) setMethod("crosscorr", "codaMCMC", function(x) crosscorr(as(x, "MCMClist"))) setMethod("mcpar", "codaMCMC", function(x) c(start(x), end(x), thin(x))) setMethod("nvar", "MCMClist", function(x) coda::nvar(x)) setMethod("varnames", "MCMClist", function(x, ...) coda::varnames(x, ...)) setMethod("chanames", "MCMClist", function(x, ...) coda::chanames(as(x, "MCMClist"), ...)) setMethod("nchain", "MCMClist", function(x) coda::nchain(x)) setMethod("niter", "MCMClist", function(x) coda::niter(x)) setMethod("thin", "MCMClist", function(x) coda::thin(x)) setMethod("crosscorr", "MCMClist", function(x) coda::crosscorr(x)) setMethod("mcpar", "MCMClist", function(x) c(start(x), end(x), thin(x))) setMethod("coef", "dcmle", function(object, ...) object@coef) setMethod("coef", "codaMCMC", function(object, ...) coef(as(object, "MCMClist"), ...)) setMethod("vcov", "dcmle", function(object, ...) object@vcov) setMethod("vcov", "codaMCMC", function(object, ...) vcov(as(object, "MCMClist"), ...)) setMethod("confint", "dcmle", function(object, parm, level = 0.95, ...) { if (is.null(nclones(object)) || nclones(object) < 2) stop("'confint' method not defined for k=1") confint(as(object, "MCMClist"), parm, level, ...) }) setMethod("confint", "dcCodaMCMC", function(object, parm, level = 0.95, ...) { if (is.null(nclones(object)) || nclones(object) < 2) stop("'confint' method not defined for k=1") confint(as(object, "MCMClist"), parm, level, ...) }) setMethod("confint", "MCMClist", function(object, parm, level = 0.95, ...) { if (is.null(nclones(object)) || nclones(object) < 2) stop("'confint' method not defined for k=1") dclone::confint.mcmc.list.dc(object, parm, level, ...) }) setMethod("confint", "codaMCMC", function(object, parm, level = 0.95, ...) { stop("'confint' method not defined for k=1") }) setMethod("quantile", "MCMClist", function(x, ...) { dclone::quantile.mcmc.list(x, ...) }) setMethod("quantile", "dcmle", function(x, ...) { quantile(as(x, "MCMClist"), ...) }) setMethod("quantile", "codaMCMC", function(x, ...) { quantile(as(x, "MCMClist"), ...) }) setMethod("start", "dcmle", function(x, ...) x@details@start) setMethod("start", "codaMCMC", function(x, ...) x@start) setMethod("end", "dcmle", function(x, ...) x@details@end) setMethod("end", "codaMCMC", function(x, ...) x@end) setMethod("frequency", "dcmle", function(x, ...) 1/thin(x)) setMethod("frequency", "codaMCMC", function(x, ...) 1/thin(x)) setMethod("frequency", "MCMClist", function(x, ...) 1/thin(x)) setMethod("time", "dcmle", function(x, ...) { val <- seq(start(x), end(x), by = thin(x)) time(ts(data = val, start = start(x), end = end(x), frequency = thin(x)), ...) }) setMethod("time", "codaMCMC", function(x, ...) { val <- seq(start(x), end(x), by = thin(x)) time(ts(data = val, start = start(x), end = end(x), frequency = thin(x)), ...) }) setMethod("window", "dcmle", function(x, ...) { as(window(as(x, "MCMClist"), ...), "dcmle") }) setMethod("window", "codaMCMC", function(x, ...) { as(window(as(x, "MCMClist"), ...), "codaMCMC") }) setMethod("update", "dcmle", function (object, ..., evaluate = TRUE) { call <- object@call extras <- match.call(expand.dots = FALSE)$... if (length(extras)) { existing <- !is.na(match(names(extras), names(call))) for (a in names(extras)[existing]) call[[a]] <- extras[[a]] if (any(!existing)) { call <- c(as.list(call), extras[!existing]) call <- as.call(call) } } if (evaluate) { out <- eval(call, parent.frame()) out@call <- call out } else call }) setMethod("stack", "dcmle", function(x, ...) { data.frame( iter=rep(time(x), nvar(x)*nchain(x)), variable=rep(rep(varnames(x), each=niter(x)), nchain(x)), chain=as.factor(rep(seq_len(nchain(x)), each=niter(x)*nvar(x))), value=x@details@values) }) setMethod("stack", "codaMCMC", function(x, ...) { data.frame( iter=rep(time(x), nvar(x)*nchain(x)), variable=rep(rep(varnames(x), each=niter(x)), nchain(x)), chain=as.factor(rep(seq_len(nchain(x)), each=niter(x)*nvar(x))), value=x@values) }) setMethod("str", "dcmle", function(object, max.level=5L, ...) utils::str(object, max.level=max.level, ...)) setMethod("str", "dcCodaMCMC", function(object, max.level=3L, ...) utils::str(object, max.level=max.level, ...)) setMethod("head", "dcmle", function(x, ...) head(as(x, "MCMClist"), ...)) setMethod("tail", "dcmle", function(x, ...) tail(as(x, "MCMClist"), ...)) setMethod("head", "codaMCMC", function(x, ...) head(as(x, "MCMClist"), ...)) setMethod("tail", "codaMCMC", function(x, ...) tail(as(x, "MCMClist"), ...)) setMethod("show", "codaMCMC", function(object) { str(object) invisible(object) }) setMethod("show", "dcmle", function(object) { cat("Call:\n") print(object@call) cat("\nCoefficients:\n") print(coef(object)) }) setClass("summary.codaMCMC", representation( settings = "integer", coef = "matrix")) setClass("summary.dcCodaMCMC", contains="summary.codaMCMC", representation( settings = "integer", coef = "matrix", convergence = "dcDiag")) setClass("summary.dcmle", contains="summary.dcCodaMCMC", representation( title="character", call = "language")) setMethod("summary", "codaMCMC", function(object, ...) { k <- nclones(object) if (is.null(k)) k <- 1L attributes(k) <- NULL settings <- c( start=start(object), end=end(object), thin=thin(object), n.iter=end(object)-start(object)+1, n.chains=nchain(object), n.clones=k) storage.mode(settings) <- "integer" coefs <- coef(object) se <- dcsd(object) cmat <- cbind(coefs, se) colnames(cmat) <- c("Estimate", "Std. Deviation") new("summary.codaMCMC", settings=settings, coef = cmat) }) setMethod("summary", "dcCodaMCMC", function(object, ...) { k <- nclones(object) if (is.null(k)) k <- 1L attributes(k) <- NULL settings <- c( start=start(object), end=end(object), thin=thin(object), n.iter=end(object)-start(object)+1, n.chains=nchain(object), n.clones=k) storage.mode(settings) <- "integer" coefs <- coef(object) se <- dcsd(object) zstat <- coefs/se pval <- 2 * pnorm(-abs(zstat)) cmat <- cbind(coefs, se, zstat, pval) colnames(cmat) <- c("Estimate", "Std. Error", "z value", "Pr(>|z|)") new("summary.dcCodaMCMC", settings=settings, coef = cmat, convergence=dcdiag(object)) }) setMethod("summary", "dcmle", function(object, title, ...) { k <- nclones(object) if (is.null(k)) k <- 1L attributes(k) <- NULL if (missing(title)) { title <- if (k > 1) { "Maximum likelihood estimation with data cloning\n\n" } else { "Bayesian estimation\n\n" } } else { title <- paste(title, "\n\n", sep="") } settings <- c( start=start(object), end=end(object), thin=thin(object), n.iter=end(object)-start(object)+1, n.chains=nchain(object), n.clones=k) storage.mode(settings) <- "integer" coefs <- coef(object) se <- dcsd(object) zstat <- coefs/se pval <- 2 * pnorm(-abs(zstat)) cmat <- cbind(coefs, se, zstat, pval) colnames(cmat) <- c("Estimate", "Std. Error", "z value", "Pr(>|z|)") new("summary.dcmle", title=title, call = object@call, settings=settings, coef = cmat, convergence=dcdiag(object)) }) setMethod("show", "summary.codaMCMC", function(object) { digits <- max(3, getOption("digits") - 3) cat("'codaMCMC' object\n") cat("\nSettings:\n") print(data.frame(t(object@settings)), digits=digits, row.names=FALSE) cat("\nCoefficients:\n") printCoefmat(object@coef, digits = digits, signif.legend = TRUE) invisible(object) }) setMethod("show", "summary.dcCodaMCMC", function(object) { digits <- max(3, getOption("digits") - 3) cat("'dcCodaMCMC' object\n") cat("\nSettings:\n") print(data.frame(t(object@settings)), digits=digits, row.names=FALSE) cat("\nCoefficients:\n") printCoefmat(object@coef, digits = digits, signif.legend = TRUE) cat("\nConvergence:\n") print(object@convergence, digits=digits, row.names=FALSE) invisible(object) }) setMethod("show", "summary.dcmle", function(object) { digits <- max(3, getOption("digits") - 3) cat(object@title) cat("Call:\n") print(object@call) cat("\nSettings:\n") print(data.frame(t(object@settings)), digits=digits, row.names=FALSE) cat("\nCoefficients:\n") printCoefmat(object@coef, digits = digits, signif.legend = TRUE) cat("\nConvergence:\n") print(object@convergence, digits=digits, row.names=FALSE) invisible(object) }) setMethod("[[", signature(x = "codaMCMC"), function (x, i, j, ...) as(as.mcmc.list(x)[i], "codaMCMC")) setMethod("[[", signature(x = "dcCodaMCMC"), function (x, i, j, ...) as(as.mcmc.list(x)[i], "dcCodaMCMC")) setMethod("[[", signature(x = "dcmle"), function (x, i, j, ...) as(as.mcmc.list(x)[i], "dcmle")) setMethod("[", signature(x = "codaMCMC"), function (x, i, j, ..., drop = TRUE) { if (missing(j)) return(x[[i]]) y <- as.mcmc.list(x)[i, j, drop] if (!inherits(y, "mcmc.list")) y else as(y, "codaMCMC") }) setMethod("[", signature(x = "dcCodaMCMC"), function (x, i, j, ..., drop = TRUE) { if (missing(j)) return(x[[i]]) y <- as.mcmc.list(x)[i, j, drop] if (!inherits(y, "mcmc.list")) y else as(y, "dcCodaMCMC") }) setMethod("[", signature(x = "dcmle"), function (x, i, j, ..., drop = TRUE) { if (missing(j)) return(x[[i]]) y <- as.mcmc.list(x)[i, j, drop] if (!inherits(y, "mcmc.list")) y else as(y, "dcmle") }) setGeneric("gelman.diag", function(x, ...) standardGeneric("gelman.diag")) setMethod("gelman.diag", "MCMClist", function(x, ...) coda::gelman.diag(x, ...)) setMethod("gelman.diag", "codaMCMC", function(x, ...) gelman.diag(as(x, "MCMClist"), ...)) setMethod("gelman.diag", "dcmle", function(x, ...) gelman.diag(as(x, "MCMClist"), ...)) setGeneric("geweke.diag", function(x, ...) standardGeneric("geweke.diag")) setMethod("geweke.diag", "MCMClist", function(x, ...) coda::geweke.diag(x, ...)) setMethod("geweke.diag", "codaMCMC", function(x, ...) geweke.diag(as(x, "MCMClist"), ...)) setMethod("geweke.diag", "dcmle", function(x, ...) geweke.diag(as(x, "MCMClist"), ...)) setGeneric("raftery.diag", function(x, ...) standardGeneric("raftery.diag")) setMethod("raftery.diag", "MCMClist", function(x, ...) coda::raftery.diag(x, ...)) setMethod("raftery.diag", "codaMCMC", function(x, ...) raftery.diag(as(x, "MCMClist"), ...)) setMethod("raftery.diag", "dcmle", function(x, ...) raftery.diag(as(x, "MCMClist"), ...)) setGeneric("heidel.diag", function(x, ...) standardGeneric("heidel.diag")) setMethod("heidel.diag", "MCMClist", function(x, ...) coda::heidel.diag(x, ...)) setMethod("heidel.diag", "codaMCMC", function(x, ...) heidel.diag(as(x, "MCMClist"), ...)) setMethod("heidel.diag", "dcmle", function(x, ...) heidel.diag(as(x, "MCMClist"), ...)) setMethod("autocorr.diag", "MCMClist", function(mcmc.obj, ...) coda::autocorr.diag(as(mcmc.obj, "mcmc.list"), ...)) setMethod("autocorr.diag", "codaMCMC", function(mcmc.obj, ...) autocorr.diag(as(mcmc.obj, "MCMClist"), ...)) setMethod("autocorr.diag", "dcmle", function(mcmc.obj, ...) autocorr.diag(as(mcmc.obj, "MCMClist"), ...)) setMethod("chisq.diag", "MCMClist", function(x, ...) dclone::chisq.diag(x)) setMethod("chisq.diag", "codaMCMC", function(x, ...) chisq.diag(as(x, "MCMClist"), ...)) setMethod("chisq.diag", "dcmle", function(x, ...) chisq.diag(as(x, "MCMClist"), ...)) setMethod("lambdamax.diag", "MCMClist", function(x, ...) dclone::lambdamax.diag(x)) setMethod("lambdamax.diag", "codaMCMC", function(x, ...) lambdamax.diag(as(x, "MCMClist"), ...)) setMethod("lambdamax.diag", "dcmle", function(x, ...) lambdamax.diag(as(x, "MCMClist"), ...))
PlotMarginals <- function(marginals, groups=NULL) { nms <- names(marginals$marginals) discrete.nodes <- nms[marginals$types] continuous.nodes <- nms[!marginals$types] posteriors <- marginals$marginals group.disc <- NULL group.cont <- NULL if(!is.null(groups)) { if(length(groups)!=length(posteriors)) { warning("Group and marginal lengths do not match.") groups <- NULL } else { group.disc <- groups[which(marginals$types)] group.cont <- groups[which(!marginals$types)] } } if(length(discrete.nodes)==0){ PlotPosteriorContinuous(posteriors, groups=group.cont) } if(length(continuous.nodes)==0){ par(mfrow=c(1,length(discrete.nodes))) for (i in 1:length(discrete.nodes)) { this.node <- discrete.nodes[i] PlotPosteriorDiscrete(posteriors[i], group=group.disc[i]) } par(mfrow=c(1,1)) } if(length(discrete.nodes)!=0 & length(continuous.nodes)!=0){ par(mfrow=c(1,length(discrete.nodes)+1)) PlotPosteriorContinuous(posteriors[continuous.nodes], groups=group.cont) for (i in 1:length(discrete.nodes)) { this.node <- discrete.nodes[i] PlotPosteriorDiscrete(posteriors[this.node], group=group.disc[i]) } par(mfrow=c(1,1)) } }