code
stringlengths
1
13.8M
confint.coxphw <- function(object, parm, level = 0.95, ...) { if (!is.null(object$betafix)) { cat(paste("The following variables were not estimated in this model", paste(names(object$coefficients)[!is.na(object$betafix)], collapse=", "), "\n\n"), sep="") } return(confint.default(object, ...)) }
set.seed(8976) n <- 200 trial <- tibble::tibble( trt = sample(c("Drug A", "Drug B"), n, replace = TRUE), age = rnorm(n, mean = 50, sd = 15) %>% as.integer(), marker = rgamma(n, 1, 1) %>% round(digits = 3), stage = sample(c("T1", "T2", "T3", "T4"), size = n, replace = TRUE) %>% factor(), grade = sample(c("I", "II", "III"), size = n, replace = TRUE) %>% factor(), response_prob = ((trt == "Drug") - 0.2 * as.numeric(stage) - 0.1 * as.numeric(grade) + 0.1 * marker) %>% { 1 / (1 + exp(-.)) }, response = runif(n) < response_prob, ttdeath_true = exp(1 + 0.2 * response + -0.1 * as.numeric(stage) + -0.1 * as.numeric(grade) + rnorm(n, sd = 0.5)) * 12, death = ifelse(ttdeath_true <= 24, 1L, 0L), ttdeath = pmin(ttdeath_true, 24) %>% round(digits = 2) ) %>% dplyr::mutate( age = ifelse(runif(n) < 0.95, age, NA_real_), marker = ifelse(runif(n) < 0.95, marker, NA_real_), response = ifelse(runif(n) < 0.95, response, NA_integer_) ) %>% dplyr::select(-dplyr::one_of("response_prob", "ttdeath_true")) summary(trial) attr(trial$trt, "label") <- "Chemotherapy Treatment" attr(trial$age, "label") <- "Age" attr(trial$marker, "label") <- "Marker Level (ng/mL)" attr(trial$stage, "label") <- "T Stage" attr(trial$grade, "label") <- "Grade" attr(trial$response, "label") <- "Tumor Response" attr(trial$death, "label") <- "Patient Died" attr(trial$ttdeath, "label") <- "Months to Death/Censor" usethis::use_data(trial, overwrite = TRUE)
gsAdaptSim <- function(SimStage, IniSim, TrialPar, SimPar, cp = 0, thetacp = -100, maxn = 100000, pdeltamin = 0, ...) { x <- gsSimulate(nstage = TrialPar$gsx$k - 1, SimStage, IniSim, TrialPar, SimPar) if (cp == 0) { cp <- 1 - x$gsx$beta } Inew <- x$gsx$n.I[x$gsx$k] - x$gsx$n.I[x$gsx$k - 1] nnewe <- ceiling(x$gsx$n.I[x$gsx$k] * x$ratio / (1 + x$ratio) - x$ne) if (length(nnewe) == 1) { nnewe <- rep(nnewe, TrialPar$nsim) } nnewc <- ceiling(x$gsx$n.I[x$gsx$k] / (1 + x$ratio) - x$nc) if (length(nnewc) == 1) { nnewc <- rep(nnewc, TrialPar$nsim) } bnew <- (x$gsx$upper$bound[x$gsx$k] - x$z * sqrt(x$gsx$n.I[x$gsx$k - 1] / x$gsx$n.I[x$gsx$k])) / sqrt(Inew / x$gsx$n.I[x$gsx$k]) lnew <- (x$gsx$lower$bound[x$gsx$k] - x$z * sqrt(x$gsx$n.I[x$gsx$k - 1] / x$gsx$n.I[x$gsx$k])) / sqrt(Inew / x$gsx$n.I[x$gsx$k]) thetahat <- x$z / sqrt(x$gsx$n.I[x$gsx$k - 1]) if (thetacp == -100) { thetacp <- thetahat } ncp <- rep(maxn, TrialPar$nsim) - x$nc - x$ne ncp[thetacp > 0] <- as.integer(ceiling(((bnew[thetacp > 0] + stats::qnorm(cp)) / thetacp[thetacp > 0])^2)) if (maxn > 0) { maxn <- maxn - x$nc - x$ne if (length(maxn) == 1) { maxn <- rep(maxn, x$nsim) } ncp[ncp > maxn] <- maxn[ncp > maxn] } flag <- 1 * (x$outcome == 0) flag <- flag * (x$xc / x$nc - x$xe / x$ne >= pdeltamin) flag <- flag * (ncp > ceiling(Inew)) ncpe <- as.integer(ceiling(ncp * x$ratio / (1 + x$ratio))) ncpc <- ncp - ncpe nnewc[flag == 1] <- ncpc[flag == 1] nnewe[flag == 1] <- ncpe[flag == 1] zero <- rep(0, x$nsim) y <- list(xc = zero, xe = zero, nc = nnewc, ne = nnewe, xadd = x$xadd, nadd = x$nadd) for (j in 1:x$nsim) { if (x$outcome[j] == 0) { y$xc[j] <- stats::rbinom(1, nnewc[j], x$pcsim) y$xe[j] <- stats::rbinom(1, nnewe[j], x$pesim) x$xc[j] <- x$xc[j] + y$xc[j] x$xe[j] <- x$xe[j] + y$xe[j] } else { y$xc[j] <- y$nc[j] / 2 y$xe[j] <- y$ne[j] / 2 } } if (length(x$nc) == 1) { x$nc <- rep(x$nc, TrialPar$nsim) } x$nc[x$outcome == 0] <- x$nc[x$outcome == 0] + nnewc[x$outcome == 0] if (length(x$ne) == 1) { x$ne <- rep(x$ne, TrialPar$nsim) } x$ne[x$outcome == 0] <- x$ne[x$outcome == 0] + nnewe[x$outcome == 0] y <- x$zStat(y) x$y <- y x$outcome <- x$outcome + (x$outcome == 0) * x$gsx$k * ((y$z >= bnew) - (y$z < lnew)) x } gsSimulate <- function(nstage = 0, SimStage, IniSim, TrialPar, SimPar) { if (nstage == 0) { nstage <- TrialPar$gsx$k } x <- IniSim(TrialPar, SimPar) nim1 <- 0 for (i in 1:nstage) { x <- SimStage(x$gsx$n.I[i], x) x$outcome <- x$outcome + (x$outcome == 0) * i * ((x$z >= x$gsx$upper$bound[i]) - (x$z < x$gsx$lower$bound[i])) } x }
"wffc.indiv" <- structure(list(totalPlacings = c(20, 20, 22, 22, 22, 24, 24, 24, 25, 27, 27, 27, 30, 30, 30, 30, 30, 31, 32, 32, 34, 34, 35, 35, 36, 38, 38, 38, 39, 41, 42, 42, 42, 42, 43, 43, 43, 44, 44, 45, 47, 49, 49, 50, 53, 53, 53, 53, 53, 54, 54, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 59, 60, 60, 60, 60, 61, 62, 63, 65, 65, 65, 66, 66, 66, 66, 66, 67, 68, 68, 69, 69, 69, 70, 70, 72, 73, 74, 74, 75, 76, 79, 79, 83, 88, 88, 88, 93, 94), points = c(51360, 48540, 58980, 39480, 35240, 52800, 52140, 28540, 53180, 47180, 47060, 35500, 40460, 36380, 34400, 32460, 29660, 41000, 40660, 29440, 48020, 30720, 45020, 39840, 44680, 38680, 37900, 28560, 39040, 29040, 43840, 38260, 28500, 19200, 36320, 35720, 22260, 43040, 24900, 33520, 29800, 34020, 20220, 33200, 46480, 28300, 27340, 21140, 15800, 36240, 34440, 24140, 33460, 29620, 36200, 27700, 24180, 26580, 23880, 26880, 24780, 11660, 29240, 21160, 17680, 10920, 22640, 21280, 18340, 25680, 16320, 6240, 16080, 11980, 9980, 9660, 8920, 6340, 16440, 6900, 18340, 17080, 11880, 23440, 9080, 13880, 6600, 20420, 13640, 14800, 6600, 16620, 2880, 9740, 7080, 6540, 3420, 5120, 540), noofcaptures = c(78, 73, 98, 59, 56, 87, 90, 40, 87, 80, 71, 56, 65, 59, 55, 54, 41, 66, 64, 44, 78, 49, 60, 69, 73, 61, 66, 44, 65, 43, 78, 64, 40, 32, 65, 58, 36, 78, 40, 52, 47, 55, 32, 53, 80, 48, 43, 33, 23, 64, 59, 39, 60, 47, 57, 53, 38, 45, 38, 39, 42, 17, 53, 33, 30, 17, 40, 35, 30, 38, 31, 6, 26, 18, 12, 14, 14, 8, 28, 8, 26, 31, 21, 37, 14, 22, 10, 35, 21, 28, 11, 27, 3, 16, 12, 11, 6, 9, 1), longest = c(540, 585, 515, 689, 580, 535, 552, 610, 475, 533, 518, 560, 535, 580, 498, 624, 627, 525, 585, 560, 550, 515, 568, 615, 652, 520, 563, 510, 580, 572, 474, 500, 615, 484, 503, 535, 498, 592, 541, 512, 590, 510, 530, 499, 501, 495, 574, 572, 604, 466, 450, 515, 513, 480, 570, 419, 530, 688, 580, 492, 514, 508, 522, 594, 477, 532, 528, 505, 493, 620, 340, 560, 571, 475, 572, 470, 486, 574, 568, 610, 548, 432, 342, 486, 480, 560, 432, 501, 590, 362, 511, 455, 450, 490, 380, 395, 332, 293, 218), individual = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0), country = c("CZE", "FRA", "CZE", "ENG", "POL", "NZL", "ENG", "FIN", "CZE", "POL", "CZE", "SVK", "ITA", "ITA", "NZL", "CAN", "NZL", "JPN", "NZL", "USA", "NZL", "CZE", "FRA", "USA", "FIN", "CAN", "POL", "FRA", "ITA", "AUS", "CAN", "SVK", "SVK", "USA", "IRE", "IRE", "ITA", "USA", "POL", "SVK", "POR", "SVK", "ENG", "FRA", "FRA", "ENG", "ENG", "AUS", "RSA", "CRO", "USA", "FIN", "POR", "POR", "AUS", "NED", "ITA", "FIN", "AUS", "JPN", "POL", "SWE", "IRE", "FIN", "IRE", "JPN", "CAN", "NED", "RSA", "BUL", "IRE", "FRA", "WAL", "WAL", "WAL", "AUS", "RSA", "WAL", "CRO", "CAN", "RSA", "NED", "CRO", "CRO", "POR", "POR", "NED", "NED", "WAL", "RSA", "JPN", "ROM", "IRE", "CRO", "NDI", "MAL", "CAN", "JPN", "WAL"), iname = c("MartinDroz", "JulienDaguillanes", "TomasStarychfojtu", "JohnHorsey", "LucjanBurda", "DesArmstrong", "SimonRobinson", "JannePirkkalainen", "TomasAdam", "PiotrKonieczny", "AntoninPesek", "JanBartko", "SandroSoldarini", "LucaPapandrea", "AaronWest", "DonaldThom", "JohnBell", "KiyoshiNakagawa", "LloydStruther", "JoshStephens", "CraigFarrar", "PavelMachan", "ChristopheIdre", "LanceEgan", "OlliToivonen", "JohnNishi", "MarekWalczyk", "BertrandJacquemin", "GianlucaMazzocco", "VernBarby", "TerenceCourtoreille", "MiroslavAntal", "MichalBenatinsky", "AnthonyNaranja", "WilliamKavenagh", "DamienWalsh", "ValerioSantiAmantini", "GeorgeDaniel", "StanislawGuzdek", "PeterBienek", "JoseDias", "BorisDzurek", "HowardCroston", "EricLelouvrier", "YannCaleri", "AndrewDixon", "MikeTinnion", "JoeRiley", "GaryGlenYoung", "IvicaMagdic", "BretBishop", "JarkkoSuominen", "PauloMorais", "NunoDuarte", "CraigColtman", "PeterElberse", "AlessandroSgrani", "VilleAnttiJaakkola", "ScottTucker", "SeiichiKomatsuzawa", "ArturTrzaskos", "TorbjornEriksson", "JohnBuckley", "JouniNeste", "JohnTrench", "TakashiKawahara", "ToddOishi", "ReneKoops", "TimRolston", "StanislawMankou", "JohnFoxton", "ThibaultGuilpain", "JamieHarries", "MichaelHeckler", "BrianJeremiah", "RickyLehman", "RobertVanRensburg", "DavidEricDavies", "BoskoBarisic", "RandyTaylor", "MarkYelland", "SimonGrootemaat", "PeterDindic", "MiroslavKaticic", "AntonioRodrigues", "HelderRodrigues", "JanKwisthout", "HansBock", "KimTribe", "AndreSteenkamp", "MisakoIshimura", "StefanFlorea", "AidenHodgins", "MarinkoPuskaric", "SabahudinPehadzicBIHI", "StephenVarga", "JohnBeaven", "YoshikoIzumiya", "DionDavies" ), comid = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99)), .Names = c("totalPlacings", "points", "noofcaptures", "longest", "individual", "country", "iname", "comid"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99"), class = "data.frame")
vcfR2DNAbin <- function( x, extract.indels = TRUE, consensus = FALSE, extract.haps = TRUE, unphased_as_NA = TRUE, asterisk_as_del = FALSE, ref.seq = NULL, start.pos = NULL, verbose = TRUE ) { if( class(x) == 'chromR' ){ x <- x@vcf } if( class(x) != 'vcfR' ){ stop( "Expecting an object of class chromR or vcfR" ) } if( consensus == TRUE & extract.haps == TRUE){ stop("consensus and extract_haps both set to TRUE. These options are incompatible. A haplotype should not be ambiguous.") } if( !is.null(start.pos) & class(start.pos) == "character" ){ start.pos <- as.integer(start.pos) } if( extract.indels == FALSE & consensus == TRUE ){ msg <- "invalid selection: extract.indels set to FALSE and consensus set to TRUE." msg <- c(msg, "There is no IUPAC ambiguity code for indels") stop(msg) } if( class(ref.seq) != 'DNAbin' & !is.null(ref.seq) ){ stop( paste("expecting ref.seq to be of class DNAbin but it is of class", class(ref.seq)) ) } if( is.list(ref.seq) ){ ref.seq <- ref.seq[[1]] } if( is.matrix(ref.seq) ){ ref.seq <- ref.seq[1,] ref.seq <- ref.seq[1:ncol(ref.seq)] } if( is.null(start.pos) & !is.null(ref.seq) ){ if( verbose == TRUE ){ warning("start.pos == NULL, this means that I do not know where the variants are located in the ref.seq. I'll try start.pos == 1, but results may be unexpected") } start.pos <- 1 } if( extract.indels == TRUE ){ x <- extract.indels(x) if( verbose == TRUE ){ message(paste("After extracting indels,", nrow(x), "variants remain.")) } } else { equal_allele_len <- function(x){ alleles <- c(myRef[x], unlist(strsplit(myAlt[x], split = ","))) alleles[is.na(alleles)] <- 'n' alleles <- format(alleles, width=max(nchar(alleles))) alleles <- gsub("\\s", "-", alleles) myRef[x] <<- alleles[1] myAlt[x] <<- paste(alleles[2:length(alleles)], collapse=",") invisible() } myRef <- getREF(x) myAlt <- getALT(x) invisible(lapply(1:length(myRef), equal_allele_len)) x@fix[,'REF'] <- myRef x@fix[,'ALT'] <- myAlt } pos <- getPOS(x) if( nrow(x@fix) == 0 ){ x <- x@gt[ 0, -1 ] } else if( sum(!is.na(x@gt[,-1])) == 0 ){ x <- x@gt[ 0, -1 ] } else { if( consensus == TRUE & extract.haps == FALSE ){ x <- extract.gt( x, return.alleles = TRUE ) x <- alleles2consensus( x ) } else { x <- extract.haps( x, unphased_as_NA = unphased_as_NA, verbose = verbose ) } } if( asterisk_as_del == TRUE){ x[ x == "*" & !is.na(x) ] <- '-' } else { x[ x == "*" & !is.na(x) ] <- 'n' } if( is.null(ref.seq) == FALSE ){ variants <- x x <- matrix( as.character(ref.seq), nrow = length(ref.seq), ncol = length(colnames(x)), byrow = FALSE ) colnames(x) <- colnames(variants) variants <- variants[ pos < start.pos + length(ref.seq), , drop = FALSE] pos <- pos[ pos < start.pos + length(ref.seq) ] variants <- variants[ pos >= start.pos, , drop = FALSE] pos <- pos[ pos >= start.pos ] pos <- pos - start.pos + 1 x[pos,] <- variants } x[ is.na(x) ] <- 'n' if( nrow(x) > 0 ){ x <- tolower( x ) } if( extract.indels == FALSE ){ x <- apply(x, MARGIN=2, function(x){ unlist(strsplit(x,"")) }) } x <- ape::as.DNAbin(t(x)) return(x) }
cancelAccountUpdates <- function(conn, acctCode="1") { if(!is.twsConnection(conn)) stop("requires twsConnection object") .reqAccountUpdates(conn, "0", acctCode) } .reqAccountUpdates <- function(conn, subscribe=TRUE, acctCode="1") { if (!is.twsConnection(conn)) stop("requires twsConnection object") con <- conn[[1]] VERSION <- "2" writeBin(.twsOutgoingMSG$REQ_ACCOUNT_DATA, con) writeBin(VERSION, con) writeBin(as.character(as.numeric(subscribe)), con) writeBin(as.character(acctCode), con) } reqAccountUpdates <- function (conn, subscribe=TRUE, acctCode="1", eventWrapper=eWrapper(), CALLBACK=twsCALLBACK, ...) { if (!is.twsConnection(conn)) stop("requires twsConnection object") .reqAccountUpdates(conn, subscribe, acctCode) on.exit(.reqAccountUpdates(conn, "0", acctCode)) verbose <- FALSE acct <- list() con <- conn[[1]] eW <- eWrapper(NULL) eW$assign.Data("data", structure(list(), class="eventAccountValue")) eW$updatePortfolio <- function (curMsg, msg, ...) { version <- as.numeric(msg[1]) contract <- twsContract(conId = msg[2], symbol = msg[3], sectype = msg[4], exch = msg[9], primary = msg[9], expiry = msg[5], strike = msg[6], currency = msg[10], right = msg[7], local = msg[11], multiplier = msg[8], combo_legs_desc = "", comboleg = "", include_expired = "") portfolioValue <- list() portfolioValue$position <- as.numeric(msg[12]) portfolioValue$marketPrice <- as.numeric(msg[13]) portfolioValue$marketValue <- as.numeric(msg[14]) portfolioValue$averageCost <- as.numeric(msg[15]) portfolioValue$unrealizedPNL <- as.numeric(msg[16]) portfolioValue$realizedPNL <- as.numeric(msg[17]) portfolioValue$accountName <- msg[18] p <- structure(list(contract = contract, portfolioValue = portfolioValue), class = "eventPortfolioValue") p } eW$updateAccountValue <- function (curMsg, msg, ...) { data <- eW$get.Data("data") data[[msg[2]]] <- c(value=msg[3], currency=msg[4]) eW$assign.Data("data", data) } while (TRUE) { socketSelect(list(con), FALSE, NULL) curMsg <- readBin(con, character(), 1) if (curMsg == .twsIncomingMSG$PORTFOLIO_VALUE) { acct[[length(acct) + 1]] <- processMsg(curMsg, con, eW, timestamp, file) } else { processMsg(curMsg, con, eW, timestamp, file) } if (curMsg == .twsIncomingMSG$ACCT_DOWNLOAD_END) break } return(structure(list(eW$get.Data("data"), acct), class="AccountUpdate")) }
err <- "interleave - expecting a list input" expect_error( interleave:::.test_list_rows( 1:5 ), err) expect_error( interleave:::.test_list_rows( matrix(1:4, ncol = 2) ), err ) expect_error( interleave:::.test_list_rows( data.frame(x = 1:3, y = 1:3 ) ), err ) expect_equal( interleave:::.test_list_rows( list( data.frame(x = 1:3, y = 1:3 ) ) ), list( 3 ) ) l <- list( 1:10 , matrix(1:16, ncol = 2) , list( list( data.frame(x = 1:10, y = 10:1 ) ) ) ) expect_equal( interleave:::.test_list_rows( l ) , list(1,8,list(list(10))) ) expect_equal( unlist( interleave:::.test_list_rows( l ) ), c(1,8,10) ) l <- list( 1:10 , matrix(1:16, ncol = 2) , list( 1:4 , matrix(1:10, ncol = 5) ) , list( list( data.frame(x = 1:10, y = 10:1 ) ) ) ) expect_equal( interleave:::.test_list_element_count( l ), list(10, 16, list(4, 10), list( list( 20 ) ) ) ) expect_error( interleave:::.test_unlist_list( 1:4 ), err ) expect_error( interleave:::.test_unlist_list( matrix(1:4, ncol = 2) ), err) expect_error( interleave:::.test_unlist_list( data.frame( x = 1:4 ) ), err ) expect_equal( interleave:::.test_unlist_list( list(1:4) ), c(1:4) ) l <- list( 1:10 , list( list( matrix(1:20, ncol = 2) ) ) ) expect_equal( interleave:::.test_unlist_list( l ), c(1:10, 1:20) ) l <- list( c(TRUE, TRUE, FALSE) , matrix(1:16, ncol = 2) , list( letters[1:4] , matrix(rep(T, 10), ncol = 5) ) , list( list( data.frame(x = 1:10, y = 10:1 ) ) ) ) list_sizes <- interleave:::.test_list_element_count( l) expect_equal( interleave:::.test_unlist_list( list_sizes ), unlist( list_sizes) ) expect_error( interleave:::.test_unlist_list( l ), err )
knitr::opts_chunk$set( collapse = TRUE, fig.width=7, fig.height = 5, comment = " library(baggr) library(ggplot2) library(gridExtra) df_yusuf <- read.table(text=" trial a n1i c n2i Balcon 14 56 15 58 Clausen 18 66 19 64 Multicentre 15 100 12 95 Barber 10 52 12 47 Norris 21 226 24 228 Kahler 3 38 6 31 Ledwich 2 20 3 20 ", header=TRUE) df_ma <- prepare_ma(df_yusuf, group = "trial", effect = "logOR") df_ma bg_model_agg <- baggr(df_ma, iter = 2000, effect = "logarithm of odds ratio") labbe(df_ma, plot_model = TRUE, shade_se = "or") a <- 9; b <- 1; c <- 99; d <- 1 cat("Risk ratio is", (a/(a+b))/(c/(c+d)), "\n" ) cat("Odds ratio is", a*d/(b*c), "\n") a <- 10; b <- 20; c <- 100; d <- 100 cat("Risk ratio is", (a/(a+b))/(c/(c+d)), "\n" ) cat("Odds ratio is", a*d/(b*c), "\n") par(mfrow = c(2,3), oma = rep(2,4)) for(es in c(1, .9, .8, .5, .25, .1)){ p_bsl <- seq(0,1,length=100) p_trt_rr <- es*p_bsl odds_trt <- es*(p_bsl/(1-p_bsl)) p_trt_or <- odds_trt / (1 + odds_trt) plot(p_trt_or ~ p_bsl, type = "l", xlab = "control event rate", ylab = "treatment event rate", main = paste0("RR=OR=",es)) lines(p_trt_rr ~ p_bsl, lty = "dashed") } title(outer = TRUE, "Compare RR (dashed) and OR (solid) of the same magnitude") bg_model_agg forest_plot(bg_model_agg, show = "both", print = "inputs") effect_plot(bg_model_agg) gridExtra::grid.arrange( plot(bg_model_agg, transform = exp) + xlab("Effect on OR"), effect_plot(bg_model_agg, transform = exp) + xlim(0, 3) + xlab("Effect on OR"), ncol = 2) bg_c <- baggr_compare(df_ma, what = "pooling", effect = "logarithm of odds ratio") plot(bg_c) effect_plot( "Partial pooling, default prior" = bg_c$models$partial, "Full pooling, default prior" = bg_c$models$full) + theme(legend.position = "bottom") a <- loocv(df_ma, pooling = "partial", iter = 500, chains = 2) b <- loocv(df_ma, pooling = "full", iter = 500, chains = 2) loo_compare(a,b) df_ind <- binary_to_individual(df_yusuf, group = "trial") head(df_ind) bg_model_ind <- baggr(df_ind, model = "logit", effect = "logarithm of odds ratio", chains = 2, iter = 500) baggr_compare(bg_model_agg, bg_model_ind) prepare_ma(df_ind, effect = "logOR") prepare_ma(df_ind, effect = "logRR") df_rare <- data.frame(group = paste("Study", LETTERS[1:5]), a = c(0, 2, 1, 3, 1), c = c(2, 2, 3, 3, 5), n1i = c(120, 300, 110, 250, 95), n2i = c(120, 300, 110, 250, 95)) df_rare df_rare_logor <- prepare_ma(df_rare, effect = "logOR") df_rare_logor pma01 <- prepare_ma(df_rare, effect = "logOR", rare_event_correction = 0.1) pma1 <- prepare_ma(df_rare, effect = "logOR", rare_event_correction = 1) pma01 bg_correction01 <- baggr(pma01, effect = "logOR", iter = 500) bg_correction025 <- baggr(df_rare_logor, effect = "logOR", iter = 500) bg_correction1 <- baggr(pma1, effect = "logOR", iter = 500) bg_rare_ind <- baggr(df_rare, model = "logit", effect = "logOR") bgc <- baggr_compare( "Correct by .10" = bg_correction01, "Correct by .25" = bg_correction025, "Correct by 1.0" = bg_correction1, "Individual data" = bg_rare_ind ) bgc plot(bgc) + theme(legend.position = "right") df_rare <- data.frame(group = paste("Study", LETTERS[1:5]), a = c(1, 2, 1, 3, 1), c = c(2, 2, 3, 3, 5), n1i = c(120, 300, 110, 250, 95), n2i = c(120, 300, 110, 250, 95)) df_rare_logor <- prepare_ma(df_rare, effect = "logOR") bg_rare_agg <- baggr(df_rare_logor, effect = "logOR") bg_rare_ind <- baggr(df_rare, effect = "logOR", model = "logit", iter = 500, chains = 2) bgc <- baggr_compare( "Summary-level (Rubin model on logOR)" = bg_rare_agg, "Individual-level (logistic model)" = bg_rare_ind ) bgc plot(bgc) bg_rare_pool_bsl <- baggr(df_rare, effect = "logOR", model = "logit", pooling_control = "partial", chains = 2, iter = 500, prior_control = normal(-4.59, 1), prior_control_sd = normal(0, 2)) bg_rare_strong_prior <- baggr(df_rare, effect = "logOR", model = "logit", chains = 2, iter = 500, prior_control = normal(-4.59, 10)) bgc <- baggr_compare( "Rubin model" = bg_rare_agg, "Independent N(0,10^2)" = bg_rare_ind, "Hierarchical prior" = bg_rare_pool_bsl, "Independent N(-4.59, 10^2)" = bg_rare_strong_prior ) bgc plot(bgc) + theme(legend.position = "right") df_ma$study_grouping <- c(1,1,1,0,0,0,0) df_ma$different_contrasts <- c(1,1,1,0,0,0,0) - .5 bg_cov1 <- baggr(df_ma, covariates = c("study_grouping"), effect = "logarithm of odds ratio") baggr_compare("No covariate" = bg_model_agg, "With covariates, 0-1 coding" = bg_cov1) bg_cov1
GetRegionOfInterest <- function(x, y=NULL, alpha=NULL, width=NULL, ...) { checkmate::assertNumber(alpha, lower=0, finite=TRUE, null.ok=TRUE) checkmate::assertNumber(width, finite=TRUE, null.ok=TRUE) if (inherits(x, "Spatial")) { xy <- sp::coordinates(x) crs <- raster::crs(x) } else { xy <- do.call("cbind", grDevices::xy.coords(x, y)[1:2]) crs <- sp::CRS(as.character(NA)) } if (is.null(alpha)) { pts <- xy[grDevices::chull(xy), ] ply <- sp::Polygons(list(sp::Polygon(pts)), ID=1) } else { ply <- .GeneralizeConvexHull(xy, alpha) } ply <- sp::SpatialPolygons(list(ply), proj4string=crs) if (is.numeric(width)) ply <- rgeos::gBuffer(ply, width=width, ...) ply } .GeneralizeConvexHull <- function(xy, alpha) { checkmate::assertMatrix(xy, mode="numeric", any.missing=FALSE, ncols=2) checkmate::assertNumber(alpha, lower=0, finite=TRUE) for (pkg in c("alphahull", "maptools")) { if (!requireNamespace(pkg, quietly=TRUE)) stop(sprintf("alpha-shape computation requires the %s package", pkg)) } xy <- unique(xy) shp <- alphahull::ashape(xy, alpha=alpha) el <- cbind(as.character(shp$edges[, "ind1"]), as.character(shp$edges[, "ind2"])) gr <- igraph::graph_from_edgelist(el, directed=FALSE) clu <- igraph::components(gr, mode="strong") ply <- sp::Polygons(lapply(seq_len(clu$no), function(i) { vids <- igraph::groups(clu)[[i]] g <- igraph::induced_subgraph(gr, vids) if (any(igraph::degree(g) != 2)) stop("non-circular polygon, try increasing alpha value", call.=FALSE) gcut <- g - igraph::E(g)[1] ends <- names(which(igraph::degree(gcut) == 1)) path <- igraph::shortest_paths(gcut, ends[1], ends[2])$vpath[[1]] idxs <- as.integer(igraph::V(g)[path]$name) pts <- shp$x[c(idxs, idxs[1]), ] sp::Polygon(pts) }), ID=1) maptools::checkPolygonsHoles(ply) }
cols <- t(col2rgb(palette())) convertColor(cols, 'sRGB', 'Lab', scale.in=255) XYZ <- convertColor(cols, 'sRGB', 'XYZ', scale.in=255) fromXYZ <- vapply( names(colorspaces), convertColor, FUN.VALUE=XYZ, from='XYZ', color=XYZ, clip=NA ) round(fromXYZ, 4) tol <- 1e-5 toXYZ <- vapply( dimnames(fromXYZ)[[3]], function(x) all(abs(convertColor(fromXYZ[,,x], from=x, to='XYZ') - XYZ)<tol), logical(1) ) toXYZ stopifnot(all(toXYZ | is.na(toXYZ))) XYZ2 <- XYZ * .7 + .15 fromXYZ2 <- vapply( c('Apple RGB', 'CIE RGB'), convertColor, FUN.VALUE=XYZ2, from='XYZ', color=XYZ2, clip=NA ) round(fromXYZ2, 4) toXYZ2 <- vapply( dimnames(fromXYZ2)[[3]], function(x) all(abs(convertColor(fromXYZ2[,,x], from=x, to='XYZ') - XYZ2)<tol), logical(1) ) stopifnot(all(toXYZ2)) stopifnot(identical(character(0), gray(numeric(), alpha=1/2)))
dtable <- function(x, bset, bsep = ".", asep = ";", missing = "x", noc = "0"){ x <- apply(x, 2 , function(x) tolower(x)) x <- as.data.frame(apply(x, 2, function(x) gsub(' ', '', x)), stringsAsFactors = FALSE) names(x) <- c("id", "act", "obs") x$act[is.na(x$act)] <- missing ids <- sort(unique(x$id)) bsep <- paste("\\",bsep, sep="") asep <- paste("\\",asep, sep="") i <- 1 size <- dim(x)[1] while (i <= size) { act <- x$act[i] if (grepl(asep, act)){ acts <- unlist( regmatches(act, regexpr(asep, act), invert = TRUE) ) x$act[i] <- acts[1] x <-rbind(x[1:i,], c(x$id[i], acts[2], x$obs[i]), x[-(1:i),] ) size <- size + 1 } i = i + 1 } dt <- stats::setNames(data.frame(matrix(ncol = 7, nrow = size)), c("id1","id2","sender_id1","behavior","no_occurrence","missing","observer")) for (i in 1:size) { dt$id1[i] <- x$id[i] act <- x$act[i] if (grepl(bsep, act)){ act <- unlist( strsplit(act, bsep) ) dt$behavior[i] <- bset[stats::na.omit(match(act, bset))] dt$sender_id1[i] = c(1,0)[!is.na(match(act, bset))] dt$id2[i] <- act[dt$sender_id1[i] + 1] } if (x$act[i] == noc) {dt$no_occurrence[i] = 1} if (x$act[i] == missing) {dt$missing[i] = 1} dt$observer[i] <- x$obs[i] } dt }
theme_classic2 <- function() { ggplot2::theme( panel.background = ggplot2::element_blank(), legend.background = ggplot2::element_blank(), legend.key = ggplot2::element_blank(), strip.background = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), axis.text = ggplot2::element_text(colour = "black"), axis.line = ggplot2::element_line(colour = "black") ) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(SimplyAgree) a1 = agree_test(x = reps$x, y = reps$y, agree.level = .8) print(a1) plot(a1, type = 1) plot(a1, type = 2) a2 = agree_reps(x = "x", y = "y", id = "id", data = reps, agree.level = .8) print(a2) plot(a2, type = 1) plot(a2, type = 2) a3 = agree_nest(x = "x", y = "y", id = "id", data = reps, agree.level = .8) print(a3) plot(a3, type = 1) plot(a3, type = 2) sf <- matrix( c(9, 2, 5, 8, 6, 1, 3, 2, 8, 4, 6, 8, 7, 1, 2, 6, 10, 5, 6, 9, 6, 2, 4, 7), ncol = 4, byrow = TRUE ) colnames(sf) <- paste("J", 1:4, sep = "") rownames(sf) <- paste("S", 1:6, sep = "") dat = as.data.frame(sf) test1 = reli_stats( data = dat, wide = TRUE, col.names = c("J1", "J2", "J3", "J4") ) print(test1) plot(test1) power_res <- blandPowerCurve( samplesizes = seq(10, 100, 1), mu = 0.5, SD = 2.5, delta = c(6,7), conf.level = c(.90,.95), agree.level = c(.8,.9) ) head(power_res) find_n(power_res, power = .8) plot(power_res)
rmgarch.test1a = function(cluster = NULL) { tic = Sys.time() data(dji30ret) ex = as.matrix(cbind(apply(dji30ret[,4:8], 1, "mean"), apply(dji30ret[,12:20], 1, "mean"))) ex = rugarch:::.lagx(ex, n.lag = 1, pad = 0) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.1 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.2 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.1@mfit$A, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2, external.regressors = ex), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.3 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], solver = "gosolnp", solver.control = list(trace=1), out.sample = 0, A.init = fit.2@mfit$A, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.4 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2, external.regressors = ex), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.5 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.4@mfit$A, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2, external.regressors = ex, robust = TRUE), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.6 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.5@mfit$A, cluster = cluster) modellik = c(0, likelihood(fit.2)-likelihood(fit.1), likelihood(fit.3)-likelihood(fit.1), likelihood(fit.4)-likelihood(fit.1), likelihood(fit.5)-likelihood(fit.1), likelihood(fit.6)-likelihood(fit.1)) postscript("test1a1.eps", width = 8, height = 5) barplot(modellik, names.arg = c(paste("C[",round(likelihood(fit.1),0), "]", sep=""),"AR(2)", "ARX(2)", "VAR(2)", "VARX(2)", "robVARX(2)"), ylab = "Diff Log-Likelihood", xlab = "Model", col = "steelblue", main = "GOGARCH with different\nconditional mean models") dev.off() postscript("test1a2.eps", width = 10, height = 8) rc = rcor(fit.1) D = as.POSIXct(dimnames(rc)[[3]]) plot(xts::xts(rc[1,2,], D), ylim = c(-0.4, 1), main = "GOGARCH Correlation [AA-AXP] under\ndifferent mean models", lty = 2, ylab = "Correlation", xlab = "Time", minor.ticks=FALSE, auto.grid=FALSE) rc = rcor(fit.2) lines(xts::xts(rc[1,2,], D), col = 2, lty = 2) rc = rcor(fit.3) lines(xts::xts(rc[1,2,], D), col = 3) rc = rcor(fit.4) lines(xts::xts(rc[1,2,], D), col = 4, lty = 2) rc = rcor(fit.5) lines(xts::xts(rc[1,2,], D), col = 5) rc = rcor(fit.6) lines(xts::xts(rc[1,2,], D), col = 6) legend("bottomleft", legend = c("C", "AR(2)", "ARX(2)", "VAR(2)", "VARX(2)", "robVARX(2)"), col = 1:6, lty = c(2,2,1,2,1,1), cex = 0.8, bty = "n") dev.off() postscript("test1a3.eps", width = 12, height = 20) T = fit.1@model$modeldata$T D = fit.1@model$modeldata$index[1:T] par(mfrow = c(3,1)) plot(xts::xts(fit.1@model$modeldata$data[1:T,1], D), main = "AA Returns vs Fit under \ndifferent mean models", xlab = "Time", ylab = "R_t", minor.ticks = FALSE, auto.grid=FALSE) lines(fitted(fit.6)[,1], lty = 2, col = 3, lwd = 0.5) lines(fitted(fit.2)[,1], lty = 2, col = 2) legend("topleft", legend = c("Actual", "robVARX(2)", "AR(2)"), col = c(1,3,2), lty = c(1,2,2), bty ="n") plot(xts::xts(fit.1@model$modeldata$data[1:T,2], D), main = "AXP Returns vs Fit under \ndifferent mean models", xlab = "Time", ylab = "R_t", minor.ticks = FALSE, auto.grid=FALSE) lines(fitted(fit.6)[,2], lty = 2, col = 3, lwd = 0.5) lines(fitted(fit.2)[,2], lty = 2, col = 2) legend("topleft", legend = c("Actual", "robVARX(2)", "AR(2)"), col = c(1,3,2), lty = c(1,2,2), bty ="n") plot(xts::xts(fit.1@model$modeldata$data[1:T,3], D), type = "l", main = "BA Returns vs Fit under \ndifferent mean models", xlab = "Time", ylab = "R_t", minor.ticks = FALSE, auto.grid=FALSE) lines(fitted(fit.6)[,3], lty = 2, col = 3, lwd = 0.5) lines(fitted(fit.2)[,3], lty = 2, col = 2) legend("topleft", legend = c("Actual", "robVARX(2)", "AR(2)"), col = c(1,3,2), lty = c(1,2,2), bty ="n") dev.off() toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1b = function(cluster = NULL) { tic = Sys.time() require(vars) data(dji30ret) ex = as.matrix(cbind(apply(dji30ret[,4:8], 1, "mean"), apply(dji30ret[,12:20], 1, "mean"))) ex = rugarch:::.lagx(ex, n.lag = 1, pad = 0) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 1, lag.max = 6), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) v2 = VAR(dji30ret[,1:3,drop=FALSE], lag.max=6, ic = "AIC") options(width = 120) zz <- file("test1b-1.txt", open="wt") sink(zz) print(fit@mfit$varcoef) cat("\n") print(fit@model$modelinc) cat("\nvars package output:\n") print(Bcoef(v2)) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 1, lag.max = 6, external.regressors = ex), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) v2 = VAR(dji30ret[,1:3,drop=FALSE], lag.max=6, ic = "AIC", exogen = ex) options(width = 120) zz <- file("test1b-2.txt", open="wt") sink(zz) print(fit@mfit$varcoef) cat("\n") print(fit@model$modelinc) cat("\nvars package output:\n") print(Bcoef(v2)) sink(type="message") sink() close(zz) toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1c = function(cluster = NULL) { tic = Sys.time() data(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica","radical")[1]) fit.1 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.2 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, gfun = "tanh", cluster = cluster) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[2]) fit.3 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) modellik = data.frame(fastica_pow3=likelihood(fit.1), fastica_tanh=likelihood(fit.2), radical=likelihood(fit.3)) rownames(modellik) = "LLH" options(width = 120) zz <- file("test1c.txt", open="wt") sink(zz) print(modellik) sink(type="message") sink() close(zz) toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1d = function(cluster = NULL) { tic = Sys.time() data(dji30ret) ex = as.matrix(cbind(apply(dji30ret[,4:8], 1, "mean"), apply(dji30ret[,12:20], 1, "mean"))) ex = rugarch:::.lagx(ex, n.lag = 1, pad = 0) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.1 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) filt.1 = gogarchfilter(fit.1, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-1.txt", open="wt") sink(zz) print(head(fitted(fit.1))==head(fitted(filt.1))) cat("\n") print(rcov(fit.1)[,,10]==rcov(filt.1)[,,10]) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "pearson", "jade", "radical")[1]) fit.2 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.1@mfit$A, cluster = cluster) filt.2 = gogarchfilter(fit.2, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-2.txt", open="wt") sink(zz) print(head(fitted(fit.2))==head(fitted(filt.2))) cat("\n") print(rcov(fit.2)[,,10]==rcov(filt.2)[,,10]) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2, external.regressors = ex), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.3 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], solver = "hybrid", solver.control = list(trace=0), out.sample = 0, A.init = fit.2@mfit$A, cluster = cluster) filt.3 = gogarchfilter(fit.3, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-3.txt", open="wt") sink(zz) print(head(fitted(fit.3))==head(fitted(filt.3))) cat("\n") print(rcov(fit.3)[,,10]==rcov(filt.3)[,,10]) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.4 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0) filt.4 = gogarchfilter(fit.4, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) filt.44 = gogarchfilter(fit.4, data = dji30ret[1:10,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-4.txt", open="wt") sink(zz) print(head(fitted(fit.4))==head(fitted(filt.4))) cat("\n") print(head(fitted(filt.44))==head(fitted(filt.4))) cat("\n") print(rcov(fit.4)[,,10]==rcov(filt.4)[,,10]) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2, external.regressors = ex), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.5 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.4@mfit$A, cluster = cluster) filt.5 = gogarchfilter(fit.5, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-5.txt", open="wt") sink(zz) print(head(fitted(fit.5))==head(fitted(filt.5))) cat("\n") print(rcov(fit.5)[,,10]==rcov(filt.5)[,,10]) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2, external.regressors = ex, robust = TRUE), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit.6 = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, A.init = fit.5@mfit$A, cluster = cluster) filt.6 = gogarchfilter(fit.6, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1d-6.txt", open="wt") sink(zz) print(head(fitted(fit.6))==head(fitted(filt.6))) cat("\n") print(rcov(fit.6)[,,10]==rcov(filt.6)[,,10]) sink(type="message") sink() close(zz) toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1e = function(cluster = NULL) { tic = Sys.time() data(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[2], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) options(width = 120) zz <- file("test1e-1.txt", open="wt") sink(zz) print(likelihood(fit)) cat("\n") print(as.matrix(fit, which = "A")) cat("\n") print(as.matrix(fit, which = "K")) cat("\n") print(as.matrix(fit, which = "U")) cat("\n") print(head(fitted(fit))) cat("\n") print(head(residuals(fit))) cat("\n") print(rcov(fit)[,,1]) cat("\n") print(rcor(fit)[,,1]) cat("\n") print(rcoskew(fit, from=1, to=2)) cat("\n") print(rcokurt(fit, from=1, to=2)) cat("\n") sink(type="message") sink() close(zz) gp = gportmoments(fit, weights = rep(1/3,3)) cf = convolution(fit, weights = rep(1/3,3), fft.step = 0.001, fft.by = 0.0001, fft.support = c(-1, 1), use.ff = TRUE, trace = 0, support.method = c("user", "adaptive")[2], cluster = cluster) np = nportmoments(cf, trace=1) postscript("test1e1.eps", width = 8, height = 12) par(mfrow = c(2,2)) plot(gp[1:1000,1], type = "p", main = "Portfolio Mean", minor.ticks=FALSE, auto.grid=FALSE) points(np[1:1000,1], col = 2, pch = 4) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, pch = c(1,4), bty="n") plot(gp[1:1000,2], type = "o", main = "Portfolio Sigma", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,2], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") plot(gp[1:1000,3], type = "o", main = "Portfolio Skewness", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,3], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") plot(gp[1:1000,4], type = "o", main = "Portfolio Kurtosis", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,4], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") dev.off() postscript("test1e2.eps", width = 8, height = 12) par(mfrow = c(2,2)) qf = qfft(cf, index = 5521) plot(seq(0.01, 0.99, by = 0.005), qf(seq(0.01, 0.99, by = 0.005)), type = "l", main = "Portfolio Quantile\nObs=5521", xlab = "Value", ylab = "Probability") lines(seq(0.01, 0.99, by = 0.005), qnorm(seq(0.01, 0.99, by = 0.005), gp[5521,1], gp[5521,2]), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") df = dfft(cf, index = 4823) plot(seq(-0.3, 0.3, by = 0.005), df(seq(-0.3, 0.3, by = 0.005)), type = "l", main = "Portfolio Density", xlab = "Value", ylab = "pdf") lines(seq(-0.3, 0.3, by = 0.005), dnorm(seq(-0.3, 0.3, by = 0.005), gp[4823,1], gp[4823,2]), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") rf = qfft(cf, index = 5519) rfx = runif(50000) sx = rf(rfx) plot(density(sx), type = "l", main = "Sampled Portfolio Density", xlab = "Value", ylab = "pdf") lines(density(qnorm(rfx, gp[5519,1], gp[5519,2])), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") dev.off() qseq = seq(0.01, 0.99, by = 0.005) qsurface = matrix(NA, ncol = length(qseq), nrow = 5521) for(i in 1:5521){ qf = qfft(cf, index = i) qsurface[i,] = qf(qseq) } png("test1e3.png", width = 800, height = 1200, res = 100) par(mar=c(1.8,1.8,1.1,1), pty = "m") x1 = shape::drapecol(qsurface, col = shape::femmecol(100), NAcol = "white") persp( x = 1:5521, y = qseq, z = qsurface, col = x1, theta = 45, phi = 25, expand = 0.5, ltheta = 120, shade = 0.75, ticktype = "simple", xlab = "Time", ylab = "Quantile", zlab = "Value",cex.axis = 0.8) dev.off() png("test1e4.png", width = 800, height = 1200, res = 100) ni = nisurface(fit, type = "cor", pair = c(1,3), factor = c(2,3), plot = TRUE) dev.off() toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1f = function(cluster = NULL) { tic = Sys.time() data(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[2], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:3,drop=FALSE], out.sample = 0, cluster = cluster) filt = gogarchfilter(fit, data = dji30ret[,1:3,drop=FALSE], out.sample = 0) options(width = 120) zz <- file("test1f.txt", open="wt") sink(zz) print(likelihood(filt)) cat("\n") print(as.matrix(filt, which = "A")) cat("\n") print(as.matrix(filt, which = "K")) cat("\n") print(as.matrix(filt, which = "U")) cat("\n") print(head(fitted(filt))) cat("\n") print(head(residuals(filt))) cat("\n") print(rcov(filt)[,,1]) cat("\n") print(rcor(filt)[,,1]) cat("\n") print(rcoskew(filt, from=1, to=2)) print(rcokurt(filt, from=1, to=2)) cat("\n") sink(type="message") sink() close(zz) gp = gportmoments(filt, weights = rep(1/3,3)) cf = convolution(filt, weights = rep(1/3,3), fft.step = 0.001, fft.by = 0.0001, fft.support = c(-1, 1), use.ff = TRUE, support.method = c("user", "adaptive")[2], cluster = cluster) np = nportmoments(cf) postscript("test1f1.eps", width = 8, height = 12) par(mfrow = c(2,2)) plot(gp[1:1000,1], type = "p", main = "Portfolio Mean", minor.ticks=FALSE, auto.grid=FALSE) points(np[1:1000,1], col = 2, pch = 4) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, pch = c(1,4), bty="n") plot(gp[1:1000,2], type = "l", main = "Portfolio Sigma", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,2], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") plot(gp[1:1000,3], type = "l", main = "Portfolio Skewness", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,3], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") plot(gp[1:1000,4], type = "l", main = "Portfolio Kurtosis", minor.ticks=FALSE, auto.grid=FALSE) lines(np[1:1000,4], col = 2) legend("topleft", legend = c("Geometric", "Semi-Analytic (FFT)"), col = 1:2, fill=1:2, bty="n") dev.off() postscript("test1f2.eps", width = 8, height = 12) par(mfrow = c(2,2)) qf = qfft(cf, index = 5521) plot(seq(0.01, 0.99, by = 0.005), qf(seq(0.01, 0.99, by = 0.005)), type = "l", main = "Portfolio Quantile\nObs=5521", xlab = "Value", ylab = "Probability") lines(seq(0.01, 0.99, by = 0.005), qnorm(seq(0.01, 0.99, by = 0.005), gp[5521,1], gp[5521,2]), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") df = dfft(cf, index = 4823) plot(seq(-0.3, 0.3, by = 0.005), df(seq(-0.3, 0.3, by = 0.005)), type = "l", main = "Portfolio Density", xlab = "Value", ylab = "pdf") lines(seq(-0.3, 0.3, by = 0.005), dnorm(seq(-0.3, 0.3, by = 0.005), gp[4823,1], gp[4823,2]), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") rf = qfft(cf, index = 5521) rfx = runif(50000) sx = rf(rfx) plot(density(sx), type = "l", main = "Sampled Portfolio Density", xlab = "Value", ylab = "pdf") lines(density(qnorm(rfx, gp[5521,1], gp[5521,2])), col = 2) legend("topleft", legend = c("FFT Portfolio", "Gaussian Portfolio"), col = 1:2, fill = 1:2, bty = "n") dev.off() qseq = seq(0.01, 0.99, by = 0.005) qsurface = matrix(NA, ncol = length(qseq), nrow = 5521) for(i in 1:5521){ qf = qfft(cf, index = i) qsurface[i,] = qf(qseq) } png("test1f3.png", width = 800, height = 1200, res = 100) par(mar=c(1.8,1.8,1.1,1), pty = "m") x1 = shape::drapecol(qsurface, col = shape::femmecol(100), NAcol = "white") persp( x = 1:5521, y = qseq, z = qsurface, col = x1, theta = 45, phi = 25, expand = 0.5, ltheta = 120, shade = 0.75, ticktype = "simple", xlab = "Time", ylab = "Quantile", zlab = "Value",cex.axis = 0.8) dev.off() png("test1f4.png", width = 800, height = 1200, res = 100) ni = nisurface(filt, type = "cor", pair = c(2,3), factor = c(1,3), plot = TRUE) dev.off() toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1g = function(cluster = NULL) { tic = Sys.time() data(dji30ret) cnames = colnames(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 2, lag.max = 6), variance.model = list(model = "sGARCH", submodel = "NULL", garchOrder = c(1,1), variance.targeting = TRUE), distribution.model = c("mvnorm", "manig", "magh")[2], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:5,drop=FALSE], out.sample = 500, cluster = cluster, gfun="tanh", maxiter1=25000) filt = gogarchfilter(fit, data = dji30ret[,1:5,drop=FALSE], out.sample = 500, cluster = cluster) filt2 = gogarchfilter(fit, data = dji30ret[,1:5,drop=FALSE], n.old = 5521-500, cluster = cluster) forc.1 = gogarchforecast(fit, n.ahead = 500, cluster = cluster) forc.2 = gogarchforecast(fit, n.ahead = 1, n.roll = 499, cluster = cluster) zz <- file("test1g-1.txt", open="wt") sink(zz) cat("\nFilter/Forecast Roll Check:\n") print(all.equal(matrix(rmgarch::last(fitted(forc.2), 1), nrow=1), matrix(as.numeric(tail(fitted(filt2), 1)), nrow=1))) print(round(rcor(forc.2)[[500]][,,1], 5) == round(rmgarch::last(rcor(filt2))[,,1],5)) print(matrix(rmgarch::last(sigma(forc.2, factors=FALSE), 1), nrow=1) - as.matrix(tail(sigma(filt2, factors=FALSE), 1))) print(matrix(rmgarch::first(sigma(forc.2, factors=FALSE), 1), nrow=1) - as.matrix(sigma(filt2, factors=FALSE)[5521-500+1,])) sink(type="message") sink() close(zz) rc1 = rcor(forc.1)[[1]] rc2 = rcor(forc.2) postscript("test1g1.eps", width = 12, height = 12) par(mfrow = c(2,2)) D = tail(fit@model$modeldata$index, 500) plot(xts::xts(sapply(rc2, function(x) x[1,2,1]),D), main = paste("Correlation Forecast\n", cnames[1],"-", cnames[2], sep = ""), ylab = "Correlation", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(rc1[1,2,], D), col = 2 ) legend("topright", legend = c("Rolling", "Unconditional"), col =1:2, fill = 1:2, bty = "n") plot(xts::xts(sapply(rc2, function(x) x[1,3,1]), D), type = "l", main = paste("Correlation Forecast\n", cnames[1],"-", cnames[3], sep = ""), ylab = "Correlation", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(rc1[1,3,], D), col = 2 ) legend("topright", legend = c("Rolling", "Unconditional"), col =1:2, fill = 1:2, bty = "n") plot(xts::xts(sapply(rc2, function(x) x[2,3,1]), D), type = "l", main = paste("Correlation Forecast\n", cnames[2],"-", cnames[3], sep = ""), ylab = "Correlation", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(rc1[2,3,], D), col = 2 ) legend("topright", legend = c("Rolling", "Unconditional"), col =1:2, fill = 1:2, bty = "n") dev.off() gp1 = gportmoments(forc.1, weights = rep(1/5,5)) gp2 = gportmoments(forc.2, weights = rep(1/5,5)) postscript("test1g2.eps", width = 12, height = 12) par(mfrow = c(2,1)) D = tail(fit@model$modeldata$index, 500) plot(xts::xts(tail(apply(fit@model$modeldata$data,1,"mean"), 500), D), main = paste("Portfolio Return Forecast"), ylab = "returns", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(gp2[,"mu", ], D), col = 2 ) lines(xts::xts(gp1[,"mu",1], D), col = 3 ) legend("topright", legend = c("Actual", "Rolling", "Unconditional"), col = 1:3, fill = 1:3, bty = "n") plot(xts::xts(sqrt(tail(apply(fit@model$modeldata$data^2,1,"mean"), 500)), D), main = paste("Portfolio Sigma Forecast"), ylab = "sigma", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(gp2[,"sigma", ], D), col = 2 ) lines(xts::xts(gp1[,"sigma",1], D), col = 3 ) legend("topright", legend = c("Abs Returns", "Rolling", "Unconditional"), col = 1:3, fill = 1:3, bty = "n") dev.off() cf1 = convolution(forc.1, weights = rep(1/5,5), fft.step = 0.001, fft.by = 0.0001, fft.support = c(-1, 1), use.ff = TRUE, trace = 0, support.method = c("user", "adaptive")[1], cluster = cluster) cf2 = convolution(forc.2, weights = rep(1/5,5), fft.step = 0.001, fft.by = 0.0001, fft.support = c(-1, 1), use.ff = TRUE, trace = 0, support.method = c("user", "adaptive")[1], cluster = cluster) np1 = nportmoments(cf1, subdivisions = 400) np2 = nportmoments(cf2, subdivisions = 400) postscript("test1g3.eps", width = 12, height = 12) par(mfrow = c(2,2)) plot(xts::xts(gp2[,"mu",], D), main = paste("Portfolio Return Forecast"), ylab = "returns", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np2[,"mu",], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") plot(xts::xts(gp2[,"sigma",], D), main = paste("Portfolio Sigma Forecast"), ylab = "sigma", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np2[,"sigma",], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") plot(xts::xts(gp2[,"skewness",], D), main = paste("Portfolio Skew Forecast"), ylab = "skewness", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np2[,"skewness",], D), col = 2 ) plot(xts::xts(gp2[,"kurtosis",], D), main = paste("Portfolio Kurtosis Forecast"), ylab = "skewness", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np2[,"kurtosis",], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") dev.off() VaR = matrix(NA, ncol = 2, nrow = 500) for(i in 0:499){ qx = qfft(cf2, index = i) VaR[i+1,1:2] = qx(c(0.01, 0.05)) } postscript("test1g4.eps", width = 12, height = 12) par(mfrow = c(2,1)) VaRplot(0.01, actual = xts::xts(tail(apply(fit@model$modeldata$data,1,"mean"), 500),D), VaR = xts::xts(VaR[,1], D)) VaRplot(0.05, actual = xts::xts(tail(apply(fit@model$modeldata$data,1,"mean"), 500),D), VaR = xts::xts(VaR[,2], D)) dev.off() zz <- file("test1g-2.txt", open="wt") sink(zz) cat("\nGOGARCH VaR:\n") print(VaRTest(0.01, actual = tail(apply(fit@model$modeldata$data,1,"mean"), 500), VaR = VaR[,1])) print(VaRTest(0.05, actual = tail(apply(fit@model$modeldata$data,1,"mean"), 500), VaR = VaR[,2])) sink(type="message") sink() close(zz) toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1h = function(cluster = NULL) { tic = Sys.time() data(dji30retw) cnames = colnames(dji30retw) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), variance.targeting = TRUE), distribution.model = c("mvnorm", "manig", "magh")[2], ica = c("fastica", "radical")[1]) roll = gogarchroll(spec, data = dji30retw[,1:10,drop=FALSE], n.ahead = 1, forecast.length = 500, refit.every = 20, refit.window = c("recursive", "moving")[1], cluster = cluster, gfun = "tanh", maxiter1=50000, rseed = 10) cf = convolution(roll, weights = rep(1/10,10), fft.step = 0.001, fft.by = 0.0001, fft.support = c(-1, 1), use.ff = FALSE, trace = 0, support.method = c("user", "adaptive")[1], cluster = cluster) VaR = matrix(NA, ncol = 2, nrow = 500) for(i in 0:499){ qx = qfft(cf, index = i) VaR[i+1,1:2] = qx(c(0.01, 0.05)) } postscript("test1h1.eps", width = 12, height = 12) par(mfrow = c(2,1)) D = as.POSIXct(tail(rownames(dji30retw), 500)) Y = tail(apply(dji30retw[,1:10],1,"mean"), 500) VaRplot(0.01, actual = xts::xts(Y, D), VaR = xts::xts(VaR[,1], D)) VaRplot(0.05, actual = xts::xts(Y, D), VaR = xts::xts(VaR[,2], D)) dev.off() zz <- file("test1h-1.txt", open="wt") sink(zz) cat("\nGOGARCH Rolling Estimation VaR:\n") print(VaRTest(0.01, actual = tail(apply(dji30retw[,1:10],1,"mean"), 500), VaR = VaR[,1])) print(VaRTest(0.05, actual = tail(apply(dji30retw[,1:10],1,"mean"), 500), VaR = VaR[,2])) sink(type="message") sink() close(zz) zz <- file("test1h-2.txt", open="wt") sink(zz) cat("\nGOGARCH Rolling Methods:\n") print(head(sigma(roll))) print(rcor(roll)[,,1,drop=FALSE]) print(rcov(roll)[,,1,drop=FALSE]) print(rcoskew(roll)[,,1]) print(rcokurt(roll)[,,1]) sink(type="message") sink() close(zz) gp = gportmoments(roll, rep(1/10,10)) np = nportmoments(cf) D = as.POSIXct(rownames(tail(dji30retw, 500))) postscript("test1h2.eps", width = 12, height = 12) par(mfrow = c(2,2)) plot(xts::xts(gp[,"mu"], D), main = paste("Portfolio Return Forecast"), ylab = "returns", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np[,"mu"], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") plot(xts::xts(gp[,"sigma"], D), main = paste("Portfolio Sigma Forecast"), ylab = "sigma", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np[,"sigma"], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") plot(xts::xts(gp[,"skewness"], D), main = paste("Portfolio Skew Forecast"), ylab = "skewness", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np[,"skewness"], D), col = 2 ) plot(xts::xts(gp[,"kurtosis"], D), main = paste("Portfolio Kurtosis Forecast"), ylab = "skewness", xlab = "Time", minor.ticks = FALSE, auto.grid = FALSE) lines(xts::xts(np[,"kurtosis"], D), col = 2 ) legend("topright", legend = c("Geometric", "Semi-Analytic(FFT)"), col = 1:2, fill = 1:2, bty = "n") dev.off() toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1i = function(cluster = NULL) { tic = Sys.time() data(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[1], lag = 3), variance.model = list(model = "gjrGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[2], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec, data = dji30ret[,1:5,drop=FALSE], out.sample = 0, cluster = cluster, gfun = "tanh", maxiter1 = 20000, rseed = 12) forc = gogarchforecast(fit, n.ahead = 1) w = matrix(rep(1/5,5), ncol = 5) gm = gportmoments(forc, weights = w) sk = w%*%rcoskew(forc, standardize = FALSE)[,,1]%*%kronecker(t(w),t(w))/gportmoments(forc, weights = w)[1,2,1]^3 ku = w%*%rcokurt(forc, standardize = FALSE)[,,1]%*%kronecker(t(w), kronecker(t(w),t(w)))/gportmoments(forc, weights = w)[1,2,1]^4 cf = convolution(forc, weights = w) nm = nportmoments(cf, weights = w) df = dfft(cf, index=0) m1 = gm[1,1,1] f = function(x) (x-m1)^4*df(x) nme = integrate(f, -Inf, Inf, rel.tol=1e-9, stop.on.error=FALSE)$value/gm[1,2,1]^4 zz <- file("test1i.txt", open="wt") sink(zz) cat("\nGOGARCH Forecast Weighted Kurtosis Differences in Methods:\n") print(all.equal(gm[1,4,1], nme)) print(all.equal(as.numeric(nm[1,4,1]), nme)) print(all.equal(as.numeric(nm[1,4,1]), gm[1,4,1])) print(all.equal(as.numeric(sk), gm[1,3,1])) print(all.equal(as.numeric(ku), gm[1,4,1])) sink(type="message") sink() close(zz) toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) } rmgarch.test1j = function(cluster = NULL) { tic = Sys.time() data(dji30ret) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "sGARCH", garchOrder = c(1,1)), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec = spec, data = dji30ret[1:1010,1:3], out.sample = 10, solver = "solnp", gfun = "tanh", maxiter1 = 20000, rseed = 25) forc = gogarchforecast(fit, n.ahead = 1, n.roll = 10) fc = matrix(fitted(forc), ncol = 3, nrow=11, byrow=TRUE) p = fit@model$modelinc[2] simM = matrix(NA, ncol = 3, nrow = 11) filt = gogarchfilter(fit, data = dji30ret[1:1010,1:3], out.sample = 0, n.old = 1000) T = fit@model$modeldata$T for(i in 1:11){ preres = fit@mfit$Y[(T-p+i):(T-1+i),] presigma = filt@mfilter$factor.sigmas[(T-p+i):(T-1+i),] prereturns = fit@model$modeldata$data[(T-p+i):(T-1+i),,drop=FALSE] sim = gogarchsim(fit, n.sim = 1, m.sim = 500, startMethod = "sample", preres = preres, presigma = presigma, prereturns = prereturns) simx = t(sapply(sim@msim$seriesSim, FUN = function(x) x)) simres = t(sapply(sim@msim$residSim, FUN = function(x) x)) simM[i, ] = simx[1,] - simres[1,] } zz <- file("test1j1.txt", open="wt") sink(zz) cat("\nAR-GOGARCH Rolling Forecast vs Rolling Simulation Check:\n") print(all.equal(simM, fc)) sink(type="message") sink() close(zz) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[3], lag = 2), variance.model = list(model = "sGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec = spec, data = dji30ret[1:1010,1:3], out.sample = 10, solver = "solnp", gfun = "tanh", maxiter1 = 20000, rseed = 25) forc = gogarchforecast(fit, n.ahead = 1, n.roll = 10) fc = matrix(fitted(forc), ncol = 3, nrow=11, byrow=TRUE) p = fit@model$modelinc[3] simM = matrix(NA, ncol = 3, nrow = 11) filt = gogarchfilter(fit, data = dji30ret[1:1010,1:3], out.sample = 0, n.old = 1000) T = fit@model$modeldata$T for(i in 1:11){ preres = fit@mfit$Y[(T-p+i):(T-1+i),] presigma = filt@mfilter$factor.sigmas[(T-p+i):(T-1+i),] prereturns = fit@model$modeldata$data[(T-p+i):(T-1+i),,drop=FALSE] sim = gogarchsim(fit, n.sim = 1, m.sim = 100, startMethod = "sample", preres = preres, presigma = presigma, prereturns = prereturns) simx = t(sapply(sim@msim$seriesSim, FUN = function(x) x)) simres = t(sapply(sim@msim$residSim, FUN = function(x) x)) simM[i, ] = simx[1,] - simres[1,] } zz <- file("test1j2.txt", open="wt") sink(zz) cat("\nVAR-GOGARCH Rolling Forecast vs Rolling Simulation Check:\n") print(all.equal(simM, fc)) sink(type="message") sink() close(zz) cnames = colnames(dji30ret[,1:3]) spec = gogarchspec( mean.model = list(model = c("constant", "AR", "VAR")[2], lag = 2), variance.model = list(model = "sGARCH", garchOrder = c(1,1), submodel = NULL, variance.targeting = FALSE), distribution.model = c("mvnorm", "manig", "magh")[1], ica = c("fastica", "radical")[1]) fit = gogarchfit(spec = spec, data = dji30ret[1:1010,1:3], out.sample = 10, solver = "solnp") forc = gogarchforecast(fit, n.ahead = 1, n.roll = 10) fc = matrix(fitted(forc), ncol = 3, nrow=11, byrow=TRUE) fs = matrix(sigma(forc, factors=FALSE), ncol = 3, nrow=11, byrow=TRUE) p = fit@model$modelinc[2] simX = vector(mode = "list", length = 11) filt = gogarchfilter(fit, data = dji30ret[1:1010,1:3], out.sample = 0, n.old = 1000) T = fit@model$modeldata$T for(i in 1:11){ preres = fit@mfit$Y[(T-p+i):(T-1+i),] presigma = filt@mfilter$factor.sigmas[(T-p+i):(T-1+i),] prereturns = fit@model$modeldata$data[(T-p+i):(T-1+i),,drop=FALSE] sim = gogarchsim(fit, n.sim = 1, m.sim = 500, startMethod = "sample", preres = preres, presigma = presigma, prereturns = prereturns) simX[[i]] = t(sapply(sim@msim$seriesSim, FUN = function(x) x)) } simM = t(sapply(simX, FUN = function(x) colMeans(x))) simS = t(sapply(simX, FUN = function(x) apply(x, 2, "sd"))) postscript("test1j.eps", width = 12, height = 12) par(mfrow=c(2,2)) boxplot(simX[[1]], main = "T+1", names = cnames) points(fc[1,], col = 3, lwd = 4, pch =12) points(simM[1,], col = 2, lwd = 2, pch = 10) points(fc[1,]+3*fs[1,], col = 4, lwd = 2, pch = 14) points(fc[1,]-3*fs[1,], col = 4, lwd = 2, pch = 14) legend("bottomleft", c("Mean[sim]", "Mean[forc]", "3sd"), col = c(2,3,4), pch=c(10,12,14), bty="n", lwd=c(2,4,2), cex=0.7) boxplot(simX[[4]], main = "T+4", names = cnames) points(fc[4,], col = 3, lwd = 4, pch =12) points(simM[4,], col = 2, lwd = 2, pch = 10) points(fc[4,]+3*fs[4,], col = 4, lwd = 2, pch = 14) points(fc[4,]-3*fs[4,], col = 4, lwd = 2, pch = 14) legend("bottomleft", c("Mean[sim]", "Mean[forc]", "3sd"), col = c(2,3,4), pch=c(10,12,14), bty="n", lwd=c(2,4,2), cex=0.7) boxplot(simX[[6]], main = "T+6", names = cnames) points(fc[6,], col = 3, lwd = 4, pch =12) points(simM[6,], col = 2, lwd = 2, pch = 10) points(fc[6,]+3*fs[6,], col = 4, lwd = 2, pch = 14) points(fc[6,]-3*fs[6,], col = 4, lwd = 2, pch = 14) legend("bottomleft", c("Mean[sim]", "Mean[forc]", "3sd"), col = c(2,3,4), pch=c(10,12,14), bty="n", lwd=c(2,4,2), cex=0.7) boxplot(simX[[11]], main = "T+11", names = cnames) points(fc[11,], col = 3, lwd = 4, pch =12) points(simM[11,], col = 2, lwd = 2, pch = 10) points(fc[11,]+3*fs[11,], col = 4, lwd = 2, pch = 14) points(fc[11,]-3*fs[11,], col = 4, lwd = 2, pch = 14) legend("bottomleft", c("Mean[sim]", "Mean[forc]", "3sd"), col = c(2,3,4), pch=c(10,12,14), bty="n", lwd=c(2,4,2), cex=0.7) dev.off() toc = Sys.time()-tic cat("Elapsed:", toc, "\n") return(toc) }
plot.fh <- function(x, label = "orig", color = c("blue", "lightblue3"), gg_theme = NULL, cooks = TRUE, range = NULL, ...) { plot_check(x = x, label = label, color = color, cooks = cooks, range = range) if (any(is.na(x$model$std_real_residuals))) { residuals <- x$model$std_real_residuals[!is.na(x$model$std_real_residuals)] warning("At least one value in the standardized realized residuals is NA. Only numerical values are plotted.") } else { residuals <- x$model$std_real_residuals } residuals <- (residuals - mean(residuals)) / sd(residuals) rand.eff <- x$model$random_effects srand.eff <- (rand.eff - mean(rand.eff)) / sd(rand.eff) tmp <- srand.eff NextMethod("plot", cooks = FALSE, boxcox = FALSE, cook_df = NULL, indexer = NULL, likelihoods = NULL, opt_lambda = FALSE, residuals = residuals, srand.eff = srand.eff, tmp = tmp ) }
plot_graph <- function(CytomeTreeObj, Ecex = 1, Ecolor = 8, Vcex = .8, Vcolor = 0, ...) { if(!methods::is(CytomeTreeObj, "CytomeTree")){ stop("CytomeTreeObj must be of class CytomeTree.") } Tree <- CytomeTreeObj$mark_tree if(is.null(Tree)) { return(cat("CytomeTree found a single population.\n")) } Tree_level <- length(Tree) adj_list <- c() cptleaf <- 1 for(level in 1:(Tree_level - 1)) { cpt <- 1 NnodeLevel <- length(Tree[[level]]) for(Nnode in 1:NnodeLevel){ if(Tree[[level]][[Nnode]] == as.character(cptleaf)){ cptleaf <- cptleaf + 1 next } L_child <- Tree[[level + 1]][[cpt]] R_child <- Tree[[level + 1]][[cpt + 1]] cpt <- cpt + 2 adj_list <- rbind(adj_list, cbind( Tree[[level]][[Nnode]], c(L_child, R_child), c("-","+") ) ) } } g <- graph.data.frame(data.frame(parent=as.character(adj_list[,1]), node=as.character(adj_list[,2]), text=adj_list[,3]) ) E(g)$label.cex <- Ecex E(g)$color <- Ecolor V(g)$label.cex <- Vcex V(g)$color <- Vcolor igraph::plot.igraph(g, layout = igraph::layout_as_tree(g), edge.label=E(g)$text, ...) }
"chdage"
impute_IMU <- function(object, verbose) { if (verbose) cat( "\r Attending to any gaps in the file" ) imu_names <- setdiff(names(object), "Timestamp") any_gaps <- (!stats::complete.cases( object[ ,imu_names] )) %>% {do.call( data.frame, rle(.) )} %>% {cbind(., stop_index = cumsum(.$lengths) )} %>% {cbind(., start_index = .$stop_index - .$lengths + 1 )} %>% { .[.$values, ] } if (!length(any_gaps)) return(object) gap_indices <- do.call( c, mapply( seq, from = any_gaps$start_index, to = any_gaps$stop_index, SIMPLIFY = FALSE )) object[gap_indices, imu_names] <- 0 object }
context("ProposalLineItemService") skip("Reduce Total Test Runtime") rdfp_options <- readRDS("rdfp_options.rds") options(rdfp.network_code = rdfp_options$network_code) options(rdfp.httr_oauth_cache = FALSE) options(rdfp.application_name = rdfp_options$application_name) options(rdfp.client_id = rdfp_options$client_id) options(rdfp.client_secret = rdfp_options$client_secret) dfp_auth(token = "rdfp_token.rds") test_that("dfp_createProposalLineItems", { expect_true(TRUE) }) test_that("dfp_getProposalLineItemsByStatement", { request_data <- list('filterStatement'=list('query'="WHERE status='ACTIVE'")) expect_message(try(dfp_getProposalLineItemsByStatement(request_data), silent=T), 'PERMISSION_DENIED') expect_error(dfp_getProposalLineItemsByStatement(request_data)) }) test_that("dfp_performProposalLineItemAction", { expect_true(TRUE) }) test_that("dfp_updateProposalLineItems", { expect_true(TRUE) })
pre_process_data <- function(data, x, y, facet = NULL, highlight = NULL, highlight_color = NULL, sort = TRUE, top_n = NULL, threshold = NULL, other = FALSE, limit = NULL) { if (!is.null(limit)) { suppressWarnings(fun_name <- rlang::ctxt_frame(n = 4)$fn_name) what <- paste0(fun_name, "(limit=)") with <- paste0(fun_name, "(top_n=)") lifecycle::deprecate_warn("0.2.0", what, with, env = parent.frame()) top_n <- limit } if (!is.null(top_n) && !sort) { rlang::abort("`top_n` must not be set when `sort = FALSE`.") } if (!is.null(threshold) && !sort) { rlang::abort("`threshold` must not be set when `sort = FALSE`.") } if (!is.null(top_n) && !is.null(threshold)) { rlang::abort("`top_n` and `threshold` must not be used simultaneously.") } if (is.null(threshold) && other) { rlang::abort("`threshold` must be set when `other = TRUE`") } x <- rlang::enquo(x) y <- rlang::enquo(y) facet <- rlang::enquo(facet) has_facet <- !rlang::quo_is_null(facet) if (other && has_facet) { rlang::abort("`other` and `facet` cannot be used in conjunction currently.") } if (rlang::quo_is_missing(y)) { if (has_facet) { data <- dplyr::count(data, !!facet, !!x) } else { data <- dplyr::count(data, !!x) } y <- rlang::sym("n") } if (!is.null(highlight)) { if (!is_highlight_spec(highlight)) { highlight <- highlight_spec(highlight) } data$.color <- create_highlight_colors( dplyr::pull(data, !!x), highlight ) } if (has_facet) { data <- dplyr::group_by(data, !!facet) } if (sort) { if (!is.null(top_n)) { data <- dplyr::top_n(data, top_n, !!y) } else if (!is.null(threshold)) { data <- apply_threshold(data, !!x, !!y, threshold, other) } data <- dplyr::ungroup(data) if (has_facet) { data <- data %>% dplyr::mutate(!!x := reorder_within(!!x, !!y, !!facet)) %>% dplyr::arrange(!!facet, !!y) } else { data <- dplyr::mutate(data, !!x := reorder(!!x, !!y, other = other)) } } data } apply_threshold <- function(data, x, y, threshold, other) { x <- rlang::enquo(x) y <- rlang::enquo(y) if (other) { data %>% dplyr::mutate(!!x := ifelse(!!y > threshold, as.character(!!x), "Other")) %>% dplyr::group_by(!!x) %>% dplyr::summarise(!!y := sum(!!y)) %>% dplyr::ungroup() } else { data %>% dplyr::arrange(!!y) %>% dplyr::filter(!!y > threshold) } }
full_factor <- function( dataset, vars, method = "PCA", hcor = FALSE, nr_fact = 1, rotation = "varimax", data_filter = "", envir = parent.frame() ) { df_name <- if (is_string(dataset)) dataset else deparse(substitute(dataset)) dataset <- get_data(dataset, vars, filt = data_filter, envir = envir) %>% mutate_if(is.Date, as.numeric) rm(envir) if (length(vars) < ncol(dataset)) vars <- colnames(dataset) anyCategorical <- sapply(dataset, function(x) is.numeric(x) || is.Date(x)) == FALSE nrObs <- nrow(dataset) nrFac <- max(1, as.numeric(nr_fact)) if (nrFac > ncol(dataset)) { return("The number of factors cannot exceed the number of variables" %>% add_class("full_factor")) nrFac <- ncol(dataset) } if (hcor) { cmat <- try(sshhr(polycor::hetcor(dataset, ML = FALSE, std.err = FALSE)), silent = TRUE) dataset <- mutate_all(dataset, radiant.data::as_numeric) if (inherits(cmat, "try-error")) { warning("Calculating the heterogeneous correlation matrix produced an error.\nUsing standard correlation matrix instead") hcor <- "Calculation failed" cmat <- cor(dataset) } else { cmat <- cmat$correlations } } else { dataset <- mutate_all(dataset, radiant.data::as_numeric) cmat <- cor(dataset) } if (method == "PCA") { fres <- psych::principal( cmat, nfactors = nrFac, rotate = rotation, scores = FALSE, oblique.scores = FALSE ) m <- fres$loadings[, colnames(fres$loadings)] cscm <- m %*% solve(crossprod(m)) fres$scores <- as.matrix(mutate_all(dataset, radiant.data::standardize)) %*% cscm } else { fres <- try(psych::fa(cmat, nfactors = nrFac, rotate = rotation, oblique.scores = FALSE, fm = "ml"), silent = TRUE) if (inherits(fres, "try-error")) { return( "An error occured. Increase the number of variables or reduce the number of factors" %>% add_class("full_factor") ) } if (sum(anyCategorical) == ncol(dataset) && isTRUE(hcor)) { isMaxMinOne <- sapply(dataset, function(x) (max(x, na.rm = TRUE) - min(x, na.rm = TRUE) == 1)) dataset <- mutate_if(dataset, isMaxMinOne, ~ (. - min(., na.rm = TRUE)) / (max(., na.rm = TRUE) - min(., na.rm = TRUE))) .irt.tau <- function() { tau <- psych::irt.tau(dataset) m <- fres$loadings[, colnames(fres$loadings), drop = FALSE] nf <- dim(m)[2] max_dat <- max(dataset) min_dat <- min(dataset) if (any(tau == Inf)) { tau[tau == Inf] <- max((max_dat - min_dat) * 5, 4) warning("Tau values of Inf found. Adjustment applied") } if (any(tau == -Inf)) { tau[tau == -Inf] <- min(-(max_dat - min_dat) * 5, -4) warning("Tau values of -Inf found. Adjustment applied") } diffi <- list() for (i in 1:nf) diffi[[i]] <- tau/sqrt(1 - m[, i]^2) discrim <- m/sqrt(1 - m^2) new.stats <- list(difficulty = diffi, discrimination = discrim) psych::score.irt.poly(new.stats, dataset, cut = 0, bounds = c(-4, 4)) } scores <- try(.irt.tau(), silent = TRUE) rm(.irt.tau) if (inherits(scores, "try-error")) { return( paste0("An error occured estimating latent factor scores using psychIrt. The error message was:\n\n", attr(scores, 'condition')$message) %>% add_class("full_factor") ) } else { fres$scores <- apply(scores[,1:nrFac, drop=FALSE], 2, radiant.data::standardize) rm(scores) colnames(fres$scores) <- colnames(fres$loadings) } } else { fres$scores <- psych::factor.scores(as.matrix(dataset), fres, method = "Thurstone")$scores } } floadings <- fres$loadings %>% { dn <- dimnames(.) matrix(., nrow = length(dn[[1]])) %>% set_colnames(., dn[[2]]) %>% set_rownames(., dn[[1]]) %>% data.frame(stringsAsFactors = FALSE) } as.list(environment()) %>% add_class("full_factor") } summary.full_factor <- function( object, cutoff = 0, fsort = FALSE, dec = 2, ... ) { if (is.character(object)) return(cat(object)) cat("Factor analysis\n") cat("Data :", object$df_name, "\n") if (!radiant.data::is_empty(object$data_filter)) { cat("Filter :", gsub("\\n", "", object$data_filter), "\n") } cat("Variables :", paste0(object$vars, collapse = ", "), "\n") cat("Factors :", object$nr_fact, "\n") cat("Method :", object$method, "\n") cat("Rotation :", object$rotation, "\n") cat("Observations:", format_nr(object$nrObs, dec = 0), "\n") if (is.character(object$hcor)) { cat(paste0("Correlation : Pearson (adjustment using polycor::hetcor failed)\n")) } else if (isTRUE(object$hcor)) { if (sum(object$anyCategorical) > 0) { cat(paste0("Correlation : Heterogeneous correlations using polycor::hetcor\n")) } else { cat(paste0("Correlation : Pearson\n")) } } else { cat("Correlation : Pearson\n") } if (sum(object$anyCategorical) > 0) { if (isTRUE(object$hcor)) { cat("** Variables of type {factor} are assumed to be ordinal **\n") if (object$method == "PCA") { cat("** Factor scores are biased when using PCA when one or more {factor} variables are included **\n\n") } else if (sum(object$anyCategorical) == length(object$vars)) { cat("** Factor scores calculated using psych::scoreIrt **\n\n") } else if (sum(object$anyCategorical) < length(object$vars)) { cat("** Factor scores are biased when a mix of {factor} and numeric variables are used **\n\n") } } else { cat("** Variables of type {factor} included without adjustment **\n\n") } } else if (isTRUE(object$hcor)) { cat("** No variables of type {factor} selected. No adjustment applied **\n\n") } else { cat("\n") } cat("Factor loadings:\n") clean_loadings(object$floadings, cutoff = cutoff, fsort = fsort, dec = dec, repl = "") %>% print() cat("\nFit measures:\n") colSums(object$floadings ^ 2) %>% rbind(., . / nrow(object$floadings)) %>% rbind(., cumsum(.[2, ])) %>% as.data.frame(stringsAsFactors = FALSE) %>% format_df(dec = dec) %>% set_rownames(c("Eigenvalues", "Variance %", "Cumulative %")) %>% print() cat("\nAttribute communalities:") data.frame(1 - object$fres$uniqueness, stringsAsFactors = FALSE) %>% format_df(dec = dec, perc = TRUE) %>% set_rownames(object$vars) %>% set_colnames("") %>% print() cat("\nFactor scores (max 10 shown):\n") as.data.frame(object$fres$scores, stringsAsFactors = FALSE) %>% .[1:min(nrow(.), 10), , drop = FALSE] %>% format_df(dec = dec) %>% print(row.names = FALSE) } plot.full_factor <- function(x, plots = "attr", shiny = FALSE, custom = FALSE, ...) { if (is.character(x)) { return(plot(x = 1, type = "n", main = x, axes = FALSE, xlab = "", ylab = "")) } else if (x$fres$factors < 2) { x <- "Plots require two or more factors" return(plot(x = 1, type = "n", main = x, axes = FALSE, xlab = "", ylab = "")) } df <- x$floadings scores <- as.data.frame(x$fres$scores) plot_scale <- if ("resp" %in% plots) max(scores) else 1 rnames <- rownames(df) cnames <- colnames(df) plot_list <- list() for (i in 1:(length(cnames) - 1)) { for (j in (i + 1):length(cnames)) { i_name <- cnames[i] j_name <- cnames[j] df2 <- cbind(df[, c(i_name, j_name)], rnames) p <- ggplot(df2, aes_string(x = i_name, y = j_name)) + theme(legend.position = "none") + coord_cartesian(xlim = c(-plot_scale, plot_scale), ylim = c(-plot_scale, plot_scale)) + geom_vline(xintercept = 0) + geom_hline(yintercept = 0) if ("resp" %in% plots) { p <- p + geom_point(data = scores, aes_string(x = i_name, y = j_name), alpha = 0.5) } if ("attr" %in% plots) { p <- p + geom_point(aes_string(color = "rnames")) + ggrepel::geom_text_repel(aes_string(color = "rnames", label = "rnames")) + geom_segment( aes_string(x = 0, y = 0, xend = i_name, yend = j_name, color = "rnames"), size = 0.5, linetype = "dashed", alpha = 0.5 ) } plot_list[[paste0(i_name, "_", j_name)]] <- p } } if (length(plot_list) > 0) { if (custom) { if (length(plot_list) == 1) plot_list[[1]] else plot_list } else { patchwork::wrap_plots(plot_list, ncol = min(length(plot_list), 2)) %>% {if (shiny) . else print(.)} } } } store.full_factor <- function(dataset, object, name = "", ...) { if (radiant.data::is_empty(name)) name <- "factor" fscores <- as.data.frame(object$fres$scores, stringsAsFactors = FALSE) indr <- indexr(dataset, object$vars, object$data_filter) fs <- data.frame(matrix(NA, nrow = indr$nr, ncol = ncol(fscores)), stringsAsFactors = FALSE) fs[indr$ind, ] <- fscores dataset[, sub("^[a-zA-Z]+([0-9]+)$", paste0(name, "\\1"), colnames(fscores))] <- fs dataset } clean_loadings <- function( floadings, cutoff = 0, fsort = FALSE, dec = 8, repl = NA ) { if (fsort) { floadings <- select(psych::fa.sort(floadings), -order) } if (cutoff == 0) { floadings %<>% round(dec) } else { ind <- abs(floadings) < cutoff floadings %<>% round(dec) floadings[ind] <- repl } floadings }
.mpiopt_init <- function(envir = .GlobalEnv){ if(!exists(".pbd_env", envir = envir)){ envir$.pbd_env <- new.env() } envir$.pbd_env$SPMD.CT <- SPMD.CT() envir$.pbd_env$SPMD.OP <- SPMD.OP() envir$.pbd_env$SPMD.IO <- SPMD.IO() envir$.pbd_env$SPMD.TP <- SPMD.TP() envir$.pbd_env$SPMD.DT <- SPMD.DT() envir$.pbd_env$SPMD.NB.BUFFER <- list() invisible() }
require(knitr) opts_chunk$set( dev="pdf", fig.path="figures/", fig.height=3, fig.width=4, out.width=".47\\textwidth", fig.keep="high", fig.show="hold", fig.align="center", prompt=TRUE, comment=NA ) require(Sleuth3) require(mosaic) require(MASS) trellis.par.set(theme=col.mosaic()) set.seed(123) knit_hooks$set(inline = function(x) { if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) x = as.character(x) h = knitr:::hilight_source(x, 'latex', list(prompt=FALSE, size='normalsize')) h = gsub("([_ h = gsub('(["\'])', '\\1{}', h) gsub('^\\\\begin\\{alltt\\}\\s*|\\\\end\\{alltt\\}\\s*$', '', h) }) showOriginal=FALSE showNew=TRUE print.pval = function(pval) { threshold = 0.0001 return(ifelse(pval < threshold, paste("p<", sprintf("%.4f", threshold), sep=""), ifelse(pval > 0.1, paste("p=",round(pval, 2), sep=""), paste("p=", round(pval, 3), sep="")))) } trellis.par.set(theme=col.mosaic()) options(digits=4) summary(case1201) pairs(~ Takers+Rank+Years+Income+Public+Expend+SAT, data=case1201) panel.hist = function(x, ...) { usr = par("usr"); on.exit(par(usr)) par(usr = c(usr[1:2], 0, 1.5) ) h = hist(x, plot=FALSE) breaks = h$breaks; nB = length(breaks) y = h$counts; y = y/max(y) rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...) } panel.lm = function(x, y, col=par("col"), bg=NA, pch=par("pch"), cex=1, col.lm="red", ...) { points(x, y, pch=pch, col=col, bg=bg, cex=cex) ok = is.finite(x) & is.finite(y) if (any(ok)) abline(lm(y[ok] ~ x[ok])) } pairs(~ Takers+Rank+Years+Income+Public+Expend+SAT, lower.panel=panel.smooth, diag.panel=panel.hist, upper.panel=panel.lm, data=case1201) require(car) scatterplotMatrix(~ Takers+Rank+Years+Income+Public+Expend+SAT, diagonal="histogram", smooth=F, data=case1201) lm1 = lm(SAT ~ Rank+log(Takers), data=case1201) summary(lm1) lm2 = lm(SAT ~ log2(Takers)+Income+Years+Public+Expend+Rank, data=case1201) summary(lm2) plot(lm2, which=4) case1201r = case1201[-c(29),] lm3 = lm(SAT ~ log2(Takers) + Income+ Years + Public + Expend + Rank, data=case1201r) anova(lm3) crPlots(lm2, term = ~ Expend) crPlots(lm3, term = ~ Expend) lm4 = lm(SAT ~ log2(Takers), data=case1201r) stepAIC(lm4, scope=list(upper=lm3, lower=~1), direction="forward", trace=FALSE)$anova stepAIC(lm3, direction="backward", trace=FALSE)$anova stepAIC(lm3, direction="both", trace=FALSE)$anova lm5 = lm(SAT ~ log2(Takers) + Expend + Years + Rank, data=case1201r) summary(lm5) sigma5 = summary(lm5)$sigma^2 sigma3 = summary(lm3)$sigma^2 n = 49 p = 4+1 Cp=(n-p)*sigma5/sigma3+(2*p-n) Cp require(leaps) explanatory = with(case1201r, cbind(log(Takers), Income, Years, Public, Expend, Rank)) with(case1201r, leaps(explanatory, SAT, method="Cp"))$which[27,] with(case1201r, leaps(explanatory, SAT, method="Cp"))$Cp[27] plot(lm5, which=1) lm7 = lm(SAT ~ Expend, data=case1201r) summary(lm7) lm8 = lm(SAT ~ Income + Expend, data=case1201r) summary(lm8) summary(case1202) panel.hist = function(x, ...) { usr = par("usr"); on.exit(par(usr)) par(usr = c(usr[1:2], 0, 1.5) ) h = hist(x, plot=FALSE) breaks = h$breaks; nB = length(breaks) y = h$counts; y = y/max(y) rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...) } panel.lm = function(x, y, col=par("col"), bg=NA, pch=par("pch"), cex=1, col.lm="red", ...) { points(x, y, pch=pch, col=col, bg=bg, cex=cex) ok = is.finite(x) & is.finite(y) if (any(ok)) abline(lm(y[ok] ~ x[ok])) } pairs(~ Bsal+Sex+Senior+Age+Educ+Exper+log(Bsal), lower.panel=panel.smooth, diag.panel=panel.hist, upper.panel=panel.lm, data=case1202) require(leaps) explanatory1 = with(case1202, cbind(Senior, Age, Educ, Exper, Senior*Educ, Age*Educ, Age*Exper)) with(case1202, leaps(explanatory1, log(Bsal), method="Cp"))$which[55,] with(case1202, leaps(explanatory1, log(Bsal), method="Cp"))$Cp[55] with(case1202, leaps(explanatory1, log(Bsal), method="Cp"))$which[49,] with(case1202, leaps(explanatory1, log(Bsal), method="Cp"))$Cp[49] BIC(lm(log(Bsal) ~ Senior+Age+Educ+Exper+Age*Educ+Age*Exper, data=case1202)) BIC(lm(log(Bsal) ~ Senior+Age+Educ+Exper+(Exper)^2+Age*Educ, data=case1202)) lm1 = lm(log(Bsal) ~ Senior + Age + Educ + Exper + Age*Educ + Age*Exper, data=case1202) summary(lm1) lm2 = lm(log(Bsal) ~ Senior + Age + Educ + Exper + Age*Educ + Age*Exper + Sex, data=case1202) summary(lm2)
get_default_netmhc2pan_version <- function() { "3.2" }
badge_projectstatus <- function(status = "concept"){ name <- c("concept", "wip", "suspended", "abandoned", "active", "inactive", "unsupported", "moved") if(!status %in% name)stop("status needs to be one of concept, wip, suspended, abandoned, active, inactive, unsupported, or moved") projectstatus <- paste0("https://www.repostatus.org/badges/latest/",status, "_md.txt" ) repostatus <- readLines(con = projectstatus, encoding = "UTF-8" ) repostatus } licbadgebuilder <- function(licensetype){ switch (licensetype, "GPL-2" = {badgepaste("https://img.shields.io/badge/license-GPL--2-blue.svg", "https://www.gnu.org/licenses/old-licenses/gpl-2.0.html")}, "GPL-3" = {badgepaste("https://img.shields.io/badge/license-GPL--3-blue.svg", "https://www.gnu.org/licenses/gpl-3.0.en.html")}, "MIT" = {badgepaste("https://img.shields.io/github/license/mashape/apistatus.svg", "https://choosealicense.com/licenses/mit/")}, "CC0" = {badgepaste("https://img.shields.io/badge/license-CC0-blue.svg", "https://choosealicense.com/licenses/cc0-1.0/")} ) } badge_travis <- function(ghaccount = NULL, ghrepo = NULL, branch = NULL, location = "."){ if(any(is.null(ghaccount), is.null(ghrepo), is.null(branch))){ credentials<- github_credentials_helper(ghaccount = ghaccount, ghrepo = ghrepo, branch = branch, location = location ) }else{ credentials <- list( ghaccount = ghaccount, ghrepo = ghrepo, branch = branch ) } referlink <- paste0("https://travis-ci.org/", credentials$ghaccount,"/", credentials$ghrepo) imagelink <- paste0(referlink, ".svg?branch=",credentials$branch) badge <-badgepaste(imagelink, referlink, name = "Build Status") badge } badge_codecov <- function(ghaccount = NULL, ghrepo = NULL, branch=NULL, location = "."){ if(any(is.null(ghaccount), is.null(ghrepo), is.null(branch))){ credentials<- github_credentials_helper(ghaccount = ghaccount, ghrepo = ghrepo, branch = branch, location = location ) }else{ credentials <- list( ghaccount = ghaccount, ghrepo = ghrepo, branch = branch ) } referlink <- paste0("https://codecov.io/gh/", credentials$ghaccount, "/", credentials$ghrepo) imagelink <- paste0(referlink, "/branch/", credentials$branch, "/graph/badge.svg" ) codecovbadge <-badgepaste(imagelink,referlink, name = "codecov") codecovbadge } badge_minimal_r_version <- function(chunk = TRUE){ r_chunk <- c( "```{r, echo = FALSE}", eval(expression("dep <- as.vector(read.dcf('DESCRIPTION')[, 'Depends'])")), eval(expression("m <- regexpr('R *\\\\(>= \\\\d+.\\\\d+.\\\\d+\\\\)', dep)")), eval(expression("rm <- regmatches(dep, m)")), eval(expression("rvers <- gsub('.*(\\\\d+.\\\\d+.\\\\d+).*', '\\\\1', rm)")), "```") img_link <- paste0("https://img.shields.io/badge/R%3E%3D-", "`r rvers`", "-6666ff.svg") referlink <- "https://cran.r-project.org/" result <- c(if(chunk){r_chunk}, badgepaste(img_link, referlink, name = "minimal R version")) result } badge_cran <- function(packagename){ img_link <- paste0("https://www.r-pkg.org/badges/version/", packagename) refer_link <- paste0("https://cran.r-project.org/package=", packagename) badgepaste(imagelink =img_link, referlink = refer_link, name = "CRAN_Status_Badge") } badge_cran_version_ago <- function(packagename){ img_link <- paste0("https://www.r-pkg.org/badges/version-ago/", packagename) refer_link <- paste0("https://cran.r-project.org/package=", packagename) badgepaste(imagelink =img_link, referlink = refer_link, name = "CRAN_Status_Badge_version_ago") } badge_cran_version_release <- function(packagename){ img_link <- paste0("https://www.r-pkg.org/badges/version-last-release/", packagename) refer_link <- paste0("https://cran.r-project.org/package=", packagename) badgepaste(imagelink =img_link, referlink = refer_link, name = "CRAN_Status_Badge_version_last_release") } badge_cran_ago <- function(packagename){ img_link <- paste0("https://www.r-pkg.org/badges/ago/", packagename) refer_link <- paste0("https://cran.r-project.org/package=", packagename) badgepaste(imagelink =img_link, referlink = refer_link, name = "CRAN_time_from_release") } badge_cran_date <- function(packagename){ img_link <- paste0("https://www.r-pkg.org/badges/last-release/", packagename) refer_link <- paste0("https://cran.r-project.org/package=", packagename) badgepaste(imagelink =img_link, referlink = refer_link, name = "CRAN_latest_release_date") } badge_cran_downloads <- function(packagename, period = NULL){ if(is.null(period)){ paste_thing <- packagename }else{ if(!period %in% c("last-week", "last-day","grand-total"))stop("Use last-week, last-day, or grand-total for period") paste_thing <- paste0(period, "/",packagename) } badgepaste(imagelink = paste0("https://cranlogs.r-pkg.org/badges/",paste_thing), referlink = paste0("https://cran.r-project.org/package=", packagename), name = "metacran downloads") } badge_packageversion <- function(chunk = TRUE){ r_chunk <- c( "```{r, echo = FALSE}", eval(expression("version <- as.vector(read.dcf('DESCRIPTION')[, 'Version'])")), eval(expression("version <- gsub('-', '.', version)")), "```") img_link <- paste0("https://img.shields.io/badge/Package%20version-", "`r version`", "-orange.svg?style=flat-square") referlink <- "commits/master" result <- c( if(chunk){r_chunk}, badgepaste(img_link, referlink, name = "packageversion")) result } badge_last_change <- function(location = "."){ badgepaste(imagelink = paste0("https://img.shields.io/badge/last%20change-", "`r ", "gsub('-', '--', Sys.Date())", "`", "-yellowgreen.svg"), referlink = "/commits/master", name = "Last-changedate") } badge_last_change_static <- function(date = NULL){ date_1 <- ifelse(is.null(date), as.character(Sys.Date()), date) paste_ready_date <- gsub('-', '--', date_1) badgepaste(imagelink = paste0("https://img.shields.io/badge/last%20change-", paste_ready_date,"-yellowgreen.svg"), referlink = "/commits/master", name = "Last-changedate") } badge_rdocumentation <- function(packagename){ badgepaste( imagelink = paste0("https://www.rdocumentation.org/badges/version/", packagename), referlink = paste0("https://www.rdocumentation.org/packages/", packagename), name = "Rdoc" ) } badge_github_star <- function(ghaccount = NULL, ghrepo = NULL, branch = NULL, location = "."){ credentials<- github_credentials_helper(ghaccount = ghaccount, ghrepo = ghrepo, branch = branch, location = location ) badgepaste( imagelink = paste0("https://githubbadges.com/star.svg?user=", credentials$ghaccount, "&repo=", credentials$ghrepo ), referlink = paste0("https://github.com/",credentials$ghaccount,"/", credentials$ghrepo), name = "star this repo" ) } badge_github_fork <- function(ghaccount = NULL, ghrepo = NULL, location = "."){ credentials<- github_credentials_helper(ghaccount = ghaccount, ghrepo = ghrepo, branch = NULL, location = location ) badgepaste( imagelink = paste0("https://img.shields.io/github/forks/", credentials$ghaccount, "/", credentials$ghrepo,".svg?style=social&label=Fork"), referlink = paste0("https://github.com/",credentials$ghaccount,"/", credentials$ghrepo,"/fork"), name = "fork this repo" ) } badge_license <- function(license = NULL, location = "."){ if(is.null(license)){ description <- read.dcf(file.path(location, "DESCRIPTION")) licensetype <- as.vector(description[1, "License"]) if(length(licensetype) == 0) stop("No license was described in DESCRIPTION") } else { licensetype <- license } recommended_licenses <- c( "GPL-2", "GPL-3", "MIT" ) if(!(licensetype %in% recommended_licenses)){ message("the license ", licensetype, " is not recommended for R packages") badgepaste(imagelink = paste0("https://img.shields.io/badge/license-", gsub("-","--", licensetype), "-lightgrey.svg"), referlink = "https://choosealicense.com/") } else { licbadgebuilder(licensetype) } } badge_rank <- function(packagename){ badgepaste( imagelink = paste0("https://www.rpackages.io/badge/", packagename, ".svg"), referlink = paste0("https://www.rpackages.io/package/", packagename), name = "rpackages.io rank" ) } badge_thanks_md <- function(add_file = TRUE){ if(!file.exists("THANKS.md") & add_file ){file.create("THANKS.md")} badgepaste( imagelink = "https://img.shields.io/badge/THANKS-md-ff69b4.svg", referlink = "THANKS.md", name = "thanks-md" ) } badge_lifecycle <- function(lifecycle = "experimental"){ lifecycle <- tolower(lifecycle) if(lifecycle == "maturing"){ badge = "https://img.shields.io/badge/lifecycle-maturing-blue.svg" }else if(lifecycle == "stable"){ badge = "https://img.shields.io/badge/lifecycle-stable-brightgreen.svg" }else if(lifecycle == "questioning"){ badge = "https://img.shields.io/badge/lifecycle-questioning-blue.svg" }else if(lifecycle == "retired"){ badge = "https://img.shields.io/badge/lifecycle-retired-orange.svg" }else if(lifecycle == "dormant"){ badge = "https://img.shields.io/badge/lifecycle-dormant-blue.svg" }else if(lifecycle == "experimental"){ badge = "https://img.shields.io/badge/lifecycle-experimental-orange.svg" }else { message("don't know what ", lifecycle, " is. So we're going for experimental") badge = "https://img.shields.io/badge/lifecycle-experimental-orange.svg" lifecycle <- "experimental" } badgepaste( imagelink = badge, referlink = paste0("https://www.tidyverse.org/lifecycle/ name = "lifecycle" ) }
BtamatW <- function(X,y,delta,N,q,MAXIT,TOL,seed=153) { n <- length(y); p <- ncol(X); if (q < p) q <- p set.seed(seed) indu <- (1:n)[delta==1] inds <- apply(matrix(rep(indu,N),nrow=N,byrow=TRUE),1,sample,size = q) intcp <- any(X[,1,drop=TRUE]!= 1) if (intcp) X <- cbind(1,X) beta <- apply(inds, 2, CandidateW, X, y, delta,MAXIT,TOL) if (p==1) beta <- matrix(beta,ncol=1,nrow=N) else beta <- t(beta) list(beta = beta)}
spls.hybrid <-function(X, Y, ncomp = 2, mode = c("regression", "canonical", "invariant", "classic"), max.iter = 500, tol = 1e-06, keepX.constraint, keepY.constraint, keepX, keepY, near.zero.var = FALSE) { if (length(dim(X)) != 2) stop("'X' must be a numeric matrix.") X = as.matrix(X) Y = as.matrix(Y) if (!is.numeric(X) || !is.numeric(Y)) stop("'X' and/or 'Y' must be a numeric matrix.") if(missing(keepX.constraint)) { if(missing(keepX)) { keepX=rep(ncol(X),ncomp) } keepX.constraint=list() }else{ if(missing(keepX)) { keepX=NULL } } if(missing(keepY.constraint)) { if(missing(keepY)) { keepY=rep(ncol(Y),ncomp) } keepY.constraint=list() }else{ if(missing(keepY)) { keepY=NULL } } if((length(keepX.constraint)+length(keepX))!=ncomp) stop("length (keepX.constraint) + length(keepX) should be ncomp") if((length(keepY.constraint)+length(keepY))!=ncomp) stop("length (keepY.constraint) + length(keepY) should be ncomp") keepX.temp=c(unlist(lapply(keepX.constraint,length)),keepX) keepY.temp=c(unlist(lapply(keepY.constraint,length)),keepY) check=Check.entry.pls(X,Y,ncomp,keepX.temp,keepY.temp) X=check$X Y=check$Y ncomp=check$ncomp X.names=check$X.names Y.names=check$Y.names ind.names=check$ind.names if(length(keepX.constraint)>0) { X.indice=X[,unlist(keepX.constraint),drop=FALSE] keepX.constraint=relist(colnames(X.indice),skeleton=keepX.constraint) } if(length(keepY.constraint)>0) { Y.indice=Y[,unlist(keepY.constraint),drop=FALSE] keepY.constraint=relist(colnames(Y.indice),skeleton=keepY.constraint) } if(near.zero.var == TRUE) { nzv.X = nearZeroVar(X) if (length(nzv.X$Position > 0)) { names.remove.X=colnames(X)[nzv.X$Position] warning("Zero- or near-zero variance predictors.\n Reset predictors matrix to not near-zero variance predictors.\n See $nzv$X for problematic predictors.") X = X[, -nzv.X$Position] if(ncol(X)==0) {stop("No more variables in X")} }else{names.remove.X=NULL} nzv.Y = nearZeroVar(Y) if (length(nzv.Y$Position > 0)) { names.remove.Y=colnames(Y)[nzv.Y$Position] warning("Zero- or near-zero variance predictors.\n Reset predictors matrix to not near-zero variance predictors.\n See $nzv$Y for problematic predictors.") Y = Y[, -nzv.Y$Position] if(ncol(Y)==0) {stop("No more variables in Y")} }else{names.remove.Y=NULL} }else{ X.scale=scale(X) sigma.X=attr(X.scale,"scaled:scale") remove=which(sigma.X==0) if(length(remove)>0) { names.remove.X=colnames(X)[remove] X=X[,-remove,drop=FALSE] X.names=X.names[-remove] }else{names.remove.X=NULL} if(ncol(X)==0) {stop("No more variables in X")} Y.scale=scale(Y) sigma.Y=attr(Y.scale,"scaled:scale") remove=which(sigma.Y==0) if(length(remove)>0) { names.remove.Y=colnames(Y)[remove] Y=Y[,-remove,drop=FALSE] Y.names=Y.names[-remove] }else{names.remove.Y=NULL} if(ncol(Y)==0) {stop("No more variables in Y")} } keepX.constraint=match.signature(X,names.remove.X,keepX.constraint) keepY.constraint=match.signature(Y,names.remove.Y,keepY.constraint) keepX.constraint= lapply(keepX.constraint,function(x){match(x,colnames(X))}) keepY.constraint= lapply(keepY.constraint,function(x){match(x,colnames(Y))}) keepX=c(unlist(lapply(keepX.constraint,length)),keepX) keepY=c(unlist(lapply(keepY.constraint,length)),keepY) n = nrow(X) q = ncol(Y) p = ncol(X) mode = match.arg(mode) X = scale(X, center = TRUE, scale = TRUE) Y = scale(Y, center = TRUE, scale = TRUE) means.X=attr(X,"scaled:center") sigma.X=attr(X,"scaled:scale") means.Y=attr(Y,"scaled:center") sigma.Y=attr(Y,"scaled:scale") X.temp = X Y.temp = Y mat.t = matrix(nrow = n, ncol = ncomp) mat.u = matrix(nrow = n, ncol = ncomp) mat.a = matrix(nrow = p, ncol = ncomp) mat.b = matrix(nrow = q, ncol = ncomp) mat.c = matrix(nrow = p, ncol = ncomp) mat.d = matrix(nrow = q, ncol = ncomp) mat.e = matrix(nrow = q, ncol = ncomp) n.ones = rep(1, n) p.ones = rep(1, p) q.ones = rep(1, q) na.X = FALSE na.Y = FALSE is.na.X = is.na(X) is.na.Y = is.na(Y) if (any(is.na.X)) na.X = TRUE if (any(is.na.Y)) na.Y = TRUE iter=NULL for (h in 1:ncomp) { nx=p-keepX[h] ny=q-keepY[h] X.aux = X.temp if (na.X) {X.aux[is.na.X] = 0} Y.aux = Y.temp if (na.Y) {Y.aux[is.na.Y] = 0} M = crossprod(X.aux, Y.aux) svd.M = svd(M, nu = 1, nv = 1) a.old = svd.M$u b.old = svd.M$v if (na.X) { t = X.aux %*% a.old A = drop(a.old) %o% n.ones A[t(is.na.X)] = 0 a.norm = crossprod(A) t = t / diag(a.norm) }else{ t = X.aux %*% a.old / drop(crossprod(a.old)) } if (na.Y) { u = Y.aux %*% b.old B = drop(b.old) %o% n.ones B[t(is.na.Y)] = 0 b.norm = crossprod(B) u = u / diag(b.norm) }else{ u = Y.aux %*% b.old / drop(crossprod(b.old)) } iterh = 1 repeat { a = t(X.aux) %*% u b = t(Y.aux) %*% t if(h<=length(keepX.constraint)) { if (nx != 0){a[-keepX.constraint[[h]]]=0} a=l2.norm(as.vector(a)) } if(h<=length(keepY.constraint)) { if (ny != 0){a[-keepY.constraint[[h]]]=0} b=l2.norm(as.vector(b)) } if(h>length(keepX.constraint)) { if (nx != 0){a=soft_thresholding(a,nx)} a=l2.norm(as.vector(a)) } if(h>length(keepY.constraint)) { if (ny != 0){b=soft_thresholding(b,ny)} b=l2.norm(as.vector(b)) } if (na.X) { t = X.aux %*% a A = drop(a) %o% n.ones A[t(is.na.X)] = 0 a.norm = crossprod(A) t = t / diag(a.norm) }else{ t = X.aux %*% a / drop(crossprod(a)) } if (na.Y) { u = Y.aux %*% b B = drop(b) %o% n.ones B[t(is.na.Y)] = 0 b.norm = crossprod(B) u = u / diag(b.norm) }else{ u = Y.aux %*% b / drop(crossprod(b)) } if (crossprod(a - a.old) < tol) {break} if (iterh == max.iter) { warning(paste("Maximum number of iterations reached for the component", h), call. = FALSE) break } a.old = a b.old = b iterh = iterh + 1 } if (na.X) { c = crossprod(X.aux, t) T = drop(t) %o% p.ones T[is.na.X] = 0 t.norm = crossprod(T) c = c / diag(t.norm) }else{ c = crossprod(X.aux, t) / drop(crossprod(t)) } X.temp = X.temp - t %*% t(c) if (mode == "canonical") { if (na.Y) { e = crossprod(Y.aux, u) U = drop(u) %o% q.ones U[is.na.Y] = 0 u.norm = crossprod(U) e = e / diag(u.norm) }else{ e = crossprod(Y.aux, u) / drop(crossprod(u)) } Y.temp = Y.temp - u %*% t(e) } if(mode == "regression") { if (na.Y) { d = crossprod(Y.aux, t) T = drop(t) %o% q.ones T[is.na.Y] = 0 t.norm = crossprod(T) d = d / diag(t.norm) }else{ d = crossprod(Y.aux, t) / drop(crossprod(t)) } Y.temp = Y.temp - t %*% t(d) } mat.t[, h] = t mat.u[, h] = u mat.a[, h] = a mat.b[, h] = b mat.c[, h] = c if (mode == "regression") {mat.d[, h] = d} if (mode == "canonical") {mat.e[, h] = e} if(mode == "classic") {Y.temp = Y.temp - t %*% t(b)} if (mode == "invariant") {Y.temp = Y} iter=c(iter,iterh) } rownames(mat.a) = rownames(mat.c) = X.names rownames(mat.b) = Y.names rownames(mat.t) = rownames(mat.u) = ind.names dim = paste("comp", 1:ncomp) colnames(mat.t) = colnames(mat.u) = dim colnames(mat.a) = colnames(mat.b) = colnames(mat.c) = dim cl = match.call() cl[[1]] = as.name('spls') result = list(call = cl, X = X, Y = Y, ncomp = ncomp, mode = mode, keepX.constraint = keepX.constraint, keepY.constraint = keepY.constraint, keepX=keepX, keepY=keepY, mat.c = mat.c, mat.d = mat.d, mat.e = mat.e, variates = list(X = mat.t, Y = mat.u), loadings = list(X = mat.a, Y = mat.b), names = list(samples = ind.names, colnames=X.names, blocks=c("X","Y"), Y = Y.names), tol = tol, max.iter = max.iter,iter=iter ) if (near.zero.var == TRUE) { result$nzv$X = nzv.X result$nzv$Y = nzv.Y } result$coeff=list(means.X=means.X,sigma.X=sigma.X,means.Y=means.Y,sigma.Y=sigma.Y) class(result) = c("pls","spls.hybrid") return(invisible(result)) }
basicOpGrob <- function(piece_side, suit, rank, cfg=pp_cfg(), x=unit(0.5, "npc"), y=unit(0.5, "npc"), z=unit(0, "npc"), angle=0, type="normal", width=NA, height=NA, depth=NA, op_scale=0, op_angle=45) { grob <- cfg$get_grob(piece_side, suit, rank, type) xy_p <- op_xy(x, y, z+0.5*depth, op_angle, op_scale) cvp <- viewport(xy_p$x, xy_p$y, width, height, angle=angle) grob <- grid::editGrob(grob, name="piece_side", vp=cvp) shadow_fn <- cfg$get_shadow_fn(piece_side, suit, rank) edge <- shadow_fn(piece_side, suit, rank, cfg, x, y, z, angle, width, height, depth, op_scale, op_angle) edge <- grid::editGrob(edge, name="other_faces") grobTree(edge, grob, cl="basic_projected_piece") } op_xy <- function(x, y, z, op_angle=45, op_scale=0) { x <- x + op_scale * z * cos(to_radians(op_angle)) y <- y + op_scale * z * sin(to_radians(op_angle)) list(x=x, y=y) } basicShadowGrob <- function(piece_side, suit, rank, cfg=pp_cfg(), x=unit(0.5, "npc"), y=unit(0.5, "npc"), z=unit(0, "npc"), angle=0, width=NA, height=NA, depth=NA, op_scale=0, op_angle=45) { cfg <- as_pp_cfg(cfg) opt <- cfg$get_piece_opt(piece_side, suit, rank) piece <- get_piece(piece_side) side <- ifelse(opt$back, "back", "face") x <- as.numeric(convertX(x, "in")) y <- as.numeric(convertY(y, "in")) z <- as.numeric(convertX(z, "in")) width <- as.numeric(convertX(width, "in")) height <- as.numeric(convertY(height, "in")) depth <- as.numeric(convertX(depth, "in")) shape <- pp_shape(opt$shape, opt$shape_t, opt$shape_r, opt$back) R <- side_R(side) %*% AA_to_R(angle, axis_x = 0, axis_y = 0) whd <- get_scaling_factors(side, width, height, depth) pc <- Point3D$new(x, y, z) token <- Token2S$new(shape, whd, pc, R) gl <- gList() opp_side <- ifelse(opt$back, "face", "back") opp_piece_side <- if (piece == "die") piece_side else paste0(piece, "_", opp_side) opp_opt <- cfg$get_piece_opt(opp_piece_side, suit, rank) gp_opp <- gpar(col=opp_opt$border_color, fill=opp_opt$background_color, lex=opp_opt$border_lex) xyz_opp <- if (opt$back) token$xyz_face else token$xyz_back xy_opp <- xyz_opp$project_op(op_angle, op_scale) grob_opposite <- polygonGrob(x = xy_opp$x, y = xy_opp$y, default.units = "in", gp = gp_opp, name="opposite_piece_side") edges <- token$op_edges(op_angle) for (i in seq_along(edges)) { name <- paste0("edge", i) gl[[i]] <- edges[[i]]$op_grob(op_angle, op_scale, name=name) } gp_edge <- gpar(col=opt$border_color, fill=opt$edge_color, lex=opt$border_lex) grob_edge <- gTree(children=gl, gp=gp_edge, name="token_edges") grobTree(grob_opposite, grob_edge) } basicEllipsoid <- function(piece_side, suit, rank, cfg=pp_cfg(), x=unit(0.5, "npc"), y=unit(0.5, "npc"), z=unit(0, "npc"), angle=0, type="normal", width=NA, height=NA, depth=NA, op_scale=0, op_angle=45) { cfg <- as_pp_cfg(cfg) opt <- cfg$get_piece_opt(piece_side, suit, rank) x <- as.numeric(convertX(x, "in")) y <- as.numeric(convertY(y, "in")) z <- as.numeric(convertX(z, "in")) width <- as.numeric(convertX(width, "in")) height <- as.numeric(convertY(height, "in")) depth <- as.numeric(convertX(depth, "in")) xyz <- ellipse_xyz()$dilate(width, height, depth)$translate(x, y, z) xy <- xyz$project_op(op_angle, op_scale) hull <- grDevices::chull(as.matrix(xy)) x <- xy$x[hull] y <- xy$y[hull] gp <- gpar(col=opt$border_color, fill=opt$background_color, lex=opt$border_lex) polygonGrob(x = x, y = y, default.units = "in", gp = gp) } ellipse_xyz <- function() { xy <- expand.grid(x=seq(0.0, 1.0, 0.05), y = seq(0.0, 1.0, 0.05)) xy <- xy[which(xy$x^2 + xy$y^2 <= 1), ] z <- sqrt(1 - xy$x^2 - xy$y^2) ppp <- data.frame(x=xy$x, y=xy$y, z=z) ppn <- data.frame(x=xy$x, y=xy$y, z=-z) pnp <- data.frame(x=xy$x, y=-xy$y, z=z) pnn <- data.frame(x=xy$x, y=-xy$y, z=-z) nnp <- data.frame(x=-xy$x, y=-xy$y, z=z) npp <- data.frame(x=-xy$x, y=xy$y, z=z) npn <- data.frame(x=-xy$x, y=xy$y, z=-z) nnn <- data.frame(x=-xy$x, y=-xy$y, z=-z) df <- 0.5 * rbind(ppp, ppn, pnp, pnn, nnp, npp, npn, nnn) Point3D$new(df) } basicPyramidTop <- function(piece_side, suit, rank, cfg=pp_cfg(), x=unit(0.5, "npc"), y=unit(0.5, "npc"), z=unit(0, "npc"), angle=0, type="normal", width=NA, height=NA, depth=NA, op_scale=0, op_angle=45) { cfg <- as_pp_cfg(cfg) x <- as.numeric(convertX(x, "in")) y <- as.numeric(convertY(y, "in")) z <- as.numeric(convertX(z, "in")) width <- as.numeric(convertX(width, "in")) height <- as.numeric(convertY(height, "in")) depth <- as.numeric(convertX(depth, "in")) xy_b <- Point2D$new(rect_xy)$npc_to_in(x, y, width, height, angle) p <- Polygon$new(xy_b) edge_types <- paste0("pyramid_", c("left", "back", "right", "face")) order <- p$op_edge_order(op_angle) df <- tibble(index = 1:4, edge = edge_types)[order, ] gl <- gList() for (i in 1:4) { opt <- cfg$get_piece_opt(df$edge[i], suit, rank) gp <- gpar(col = opt$border_color, lex = opt$border_lex, fill = opt$background_color) edge <- p$edges[df$index[i]] ex <- c(edge$p1$x, edge$p2$x, x) ey <- c(edge$p1$y, edge$p2$y, y) ez <- c(z - 0.5 * depth, z - 0.5 * depth, z + 0.5 * depth) exy <- Point3D$new(x = ex, y = ey, z = ez)$project_op(op_angle, op_scale) gl[[i]] <- polygonGrob(x = exy$x, y = exy$y, gp = gp, default.units = "in") } if (nigh((angle - op_angle) %% 90, 0)) { base_mid <- exy[1]$midpoint(exy[2]) xy_mid <- base_mid$midpoint(exy[3]) vheight <- base_mid$distance_to(exy[3]) vp <- viewport(x = xy_mid$x, y = xy_mid$y, default.units = "in", angle = op_angle - 90, width = width, height = vheight) gl[[4]] <- grobTree(cfg$get_grob(df$edge[i], suit, rank, "picture"), vp = vp) } gTree(children=gl, cl="projected_pyramid_top") } basicPyramidSide <- function(piece_side, suit, rank, cfg=pp_cfg(), x=unit(0.5, "npc"), y=unit(0.5, "npc"), z=unit(0, "npc"), angle=0, type="normal", width=NA, height=NA, depth=NA, op_scale=0, op_angle=45) { cfg <- as_pp_cfg(cfg) x <- as.numeric(convertX(x, "in")) y <- as.numeric(convertY(y, "in")) z <- as.numeric(convertX(z, "in")) width <- as.numeric(convertX(width, "in")) height <- as.numeric(convertY(height, "in")) depth <- as.numeric(convertX(depth, "in")) xy_b <- Point2D$new(pyramid_xy)$npc_to_in(x, y, width, height, angle) p <- Polygon$new(xy_b) theta <- 2 * asin(0.5 * width / height) yt <- 1 - cos(theta) xy_t <- Point2D$new(x = 0:1, y = yt)$npc_to_in(x, y, width, height, angle) gl <- gList() opposite_edge <- switch(piece_side, "pyramid_face" = "pyramid_back", "pyramid_back" = "pyramid_face", "pyramid_left" = "pyramid_right", "pyramid_right" = "pyramid_left") opt <- cfg$get_piece_opt(opposite_edge, suit, rank) gp <- gpar(col = opt$border_color, lex = opt$border_lex, fill = opt$background_color) exy <- Point3D$new(x = xy_b$x, y = xy_b$y, z = z - 0.5 * depth)$project_op(op_angle, op_scale) gl[[1]] <- polygonGrob(x = exy$x, y = exy$y, gp = gp, default.units = "in") gl[[2]] <- nullGrob() gl[[3]] <- nullGrob() edge_types <- paste0("pyramid_", switch(piece_side, "pyramid_face" = c("right", "bottom", "left"), "pyramid_left" = c("face", "bottom", "back"), "pyramid_back" = c("left", "bottom", "right"), "pyramid_right" = c("back", "bottom", "face") )) order <- p$op_edge_order(op_angle) df <- tibble(index = 1:3, edge = edge_types)[order, ] gli <- 2 for (i in 1:3) { edge_ps <- df$edge[i] index <- df$index[i] if (edge_ps == "pyramid_bottom") next opt <- cfg$get_piece_opt(edge_ps, suit, rank) gp <- gpar(col = opt$border_color, lex = opt$border_lex, fill = opt$background_color) edge <- p$edges[index] if (index == 1) { ex <- c(edge$p1$x, edge$p2$x, edge$p2$x) ey <- c(edge$p1$y, edge$p2$y, xy_t$y[1]) ez <- c(z - 0.5 * depth, z - 0.5 * depth, z + 0.5 * depth) } else { ex <- c(edge$p1$x, edge$p2$x, edge$p1$x) ey <- c(edge$p1$y, edge$p2$y, xy_t$y[2]) ez <- c(z - 0.5 * depth, z - 0.5 * depth, z + 0.5 * depth) } exy <- Point3D$new(x = ex, y = ey, z = ez)$project_op(op_angle, op_scale) gl[[gli]] <- polygonGrob(x = exy$x, y = exy$y, gp = gp, default.units = "in") gli <- gli + 1 } x_f <- xy_b$x y_f <- c(xy_b$y[1], xy_t$y) z_f <- c(z - 0.5 * depth, z + 0.5 * depth, z + 0.5 * depth) opt <- cfg$get_piece_opt(piece_side, suit, rank) gp <- gpar(col = opt$border_color, lex = opt$border_lex, fill = opt$background_color) exy <- Point3D$new(x = x_f, y = y_f, z = z_f)$project_op(op_angle, op_scale) gl[[4]] <- polygonGrob(x = exy$x, y = exy$y, gp = gp, default.units = "in") diff_angle <- (op_angle - angle) %% 360 if ((nigh(diff_angle, 90) || nigh(diff_angle, 270)) && nigh(angle %% 90, 0)) { base_mid <- exy[2]$midpoint(exy[3]) xy_mid <- base_mid$midpoint(exy[1]) vheight <- base_mid$distance_to(exy[1]) vp <- viewport(x = xy_mid$x, y = xy_mid$y, default.units = "in", angle = angle, width = width, height = vheight) gl[[4]] <- grobTree(cfg$get_grob(piece_side, suit, rank, "picture"), vp = vp) } gTree(children=gl, cl="projected_pyramid_side") }
pssm.survivalcurv <- function(x,cov1,cov2,timeToProgression=FALSE,covariance=TRUE){ sp=length([email protected])==0 ss=length([email protected])==0 cd1=(!is.null(cov1))&(!sp) cd2=(!is.null(cov2))&(!ss) if(cd1) dc1=dim(cov1) else dc1=rep(0,2) if(cd2) dc2=dim(cov2) else dc2=rep(0,2) namesc1=c("rep","tdeath","cdeath","tprog0","tprog1",[email protected],[email protected]) namesc=namesc1[namesc1!=""] if(!(sp|ss)){ tfcn2<-function(dt) llikef([email protected],[email protected],dt, m=x@intervals,accumulate=FALSE,gradient=FALSE) tfcn1<-function(dt) { lp=dim(dt)[1] outp<-function(vv){ out1<-tfcn2(dt)(vv) gradient=matrix(NaN,lp,length(vv)) for(i in (1:lp)){ try(gradient[i,]<-grad(function (xt) tfcn2(dt[i,])(xt),vv),silent=FALSE) } attr(out1,"gradient")<-gradient return(out1) } return(outp) } } else { if (sp){ tfcn1<-function(dt) { lp=dim(dt)[1] outp=function(vv){ out1<-rsurv([email protected],dt,m=x@intervals,accumulate=FALSE)(vv) gradient=matrix(NaN,lp,length(vv)) for (i in (1:lp)) try(gradient[i,]<-grad(function(xt) rsurv([email protected],data.frame(dt[i,]),m=x@intervals,accumulate=FALSE)(xt),vv),silent=TRUE) attr(out1,"gradient")<-gradient return(out1) } return(outp) } tfcn2<-function(dt) rsurv([email protected],dt,m=x@intervals,accumulate=FALSE) } else { tfcn1<-function(dt){ mtt=dim(dt)[1] outp=function(vv){ out1=rprog([email protected],dt,m=x@intervals,accumulate=FALSE)(vv) gradient=matrix(NaN,mtt,length(vv)) for (i in (1:mtt)) try(gradient[i,]<-grad( function(xt) rprog([email protected],data.frame(dt[i,]), m=x@intervals,accumulate=FALSE)(xt),vv),silent=TRUE) attr(out1,"gradient")<-gradient return(out1)} return(outp) } tfcn2<-function(dt) rprog([email protected],dt,m=x@intervals,accumulate=FALSE) } } curv1=NULL if (!(sp|ss)) curv1=c('s1','s2') else curv1='s2' curv1=unique(curv1) nt=function(t1,t2,t3,t4,t5) return(data.frame(rep=t1,tdeath=t2,cdeath=t3,tprog0=t4,tprog1=t5,stringsAsFactors=FALSE)) repframe=function(x,m){out=NULL for (i in (1:m)) out=rbind(out,x) return(out)} cls=function(t){ ls=list(pr=nt('pr',t,0,t,NA),s1=nt('s1',t,0,0,t),s2=nt('s2',t,0,t,NA),dp=nt('dp',t,0,t,t),ds=nt('ds',t,1,0,t)) inp=list(NULL,NULL) lt=length(t) for (i in 1:length(curv1)) { inp[[1]]=rbind(inp[[1]],ls[[curv1[i]]]) inp[[2]]=rbind(inp[[2]],diag(rep(1,lt)))} return(inp) } idt=function(ts){ tt=ts[[1]] vs=dim(tt)[1] rv=max(max(dc1[1],dc2[1]),1) mm=rv*vs inp=data.frame(rep=rep(tt[,1],rv),time=rep(tt[,2],rv),stringsAsFactors=FALSE) if (cd1){ fcov1=data.frame(matrix(rep(cov1,each=vs),mm,dc1[2])); names(fcov1)<[email protected] inp=cbind(inp,fcov1)} if (cd2){ fcov2=data.frame(matrix(rep(cov2,each=vs),mm,dc2[2])); names(fcov2)<[email protected] inp=cbind(inp,fcov2)} rownames(inp)<-as.character(1:mm) inp2=diag(rep(1,rv))%x%ts[[2]] return(list(inp,inp2)) } sortrows<-function(x,r){ out=x for (i in seq(r,1,-1)) out=out[order(out[,i]),] return(out) } outp=function(ts,p){ tt=ts[[1]] vs=dim(tt)[1] rv=max(max(dc1[1],dc2[1]),1) mm=rv*vs dt=data.frame(repframe(tt,rv),idt(ts)[[1]][,-(1:2)]) names(dt)<-namesc if(covariance){ fcc=tfcn1(dt) tmp1=fcc(x@estimates) fc=exp(tmp1) me=length(x@estimates) dlogf=attr(tmp1,"gradient") nrows=dim(dlogf)[1] vlogf=dlogf%*%[email protected]%*%t(dlogf) if (p!=0){ pp=p E12=matrix([email protected][1:(me-1),me],me-1,1) [email protected][me,me] ED=rbind(cbind(matrix(0,me-1,me-1),pp*E12), cbind(matrix(0,1,me-1),pp*e22)) EDE=rbind(cbind(pp*E12%*%t(E12),e22*pp*E12), cbind(e22*pp*t(E12),pp*e22^2)) pest=x@estimates-(ED%*%matrix(x@estimates,me,1))/(1+e22*pp) [email protected]/(1+pp*e22) tmp1=fcc(pest) fc=exp(tmp1) dlogf=attr(tmp1,"gradient") vlogf=dlogf%*%cvar%*%t(dlogf) } fk=matrix(fc,mm,mm) cdc=fk*vlogf*t(fk) ou=cbind(matrix(fc,nrows,1),cdc) colnames(ou)<-c('estimate',as.character(1:mm)) rownames=as.character(1:mm) return(ou) } else { fcc=tfcn2(dt) fc=exp(fcc(x@estimates)) ou=matrix(fc,length(fc),1) colnames(ou)<-c('estimate') rownames(ou)<as.character(1:length(fc)) return(ou)} } out<-function(ts,p=0) { rt<-function(t){ifelse(t==0,0.00001,t*x@rescale)} rti<-function(t){ifelse(t==0.00001,0,t/x@rescale)} t=rt(ts) vin=cls(t) vt=idt(vin) vu=outp(vin,p) xvals=colnames((vt)[[1]])[-1] vt[[1]][,2]<-rti(vt[[1]][,2]) v=cbind(vt[[1]],vu) ninfo=dc1[2]+dc2[2]+2 names(v)<-c(names(vt[[1]]),colnames(vu)) if (!(sp|ss|timeToProgression)){ ou=cbind(v[v[,1]==v[1,1],1:ninfo],estimate=t(vt[[2]])%*%matrix(v[,"estimate"],length(v[,"estimate"]),1)) names(ou)[[ninfo+1]]="estimate" } else { ou=data.frame(v[,c("rep",xvals),drop=FALSE],estimate=v[,"estimate"],stringsAsFactors=FALSE) } if (covariance){ cov=t(vt[[2]])%*% as.matrix(v[,-(1:(ninfo+1))]) %*%vt[[2]] attr(ou,"covariance")<-cov } return(ou)} return(out) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(FuzzySTs) mat <- matrix(c(1,2,3,7,6,5), ncol = 2) is.alphacuts(mat) X <- TrapezoidalFuzzyNumber(1,2,3,4) alpha.X <- alphacut(X, seq(0,1,0.01)) nbreakpoints(alpha.X) GFN <- GaussianFuzzyNumber(mean = 0, sigma = 1, alphacuts = TRUE, plot=TRUE) is.alphacuts(GFN) GBFN <- GaussianBellFuzzyNumber(left.mean = -1, left.sigma = 1, right.mean = 2, right.sigma = 1, alphacuts = TRUE, plot=TRUE) is.alphacuts(GBFN) X <- TrapezoidalFuzzyNumber(5,6,7,8) Y <- TrapezoidalFuzzyNumber(1,2,3,4) Fuzzy.Difference(X,Y) X <- TrapezoidalFuzzyNumber(1,2,3,4) head(Fuzzy.Square(X, plot=TRUE)) mat <- array(c(1,1,2,2,3,3,5,5,6,6,7,7),dim=c(2,3,2)) is.fuzzification(mat) mat <- matrix(c(1,1,2,2,3,3,4,4),ncol=4) is.trfuzzification(mat) data <- matrix(c(1,1,2,2,3,3,4,4),ncol=4) data.tr <- tr.gfuzz(data) data <- matrix(c(1,2,3,2,2,1,1,3,1,2),ncol=1) MF111 <- TrapezoidalFuzzyNumber(0,1,1,2) MF112 <- TrapezoidalFuzzyNumber(1,2,2,3) MF113 <- TrapezoidalFuzzyNumber(2,3,3,3) PA11 <- c(1,2,3) data.fuzzified <- FUZZ(data,mi=1,si=1,PA=PA11) is.trfuzzification(data.fuzzified) data <- matrix(c(1,2,3,2,2,1,1,3,1,2),ncol=1) MF111 <- TrapezoidalFuzzyNumber(0,1,1,2) MF112 <- TrapezoidalFuzzyNumber(1,2,2,3) MF113 <- TrapezoidalFuzzyNumber(2,3,3,3) PA11 <- c(1,2,3) data.fuzzified <- GFUZZ(data,mi=1,si=1,PA=PA11) is.fuzzification(data.fuzzified) X <- TrapezoidalFuzzyNumber(1,2,3,4) Y <- TrapezoidalFuzzyNumber(4,5,6,7) distance(X, Y, type = "DSGD.G") distance(X, Y, type = "GSGD")
confplot <- function(x, ...) { UseMethod("confplot") } confplot.default <- function(x, y1=NULL, y2=NULL, add=FALSE, xlab=NULL, ylab=NULL, border=NA, col="lightgray", ...) { if(is.vector(x)) { if(is.null(xlab)) xlab <- deparse(substitute(x)) if(is.null(y1)) stop("'y1' should not be NULL when 'x' is a vector") if(is.vector(y1) && is.null(y2)) stop("'y2' should not be NULL when 'x' and 'y1' are vectors") if(!is.null(ncol(y1))) { if(ncol(y1) != 2) stop("'y1' should be a vector or contain 2 columns") y2 <- y1[,2] y1 <- y1[,1] } } else if(ncol(x) == 3) { if(is.null(xlab)) xlab <- colnames(x)[1] y1 <- x[,2] y2 <- x[,3] x <- x[,1] } else stop("'x' should be a vector or contain 3 columns") if(is.null(ylab)) ylab <- "" na <- is.na(x) | is.na(y1) | is.na(y2) x <- x[!na][order(x[!na])] y1 <- y1[!na][order(x[!na])] y2 <- y2[!na][order(x[!na])] if(!add) suppressWarnings(matplot(range(x), range(c(y1,y2)), type="n", xlab=xlab, ylab=ylab, ...)) polygon(c(x,rev(x)), c(y1,rev(y2)), border=border, col=col, ...) invisible(data.frame(x, y1, y2)) } confplot.formula <- function(formula, data, subset, na.action=NULL, ...) { m <- match.call(expand.dots=FALSE) if(is.matrix(eval(m$data,parent.frame()))) m$data <- as.data.frame(data) m$... <- NULL m[[1]] <- quote(model.frame) mf <- eval(m, parent.frame()) if(is.matrix(mf[[1]])) { lhs <- as.data.frame(mf[[1]]) confplot.default(cbind(mf[-1],lhs), ...) } else { confplot.default(mf[2:1], ...) } }
DataReader <- function(client) { reader <- list( client = client, get = function(x) reader[[x]], set = function(x, value) reader[[x]] <<- value ) reader$CreateTs <- function(series) { result <- list() frequencies.seq <- list(A = "year", H = "6 month", Q = "quarter", M = "month", W = "week", D = "day") for (i in 1:length(series)) { title <- names(series[i]) freq <- substring(title, 1, 1) freq.seq <- unlist(frequencies.seq)[freq] dates <- as.Date(names(series[[i]])) if (length(dates) == 0) { next } min.date <- min(dates) max.date <- max(dates) all.dates <- seq(min.date, max.date, by = freq.seq) values <- series[[i]][as.character(all.dates)] values[sapply(values,is.null)] <- NA values <- unname(unlist(values)) start.by.freq <- switch(freq, "A" = c(year(min.date), 1), "H" = c(year(min.date), (month(min.date)-1)%/%6+1), "Q" = c(year(min.date), quarter(min.date)), "M" = c(year(min.date), month(min.date)), "W" = c(year(min.date), week(min.date)), "D" = c(year(min.date), day(min.date))) result[[title]] <- ts(values, start = start.by.freq, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateXts <- function(series) { result <- list() for (i in 1:length(series)) { title <- names(series[i]) if (length(names(series[[i]])) == 0) { next } dates <- as.Date(names(series[[i]])) freq <- substring(title, 1, 1) dates.xts <- switch (freq, "Q" = as.yearqtr(dates), "M" = as.yearmon(dates), dates) values <- unlist(series[[i]], use.names = FALSE) result[[title]] <- xts(values, order.by = dates.xts, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateZoo <- function(series) { result <- list() for (i in 1:length(series)) { title <- names(series[i]) dates <- as.Date(names(series[[i]])) if (length(dates) == 0) { next } freq <- substring(title, 1, 1) dates.zoo <- switch (freq, "A" = as.numeric(format(dates, "%Y")), "Q" = as.yearqtr(dates), "M" = as.yearmon(dates), dates ) values <- unlist(series[[i]], use.names = FALSE) result[[title]] <- zoo(values, order.by = dates.zoo, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateSeriesForTsXtsZoo <- function (resp, series) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } frequency <- serie.point$Frequency name <- frequency for (stub in resp$stub) { dim <- stub$dimensionId name <- paste(name, serie.point[[dim]], sep = " - ") } if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) stop(simpleError("Types ts, xts, zoo are not supported for flat datasets"))) series[[name]][time] <- serie.point$Value } return (series) } reader$CreateMatrixForFrameOrTable <- function(data.rows, series) { list.for.matrix <- sapply(1:length(series), function (i) { t <- lapply(data.rows, function(j) { series[[i]][[j]]}) t[sapply(t,is.null)]<-NA unlist(t) }) matrix <- matrix(list.for.matrix, nrow = length(data.rows), ncol = length(series)) return (matrix) } reader$GetFTableByData <- function (data.rows, data.columns, series, row.equal.dates = TRUE) { matrix <- reader$CreateMatrixForFrameOrTable(data.rows, series) length.by.columns <- unlist(lapply(1:length(data.columns), function(x) length(data.columns[[x]])), recursive = F) length.of.all.dimension <- c(length(data.rows), length.by.columns) matrix.arr <- array(matrix, length.of.all.dimension) if (row.equal.dates) { dimnames(matrix.arr) <- c(list(date = data.rows), data.columns) } else { dimnames(matrix.arr) <- c(list(attributes = data.rows), data.columns) } data.table <- ftable(matrix.arr, row.vars = 1, col.vars = 2:(length(data.columns) + 1)) return (data.table) } reader$GetDataFrameByData <- function(data.rows, series) { matrix <- reader$CreateMatrixForFrameOrTable(data.rows, series) data.frame <- as.data.frame(matrix, row.names = data.rows, stringsAsFactors = FALSE) colnames(data.frame) <- names(series) return (data.frame) } reader$GetXtsByData <- function(data.rows, series) { matrix <- reader$CreateMatrixForFrameOrTable(data.rows, series) data.frame <- xts(matrix, order.by = as.Date(data.rows)) colnames(data.frame) <- names(series) return (data.frame) } reader$GetSeriesNameWithMetadata <- function(series.point) { names <- list() for (dim in reader$get("dimensions")) { for (item in dim$items) { if (item$name == series.point[dim$dim.model$id]) { dim.attr <- item$fields break } } for (attr in dim$fields) { if (!attr$isSystemField) { for (i in 1: length(dim.attr)) { if (IsEqualStringsIgnoreCase(names(dim.attr[i]), attr$name)) { names[[paste(dim$dim.model$name, attr$displayName, sep=" ")]] <- dim.attr[[i]] } } } } } names[["Unit"]] <- series.point$Unit names[["Scale"]] <- series.point$Scale names[["Mnemonics"]] <- ifelse(is.null(series.point$Mnemonics), "NULL", series.point$Mnemonics) for (attr in reader$dataset$time.series.attributes) { names[[attr$name]] <- series.point[[attr$name]] } return (names) } reader$CreateAttributesNamesForMetadata <- function() { data.rows <- NULL for (dim in reader$dimensions) { for (attr in dim$fields) { if (!attr$isSystemField) { data.rows <- c(data.rows, paste(dim$dim.model$name, attr$displayName, sep = " ")) } } } data.rows <- c(data.rows, c("Unit", "Scale", "Mnemonics")) for (attr in reader$dataset$time.series.attributes) { data.rows <- c(data.rows, attr$name) } return(data.rows) } reader$CreateSeriesForMetaDataTable <- function(resp, series, data.columns) { for (serie.point in resp$data) { name <- NULL name.meta <- list() for (j in 1:length(resp$stub)) { dim <- resp$stub[[j]]$dimensionId dim.name <- reader$FindDimension(dim)$name name.element <- serie.point[[dim]] if (!name.element %in% data.columns[[dim.name]]) { data.columns[[dim.name]] <- c(data.columns[[dim.name]], name.element) } name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$Frequency name <- paste(name, frequency, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (!frequency %in% data.columns[["Frequency"]]) { data.columns[["Frequency"]] <- c(data.columns[["Frequency"]], frequency) } if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (list(series, data.columns)) } reader$CreateSeriesForMetaDataFrame <- function (resp, series) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } name <- NULL name.meta <- list() for (j in 1:length(resp$stub)) { dim <- resp$stub[[j]]$dimensionId name.element <- serie.point[[dim]] name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$Frequency name <- paste(name, frequency, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (series) } reader$CreateMetaDataFrame <- function(resp) { data.rows <- reader$CreateAttributesNamesForMetadata() series <- reader$CreateSeriesForMetaDataFrame (resp, list())[[1]] data.table <- reader$GetDataFrameByData(data.rows, series) return (data.table) } reader$CreateSeriesForDataTable <- function (resp, series, data.rows, data.columns) { for (serie.point in resp$data) { name <- NULL for (stub in resp$stub) { dim <- stub$dimensionId dim.name <- reader$FindDimension(dim)$name name.element <- serie.point[[dim]] if (!name.element %in% data.columns[[dim.name]]) { data.columns[[dim.name]] <- c(data.columns[[dim.name]], name.element) } name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$Frequency name <- paste(name, frequency, sep = " - ") if (!frequency %in% data.columns[["Frequency"]]) { data.columns[["Frequency"]] <- c(data.columns[["Frequency"]], frequency) } if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) serie.point$Time) if (!time %in% data.rows) { data.rows <- c(data.rows, time) } series[[name]][time] <- serie.point$Value } return (list(series, data.rows, data.columns)) } reader$CreateDataTable <- function(resp) { result <- reader$CreateSeriesForDataTable(resp, list(), NULL, list()) series <- result[[1]] data.rows <- result[[2]] data.columns <- result[[3]] data.rows <- sort(data.rows) data.table <- reader$GetFTableByData(data.rows, data.columns, series) return (data.table) } reader$CreateSeriesForDataFrame <- function(resp, series, data.rows) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } name <- NULL for (stub in resp$stub) { dim <- stub$dimensionId name.element <- serie.point[[dim]] name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$Frequency name <- paste(name, frequency, sep = " - ") if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) serie.point$Time) if (!time %in% data.rows) { data.rows <- c(data.rows, time) } series[[name]][time] <- serie.point$Value } return (list(series, data.rows)) } reader$CreateDataFrame <- function(resp) { result <- reader$CreateSeriesForDataFrame(resp, list(), NULL) series <- result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetDataFrameByData(data.rows, series) return (data.table) } reader$CreateResultObjectByType <- function (result, type) { switch (type, "DataFrame" = { series = result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetDataFrameByData(data.rows, series) return (data.table) }, "MetaDataFrame" = { data.rows <- reader$CreateAttributesNamesForMetadata() data.table <- reader$GetDataFrameByData(data.rows, result) return (data.table) }, "DataTable" = { series = result [[1]] data.rows <- sort(result[[2]]) data.columns <- result[[3]] data.table <- reader$GetFTableByData(data.rows, data.columns, series) return (data.table) }, "MetaDataTable" = { series = result[[1]] data.rows <- reader$CreateAttributesNamesForMetadata() data.columns <- result[[2]] data.table <- reader$GetFTableByData(data.rows, data.columns, series, FALSE) return (data.table) }, "zoo" = { return (reader$CreateZoo(result)) }, "xts" = { series = result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetXtsByData(data.rows, series) return (data.table) }, "ts" = { return (reader$CreateTs(result)) } ) } reader$CreateResultSeries <- function(data, result, type) { switch (type, "DataTable" = { series <- result[[1]] data.rows <- result[[2]] data.columns <- result[[3]] return(reader$CreateSeriesForDataTable(data, series, data.rows, data.columns)) }, "MetaDataTable" = { series <- result [[1]] data.columns <- result[[2]] return(reader$CreateSeriesForMetaDataTable(data, series, data.columns)) }, "DataFrame" = { series <- result[[1]] data.rows <- result[[2]] return(reader$CreateSeriesForDataFrame(data, series, data.rows)) }, "MetaDataFrame" = { return(reader$CreateSeriesForMetaDataFrame(data, result)) }, "ts" = { return(reader$CreateSeriesForTsXtsZoo(data, result)) }, "xts" = { return(reader$CreateSeriesForTsXtsZoo(data, result)) }, "zoo" = { return(reader$CreateSeriesForTsXtsZoo(data, result)) }, { error <- simpleError(sprintf("Unknown type %1s", type)) stop(error) } ) } reader$LoadDimensions <- function () { l <- list () for (dim in reader$get("dataset")$dimensions) { d <- Dimension(reader$client$GetDimension(reader$get("dataset")$id, dim$id)) l <- c(l, d) } reader$set("dimensions", l) } reader <- list2env(reader) return(reader) } SelectionDataReader <- function(client, selection) { reader <- DataReader (client) reader$set("selection", selection) reader$CheckCorrectFrequencies <- function (values) { correct.freq <- list("A","H","Q","M","W","D") list.condition <- !values %in% correct.freq list.err <- values[list.condition] if (length(list.err)>0) { error <- simpleError(sprintf("The following frequencies are not correct: %1s", paste(list.err, sep="", collapse =","))) stop(error) } return (TRUE) } reader$FindDimension <- function (dim.name.or.id) { dim <- reader$dataset$FindDimensionByName(dim.name.or.id) if (is.null(dim)) { dim <- reader$dataset$FindDimensionById(dim.name.or.id) } return (dim) } reader$GetDimMembers <- function(dim, split.values) { members <- NULL for (value in split.values) { if (is.null(value)) { error <- simpleError(sprintf("Selection for dimension %1s is empty", dim$name)) stop(error) } member <- dim$FindMemberById(value) if (is.null(member)) member <- dim$FindMemberByName(value) if (is.null(member)& !is.na(suppressWarnings(as.numeric(value)))) member <- dim$FindMemberByKey(as.numeric(value)) members <- c(members, member$key) } return (members) } reader$AddFullSelectionByEmptyDimValues <- function(filter.dims, request) { dims <- lapply(1:length(reader$dataset$dimensions), function(x) reader$dataset$dimensions[[x]]$id) if (length(filter.dims)>0) { dims.from.filter <- lapply(1:length(filter.dims), function(x) filter.dims[[x]]$id) list.condition <- sapply(dims, function(x) ! x %in% dims.from.filter) out.of.filter.dim.names <- dims[list.condition] } else { out.of.filter.dim.names <- dims } for (id in out.of.filter.dim.names) { l <- c(request$get("stub"), PivotItem(id, list())) request$set("stub", l) } } reader$CreatePivotRequest <- function () { request <- PivotRequest(reader$dataset$id) filter.dims <- list() time.range <- NULL for (item in names(reader$selection)) { value <- reader$selection[item][[1]] if (item == "timerange") { time.range <- value next } splited.values <- as.list(strsplit(value, ';')[[1]]) if (item == "frequency") { if (reader$CheckCorrectFrequencies(splited.values)) { request$set("frequencies", splited.values) next } } dim <- reader$FindDimension(item) if (is.null(dim)) { error <- simpleError(sprintf("Dimension with id or name %1s is not found", item)) stop(error) } filter.dims <- c(filter.dims, dim) for (dimension in reader$dimensions) { if(dimension$dim.model$id == dim$id) { dim2 <- dimension break } } members <- reader$GetDimMembers(dim2, splited.values) if (length(members) == 0) { e = simpleError(sprintf("Selection for dimension %1s is empty", dim$name)) stop(e) } l <- c(request$get("stub"), PivotItem(dim$id, members)) request$set("stub", l) } reader$AddFullSelectionByEmptyDimValues(filter.dims, request) if (length(time.range != 0)) { l <- c(request$get("header"), PivotTimeItem("Time", time.range, "range")) request$set("header", l) } else { l <- c(request$get("header"), PivotTimeItem("Time", list(), "allData")) request$set("header", l) } return (request) } return (reader) } PivotDataReader <- function(client, selection) { reader <- SelectionDataReader (client, selection) reader$GetObjectByType <- function(type) { reader$LoadDimensions() result <- switch (type, "MetaDataTable" = { list (list(), list()) }, "DataTable" = { list (list(), NULL, list()) }, "DataFrame" = { list (list(), NULL, list()) }, list() ) return (reader$GetObjectForFlatDataset(type, result)) } reader$GetObjectForFlatDataset <- function (type, result) { pivot.request <- reader$CreatePivotRequest() pivot.request.json <- pivot.request$SaveToJson() data <- reader$client$GetData(pivot.request.json) if (length(data$data) == 0) { warning(simpleError("Dataset do not have data by this selection")) return (NULL) } result <- reader$CreateResultSeries(data, result, type) return (reader$CreateResultObjectByType(result, type)) } return (reader) } StreamingDataReader <- function(client, selection) { reader <- SelectionDataReader (client, selection) reader$CreateSeriesForTsXtsZoo <- function (resp, series) { frequencies.seq <- list(A = "year", H = "6 month", Q = "quarter", M = "month", W = "week", D = "day") for (serie.point in resp) { all.values <- serie.point$values frequency <- serie.point$frequency name <- frequency for (dim in reader$dimensions) { name <- paste(name, serie.point[[dim$dim.model$id]]$name, sep = " - ") } if (is.null(series[[name]])) { series[[name]] <- list() } data.begin <- as.Date(serie.point$startDate) data.end <- as.Date(serie.point$endDate) if (frequency == "W") { data.begin <- data.begin - days(as.numeric(strftime(data.begin, "%u"))-1) data.end <- data.end - days(as.numeric(strftime(data.end, "%u"))-1) } all.dates<- seq(data.begin, data.end, by = frequencies.seq[[frequency]]) index.without.nan <- which(!all.values %in% list(NULL)) dates <- format(all.dates[index.without.nan], "%Y-%m-%d") serie <- setNames(all.values[index.without.nan], dates) series[[name]] <- serie } return (series) } reader$GetSeriesNameWithMetadata <- function(series.point) { names <- list() for (dim in reader$dimensions) { for (item in dim$items) { if (item$name == series.point[[dim$dim.model$id]]$name) { dim.attr <- item$fields break } } for (attr in dim$fields) { if (!attr$isSystemField) { for (i in 1: length(dim.attr)) { if (IsEqualStringsIgnoreCase(names(dim.attr[i]), attr$name)) { names[[paste(dim$dim.model$name, attr$displayName, sep=" ")]] <- dim.attr[[i]] } } } } } names[["Unit"]] <- series.point$unit names[["Scale"]] <- series.point$scale names[["Mnemonics"]] <- ifelse(is.null(series.point$mnemonics), "NULL", series.point$mnemonics) for (attr in reader$dataset$time.series.attributes) { names[[attr$name]] <- series.point$timeseriesAttributes[[attr$name]] } return (names) } reader$CreateSeriesForMetaDataTable <- function(resp, series, data.columns) { for (serie.point in resp) { name <- NULL name.meta <- list() for (dim in reader$dimensions) { name.element <- serie.point[[dim$dim.model$id]]$name dim.name <- dim$dim.model$name if (!name.element %in% data.columns[[dim.name]]) { data.columns[[dim.name]] <- c(data.columns[[dim.name]], name.element) } name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$frequency name <- paste(name, frequency, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (!frequency %in% data.columns[["Frequency"]]) { data.columns[["Frequency"]] <- c(data.columns[["Frequency"]], frequency) } if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (list(series, data.columns)) } reader$CreateSeriesForMetaDataFrame <- function (resp, series) { for (serie.point in resp) { name <- NULL name.meta <- list() for (dim in reader$dimensions) { name.element <- serie.point[[dim$dim.model$id]]$name name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$frequency name <- paste(name, frequency, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (series) } reader$CreateSeriesForDataTable <- function (resp, series, data.rows, data.columns) { frequencies.seq <- list(A = "year", H = "6 month", Q = "quarter", M = "month", W = "week", D = "day") for (serie.point in resp) { all.values <- serie.point$values name <- NULL for (dim in reader$dimensions) { name.element <- serie.point[[dim$dim.model$id]]$name name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) dim.name <- dim$dim.model$name if (!name.element %in% data.columns[[dim.name]]) { data.columns[[dim.name]] <- c(data.columns[[dim.name]], name.element) } } frequency <- serie.point$frequency name <- paste(name, frequency, sep = " - ") if (!frequency %in% data.columns[["Frequency"]]) { data.columns[["Frequency"]] <- c(data.columns[["Frequency"]], frequency) } if (is.null(series[[name]])) { series[[name]] <- list() } data.begin <- as.Date(serie.point$startDate) data.end <- as.Date(serie.point$endDate) if (frequency == "W") { data.begin <- data.begin - days(as.numeric(strftime(data.begin,"%u"))-1) data.end <- data.end - days(as.numeric(strftime(data.end,"%u"))-1) } all.dates<- seq(data.begin, data.end, by = frequencies.seq[[frequency]]) index.without.nan <- which(!all.values %in% list(NULL)) dates <- format(all.dates[index.without.nan ], "%Y-%m-%d") data.rows <- unique(c(data.rows, dates)) serie <- setNames(all.values[index.without.nan], dates) series[[name]] <- serie } return (list(series, data.rows, data.columns)) } reader$CreateSeriesForDataFrame <- function(resp, series, data.rows) { frequencies.seq <- list(A = "year", H = "6 month", Q = "quarter", M = "month", W = "week", D = "day") for (serie.point in resp) { all.values <- serie.point$values name <- NULL for (dim in reader$dimensions) { name.element <- serie.point[[dim$dim.model$id]]$name name <- ifelse(is.null(name), name.element, paste(name, name.element, sep = " - ")) } frequency <- serie.point$frequency name <- paste(name, frequency, sep = " - ") if (is.null(series[[name]])) { series[[name]] <- list() } data.begin <- as.Date(serie.point$startDate) data.end <- as.Date(serie.point$endDate) if (frequency == "W") { data.begin <- data.begin - days(as.numeric(strftime(data.begin, "%u"))-1) data.end <- data.end - days(as.numeric(strftime(data.end, "%u"))-1) } all.dates<- seq(data.begin, data.end, by = frequencies.seq[[frequency]]) index.without.nan <- which(!all.values %in% list(NULL)) dates <- format(all.dates[index.without.nan ], "%Y-%m-%d") data.rows <- unique(c(data.rows, dates)) serie <- setNames(all.values[index.without.nan], dates) series[[name]] <- serie } return (list(series, data.rows)) } reader$CreateResultSeries <- function(data, result, type) { switch (type, "DataTable" = { series <- result[[1]] data.rows <- result[[2]] data.columns <- result[[3]] return(reader$CreateSeriesForDataTable(data, series, data.rows, data.columns)) }, "MetaDataTable" = { series <- result [[1]] data.columns <- result[[2]] return(reader$CreateSeriesForMetaDataTable(data, series, data.columns)) }, "DataFrame" = { series <- result[[1]] data.rows <- result[[2]] return(reader$CreateSeriesForDataFrame(data, series, data.rows)) }, "MetaDataFrame" = { return(reader$CreateSeriesForMetaDataFrame(data, result)) }, "ts" = { return(reader$CreateSeriesForTsXtsZoo(data, result)) }, "xts" = { series <- result[[1]] data.rows <- result[[2]] return(reader$CreateSeriesForDataFrame(data, series, data.rows)) }, "zoo" = { return(reader$CreateSeriesForTsXtsZoo(data, result)) }, { error <- simpleError(sprintf("Unknown type %1s", type)) stop(error) } ) } reader$GetObjectForRegularDataset <- function (type, result) { pivot.request <- reader$CreatePivotRequest() pivot.request.json <- pivot.request$SaveToJson() data <- reader$client$GetRawData(pivot.request.json) if (length(data) == 0) { warning(simpleError("Dataset do not have data by this selection")) return (NULL) } result <- reader$CreateResultSeries(data, result, type) return (reader$CreateResultObjectByType(result, type)) } reader$GetObjectByType <- function(type) { reader$LoadDimensions() result <- switch (type, "MetaDataTable" = { list (list(), list()) }, "DataTable" = { list (list(), NULL, list()) }, "DataFrame" = { list (list(), NULL, list()) }, "xts" = { list (list(), NULL, list()) }, list() ) return (reader$GetObjectForRegularDataset(type, result)) } return (reader) } MnemonicsDataReader<- function(client, mnemonics) { reader <- DataReader (client) reader$set("mnemonics", mnemonics) reader$CreateTs <- function(series) { result <- list() frequencies.seq <- list(A = "year", H = "6 month", Q = "quarter", M = "month", W = "week", D = "day") for (i in 1:length(series)) { title.with.freq <- names(series[i]) freq <- substring(title.with.freq, 1, 1) title <- substring(title.with.freq, 5) freq.seq <- unlist(frequencies.seq)[freq] dates <- as.Date(names(series[[i]])) if (length(dates) == 0) { next } min.date <- min(dates) max.date <- max(dates) all.dates <- seq(min.date, max.date, by = freq.seq) values <- sapply(1:length(all.dates), function(x) { dat <- all.dates[x] cond.v <- dat %in% dates return(ifelse (cond.v, series[[i]][[as.character(dat)]], NA)) }) start.by.freq <- switch(freq, "A" = c(year(min.date), 1), "H" = c(year(min.date), (month(min.date)-1)%/%6+1), "Q" = c(year(min.date), quarter(min.date)), "M" = c(year(min.date), month(min.date)), "W" = c(year(min.date), week(min.date)), "D" = c(year(min.date), day(min.date))) result[[title]] <- ts(values, start = start.by.freq, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateXts <- function(series) { result <- list() for (i in 1:length(series)) { title.with.freq <- names(series[i]) if (length(names(series[[i]])) == 0) { next } dates <- as.Date(names(series[[i]])) freq <- substring(title.with.freq, 1, 1) title <- substring(title.with.freq, 5) dates.xts <- switch (freq, "Q" = as.yearqtr(dates), "M" = as.yearmon(dates), dates) values <- unlist(series[[i]], use.names = FALSE) result[[title]] <- xts(values, order.by = dates.xts, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateZoo <- function(series) { result <- list() for (i in 1:length(series)) { title.for.freq <- names(series[i]) dates <- as.Date(names(series[[i]])) if (length(dates) == 0) { next } freq <- substring(title.for.freq, 1, 1) title <- substring(title.for.freq, 5) dates.zoo <- switch (freq, "A" = as.numeric(format(dates, "%Y")), "Q" = as.yearqtr(dates), "M" = as.yearmon(dates), dates ) values <- unlist(series[[i]], use.names = FALSE) result[[title]] <- zoo(values, order.by = dates.zoo, frequency = FrequencyToInt(freq)) } return (result) } reader$CreateSeriesForTsXtsZoo <- function (resp, series, mnemonic) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } frequency <- serie.point$Frequency name <- paste(frequency, mnemonic, sep = " - ") if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) stop(simpleError("Types ts, xts, zoo are not supported for flat datasets"))) series[[name]][time] <- serie.point$Value } return (series) } reader$GetDataFrameByData <- function(data.rows, series) { matrix <- reader$CreateMatrixForFrameOrTable(data.rows, series) data.frame <- as.data.frame(matrix, row.names = data.rows, stringsAsFactors = FALSE) colnames(data.frame) <- substring(names(series),5) return (data.frame) } reader$CreateSeriesForMetaDataTable <- function(resp, series, data.columns, data.rows, mnemonic) { for (serie.point in resp$data) { name.meta <- list() frequency <- serie.point$Frequency name <- paste(frequency, mnemonic, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (!mnemonic %in% data.columns[["Mnemonics"]]) { data.columns[["Mnemonics"]] <- c(data.columns[["Mnemonics"]], mnemonic) } if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (list(series, data.rows, data.columns)) } reader$CreateSeriesForMetaDataFrame <- function (resp, series, mnemonic) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } name.meta <- list() frequency <- serie.point$Frequency name <- paste(frequency, mnemonic, sep = " - ") name.meta <- reader$GetSeriesNameWithMetadata(serie.point) if (is.null(series[[name]])) { series[[name]] <- name.meta } } return (series) } reader$CreateSeriesForDataTable <- function (resp, series, data.rows, data.columns, mnemonic) { for (serie.point in resp$data) { frequency <- serie.point$Frequency name <- paste(frequency, mnemonic, sep = " - ") if (!mnemonic %in% data.columns[["Mnemonics"]]) { data.columns[["Mnemonics"]] <- c(data.columns[["Mnemonics"]], mnemonic) } if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) serie.point$Time) if (!time %in% data.rows) { data.rows <- c(data.rows, time) } series[[name]][time] <- serie.point$Value } return (list(series, data.rows, data.columns)) } reader$CreateSeriesForDataFrame <- function(resp, series, data.rows, mnemonic) { for (serie.point in resp$data) { if (is.null(serie.point$Value)) { next } frequency <- serie.point$Frequency name <- paste(frequency, mnemonic, sep = " - ") if (is.null(series[[name]])) { series[[name]] <- list() } time <- tryCatch(format(as.Date(serie.point$Time), "%Y-%m-%d"), error = function(e) serie.point$Time) if (!time %in% data.rows) { data.rows <- c(data.rows, time) } series[[name]][time] <- serie.point$Value } return (list(series, data.rows)) } reader$CreateAttributesNamesForMetadata <- function(data.rows) { for (dim in reader$dimensions) { for (attr in dim$fields) { if (!attr$isSystemField) { value <- paste(dim$dim.model$name, attr$displayName, sep = " ") if (!value %in% data.rows) { data.rows <- c(data.rows, value) } } } } if (!"Unit" %in% data.rows) { data.rows <- c(data.rows, c("Unit", "Scale", "Mnemonics")) } for (attr in reader$dataset$time.series.attributes) { if (!attr$name %in% data.rows) { data.rows <- c(data.rows, attr$name) } } return(data.rows) } reader$CreateResultObjectByType <- function (result, type) { switch (type, "DataFrame" = { series <- result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetDataFrameByData(data.rows, series) return (data.table) }, "MetaDataFrame" = { series <- result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetDataFrameByData(data.rows, series) return (data.table) }, "DataTable" = { series <- result [[1]] data.rows <- sort(result[[2]]) data.columns <- result[[3]] data.table <- reader$GetFTableByData(data.rows, data.columns, series) return (data.table) }, "MetaDataTable" = { series <- result[[1]] data.rows <- sort(result[[2]]) data.columns <- result[[3]] data.table <- reader$GetFTableByData(data.rows, data.columns, series, FALSE) return (data.table) }, "zoo" = { return (reader$CreateZoo(result)) }, "xts" = { series <- result[[1]] data.rows <- sort(result[[2]]) data.table <- reader$GetXtsByData(data.rows, series) return (data.table) }, "ts" = { return (reader$CreateTs(result)) } ) } reader$CreateResultSeries <- function(data, result, type, mnemonic) { switch (type, "DataTable" = { series <- result[[1]] data.rows <- result[[2]] data.columns <- result[[3]] return(reader$CreateSeriesForDataTable(data, series, data.rows, data.columns, mnemonic)) }, "MetaDataTable" = { series <- result [[1]] data.columns <- result[[3]] data.rows <- result[[2]] return(reader$CreateSeriesForMetaDataTable(data, series, data.columns, data.rows, mnemonic)) }, "DataFrame" = { series <- result[[1]] data.rows <- result[[2]] return(reader$CreateSeriesForDataFrame(data, series, data.rows, mnemonic)) }, "MetaDataFrame" = { res <- reader$CreateSeriesForMetaDataFrame(data, result[[1]], mnemonic) return (list(res, result[[2]])) }, "ts" = { return(reader$CreateSeriesForTsXtsZoo(data, result, mnemonic)) }, "xts" = { series <- result[[1]] data.rows <- result[[2]] return(reader$CreateSeriesForDataFrame(data, series, data.rows, mnemonic)) }, "zoo" = { return(reader$CreateSeriesForTsXtsZoo(data, result, mnemonic)) }, { error <- simpleError(sprintf("Unknown type %1s", type)) stop(error) } ) } reader$GetObjectForSearchingByMnemonicsInOneDataset <- function(type, result) { mnemonics.resp <- reader$client$GetMnemonics(reader$mnemonics) if (length(mnemonics.resp)==0) { warning(simpleError("Series by these mnemonics don't found")) return (NULL) } for (item in mnemonics.resp) { data <- item$pivot if (!IsEqualStringsIgnoreCase(reader$get("dataset")$id, data$dataset)) { next } mnemonic <- item$mnemonics if (type == "MetaDataFrame" || type == "MetaDataTable") { result[[2]] <- reader$CreateAttributesNamesForMetadata (result[[2]]) } result <- reader$CreateResultSeries(data, result, type, mnemonic) } return (reader$CreateResultObjectByType(result, type)) } reader$GetObjectForSearchingByMnemonicsAccrossDatasets <- function(type, result) { mnemonics.resp <- reader$client$GetMnemonics(reader$mnemonics) if (length(mnemonics.resp)==0) { warning(simpleError("Series by these mnemonics don't found")) return (NULL) } datasets.list <- list() dimensions.list <- list() for (item in mnemonics.resp) { data <- item$pivot if (is.null(data)) { next } mnemonic <- item$mnemonics if (type == "MetaDataFrame" || type == "MetaDataTable") { dataset.id <- data$dataset if (!dataset.id %in% names(datasets.list)) { dataset <- Dataset(reader$client$GetDataset(dataset.id)) reader$set("dataset", dataset) datasets.list[[dataset.id]] <- dataset reader$LoadDimensions() dimensions.list[[dataset.id]] <- reader$get("dimensions") result[[2]] <- reader$CreateAttributesNamesForMetadata (result[[2]]) } else { reader$set("dataset", datasets.list[[dataset.id]]) reader$set("dimensions", dimensions.list[[dataset.id]]) } } result <- reader$CreateResultSeries(data, result, type, mnemonic) } return (reader$CreateResultObjectByType(result, type)) } reader$GetObjectByType <- function(type) { result <- switch (type, "MetaDataTable" = { list (list(), NULL, list()) }, "MetaDataFrame" = { list (list(), NULL) }, "DataTable" = { list (list(), NULL, list()) }, "DataFrame" = { list (list(), NULL, list()) }, "xts" = { list (list(), NULL, list()) }, list() ) if (!is.null(reader$dataset)) { reader$LoadDimensions() return (reader$GetObjectForSearchingByMnemonicsInOneDataset(type, result)) } return (reader$GetObjectForSearchingByMnemonicsAccrossDatasets(type, result)) } return (reader) }
ifunc_run_as_addin <- function() { rstudioapi::isAvailable() && rstudioapi::getActiveDocumentContext()$id != " } ifunc_show_alert <- function(run_as_addin) { show_alert <- is.null(getOption("questionr_hide_alert")) if (show_alert) { options(questionr_hide_alert = TRUE) div(class = "alert alert-warning alert-dismissible", HTML('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'), HTML(gettext("<strong>Warning :</strong> This interface doesn't do anything by itself.", domain = "R-questionr")), if (run_as_addin) { HTML(gettext("It will generate R code, insert it in your current R script, and you'll have to run it yourself.", domain = "R-questionr")) } else { HTML(gettext("It only generates R code you'll have to copy/paste into your script and run yourself.", domain = "R-questionr")) } )} } ifunc_get_css <- function() { css.file <- system.file(file.path("shiny", "css", "ifuncs.css"), package = "questionr") out <- paste(readLines(css.file),collapse="\n") HTML(out) } `%||%` <- function(x, y) { if (!is.null(x)) x else y }
input_data <- function(m, filter = FALSE, na = ".", ...) { UseMethod("input_data") } input_data.nm_generic <- function(m, filter = FALSE, na = ".", ...) { file_name <- data_path(m) if (is.na(file_name)) { return(dplyr::tibble()) } if (normalizePath(dirname(file_name), mustWork = FALSE) == normalizePath("DerivedData", mustWork = FALSE)) { d <- read_derived_data(basename(tools::file_path_sans_ext(file_name)), ...) } else { d <- utils::read.csv(file_name, na = na, ...) } if (filter) { data_filter <- parse(text = data_filter_char(m, data = d)) d <- subset(d, eval(data_filter)) } d } input_data.nm_list <- function(m, filter = FALSE, na = ".", ...) { data_paths <- data_path(m) if (length(unique(data_paths)) != 1) stop("multiple data files detected. Aborting...") m <- as_nm_generic(m[[1]]) d <- input_data(m, filter = filter, na = na, ...) d } ignore <- function(ctl, ignore_char) { UseMethod("ignore") } ignore.nm_generic <- function(ctl, ignore_char) { m <- ctl if (missing(ignore_char)) { return(data_ignore_char(m)) } ctl <- ctl_contents(m) ctl <- update_ignore(ctl, ignore_char) m <- m %>% ctl_contents_simple(ctl) m } ignore.nm_list <- Vectorize_nm_list(ignore.nm_generic, replace_arg = "ignore_char") update_ignore <- function(ctl, ignore_char) { ctl <- ctl_list(ctl) ignore_present <- any(grepl(".*IGNORE\\s*=\\s*\\(", ctl$DATA)) if (ignore_present) { ctl$DATA <- ctl$DATA[!grepl("^(\\s*)IGNORE\\s*=\\s*\\(*\\S[^\\)]+\\)*(\\s*)$", ctl$DATA)] ctl$DATA <- gsub( "(.*)IGNORE\\s*=\\s*\\(+\\S[^\\)]+\\)+(.*)", "\\1\\2", ctl$DATA ) } ignore_char <- gsub("\\s*\\|\\s*", ", ", ignore_char) ignore_char <- gsub("==", ".EQ.", ignore_char) ignore_char <- gsub("!=", ".NE.", ignore_char) ignore_char <- gsub(">", ".GT.", ignore_char) ignore_char <- gsub("<", ".LT.", ignore_char) ignore_char <- gsub(">=", ".GE.", ignore_char) ignore_char <- gsub("<=", ".LE.", ignore_char) ignore_char <- gsub("\\s+(\\.\\S+\\.)\\s+", "\\1", ignore_char) ignore_char <- paste0("IGNORE=(", ignore_char, ")") last_line <- ctl$DATA[length(ctl$DATA)] if (grepl("^\\s*$", last_line)) { ctl$DATA[length(ctl$DATA)] <- ignore_char } else { ctl$DATA <- append(ctl$DATA, ignore_char) } ctl$DATA <- append(ctl$DATA, "") ctl }
NULL ip_address <- function(x = character()) { wrap_parse_address(x) } new_ip_address <- function(address1 = integer(), address2 = integer(), address3 = integer(), address4 = integer(), is_ipv6 = logical()) { vec_assert(address1, ptype = integer()) vec_assert(address2, ptype = integer()) vec_assert(address3, ptype = integer()) vec_assert(address4, ptype = integer()) vec_assert(is_ipv6, ptype = logical()) new_rcrd(list( address1 = address1, address2 = address2, address3 = address3, address4 = address4, is_ipv6 = is_ipv6 ), class = "ip_address") } is_ip_address <- function(x) inherits(x, "ip_address") as_ip_address <- function(x) UseMethod("as_ip_address") as_ip_address.character <- function(x) ip_address(x) as_ip_address.ip_interface <- function(x) { new_ip_address( field(x, "address1"), field(x, "address2"), field(x, "address3"), field(x, "address4"), field(x, "is_ipv6") ) } as.character.ip_address <- function(x, ...) wrap_print_address(x) format.ip_address <- function(x, exploded = FALSE, ...) { wrap_print_address(x, exploded) } vec_proxy_compare.ip_address <- function(x, ...) wrap_compare_address(x) vec_ptype_abbr.ip_address <- function(x, ...) { "ip_addr" }
teardown({ file.remove(exist_file) purrr::walk(exist_file_list, file.remove) }) test_that("Test files as expected", { expect_true(file.exists(exist_file)) expect_true(all(file.exists(exist_file_vector))) expect_false(file.exists(bad_file)) }) test_that("Test file utils work", { expect_invisible(cmd_error_if_missing(exist_file_list)) expect_invisible(cmd_error_if_missing(exist_file_vector)) expect_invisible(cmd_error_if_missing(exist_file)) expect_error(cmd_error_if_missing(bad_file), "was not found") }) test_that("UI file exists works", { expect_invisible(cmd_ui_file_exists(exist_file)) expect_message(cmd_ui_file_exists(exist_file), cli::symbol$tick) expect_message(cmd_ui_file_exists(bad_file), cli::symbol$cross) expect_error(cmd_ui_file_exists(exist_file_vector), "length 1") expect_error(cmd_ui_file_exists(exist_file_list)) })
mlnormal_soft_thresholding <- function( x, lambda ) { x_abs <- abs(x) x <- ifelse( x_abs > lambda, x - sign(x) * lambda, 0 ) return(x) }
nsplit <- function(p, G, use.all = TRUE, fix.partition = NULL){ if(length(G)>1){ n.splits <- numeric(length(G)) for(g.ind in 1:length(G)){ n.splits[g.ind] <- nsplit(p, G[g.ind], use.all=use.all, fix.partition=fix.partition[[g.ind]]) } return(n.splits) } if(any(c(!is.numeric(p), length(p)!=1, p<1, !(p%%1==0)))) stop("p should be a positive interger.") if(any(c(!is.numeric(G), any(G<1), !any((G%%1==0)), any(G>p)))) stop("G should be a positive interger less or equal to p.") if(!is.null(fix.partition)){ if(any(!is.matrix(fix.partition), ncol(fix.partition)!=G)) stop("fix.partition should be a matrix with G columns") fix.sum <- rowSums(fix.partition) if(use.all) if(any(fix.sum!=p)) stop("The number of variables used does not sum to p. Set use.all to FALSE if needed.") else if(any(fix.sum>p)) stop("Some fixed partitions have an invalid number of total variables") } if(G==p) return(1) n.splits <- numeric(1) for(g in G){ if(is.null(fix.partition)) partitions <- generate_partitions(p, G, use.all) else partitions <- fix.partition for(n.partition in 1:nrow(partitions)){ n.splits <- n.splits + multicool::multinom(c(partitions[n.partition,],p-sum(partitions[n.partition,])), counts=TRUE)/ prod(factorial(table(partitions[n.partition,]))) } } return(n.splits) }
storeMetaChunkWise <- function(meta_envir,con, schema = "timeseries", tbl = "meta_data_unlocalized", keys=NULL, chunksize = NULL, quiet = T){ warning("chunkwise storage is deprecated. Simply use updateMetaInformation, which capable of COPY-based bulk inserts now.") updateMetaInformation(meta = meta_envir, con = con, schema = schema, tbl = tbl, keys = ls(envir = meta_envir), quiet = quiet) }
library(lavaan) data(sesamesim) sesameCFA <- sesamesim names(sesameCFA)[6] <- "pea" model1 <- ' A =~ Ab + Al + Af + An + Ar + Ac B =~ Bb + Bl + Bf + Bn + Br + Bc ' fit1 <- sem(model1, data = sesameCFA, std.lv = TRUE) hypotheses1 <- "A=~Ab > .6 & A=~Al > .6 & A=~Af > .6 & A=~An > .6 & A=~Ar > .6 & A=~Ac >.6 & B=~Bb > .6 & B=~Bl > .6 & B=~Bf > .6 & B=~Bn > .6 & B=~Br > .6 & B=~Bc >.6" set.seed(100) y <- bain(fit1,hypotheses1,standardize = TRUE) y_gor <- gorica(fit1,hypotheses1, standardize = TRUE) test_that("bain and gorica give similar results", { expect_equivalent(y$fit$PMPb[1:2], y_gor$fit$gorica_weights, tolerance = .1) })
Cy0 <- function(object, plot = FALSE, add = FALSE, ...) { cpD1 <- efficiency(object, plot = FALSE)$cpD1 Fluo <- as.numeric(predict(object, newdata = data.frame(Cycles = cpD1), which = "y")) slope <- object$MODEL$d1(cpD1, t(coef(object))) Cy0 <- cpD1 - (Fluo/slope) if (plot) { plot(object, ...) add = TRUE } if (add) { points(cpD1, Fluo, col = "blueviolet", pch = 16, ...) abline((-cpD1 * slope) + Fluo, slope) abline(h = 0) points(Cy0, 0, col = "blueviolet", pch = 16, ...) } return(round(Cy0, 2)) }
graphUpdateOne <- function (w, G, vec01) { n <-length(w) locZero <- which(vec01 == 0) if (length(locZero) == 0) { result <- list(w=w, G=G, vec01=vec01, isNodeRemoved=FALSE) return (result) } rmIndex <- locZero[1] for (i in 1:n) { if (i != rmIndex) { w[i] <- w[i] + w[rmIndex]*G[rmIndex,i] for (j in 1:n) { if ( (j != i) & (j != rmIndex)) { G[i,j] <- (G[i,j] + G[i,rmIndex]*G[rmIndex,j])/(1-G[i,rmIndex]*G[rmIndex,i]) } } } } result <- list(w=w[-rmIndex], G=G[-rmIndex,-rmIndex], vec01=vec01[-rmIndex], isNodeRemoved=TRUE) return (result) } graphUpdate <- function (w, G, vec01) { n <-length(w) locZero <- which(vec01 == 0) if (length(locZero) == 0) { result <- list(w=w, G=G, isNodeRemoved=FALSE) return (result) } for (k in 1:length(locZero)) { tmp <- graphUpdateOne(w=w,G=G,vec01=vec01) w <- tmp$w G <- tmp$G vec01 <- tmp$vec01 } result <- list(w=w, G=G, isNodeRemoved=TRUE) return (result) }
.ts_lastplot_env <- new.env(parent = emptyenv()) ts_plot <- function(..., title, subtitle, ylab = "", family = getOption("ts_font", "sans")) { value <- NULL id <- NULL x <- ts_dts(ts_c(...)) if (nrow(ts_na_omit(x)) == 0L) stop0("no data values to plot") x <- combine_id_cols(x) if (missing("title")) { has.title <- FALSE } else { has.title <- TRUE } if (missing("subtitle")) { has.subtitle <- FALSE } else { has.subtitle <- TRUE } op <- par(no.readonly = TRUE) cex <- 0.9 title.cex <- 1.2 text.col <- "grey10" axis.text.col <- text.col col.lab <- axis.text.col if (number_of_series(x) > 1) { has.legend <- TRUE } else { has.legend <- FALSE } if (has.legend) { mar.b <- 4.5 } else { mar.b <- 2 } if (has.title && has.subtitle) { mar.t <- 4 } else if (has.title || has.subtitle) { mar.t <- 3 } else { mar.t <- 1 } if (ylab == "") { mar.l <- 3 } else { mar.l <- 4 } par( fig = c(0, 1, 0, 1), oma = c(0.5, 1, 2, 1), mar = c(0, 0, 0, 0), col.lab = col.lab, cex.lab = 0.8, family = family ) plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n") if (has.title) { mtext( title, cex = title.cex, side = 3, line = 0, adj = 0, font = 2, col = text.col ) } if (has.subtitle) { shift <- if (has.title) -1.2 else 0 mtext( subtitle, cex = cex, side = 3, line = shift, adj = 0, col = text.col ) } cid <- dts_cname(x)$id ctime <- dts_cname(x)$time cvalue <- dts_cname(x)$value if (length(cid) == 0L) { x$id <- "dummy" cid <- "id" setcolorder(x, c("id", ctime, cvalue)) } setnames( x, c(cid, ctime, cvalue), c("id", "time", "value") ) tind <- as.POSIXct(x[, time]) tnum <- as.numeric(tind) xlim <- range(tnum) values <- x[, value] values[!is.finite(values)] <- NA ylim <- range(values, na.rm = TRUE) xticks <- pretty(tind) xlabels <- attr(xticks, "labels") ids <- as.character(unique(x[, id])) if ((length(ids)) > 20L) { message("too many series. Only showing the first 20.") ids <- ids[1:20] } col <- getOption("tsbox.col", colors_tsbox()) lty <- getOption("tsbox.lty", "solid") lwd <- getOption("tsbox.lwd", 1.5) recycle_par <- function(x) { x0 <- x[1:(min(length(x), length(ids)))] cbind(ids, x0)[, 2] } col <- recycle_par(col) lty <- recycle_par(lty) lwd <- recycle_par(lwd) if (has.legend) { legend( "bottomleft", legend = ids, horiz = TRUE, bty = "n", lty = lty, lwd = lwd, col = col, cex = 0.9 * cex, adj = 0, text.col = text.col ) } par(mar = c(mar.b, mar.l, mar.t, 1.4), new = TRUE) plot( x = tind, type = "n", lty = lty[1], pch = 19, col = 1, cex = 1.5, lwd = lwd[1], las = 1, bty = "n", xaxt = "n", xlim = xlim, ylim = ylim, xlab = "", ylab = ylab, yaxt = "n" ) axis( 2, at = axTicks(2), labels = sprintf("%s", axTicks(2)), las = 1, cex.axis = 0.8, col = NA, line = -0.5, col.axis = axis.text.col ) axis( side = 1, at = (xticks), labels = xlabels, las = 1, cex.axis = 0.8, col = NA, line = 0.5, tick = TRUE, padj = -2, col.axis = axis.text.col ) abline(h = axTicks(2), v = xticks, col = "grey80", lty = "dotted", lwd = 0.5) for (i in seq(ids)) { .idi <- ids[i] cd <- x[id == .idi] cd <- cd[!is.na(value)] x.i <- as.numeric(as.POSIXct(cd[, time])) lines( y = cd[, value], x = x.i, col = col[i], lty = lty[i], lwd = lwd[i] ) } cl <- match.call() assign("ts_lastplot_call", cl, envir = .ts_lastplot_env) } ts_lastplot_call <- function() { get("ts_lastplot_call", envir = .ts_lastplot_env) } ts_save <- function(filename = tempfile(fileext = ".pdf"), width = 10, height = 5, device = NULL, open = TRUE) { if (!grepl("\\.[a-z]+$", filename) && is.null(device)) { filename <- paste0(filename, ".pdf") } if (is.null(device)) { device <- gsub(".*\\.([a-z]+)$", "\\1", tolower(filename)) } else { filename <- gsub("\\.[a-z]+$", paste0(".", device), tolower(filename)) } filename <- normalizePath(filename, mustWork = FALSE) cl <- ts_lastplot_call() if (is.null(cl) || !inherits(cl, "call")) { stop0("ts_plot() must be called first.") } if (device == "pdf") { pdf(file = filename, width = width, height = height) } else if (device == "png") { png( filename = filename, width = width, height = height, units = "in", res = 150 ) } else if (device == "bmp") { bmp( filename = filename, width = width, height = height, units = "in", res = 150 ) } else if (device == "jpeg") { jpeg( filename = filename, width = width, height = height, units = "in", res = 150 ) } else if (device == "tiff") { tiff( filename = filename, width = width, height = height, units = "in", res = 150 ) } else { stop0("device not supported: ", device) } eval(cl, envir = parent.frame()) dev.off() if (open) browseURL(filename) invisible(TRUE) }
context("scatterplot") test_that("test scales", { expect_silent(plot_scatterplot(na.omit(airquality), by = "Ozone", scale_x = "reverse", scale_y = "sqrt")) expect_silent(plot_scatterplot(iris, by = "Species", scale_y = "log10")) expect_error(plot_scatterplot(iris, by = "Species", scale_x = "log10")) expect_error(plot_scatterplot(iris, by = "Species", scale_x = "log")) }) test_that("test return object", { scatterplot_list <- plot_scatterplot(iris, by = "Species") expect_is(scatterplot_list, "list") expect_equal(names(scatterplot_list), "page_1") expect_true(is.ggplot(scatterplot_list[[1]])) scatterplot_list2 <- plot_scatterplot(iris, by = "Species", nrow = 1L, ncol = 1L) expect_is(scatterplot_list2, "list") expect_equal(names(scatterplot_list2), c("page_1", "page_2", "page_3", "page_4")) expect_true(all(vapply(scatterplot_list2, is.ggplot, TRUE))) })
"data.gen1"
context("looping in pipelines") foo <- function(x){ sqrt(x) %v>% is.na } test_that("Lists over nested functions produce the correct output", { expect_equal( -1:1 %>>% { lapply(., foo) } %>% {sapply(.single_value(.), is_rmonad)}, c(TRUE, TRUE, TRUE) ) expect_equal( -1:1 %>>% { lapply(., foo) } %>>% combine %>% .single_value, list(TRUE, FALSE, FALSE) ) expect_equal( -1:1 %>% { lapply(., foo) } %>% combine %>% .single_value, -1:1 %>>% { lapply(., foo) } %>>% combine %>% .single_value ) })
expected <- eval(parse(text="\"pkgB_.tar.gz\"")); test(id=0, code={ argv <- eval(parse(text="list(\"([[:digit:]]+[.-]){1,}[[:digit:]]+\", \"\", \"pkgB_1.0.tar.gz\", FALSE, FALSE, FALSE, FALSE)")); .Internal(`gsub`(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
context("Spellchecker") test_that("Error if not interactive", { skip_if(interactive()) expect_error(check_spelling(rstudio = TRUE), regexp = "interactive") }) test_that("School funding report checks out", { expect_null(check_spelling("./SchoolFunding/SchoolFunding.tex", known.correct = c("SRS", "SE.XPD.TOTL.GD.XS", "WDI", "SSNP", "underfunded", "overfund[a-z]*", "NMS", "WPI", "DET", "phas", "NP", "SATs", "ENG", "th", "stds", "RCTs", "CAGR"), ignore.lines = 1551)) }) test_that("Check spelling of multiple input document", { expect_error(check_spelling("./spellcheck_multi_input/spellcheck_multi_input.tex"), regexp = "failed on above line") }) test_that("Abbreviations", { expect_error(check_spelling("spellcheck-abbrevs.tex")) }) test_that("Initalisms", { expect_null(check_spelling("./spelling/abbrev/abbrev-defd-ok.tex")) expect_null(check_spelling("./spelling/abbrev/abbrev-defd-ok-2.tex")) expect_equal(extract_validate_abbreviations(readLines("./spelling/abbrev/abbrev-defd-ok-stopwords.tex")), c("QXFEoC", "AIAS")) expect_equal(extract_validate_abbreviations(readLines("./spelling/abbrev/abbrev-plural.tex")), c("LVR")) }) test_that("Initialism checking doesn't fail if at start of sentence", { expect_null(check_spelling("./spelling/abbrev/abbrev-at-line-start.tex")) }) test_that("Add to dictionary, ignore spelling in", { expect_error(check_spelling("./spelling/add_to_dictionary-wrong.tex"), regexp = "[Ss]pellcheck failed") expect_error(check_spelling("./spelling/ignore_spelling_in-wrong.tex", pre_release = FALSE), regexp = "[Ss]pellcheck failed") expect_null(check_spelling("./spelling/add_to_dictionary-ok.tex")) expect_null(check_spelling("./spelling/ignore_spelling_in-ok.tex", pre_release = FALSE)) expect_null(check_spelling("./spelling/ignore_spelling_in-ok-2.tex", pre_release = FALSE)) expect_error(check_spelling("./spelling/ignore_spelling_in-ok.tex"), regexp = "pre_release = TRUE") expect_null(check_spelling("./spelling/add_to_dictionary-ok-req-hunspell.tex", pre_release = FALSE)) }) test_that("Ignore spelling in input", { expect_error(check_spelling("./spelling/input/a.tex", pre_release = TRUE), regexp = "Spellcheck failed on above line with .asofihsafioh") expect_null(check_spelling("./spelling/input/a.tex", pre_release = FALSE)) expect_null(check_spelling("./spelling/input/b.tex", pre_release = TRUE)) }) test_that("Stop if present", { expect_error(check_spelling("./stop_if_present/should-stop.tex"), regexp = "skillset") expect_error(check_spelling("./stop_if_present/should-stop-2.tex"), regexp = "skillset") expect_error(check_spelling("./stop_if_present/stop_even_if_added.tex"), regexp = "skillset") expect_error(check_spelling("./stop_if_present_inputs/stop-if-held-in-inputs.tex"), regexp = "skillset") expect_error(check_spelling("./stop_if_present/should-stop-3.tex"), regexp = "percent") expect_null(check_spelling("./stop_if_present/should-not-stop.tex")) }) test_that("Lower-case governments should error", { expect_error(check_spelling("./spelling/Govt/NSWgovt.tex"), regexp = "uppercase G") expect_error(check_spelling("./spelling/Govt/ACTgovt.tex"), regexp = "uppercase G") expect_error(check_spelling("./spelling/Govt/NTgovt.tex"), regexp = "uppercase G") expect_error(check_spelling("./spelling/Govt/Queenslandgovt.tex"), regexp = "uppercase G") expect_error(check_spelling("./spelling/Govt/WAgovt.tex"), regexp = "uppercase G") }) test_that("Some lower-case governments should not", { expect_null(check_spelling("./spelling/Govt/ok-as-adj.tex")) expect_null(check_spelling("./spelling/Govt/ok-as-adj2.tex")) }) test_that("'percent' error should only occur in a Grattan report", { percent_spellcheck.tex <- tempfile(fileext = ".tex") writeLines( text = c("\\documentclass{article}", "\\begin{document}", "The word percent is not invalid.", "\\end{document}"), con = percent_spellcheck.tex ) expect_null(check_spelling(percent_spellcheck.tex)) }) test_that("Includepdf doesn't result in a failed include message", { expect_null(check_spelling("./spelling/includepdf-ok.tex")) }) test_that("Should error", { expect_error(check_spelling("spelling/misc-error.tex"), regexp = "Spellcheck") expect_error(check_spelling("spelling/typo-suggest.tex"), regex = "Spellcheck") }) test_that("RStudio API", { skip_on_cran() skip_if_not(interactive()) expect_error(check_spelling("spelling/typo-suggest.tex", rstudio = TRUE), regexp = "Spellcheck") expect_false(Sys.info()['sysname'] %in% "Windows" && utils::readClipboard() != "Sydney") }) test_that("Inputs should respect dict_lang at top level", { expect_null(check_spelling("spelling/dict-lang-input/root.tex", dict_lang = "en_US")) }) test_that("Lonesome footcites", { footcite.tex <- tempfile(fileext = ".tex") writeLines(c("\\documentclass{article}", "\\begin{document}", "A claim.\\footnote{textcite{not-yet-cited}.}", "\\end{document}", ""), footcite.tex) expect_error(check_spelling(footcite.tex), regexp = "[Ss]pellcheck") }) test_that("Multi-ignore", { multi.tex <- tempfile(fileext = ".tex") writeLines(c("\\documentclass{article}", "\\begin{document}", "A claim.\\mymulticmd{okay}{sudifhds}{ihsodfidoshf}", "\\end{document}", ""), multi.tex) expect_null(check_spelling(multi.tex, ignore_spelling_in_nth = list("mymulticmd" = 2:3))) expect_error(check_spelling(multi.tex, ignore_spelling_in_nth = list("mymulticmd" = c(1L, 3L))), regexp = "sudifhds") }) test_that("Like Energy-2018-WholesaleMarketPower", { expect_null(check_spelling("spelling/chapref/in-comments.tex", ignore_spelling_in_nth = list(Chaprefrange = 1:2))) }) test_that("Spellcheck verb", { expect_null(check_spelling("spelling/verb.tex")) }) test_that("pre-release + add to dictionary outside", { tempfile.tex <- tempfile(fileext = ".tex") writeLines(c("\\documentclass{article}", "% add_to_dictionary: ok", "\\begin{document}", "% add_to_dictionary: notok", "Not ok.", "\\end{document}"), tempfile.tex) expect_null(check_spelling(tempfile.tex, pre_release = FALSE)) expect_error(check_spelling(tempfile.tex, pre_release = TRUE), regexp = "When pre_release = TRUE, % add_to_dictionary: lines must not be situated outside the document preamble.", fixed = TRUE) }) test_that("known.correct.fixed", { tempfile.tex <- tempfile(fileext = ".tex") writeLines(c("\\documentclass{article}", "% add_to_dictionary: ok", "\\begin{document}", "QETYY-high.", "\\end{document}"), tempfile.tex) expect_null(check_spelling(tempfile.tex, pre_release = FALSE, known.correct.fixed = "QETYY")) }) test_that("get_file_path.works", { expect_equal(get_input_file_path(.path = "./nest1", .input = "nest1/nest2/file.tex"), "./nest1/nest2/file.tex") expect_equal(get_input_file_path(.path = "./nest1", .input = "nest2/file.tex"), "./nest1/nest2/file.tex") expect_equal(get_input_file_path(.path = "./nest1", .input = "file.tex"), "./nest1/file.tex") }) test_that("Nested inputs", { skip_on_cran() temp_dir <- tempfile() hutils::provide.dir(temp_dir) hutils::provide.dir(file.path(temp_dir, "tex")) hutils::provide.dir(file.path(temp_dir, "tex", "bo")) root.tex <- file.path(temp_dir, "root.tex") skip_if_not(file.create(root.tex)) writeLines(c("\\documentclass{article}", "\\input{tex/preamble}", "\\begin{document}", "\\input{tex/a}", "\\input{tex/b}", "\\end{document}"), root.tex) writeLines(c("\\input{tex/b}", "\\input{tex/bo/ra}", "\\end{document}"), file.path(temp_dir, "tex", "a.tex")) writeLines(c("\\textbf{ok}", "ok"), file.path(temp_dir, "tex", "b.tex")) writeLines(c("\\textbf{njok}", "ok"), file.path(temp_dir, "tex", "bo", "ra.tex")) expect_error(check_spelling(root.tex), regexp = "njok") expect_null(check_spelling(root.tex, ignore_spelling_in = "textbf")) expect_null(check_spelling(file.path(temp_dir, "tex", "a.tex"), tex_root = temp_dir, ignore_spelling_in = "textbf")) })
stat.anova <- function(table, test=c("Rao","LRT","Chisq", "F", "Cp"), scale, df.scale, n) { test <- match.arg(test) dev.col <- match("Deviance", colnames(table)) if (test == "Rao") dev.col <- match("Rao", colnames(table)) if (is.na(dev.col)) dev.col <- match("Sum of Sq", colnames(table)) switch(test, "Rao" = ,"LRT" = ,"Chisq" = { dfs <- table[, "Df"] vals <- table[, dev.col]/scale * sign(dfs) vals[dfs %in% 0] <- NA vals[!is.na(vals) & vals < 0] <- NA cbind(table, "Pr(>Chi)" = pchisq(vals, abs(dfs), lower.tail = FALSE) ) }, "F" = { dfs <- table[, "Df"] Fvalue <- (table[, dev.col]/dfs)/scale Fvalue[dfs %in% 0] <- NA Fvalue[!is.na(Fvalue) & Fvalue < 0] <- NA cbind(table, F = Fvalue, "Pr(>F)" = pf(Fvalue, abs(dfs), df.scale, lower.tail = FALSE) ) }, "Cp" = { if ("RSS" %in% names(table)) { cbind(table, Cp = table[, "RSS"] + 2*scale*(n - table[, "Res.Df"])) } else { cbind(table, Cp = table[, "Resid. Dev"] + 2*scale*(n - table[, "Resid. Df"])) } }) } printCoefmat <- function(x, digits = max(3L, getOption("digits") - 2L), signif.stars = getOption("show.signif.stars"), signif.legend = signif.stars, dig.tst = max(1L, min(5L, digits - 1L)), cs.ind = 1:k, tst.ind = k+1, zap.ind = integer(), P.values = NULL, has.Pvalue = nc >= 4L && length(cn <- colnames(x)) && substr(cn[nc], 1L, 3L) %in% c("Pr(", "p-v"), eps.Pvalue = .Machine$double.eps, na.print = "NA", quote = FALSE, right = TRUE, ...) { if(is.null(d <- dim(x)) || length(d) != 2L) stop("'x' must be coefficient matrix/data frame") nc <- d[2L] if(is.null(P.values)) { scp <- getOption("show.coef.Pvalues") if(!is.logical(scp) || is.na(scp)) { warning("option \"show.coef.Pvalues\" is invalid: assuming TRUE") scp <- TRUE } P.values <- has.Pvalue && scp } else if(P.values && !has.Pvalue) stop("'P.values' is TRUE, but 'has.Pvalue' is not") if(has.Pvalue && !P.values) { d <- dim(xm <- data.matrix(x[,-nc , drop = FALSE])) nc <- nc - 1 has.Pvalue <- FALSE } else xm <- data.matrix(x) k <- nc - has.Pvalue - (if(missing(tst.ind)) 1 else length(tst.ind)) if(!missing(cs.ind) && length(cs.ind) > k) stop("wrong k / cs.ind") Cf <- array("", dim=d, dimnames = dimnames(xm)) ok <- !(ina <- is.na(xm)) for (i in zap.ind) xm[, i] <- zapsmall(xm[, i], digits) if(length(cs.ind)) { acs <- abs(coef.se <- xm[, cs.ind, drop=FALSE]) if(any(ia <- is.finite(acs))) { digmin <- 1 + if(length(acs <- acs[ia & acs != 0])) floor(log10(range(acs[acs != 0], finite = TRUE))) else 0 Cf[,cs.ind] <- format(round(coef.se, max(1L, digits - digmin)), digits = digits) } } if(length(tst.ind)) Cf[, tst.ind] <- format(round(xm[, tst.ind], digits = dig.tst), digits = digits) if(any(r.ind <- !((1L:nc) %in% c(cs.ind, tst.ind, if(has.Pvalue) nc)))) for(i in which(r.ind)) Cf[, i] <- format(xm[, i], digits = digits) ok[, tst.ind] <- FALSE okP <- if(has.Pvalue) ok[, -nc] else ok x1 <- Cf[okP] dec <- getOption("OutDec") if(dec != ".") x1 <- chartr(dec, ".", x1) x0 <- (xm[okP] == 0) != (as.numeric(x1) == 0) if(length(not.both.0 <- which(x0 & !is.na(x0)))) { Cf[okP][not.both.0] <- format(xm[okP][not.both.0], digits = max(1L, digits - 1L)) } if(any(ina)) Cf[ina] <- na.print if(P.values) { if(!is.logical(signif.stars) || is.na(signif.stars)) { warning("option \"show.signif.stars\" is invalid: assuming TRUE") signif.stars <- TRUE } if(any(okP <- ok[,nc])) { pv <- as.vector(xm[, nc]) Cf[okP, nc] <- format.pval(pv[okP], digits = dig.tst, eps = eps.Pvalue) signif.stars <- signif.stars && any(pv[okP] < .1) if(signif.stars) { Signif <- symnum(pv, corr = FALSE, na = FALSE, cutpoints = c(0, .001,.01,.05, .1, 1), symbols = c("***","**","*","."," ")) Cf <- cbind(Cf, format(Signif)) } } else signif.stars <- FALSE } else signif.stars <- FALSE print.default(Cf, quote = quote, right = right, na.print = na.print, ...) if(signif.stars && signif.legend) { if((w <- getOption("width")) < nchar(sleg <- attr(Signif,"legend"))) sleg <- strwrap(sleg, width = w - 2, prefix = " ") cat("---\nSignif. codes: ", sleg, sep = "", fill = w+4 + max(nchar(sleg,"bytes") - nchar(sleg))) } invisible(x) } print.anova <- function(x, digits = max(getOption("digits") - 2L, 3L), signif.stars = getOption("show.signif.stars"), ...) { if (!is.null(heading <- attr(x, "heading"))) cat(heading, sep = "\n") nc <- dim(x)[2L] if(is.null(cn <- colnames(x))) stop("'anova' object must have colnames") has.P <- grepl("^(P|Pr)\\(", cn[nc]) zap.i <- 1L:(if(has.P) nc-1 else nc) i <- which(substr(cn,2,7) == " value") i <- c(i, which(!is.na(match(cn, c("F", "Cp", "Chisq"))))) if(length(i)) zap.i <- zap.i[!(zap.i %in% i)] tst.i <- i if(length(i <- grep("Df$", cn))) zap.i <- zap.i[!(zap.i %in% i)] printCoefmat(x, digits = digits, signif.stars = signif.stars, has.Pvalue = has.P, P.values = has.P, cs.ind = NULL, zap.ind = zap.i, tst.ind = tst.i, na.print = "", ...) invisible(x) }
web_table <- function(data , caption = NULL , digits = 2 , rnames = FALSE , buttons = NULL , file_name = "file" , scrolly = NULL ){ if(!is.data.frame(data)) stop("Use a data frame or table") where <- NULL if(is.null(scrolly)) scrolly <- "60vh" if (is.null(buttons)) { ext <- c('Buttons', 'Scroller') } else { ext <- c('Scroller') } botones <- list( list(extend = 'copy') , list(extend = 'excel', filename = file_name) ) data %>% mutate(across(where(is.numeric), ~round(., digits = digits))) %>% datatable(extensions = ext , rownames = rnames , options = list( dom = 'Bt' , buttons = botones , deferRender = TRUE , scroller = TRUE , scrollX = TRUE , scrollY = scrolly , columnDefs = list(list(width = '200px' , targets = "_all")) , initComplete = DT::JS( "function(settings, json) {", "$(this.api().table().header()).css({'background-color': ' "}") ) , caption = caption) }
"States"
library(Polychrome) set.seed(4528) tempPal <- createPalette(40, c(" tempPal <- tempPal[-(1:2)] swatch(tempPal) tempPal.deut <- colorDeficit(tempPal, "deut") tempPal.prot <- colorDeficit(tempPal, "prot") tempPal.trit <- colorDeficit(tempPal, "trit") shift <- function(i, k=length(tempPal)) c(i, 1:(i-1), (1+i):k) co <- shift(13) pd <- computeDistances(tempPal.deut[co]) pp <- computeDistances(tempPal.prot[co]) pt <- computeDistances(tempPal.trit[co]) rd <- rank(pd)[order(names(pd))] rp <- rank(pd)[order(names(pp))] rt <- rank(pd)[order(names(pt))] score <- 2*rd + 1.5*rp + rt x <- tempPal[names(rev(sort(score)))][1:12] plotDistances(x,cex=2) y <- colorDeficit(x, "deut") z <- colorDeficit(x, "prot") w <- colorDeficit(x, "trit") opar <- par(mfrow=c(2,2)) swatch(x, main="Normal") swatch(y, main="Deuteranope") swatch(z, main="Protanope") swatch(w, main="Tritanope") par(opar) names(x) <- colorNames(x) safeColors <- x plotDistances(safeColors,cesafeColors=2) opar <- par(mfrow=c(2,2)) swatch(safeColors) swatchHue(safeColors) swatchLuminance(safeColors) ranswatch(safeColors) par(opar) rancurves(safeColors, lwd=3) ranpoints(safeColors, cesafeColors=1.5) uvscatter(safeColors) luminance(safeColors) plothc(safeColors) plotpc(safeColors)
policyMatrix <- function(network, ..., useDefaultPolicies = TRUE) { coll <- checkmate::makeAssertCollection() utility_nodes <- names(network[["nodeUtility"]])[vapply(X = network[["nodeUtility"]], FUN = identity, FUN.VALUE = logical(1))] decision_nodes <- names(network$nodeDecision)[vapply(X = network[["nodeDecision"]], FUN = identity, FUN.VALUE = logical(1))] decision_nodes <- decision_nodes[!decision_nodes %in% utility_nodes] defaultPolicies <- network[["nodePolicyValues"]][decision_nodes] policies <- list(...) policies <- policies[!names(policies) %in% utility_nodes] if (!length(policies)) return(defaultPolicyMatrix(network)) checkmate::assertSubset(x = names(policies), choices = network[["nodes"]], add = coll) checkmate::reportAssertions(coll) if (any(names(policies) %in% names(defaultPolicies))){ defaultPolicies <- defaultPolicies[!names(defaultPolicies) %in% names(policies)] } expand.grid(c(policies, defaultPolicies), stringsAsFactors=FALSE) } defaultPolicyMatrix <- function(network) { coll <- checkmate::makeAssertCollection() utility_nodes <- names(network[["nodeUtility"]])[vapply(X = network[["nodeUtility"]], FUN = identity, FUN.VALUE = logical(1))] decision_nodes <- names(network[["nodeDecision"]])[vapply(X = network[["nodeDecision"]], FUN = identity, FUN.VALUE = logical(1))] decision_nodes <- decision_nodes[!decision_nodes %in% utility_nodes] if (!length(decision_nodes)) coll$push(paste0("There are no decision nodes in '", substitute(network), "'.")) decision_options <- lapply(decision_nodes, policyMatrixValues, network) names(decision_options) <- decision_nodes expand.grid(decision_options) }
fit_univariate <- function(x, distribution, type = 'continuous') { stopifnot(type == 'discrete' & is.integer(x) | type == 'continuous' & is.double(x) | type == 'empirical' & is.numeric(x)) discreteDists <- c('geom', 'nbinom', 'pois', 'dunif') continuousDists <- c('exp', 'cauchy', 'gamma', 'lnorm', 'norm', 'unif', 'weibull', 'llogis', 'logis', 'invweibull', 'invgamma') if (!distribution %in% c(discreteDists, continuousDists, 'empirical')) { stop("distribution not in supported distributions") } if (distribution %in% 'empirical') { fit_empirical(x) } else { build_dist(x, distribution) } } build_dist <- function(x, distribution) { type <- paste0(c('d', 'p', 'q', 'r'), distribution) funs <- lapply(type, function(type) { match.fun(type) }) names(funs) <- type if (distribution %in% 'dunif') { parameters <- c(min = min(x), max = max(x)) } else { parameters <- fitdistrplus::fitdist(data = x, distr = distribution)[['estimate']] } funs <- lapply(stats::setNames(funs, names(funs)), gen_dist_fun, parameters = parameters) funs[['parameters']] <- parameters structure(funs, class = "distfun") } fit_univariate_man <- function(distribution, parameters) { type <- paste0(c('d', 'p', 'q', 'r'), distribution) funs <- lapply(type, function(type) { match.fun(type) }) names(funs) <- type allParams <- unique(names(unlist(lapply(unname(funs), formals)))) specParams <- names(parameters) matchedArgs <- match.arg(specParams, allParams, several.ok = TRUE) if (length(matchedArgs) != length(specParams)) { stop("Specified names of parameters do not match argument names of functions") } funs <- lapply(stats::setNames(funs, names(funs)), gen_dist_fun, parameters = parameters) funs[['parameters']] <- parameters structure(funs, class = "distfun") } gen_dist_fun <- function(f, parameters, ...) { function(...) do.call(f, c(list(...), parameters)) } fit_empirical <- function(x) { stopifnot(is.double(x) | is.integer(x)) if (is.integer(x)) { fit_empirical_discrete(x) } else { fit_empirical_continuous(x) } } fit_empirical_discrete <- function(x) { stopifnot(is.integer(x)) x <- sort(x) values <- unique(x) probs <- tabulate(as.factor(x))/length(x) names(probs) <- values d <- Vectorize(function(x) { probs[x == values] }) p <- Vectorize(function(q) { sum(probs[q >= values]) }) q <- Vectorize(function(p) { if (p < 0 | p > 1) { warning("NaNs produced", call. = FALSE) NaN } else { max(values[1], values[cumsum(probs) <= p]) } }) r <- function(n) { sample(x = values, size = n, prob = probs, replace = TRUE) } structure(list(dempDis = d, pempDis = p, qempDis = q, rempDis = r, parameters = probs), class = "distfun") } fit_empirical_continuous <- function(x) { stopifnot(is.double(x)) x <- sort(x) nbins <- diff(range(x)) / (2 * stats::IQR(x) / length(x)^(1/3)) bins <- sapply(split(x, cut(x, nbins)), length) intervals <- get_interval_nums(names(bins)) mids <- sapply(intervals, mean) leftEnds <- sapply(intervals, min) rightEnds <- sapply(intervals, max) probs <- bins/sum(bins) d <- Vectorize(function(x) { if ( x > max(rightEnds) | x < min(leftEnds)) { 0 } else { probs[x >= leftEnds & x < rightEnds] } }) p <- Vectorize(function(q) { sum(probs[q >= leftEnds]) }) q <- Vectorize(function(p) { if (p < 0 | p > 1) { warning("NaNs produced", call. = FALSE) NaN } else { max(mids[1], mids[cumsum(probs) <= p]) } }) r <- function(n) { sample(x = mids, size = n, prob = probs, replace = TRUE) } structure(list(dempCont = d, pempCont = p, qempCont = q, rempCont= r, parameters = probs), class = "distfun") } get_interval_nums <- function(cuts) { numChars <- strsplit(gsub('\\(|\\]|\\)|\\]', "", cuts), ",") lapply(numChars, as.numeric) }
tepBADA <- function(DATA,scale=TRUE,center=TRUE,DESIGN=NULL,make_design_nominal=TRUE,group.masses=NULL,weights=NULL,graphs=TRUE,k=0){ DESIGN <- texpoDesignCheck(DATA,DESIGN,make_design_nominal,force_bary=TRUE) colDESIGN <- colnames(DESIGN) massedDESIGN <- t(apply(DESIGN,1,'/',colSums(DESIGN))) colnames(massedDESIGN) <- colDESIGN main <- deparse(substitute(DATA)) DATA <- as.matrix(DATA) R <- expo.scale(t(massedDESIGN) %*% DATA,scale=scale,center=center) this.center <- attributes(R)$`scaled:center` this.scale <- attributes(R)$`scaled:scale` RMW <- computeMW(R,masses=group.masses,weights=weights) colnames(R) <- colnames(DATA) rownames(R) <- colnames(DESIGN) Rdesign <- diag(nrow(R)) rownames(Rdesign) <- rownames(R) res <- epGPCA(R, DESIGN=Rdesign, make_design_nominal=FALSE, scale = FALSE, center = FALSE, masses = RMW$M, weights = RMW$W, graphs = FALSE, k = k) res <- res$ExPosition.Data res$center <- this.center res$scale <- this.scale supplementaryRes <- supplementaryRows(DATA,res) res$fii <- supplementaryRes$fii res$dii <- supplementaryRes$dii res$rii <- supplementaryRes$rii res$lx <- res$fii res$ly <- supplementaryCols(t(massedDESIGN),res,center=FALSE,scale=FALSE)$fjj assignments <- fii2fi(DESIGN,res$fii,res$fi) assignments$r2 <- R2(RMW$M,res$di,ind.masses=NULL,res$dii) class(assignments) <- c("tepAssign","list") res$assign <- assignments class(res) <- c("tepBADA","list") tepPlotInfo <- tepGraphs(res=res,DESIGN=DESIGN,main=main,graphs=graphs,lvPlots=FALSE) return(tepOutputHandler(res=res,tepPlotInfo=tepPlotInfo)) }
rxor <- function(n=1, p=0) { y <- factor(rep(c(1,1,0,0), n)) x1 <- rep(c(1,0,1,0), n) x2 <- rep(c(0,1,1,0), n) X <- NULL if (p > 0) { X <- matrix(ifelse(runif(p*4*n)<0.5, 0, 1), ncol=p, nrow=4*n) colnames(X) <- paste0("x", 3:(p+2)) } if (p == 0) { out <- data.frame(x1=x1, x2=x2, y=y) } else { out <- data.frame(x1=x1, x2=x2, X, y=y) } out }
if(getRversion() >= "2.15.1") utils::globalVariables(c("MouseGMT", "genesetHuman","en_ES_Rank_Matrix","MB_SampleInfo")) MM2S.mouse<-function(InputMatrix, parallelize, seed, dir) { if(!missing(seed)){ set.seed(seed) } mouseData<-InputMatrix mdm <- NULL if (is.na(as.numeric(mouseData[1,1]))) { mdm <- mouseData[-1,-1, drop=FALSE] colnames(mdm) <- mouseData[1,][-1] rownames(mdm) <- mouseData[,1][-1] mouseData <- mdm } if (is.na(as.numeric(mouseData[1,ncol(mouseData)]))) { mdm <- mouseData[-1,-1, drop=FALSE] colnames(mdm) <- mouseData[1,][-ncol(mouseData)] rownames(mdm) <- mouseData[,1][-1] mouseData <- mdm } ExpressionMatrixMouse <- as.matrix(mouseData) ExpressionMatrixMouse <- apply(ExpressionMatrixMouse, c(1,2), as.numeric) rownames(ExpressionMatrixMouse) <- rownames(mouseData) availcore=1 if(!is.numeric(parallelize)) { message("Number of Cores needed") stop() } else{availcore=parallelize} MouseData<-ExpressionMatrixMouse set.seed(seed) MouseGSVA<-gsva(MouseData, MouseGMT$genesets,method="ssgsea", ssgsea.norm=FALSE, min.sz=20,max.sz=100, parallel.sz=availcore,verbose=FALSE) genesetMouse<-rownames(MouseGSVA) commonSet<-intersect(genesetHuman,genesetMouse) message("There are ",length(commonSet)," common genesets between Human MB and the Test Data.") MouseGSVA<-MouseGSVA[commonSet,, drop=FALSE] MouseGSVA<-t(MouseGSVA) GenesetStatNormal<-GenesetStatNormal[commonSet] GenesetStatGroup3<-GenesetStatGroup3[commonSet] GenesetStatGroup4<-GenesetStatGroup4[commonSet] GenesetStatWNT<-GenesetStatWNT[commonSet] GenesetStatSHH<-GenesetStatSHH[commonSet] geneset<-commonSet FeatureSelection<-c(names(sort(GenesetStatSHH,decreasing=FALSE))[1:24], names(sort(GenesetStatNormal,decreasing=FALSE))[1:24], names(sort(GenesetStatGroup4,decreasing=FALSE))[1:24], names(sort(GenesetStatGroup3,decreasing=FALSE))[1:24], names(sort(GenesetStatWNT,decreasing=FALSE))[1:24]) NorthcottFeatures<-unique(FeatureSelection) message("Of these, ", length(NorthcottFeatures)," feature-selected genesets are being used for classification") MouseGSVA<-MouseGSVA[,NorthcottFeatures, drop=FALSE] MouseGSVA<-t(MouseGSVA) genesetMouse<-rownames(MouseGSVA) Matrix_RANK_Human<-data.frame(NorthcottFeatures) for(sample in 1:ncol(Frozen_ES_Rank_Matrix)) { TempRankHuman<-Frozen_ES_Rank_Matrix[,sample] TempRankHuman<-TempRankHuman[which(TempRankHuman %in% NorthcottFeatures)] Matrix_RANK_Human[,(colnames(Frozen_ES_Rank_Matrix)[sample])]<-match(factor(NorthcottFeatures),factor(TempRankHuman)) } rownames(Matrix_RANK_Human)<-NorthcottFeatures Human_GSVA_Matrix<-Matrix_RANK_Human[,-1] Matrix_RANK_Mouse<-data.frame(genesetMouse) for(sample in 1:ncol(MouseGSVA)) { TempRankMouse<-sort(MouseGSVA[,sample],decreasing=TRUE) Matrix_RANK_Mouse[,(colnames(MouseGSVA)[sample])]<-match(Matrix_RANK_Mouse$geneset,names(TempRankMouse)) } rownames(Matrix_RANK_Mouse)<-Matrix_RANK_Mouse$geneset Mouse_GSVA_Matrix<-Matrix_RANK_Mouse[,-1, drop=FALSE] Human_GSVA_Matrix80<-Human_GSVA_Matrix Mouse_GSVA_Matrix80<-Mouse_GSVA_Matrix geneset<-rownames(Human_GSVA_Matrix80) Northcott<-t(Human_GSVA_Matrix80) Mouse<-t(Mouse_GSVA_Matrix80) Northcott<-as.data.frame(Northcott) Northcott[,"Group"]<- MB_SampleInfo$subtype[match((rownames(Northcott)),MB_SampleInfo$Sample_ID)] Mouse<-as.data.frame(Mouse) Mouse[,"Group"]<- "MouseSamples" Mouse$Group<-as.factor(Mouse$Group) TrainSet<-Northcott TestSet<-Mouse TrainSet<-TrainSet[,-ncol(TrainSet)] set.seed(seed) TestKKNN<-kknn(formula = Northcott$Group ~ ., TrainSet, TestSet, na.action = na.omit(),k = 5, distance = 1, kernel = "rectangular", scale=TRUE) MM2S_Prediction<-as.character(TestKKNN$fitted.values) RESULTS<-(cbind(rownames(Mouse),MM2S_Prediction,TestKKNN$prob*100,TestKKNN$CL)) listOfCols<-c("SampleName","MM2S_Prediction","Gr3_Confidence","Gr4_Confidence","Normal_Confidence","SHH_Confidence","WNT_Confidence","Neighbor1","Neighbor2","Neighbor3","Neighbor4","Neighbor5") colnames(RESULTS) <- listOfCols message("\n") message("OUTPUT OF MM2S:","\n") print.table(RESULTS) if(!missing(dir)){ write.table(RESULTS,file=file.path(dir, "MM2S_Predictions.xls"),sep="\t",col.names=listOfCols,row.names=FALSE) } FINAL<-TestKKNN$prob*100 colnames(FINAL)<-c("Group3","Group4","Normal","SHH","WNT") rownames(FINAL)<-rownames(Mouse) return(list(RankMatrixTesting=t(Mouse_GSVA_Matrix80), RankMatrixTraining=t(Human_GSVA_Matrix80), Predictions=FINAL,MM2S_Subtype=RESULTS[,1:2])) }
variable.fct <- function( varname ,i ,T.mcDiff ,lagTerms ,Time ,varname.i ,dat ,dat.na ){ ti.temp <- rep(1, times = Time-lagTerms-1) + if(Time-lagTerms-1 - T.mcDiff > 0){c(rep(0, times = T.mcDiff - lagTerms), 1:(Time - T.mcDiff - 1))} else{rep(0, times = Time-lagTerms-1)} tend.temp <- lagTerms:(Time-2) Matrix::t(Matrix::bdiag(mapply(ti = ti.temp, t.end = tend.temp , FUN = dat.fct, lagTerms = lagTerms, varname = varname , MoreArgs = list(i = i , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) , SIMPLIFY = FALSE))) } variable.pre.fct <- function( varname ,lagTerms ,T.mcDiff ,i ,Time ,varname.i ,dat ,dat.na ){ ti.temp <- rep(1, times = Time-lagTerms-1) + if(Time-lagTerms-1 - T.mcDiff > 0){c(rep(0, times = T.mcDiff - lagTerms), 1:(Time - T.mcDiff - 1))} else{rep(0, times = Time-lagTerms-1)} tend.temp <- (lagTerms+1):(Time-1) Matrix::t(Matrix::bdiag(mapply(ti = ti.temp, t.end = tend.temp, FUN = dat.fct.pre, lagTerms = lagTerms, varname = varname , MoreArgs = list(i = i, Time = Time , varname.i = varname.i, dat = dat, dat.na = dat.na), SIMPLIFY = FALSE))) } variable.ex.fct <- function( varname ,lagTerms ,T.mcDiff ,i ,Time ,varname.i ,inst.reg.ex.expand ,dat ,dat.na ){ if(inst.reg.ex.expand){ t.start <- rep(1, times = Time-lagTerms-1) + if(Time-T.mcDiff > 0){c(rep(0, times = Time-lagTerms-1-(Time-T.mcDiff)), (1:(Time - T.mcDiff)))} else{0} t.end <- t.start + (T.mcDiff-1) t.req.i <- 1:(Time-lagTerms-1) t.req.e <- (1:(Time-lagTerms-1)) + (lagTerms+1) } else { t.start <- rep(1, times = Time-lagTerms-1) + if(Time-T.mcDiff > 0){c(rep(0, times = Time-lagTerms-1-(Time-T.mcDiff)), (1:(Time - T.mcDiff)))} else{0} t.end <- (lagTerms+2):(Time) t.req.i <- 1:(Time-lagTerms-1) t.req.e <- (1:(Time-lagTerms-1)) + (lagTerms+1) } err.term.start <- t.start Matrix::t(Matrix::bdiag(mapply(ti = t.start, t.end = t.end, err.term.start = err.term.start, t.req.i = t.req.i, t.req.e = t.req.e, FUN = dat.fct.ex, varname = varname , MoreArgs = list(i = i, Time = Time , varname.i = varname.i, dat = dat, dat.na = dat.na), SIMPLIFY = FALSE))) } dat.fct <- function( ti ,t.end ,i ,lagTerms ,varname ,Time ,varname.i ,dat ,dat.na ){ dat[dat[, varname.i] == i, varname][ti:t.end]* (as.numeric(!is.na(dat.na[dat.na[, varname.i] == i, varname][t.end-lagTerms+1] * dat.na[dat.na[, varname.i] == i, varname][t.end] * dat.na[dat.na[, varname.i] == i, varname][t.end+1] * dat.na[dat.na[, varname.i] == i, varname][t.end+2]))) } dat.fct.pre <- function( ti ,t.end ,i ,lagTerms ,varname ,Time ,varname.i ,dat ,dat.na ){ dat[dat[, varname.i] == i, varname][ti:t.end]* (as.numeric(!is.na(dat.na[dat.na[, varname.i] == i, varname][t.end-lagTerms+1] * dat.na[dat.na[, varname.i] == i, varname][t.end] * dat.na[dat.na[, varname.i] == i, varname][t.end+1]))) } dat.fct.ex <- function( ti ,t.end ,t.req.i ,t.req.e ,err.term.start ,i ,varname ,Time ,varname.i ,dat ,dat.na ){ dat[dat[, varname.i] == i, varname][ti:t.end]* (as.numeric(!is.na(dat.na[dat.na[, varname.i] == i, varname][ti:t.end] * dat.na[dat.na[, varname.i] == i, varname][rep((err.term.start+2), times = length(ti:t.end))])))* as.numeric(!is.na(dat.na[dat.na[, varname.i] == i, varname][rep(t.req.i, times = length(ti:t.end))]))* as.numeric(!is.na(dat.na[dat.na[, varname.i] == i, varname][rep(t.req.e, times = length(ti:t.end))])) } LEV.fct <- function( varname ,i ,T.mcLev ,lagTerms ,use.mc.diff ,inst.stata ,Time ,varname.i ,dat ,dat.na ){ if(use.mc.diff & !(inst.stata)){ ti.temp <- max(2,lagTerms) tend.temp <- Time-1 Matrix::Diagonal(do.call(what = datLEV.fct, args = list(ti = ti.temp, t.end = tend.temp, i = i, varname = varname, lagTerms = lagTerms, use.mc.diff = use.mc.diff, inst.stata = inst.stata , dat.na = dat.na, dat = dat, varname.i = varname.i, Time = Time)), n = Time-max(2,lagTerms)) } else{ ti.temp <- rep(max(2,lagTerms), times = Time-max(2,lagTerms)) + if(Time-max(2,lagTerms)-T.mcLev > 0){c(rep(0, times = T.mcLev-1), 1:(Time-max(2,lagTerms)-T.mcLev+1))} else{rep(0, times = Time-max(2,lagTerms))} tend.temp <- max(2,lagTerms):(Time-1) Matrix::t(Matrix::bdiag(mapply(ti = ti.temp, t.end = tend.temp, lagTerms = lagTerms, FUN = datLEV.fct, varname = varname, MoreArgs = list(i = i, use.mc.diff = use.mc.diff, inst.stata = inst.stata , dat.na = dat.na, dat = dat, varname.i = varname.i, Time = Time)) ))* as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(max(2,lagTerms)-1):(Time-1)]))) } } LEV.pre.fct <- function( varname ,i ,T.mcLev ,lagTerms ,use.mc.diff ,inst.stata ,Time ,varname.i ,dat ,dat.na ){ if(use.mc.diff & !(inst.stata)){ ti.temp <- max(2,lagTerms) tend.temp <- Time Matrix::Diagonal(do.call(what = datLEV.pre.fct, args = list(ti = ti.temp, t.end = tend.temp, lagTerms = lagTerms, varname = varname, i = i, use.mc.diff = use.mc.diff, inst.stata = inst.stata , dat = dat, dat.na = dat.na, varname.i = varname.i, Time = Time)), n = Time-max(2,lagTerms)+1) } else{ ti.temp <- rep(max(2,lagTerms), times = Time-max(2,lagTerms)+1) + if(Time-max(2,lagTerms)-T.mcLev > 0){c(rep(0, times = T.mcLev), 1:(Time-max(2,lagTerms)-T.mcLev+1))} else{rep(0, times = Time-max(2,lagTerms)+1)} tend.temp <- max(2,lagTerms):(Time) Matrix::t(Matrix::bdiag(mapply(ti = ti.temp, t.end = tend.temp, lagTerms = lagTerms, FUN = datLEV.pre.fct, varname = varname, MoreArgs = list(i = i, use.mc.diff = use.mc.diff, inst.stata = inst.stata , dat = dat, dat.na = dat.na, varname.i = varname.i, Time = Time))) )* as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(lagTerms-1):Time]))) } } datLEV.fct <- function( ti ,t.end ,i ,lagTerms ,varname ,use.mc.diff ,inst.stata ,Time ,varname.i ,dat ,dat.na ){ if(use.mc.diff & !(inst.stata)){ (dat[dat[, varname.i] == i, varname][ti:t.end]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][(ti - max(2,lagTerms) + 1):(t.end - max(2,lagTerms) + 1)]* dat.na[dat[, varname.i] == i, varname][(ti):(t.end)]* dat.na[dat[, varname.i] == i, varname][(ti + 1):(t.end + 1)] )) - dat[dat[, varname.i] == i, varname][(ti - 1):(t.end - 1)]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][(ti - max(2,lagTerms) + 1):(t.end - max(2,lagTerms) + 1)]* dat.na[dat[, varname.i] == i, varname][(ti):(t.end)]* dat.na[dat[, varname.i] == i, varname][(ti + 1):(t.end + 1)] )) ) * as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(ti-1):(t.end)]))) } else{ (dat[dat[, varname.i] == i, varname][ti:t.end]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][t.end - max(2,lagTerms) + 1]* dat.na[dat[, varname.i] == i, varname][t.end]* dat.na[dat[, varname.i] == i, varname][t.end+1] )) - dat[dat[, varname.i] == i, varname][(ti - 1):(t.end - 1)]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][t.end - max(2,lagTerms) + 1]* dat.na[dat[, varname.i] == i, varname][t.end]* dat.na[dat[, varname.i] == i, varname][t.end+1] )) ) * as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(ti-1):(t.end)]))) } } datLEV.pre.fct <- function( ti ,t.end ,i ,varname ,lagTerms ,use.mc.diff ,inst.stata ,Time ,varname.i ,dat ,dat.na ){ if(is.na(dat.na[dat.na[, varname.i] == i, varname][ti])){ ti = ti+1 t.end = t.end+1 } if(use.mc.diff & !(inst.stata)){ (dat[dat[, varname.i] == i, varname][(ti):t.end]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][(ti):(t.end)] )) - dat[dat[, varname.i] == i, varname][(ti-1):(t.end-1)]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][(ti-1):(t.end-1)] )) ) * as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(ti-1):(t.end)]))) } else{ (dat[dat[, varname.i] == i, varname][(ti):t.end] * as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][t.end - 1]* dat.na[dat[, varname.i] == i, varname][t.end] )) - dat[dat[, varname.i] == i, varname][(ti-1):(t.end - 1)]* as.numeric(!is.na(dat.na[dat[, varname.i] == i, varname][t.end - 1]* dat.na[dat[, varname.i] == i, varname][t.end] )) ) * as.vector(!is.na(diff(dat.na[dat.na[, varname.i] == i, varname][(ti-1):(t.end)]))) } } Z_i.fct <- function( i ,Time ,varname.i ,use.mc.diff ,use.mc.lev ,use.mc.nonlin ,use.mc.nonlinAS ,include.y ,varname.y ,inst.stata ,include.dum ,dum.diff ,dum.lev ,colnames.dum ,fur.con ,fur.con.diff ,fur.con.lev ,varname.reg.estParam.fur ,include.x ,end.reg ,varname.reg.end ,pre.reg ,varname.reg.pre ,ex.reg ,varname.reg.ex ,lagTerms.y ,maxLags.y ,max.lagTerms ,maxLags.reg.end ,maxLags.reg.pre ,maxLags.reg.ex ,inst.reg.ex.expand ,dat ,dat.na ){ i <- as.numeric(i) if(use.mc.diff){ if(include.y){ Z_i.mc.diff_end.y <- do.call(what = "cbind", args = sapply(X = varname.y, FUN = variable.fct, i = i, T.mcDiff = maxLags.y, lagTerms = max.lagTerms , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } if(include.x){ if(end.reg){ if(length(varname.reg.end) == 1){ Z_i.mc.diff_end.x <- do.call(what = "cbind", args = sapply(FUN = variable.fct, varname.reg.end, i = i, T.mcDiff = maxLags.reg.end, lagTerms = max.lagTerms , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } else{ Z_i.mc.diff_end.x <- do.call(what = "cbind", args = mapply(FUN = variable.fct, varname.reg.end, T.mcDiff = maxLags.reg.end , MoreArgs = list(i = i, Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , dat = dat, dat.na = dat.na)) ) } } if(pre.reg){ if(length(varname.reg.pre) == 1){ Z_i.mc.diff_pre <- do.call(what = "cbind", args = sapply(FUN = variable.pre.fct, varname.reg.pre, i = i, T.mcDiff = maxLags.reg.pre, lagTerms = max.lagTerms , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } else{ Z_i.mc.diff_pre <- do.call(what = "cbind", args = mapply(FUN = variable.pre.fct, varname.reg.pre, T.mcDiff = maxLags.reg.pre , MoreArgs = list(i = i, Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , dat = dat, dat.na = dat.na)) ) } } if(ex.reg){ if(length(varname.reg.ex) == 1){ Z_i.mc.diff_ex <- do.call(what = "cbind", args = sapply(FUN = variable.ex.fct, varname.reg.ex, i = i, T.mcDiff = maxLags.reg.ex, lagTerms = max.lagTerms, inst.reg.ex.expand = inst.reg.ex.expand , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } else{ Z_i.mc.diff_ex <- do.call(what = "cbind", args = mapply(FUN = variable.ex.fct, varname.reg.ex, T.mcDiff = maxLags.reg.ex , MoreArgs = list(i = i, Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , inst.reg.ex.expand = inst.reg.ex.expand , dat = dat, dat.na = dat.na)) ) } } } Z_i.mc.diff_temp <- do.call(what = "cbind", args = mget(ls(pattern = "Z_i.mc.diff"))) n.inst.diff <- ncol(Z_i.mc.diff_temp) n.obs.diff <- nrow(Z_i.mc.diff_temp) } if(use.mc.lev){ if(include.y){ Z_i.mc.lev_end.y <- do.call(what = "cbind", args = sapply(X = varname.y, FUN = LEV.fct, i = i, T.mcLev = maxLags.y, lagTerms = max.lagTerms, use.mc.diff = use.mc.diff, inst.stata = inst.stata , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } if(include.x){ if(end.reg){ if(length(varname.reg.end) == 1){ Z_i.mc.lev_end.x <- do.call(what = "cbind", args = sapply(FUN = LEV.fct, i = i, varname.reg.end, T.mcLev = maxLags.reg.end, lagTerms = max.lagTerms, use.mc.diff = use.mc.diff, inst.stata = inst.stata , Time = Time, varname.i = varname.i, dat = dat, dat.na = dat.na) ) } else{ Z_i.mc.lev_end.x <- do.call(what = "cbind", args = mapply(FUN = LEV.fct, varname.reg.end, T.mcLev = maxLags.reg.end , MoreArgs = list(use.mc.diff = use.mc.diff, inst.stata = inst.stata , i = i, Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , dat = dat, dat.na = dat.na)) ) } } if(ex.reg | pre.reg){ varname.ex.pre.temp <- c({if(!(is.null("varname.reg.ex"))){varname.reg.ex}}, {if(!(is.null("varname.reg.pre"))){varname.reg.pre}} ) T.mcLev.temp <- c({if(!(is.null("varname.reg.ex"))){maxLags.reg.ex - 1}}, {if(!(is.null("varname.reg.pre"))){maxLags.reg.pre}} ) if(length(varname.ex.pre.temp) == 1){ Z_i.mc.lev_ex.pre <- do.call(what = "cbind", args = sapply(FUN = LEV.pre.fct, i = i, varname.ex.pre.temp, T.mcLev = T.mcLev.temp , use.mc.diff = use.mc.diff, inst.stata = inst.stata , Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , dat = dat, dat.na = dat.na) ) } else{ Z_i.mc.lev_ex.pre <- do.call(what = "cbind", args = mapply(FUN = LEV.pre.fct, varname.ex.pre.temp, T.mcLev = T.mcLev.temp ,MoreArgs = list(i = i, use.mc.diff = use.mc.diff, inst.stata = inst.stata , Time = Time, varname.i = varname.i, lagTerms = max.lagTerms , dat = dat, dat.na = dat.na)) ) } } } Z_i.mc.lev_end <- do.call(what = "cbind", args = mget(ls(pattern = "Z_i.mc.lev_end"))) if(include.x & (include.y | end.reg) & (ex.reg | pre.reg)){ Z_i.mc.lev <- cbind(rbind(0, Z_i.mc.lev_end), Z_i.mc.lev_ex.pre) } else{ if((include.y | end.reg) & ((include.dum & dum.lev) | (fur.con & fur.con.lev))){ if(max.lagTerms == 1){ Z_i.mc.lev <- rbind(0, Z_i.mc.lev_end) } else{ Z_i.mc.lev <- Z_i.mc.lev_end } } else{ Z_i.mc.lev <- Z_i.mc.lev_end } } n.inst.lev <- ncol(Z_i.mc.lev) n.obs.lev <- nrow(Z_i.mc.lev) if(use.mc.diff){ Z_i.temp <- Matrix::bdiag(list(Z_i.mc.diff_temp, Z_i.mc.lev)) } else{ Z_i.temp <- Z_i.mc.lev } } if(use.mc.nonlin){ if(use.mc.nonlinAS){ Z_i.mc.AS4 <- diag(as.numeric(!(is.na(diff(dat.na[dat[, varname.i] == i, varname.y], differences = max.lagTerms+2))) )[if(maxLags.y - (max.lagTerms+2) + 1 < Time - (max.lagTerms+2)){-(1:(Time - (max.lagTerms+2) - (maxLags.y - (max.lagTerms+2)+1)))}], nrow = Time - (max.lagTerms+2) - length((1:(Time - (max.lagTerms+2) - (maxLags.y - (max.lagTerms+2)+1))))) } else { Z_i.mc.AS4 <- diag(as.numeric(!(is.na(diff(dat.na[dat[, varname.i] == i, varname.y], differences = max.lagTerms+2))) )) } if(use.mc.diff & !(use.mc.lev)){ Z_i.temp <- Matrix::bdiag(list(Z_i.mc.diff_temp, Z_i.mc.AS4)) } if(!(use.mc.diff) & use.mc.lev){ Z_i.temp <- Matrix::bdiag(Z_i.mc.AS4, Z_i.mc.lev) } if(!(use.mc.diff) & !(use.mc.lev)){ Z_i.temp <- Z_i.mc.AS4 } if(use.mc.diff & use.mc.lev){ Z_i.temp <- Matrix::bdiag(Z_i.mc.diff_temp, Z_i.mc.AS4, Z_i.mc.lev) } n.inst.nl <- ncol(Z_i.mc.AS4) n.obs.nl <- nrow(Z_i.mc.AS4) } if(!(use.mc.lev) & !(use.mc.nonlin)){ Z_i.temp <- Z_i.mc.diff_temp } if(include.dum){ ind_vec.diff.row <- is.na(diff(dat.na[dat[, varname.i] == i, varname.y][1:(Time)], differences = max.lagTerms+1) ) ind_vec.lev.row <- is.na(diff(dat.na[dat[, varname.i] == i, varname.y][1:(Time)], differences = max.lagTerms) ) ind_vec.diff.col <- is.na(diff(dat.na[dat[, varname.i] == i , varname.y][2:Time], differences = max.lagTerms) ) ind_vec.lev.col <- is.na(diff(dat.na[dat[, varname.i] == i , varname.y][1:Time], differences = max.lagTerms) ) if(dum.lev){ if(max.lagTerms > 1){ Z_i.dum_4.lev <- as.matrix(dat[dat[, varname.i] == i, colnames.dum[-c(1:(max.lagTerms-1))]][-c(1:max.lagTerms), ]) } else{ Z_i.dum_4.lev <- as.matrix(dat[dat[, varname.i] == i, colnames.dum][-c(1:max.lagTerms), ]) } Z_i.dum_4.lev[ind_vec.lev.row, ] <- 0 Z_i.dum_4.lev[ ,ind_vec.lev.col] <- 0 colnames.dum_4.lev <- colnames(Z_i.dum_4.lev) colnames(Z_i.dum_4.lev) <- NULL rownames(Z_i.dum_4.lev) <- NULL if(use.mc.nonlin){ Z_i.dum_2.nl <- matrix(0, ncol = ncol(Z_i.dum_4.lev), nrow = nrow(Z_i.mc.AS4)) colnames.dum_2.nl <- colnames.dum_4.lev colnames(Z_i.dum_2.nl) <- NULL } if(dum.diff){ Z_i.dum_1.diff <- as.matrix(dat[dat[, varname.i] == i, colnames.dum[-c(1:max.lagTerms)]][(2+max.lagTerms):Time, ] - rbind(dat[dat[, varname.i] == i, colnames.dum[-c(1:max.lagTerms)]][(2+(max.lagTerms-1)):(Time-1), ])) colnames.dum_1.diff <- paste("D.", colnames.dum_4.lev, sep = "") colnames(Z_i.dum_1.diff) <- NULL rownames(Z_i.dum_1.diff) <- NULL } if(dum.diff & dum.lev){ if(use.mc.nonlin){ Z_i.dum <- Matrix::bdiag(Z_i.dum_1.diff, rbind(Z_i.dum_2.nl, Z_i.dum_4.lev)) } else{ Z_i.dum <- do.call(what = Matrix::bdiag, mget(ls(pattern = "Z_i.dum_"))) } } else{ if((use.mc.diff | fur.con.diff) & !dum.diff){ Z_i.dum_1.diff <- matrix(0, ncol = ncol(Z_i.dum_4.lev), nrow = (Time-max.lagTerms-1)) colnames.dum_1.diff <- colnames(Z_i.dum_4.lev) if(use.mc.nonlin){ Z_i.dum <- rbind(Z_i.dum_1.diff, Z_i.dum_2.nl, Z_i.dum_4.lev) } else{ Z_i.dum <- rbind(Z_i.dum_1.diff, Z_i.dum_4.lev) } } else{ if(length(ls(pattern = "Z_i.dum_")) == 1){ Z_i.dum <- Z_i.dum_4.lev } else{ Z_i.dum <- do.call(what = rbind, mget(ls(pattern = "Z_i.dum_"))) } } } } if(dum.diff & !(dum.lev)){ Z_i.dum_1.diff <- as.matrix(dat[dat[, varname.i] == i, colnames.dum[-c(1:max.lagTerms)]][(2+max.lagTerms):Time, ] - rbind(dat[dat[, varname.i] == i, colnames.dum[-c(1:max.lagTerms)]][(2+(max.lagTerms-1)):(Time-1), ])) Z_i.dum_1.diff[ind_vec.diff.row, ] <- 0 Z_i.dum_1.diff[ ,ind_vec.diff.col] <- 0 colnames.dum_1.diff <- paste("D.", colnames(Z_i.dum_1.diff), sep = "") colnames(Z_i.dum_1.diff) <- NULL rownames(Z_i.dum_1.diff) <- NULL if(use.mc.nonlin){ Z_i.dum_2.nl <- matrix(0, ncol = ncol(Z_i.dum_1.diff), nrow = nrow(Z_i.mc.AS4)) colnames.dum_2.nl <- colnames(Z_i.dum_2.nl) colnames(Z_i.dum_2.nl) <- NULL } if(use.mc.lev){ if(fur.con.lev | ex.reg | pre.reg){ Z_i.dum_4.lev <- matrix(0, ncol = ncol(Z_i.dum_1.diff), nrow = (Time - max.lagTerms)) } else{ Z_i.dum_4.lev <- matrix(0, ncol = ncol(Z_i.dum_1.diff), nrow = (Time - max(2,max.lagTerms))) } colnames.dum_4.lev <- colnames(Z_i.dum_1.diff) colnames(Z_i.dum_4.lev) <- NULL } Z_i.dum <- do.call(what = "rbind", args = mget(ls(pattern = "Z_i.dum_"))) rownames(Z_i.dum) <- NULL } colnames_Z_i.dum <- unique(as.vector(do.call(what = "c", mget(ls(pattern = "colnames.dum_"))))) if(nrow(Z_i.temp) < nrow(Z_i.dum)){ if(use.mc.lev){ Z_i.temp <- rbind(matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.dum) - nrow(Z_i.temp)), Z_i.temp) } else{ if(use.mc.diff){ Z_i.temp <- rbind(Z_i.temp, matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.dum) - nrow(Z_i.temp))) } else{ if(use.mc.nonlin & !use.mc.diff & !use.mc.lev){ if(dum.diff){ Z_i.temp <- rbind(matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.dum) - nrow(Z_i.temp)), Z_i.temp) } else{ Z_i.temp <- rbind(Z_i.temp, matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.dum) - nrow(Z_i.temp))) } } } } } Z_i.temp <- cbind(Z_i.temp, as.matrix(Z_i.dum)) if(dum.diff & dum.lev){ colnames_Z_i.dum <- colnames_Z_i.dum[-1] n.inst.dum <- c(length(get(ls(pattern = "colnames.dum_1"))) -1, length(get(ls(pattern = "colnames.dum_4")))) } else{ if(dum.diff & !(dum.lev)){ n.inst.dum <- length(get(ls(pattern = "colnames.dum_1"))) } if(dum.lev & !(dum.diff)){ n.inst.dum <- length(get(ls(pattern = "colnames.dum_4"))) } } } else{ colnames_Z_i.dum <- NULL } if(fur.con){ ind_vec.diff.row <- is.na(diff(dat.na[dat[, varname.i] == i, varname.y][1:Time], differences = max.lagTerms+1) ) ind_vec.lev.row <- is.na(diff(dat.na[dat[, varname.i] == i, varname.y][1:(Time)], differences = max.lagTerms) ) if(fur.con.diff){ if(length(varname.reg.estParam.fur) == 1){ Z_i.furCon.temp_diff <- diff(as.matrix(dat.na[dat[, varname.i] == i, varname.reg.estParam.fur][-c(1:max.lagTerms)]), differences = 1) Z_i.furCon.temp_diff[ind_vec.diff.row] <- 0 colnames.fur.con.diff <- varname.reg.estParam.fur rownames(Z_i.furCon.temp_diff) <- NULL colnames(Z_i.furCon.temp_diff) <- NULL } else{ Z_i.furCon.temp_diff <- diff(as.matrix(dat.na[dat[, varname.i] == i, varname.reg.estParam.fur][-c(1:max.lagTerms), ]), differences = 1) Z_i.furCon.temp_diff[ind_vec.diff.row, ] <- 0 colnames.fur.con.diff <- colnames(Z_i.furCon.temp_diff) rownames(Z_i.furCon.temp_diff) <- NULL colnames(Z_i.furCon.temp_diff) <- NULL } } if(fur.con.lev){ if(length(varname.reg.estParam.fur) == 1){ Z_i.furCon.temp_lev <- as.matrix(dat.na[dat[, varname.i] == i, varname.reg.estParam.fur][1:Time][-c(1:max.lagTerms)] ) Z_i.furCon.temp_lev[ind_vec.lev.row] <- 0 colnames.fur.con.lev <- varname.reg.estParam.fur rownames(Z_i.furCon.temp_lev) <- NULL colnames(Z_i.furCon.temp_lev) <- NULL } else{ Z_i.furCon.temp_lev <- as.matrix(dat.na[dat[, varname.i] == i, varname.reg.estParam.fur][1:Time, ][-c(1:max.lagTerms), ] ) Z_i.furCon.temp_lev[ind_vec.lev.row, ] <- 0 colnames.fur.con.lev <- colnames(Z_i.furCon.temp_lev) rownames(Z_i.furCon.temp_lev) <- NULL colnames(Z_i.furCon.temp_lev) <- NULL } } if(fur.con.diff & fur.con.lev){ if(length(varname.reg.estParam.fur) == 1){ if(use.mc.nonlin){ Z_i.furCon.diff <- as.matrix(c(Z_i.furCon.temp_diff, rep(0, times = nrow(Z_i.furCon.temp_lev) + nrow(Z_i.mc.AS4)))) Z_i.furCon.lev <- as.matrix(c(rep(0, times = nrow(Z_i.furCon.temp_diff) + nrow(Z_i.mc.AS4)), Z_i.furCon.temp_lev)) } else{ Z_i.furCon.diff <- as.matrix(c(Z_i.furCon.temp_diff, rep(0, times = nrow(Z_i.furCon.temp_lev)))) Z_i.furCon.lev <- as.matrix(c(rep(0, times = nrow(Z_i.furCon.temp_diff)), Z_i.furCon.temp_lev)) } } else{ if(use.mc.nonlin){ Z_i.furCon.diff <- rbind(Z_i.furCon.temp_diff, matrix(0, ncol = ncol(Z_i.furCon.temp_diff), nrow = nrow(Z_i.furCon.temp_lev) + nrow(Z_i.mc.AS4))) Z_i.furCon.lev <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp_lev), nrow = nrow(Z_i.furCon.temp_diff) + nrow(Z_i.mc.AS4)), Z_i.furCon.temp_lev) } else{ Z_i.furCon.diff <- rbind(Z_i.furCon.temp_diff, matrix(0, ncol = ncol(Z_i.furCon.temp_diff), nrow = nrow(Z_i.furCon.temp_lev))) Z_i.furCon.lev <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp_lev), nrow = nrow(Z_i.furCon.temp_diff)), Z_i.furCon.temp_lev) } } Z_i.furCon.temp <- cbind(Z_i.furCon.diff, Z_i.furCon.lev) n.inst.furCon <- c(length(get(ls(pattern = "colnames.fur.con.diff"))), length(get(ls(pattern = "colnames.fur.con.lev")))) } else{ if(fur.con.diff){ Z_i.furCon.temp <- Z_i.furCon.temp_diff n.inst.furCon <- length(get(ls(pattern = "colnames.fur.con.diff"))) if(nrow(Z_i.furCon.temp) != nrow(Z_i.temp)){ if(!include.dum){ if((use.mc.lev | use.mc.nonlin) & !use.mc.diff){ Z_i.furCon.temp <- rbind(Z_i.furCon.temp, matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp))) } if(use.mc.diff & use.mc.lev){ Z_i.furCon.temp <- rbind(Z_i.furCon.temp, matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp) - nrow(Z_i.furCon.temp))) } if(use.mc.diff & use.mc.nonlin){ Z_i.furCon.temp <- rbind(Z_i.furCon.temp, matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp) - nrow(Z_i.furCon.temp))) } } else{ if((use.mc.lev | use.mc.nonlin) & !use.mc.diff){ Z_i.furCon.temp <- rbind(Z_i.furCon.temp, matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp) - nrow(Z_i.furCon.temp))) } if(use.mc.diff){ Z_i.furCon.temp <- rbind(Z_i.furCon.temp, matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp) - nrow(Z_i.furCon.temp))) } } } } else{ Z_i.furCon.temp <- Z_i.furCon.temp_lev n.inst.furCon <- length(get(ls(pattern = "colnames.fur.con.lev"))) if(dum.diff & !dum.lev){ if(use.mc.lev & !use.mc.diff){ if(nrow(Z_i.temp) > nrow(Z_i.furCon.temp)){ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)-nrow(Z_i.furCon.temp)), Z_i.furCon.temp) } } else{ if(use.mc.lev & use.mc.diff){ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)-nrow(Z_i.furCon.temp)), Z_i.furCon.temp) } else{ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)), Z_i.furCon.temp) } } } else{ if(use.mc.diff & !use.mc.lev & !include.dum){ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)), Z_i.furCon.temp) } if(!use.mc.diff & !use.mc.lev & use.mc.nonlin){ if(dum.lev){ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)-nrow(Z_i.furCon.temp)), Z_i.furCon.temp) } else{ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp)), Z_i.furCon.temp) } } if(nrow(Z_i.furCon.temp) < nrow(Z_i.temp)){ Z_i.furCon.temp <- rbind(matrix(0, ncol = ncol(Z_i.furCon.temp), nrow = nrow(Z_i.temp) - nrow(Z_i.furCon.temp)), Z_i.furCon.temp) } } } } if(nrow(Z_i.temp) < nrow(Z_i.furCon.temp)){ if(use.mc.lev){ Z_i.temp <- rbind(matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.furCon.temp) - nrow(Z_i.temp)), Z_i.temp) } else{ Z_i.temp <- rbind(Z_i.temp, matrix(0, ncol = ncol(Z_i.temp), nrow = nrow(Z_i.furCon.temp) - nrow(Z_i.temp))) } } Z_i.temp <- cbind(Z_i.temp, Z_i.furCon.temp) Z_i.temp[is.na(Z_i.temp)] <- 0 } n.inst <- c(if(use.mc.diff){ n.inst.diff }, if(use.mc.lev){ n.inst.lev }, if(use.mc.nonlin){ n.inst.nl }, if(include.dum){ n.inst.dum }, if(fur.con){ n.inst.furCon } ) names(n.inst) <- c(if(use.mc.diff){ "inst.diff" }, if(use.mc.lev){ "inst.lev" }, if(use.mc.nonlin){ "inst.nl" }, if(include.dum & dum.diff){ "dum.diff" }, if(include.dum & dum.lev){ "dum.lev" }, if(fur.con & fur.con.diff){ "inst.furCon.diff" }, if(fur.con & fur.con.lev){ "inst.furCon.lev" } ) n.obs <- c(if(use.mc.diff){ n.obs.diff }, if(use.mc.lev){ n.obs.lev }, if(use.mc.nonlin){ n.obs.nl } ) names(n.obs) <- c(if(use.mc.diff){ "n.obs.diff" }, if(use.mc.lev){ "n.obs.lev" }, if(use.mc.nonlin){ "n.obs.nl" }) return(list(Z_i.temp = Z_i.temp, colnames.dum = colnames_Z_i.dum, n.inst = n.inst, n.obs = n.obs)) }
layer_histograms <- function(vis, ..., width = NULL, center = NULL, boundary = NULL, closed = c("right", "left"), stack = TRUE, binwidth) { if (!missing(binwidth)) { width <- binwidth deprecated("binwidth", "width", version = "0.3.0") } closed <- match.arg(closed) new_props <- merge_props(cur_props(vis), props(...)) check_unsupported_props(new_props, c("x", "y", "x2", "y2"), c("enter", "exit", "hover"), "layer_histograms") x_var <- find_prop_var(new_props, "x.update") x_val <- eval_vector(cur_data(vis), x_var) vis <- set_scale_label(vis, "x", prop_label(new_props$x.update)) vis <- scale_numeric(vis, "y", domain = c(0, NA), expand = c(0, 0.05), label = "count") layer_f(vis, function(x) { x <- compute_bin(x, x_var, width = width, center = center, boundary = boundary, closed = closed) if (stack) { x <- compute_stack(x, stack_var = ~count_, group_var = ~x_) rect_props <- merge_props( new_props, props(x = ~xmin_, x2 = ~xmax_, y = ~stack_upr_, y2 = ~stack_lwr_) ) x <- emit_rects(x, rect_props) } else { rect_props <- merge_props( new_props, props(x = ~xmin_, x2 = ~xmax_, y = ~count_, y2 = 0) ) x <- emit_rects(x, rect_props) } x }) } layer_freqpolys <- function(vis, ..., width = NULL, center = NULL, boundary = NULL, closed = c("right", "left"), binwidth) { if (!missing(binwidth)) { width <- binwidth deprecated("binwidth", "width", version = "0.3.0") } closed <- match.arg(closed) new_props <- merge_props(cur_props(vis), props(...)) check_unsupported_props(new_props, c("x", "y"), c("enter", "exit", "hover"), "layer_freqpolys") x_var <- find_prop_var(new_props, "x.update") x_val <- eval_vector(cur_data(vis), x_var) vis <- set_scale_label(vis, "x", prop_label(new_props$x.update)) vis <- set_scale_label(vis, "y", "count") params <- bin_params(range(x_val, na.rm = TRUE), width = value(width), center = value(center), boundary = value(boundary), closed = value(closed)) layer_f(vis, function(x) { x <- compute_bin(x, x_var, width = params$width, boundary = params$origin, closed = params$closed, pad = TRUE) path_props <- merge_props(new_props, props(x = ~x_, y = ~count_)) x <- emit_paths(x, path_props) x }) }
kppm <- function(X, ...) { UseMethod("kppm") } kppm.formula <- function(X, clusters = c("Thomas","MatClust","Cauchy","VarGamma","LGCP"), ..., data=NULL) { callstring <- short.deparse(sys.call()) cl <- match.call() if(!inherits(X, "formula")) stop(paste("Argument 'X' should be a formula")) formula <- X if(spatstat.options("expand.polynom")) formula <- expand.polynom(formula) if(length(formula) < 3) stop(paste("Formula must have a left hand side")) Yexpr <- formula[[2L]] trend <- formula[c(1L,3L)] thecall <- call("kppm", X=Yexpr, trend=trend, data=data, clusters=clusters) ncall <- length(thecall) argh <- list(...) nargh <- length(argh) if(nargh > 0) { thecall[ncall + 1:nargh] <- argh names(thecall)[ncall + 1:nargh] <- names(argh) } callenv <- list2env(as.list(data), parent=parent.frame()) result <- eval(thecall, envir=callenv, enclos=baseenv()) result$call <- cl result$callframe <- parent.frame() if(!("callstring" %in% names(list(...)))) result$callstring <- callstring return(result) } kppm.ppp <- kppm.quad <- function(X, trend = ~1, clusters = c("Thomas","MatClust","Cauchy","VarGamma","LGCP"), data=NULL, ..., covariates = data, subset, method = c("mincon", "clik2", "palm", "adapcl"), improve.type = c("none", "clik1", "wclik1", "quasi"), improve.args = list(), weightfun=NULL, control=list(), stabilize=TRUE, algorithm, statistic="K", statargs=list(), rmax = NULL, epsilon=0.01, covfunargs=NULL, use.gam=FALSE, nd=NULL, eps=NULL) { cl <- match.call() callstring <- paste(short.deparse(sys.call()), collapse="") Xname <- short.deparse(substitute(X)) clusters <- match.arg(clusters) improve.type <- match.arg(improve.type) method <- match.arg(method) if(method == "mincon") statistic <- pickoption("summary statistic", statistic, c(K="K", g="pcf", pcf="pcf")) if(missing(algorithm)) { algorithm <- if(method == "adapcl") "Broyden" else "Nelder-Mead" } else check.1.string(algorithm) ClusterArgs <- list(method = method, improve.type = improve.type, improve.args = improve.args, weightfun=weightfun, control=control, stabilize=stabilize, algorithm=algorithm, statistic=statistic, statargs=statargs, rmax = rmax) Xenv <- list2env(as.list(covariates), parent=parent.frame()) X <- eval(substitute(X), envir=Xenv, enclos=baseenv()) isquad <- is.quad(X) if(!is.ppp(X) && !isquad) stop("X should be a point pattern (ppp) or quadrature scheme (quad)") if(is.marked(X)) stop("Sorry, cannot handle marked point patterns") if(!missing(subset)) { W <- eval(subset, covariates, parent.frame()) if(!is.null(W)) { if(is.im(W)) { W <- solutionset(W) } else if(!is.owin(W)) { stop("Argument 'subset' should yield a window or logical image", call.=FALSE) } X <- X[W] } } po <- ppm(Q=X, trend=trend, covariates=covariates, forcefit=TRUE, rename.intercept=FALSE, covfunargs=covfunargs, use.gam=use.gam, nd=nd, eps=eps) XX <- if(isquad) X$data else X if(is.null(weightfun)) switch(method, adapcl = { weightfun <- function(d) { as.integer(abs(d) <= 1)*exp(1/(d^2-1)) } attr(weightfun, "selfprint") <- "Indicator(-1 <= distance <= 1) * exp(1/(distance^2-1))" }, mincon = { }, { RmaxW <- (rmax %orifnull% rmax.rule("K", Window(XX), intensity(XX))) / 2 weightfun <- function(d) { as.integer(d <= RmaxW) } attr(weightfun, "selfprint") <- paste0("Indicator(distance <= ", RmaxW, ")") }) out <- switch(method, mincon = kppmMinCon(X=XX, Xname=Xname, po=po, clusters=clusters, control=control, stabilize=stabilize, statistic=statistic, statargs=statargs, rmax=rmax, algorithm=algorithm, ...), clik2 = kppmComLik(X=XX, Xname=Xname, po=po, clusters=clusters, control=control, stabilize=stabilize, weightfun=weightfun, rmax=rmax, algorithm=algorithm, ...), palm = kppmPalmLik(X=XX, Xname=Xname, po=po, clusters=clusters, control=control, stabilize=stabilize, weightfun=weightfun, rmax=rmax, algorithm=algorithm, ...), adapcl = kppmCLadap(X=XX, Xname=Xname, po=po, clusters=clusters, control=control, epsilon=epsilon, weightfun=weightfun, rmax=rmax, algorithm=algorithm, ...)) h <- attr(out, "h") out <- append(out, list(ClusterArgs=ClusterArgs, call=cl, callframe=parent.frame(), callstring=callstring)) DPP <- list(...)$DPP class(out) <- c(ifelse(is.null(DPP), "kppm", "dppm"), class(out)) if(improve.type != "none") out <- do.call(improve.kppm, append(list(object = out, type = improve.type), improve.args)) attr(out, "h") <- h return(out) } kppmMinCon <- function(X, Xname, po, clusters, control=list(), stabilize=TRUE, statistic, statargs, algorithm="Nelder-Mead", DPP=NULL, ...) { stationary <- is.stationary(po) if(stationary) { lambda <- summary(po)$trend$value } else { w <- as.owin(po, from="covariates") if(!is.mask(w)) w <- NULL lambda <- predict(po, locations=w) } if(!is.null(DPP)){ tmp <- dppmFixIntensity(DPP, lambda, po) clusters <- tmp$clusters lambda <- tmp$lambda po <- tmp$po } mcfit <- clusterfit(X, clusters, lambda = lambda, dataname = Xname, control = control, stabilize=stabilize, statistic = statistic, statargs = statargs, algorithm=algorithm, ...) fitinfo <- attr(mcfit, "info") attr(mcfit, "info") <- NULL Fit <- list(method = "mincon", statistic = statistic, Stat = fitinfo$Stat, StatFun = fitinfo$StatFun, StatName = fitinfo$StatName, FitFun = fitinfo$FitFun, statargs = statargs, pspace = fitinfo$pspace, mcfit = mcfit, maxlogcl = NULL) if(!is.null(DPP)){ clusters <- update(clusters, as.list(mcfit$par)) out <- list(Xname = Xname, X = X, stationary = stationary, fitted = clusters, po = po, Fit = Fit) } else{ out <- list(Xname = Xname, X = X, stationary = stationary, clusters = clusters, modelname = fitinfo$modelname, isPCP = fitinfo$isPCP, po = po, lambda = lambda, mu = mcfit$mu, par = mcfit$par, clustpar = mcfit$clustpar, clustargs = mcfit$clustargs, modelpar = mcfit$modelpar, covmodel = mcfit$covmodel, Fit = Fit) } return(out) } clusterfit <- function(X, clusters, lambda = NULL, startpar = NULL, ..., q=1/4, p=2, rmin=NULL, rmax=NULL, ctrl=list(q=q, p=p, rmin=rmin, rmax=rmax), statistic = NULL, statargs = NULL, algorithm="Nelder-Mead", verbose=FALSE, pspace=NULL){ if(verbose) splat("Fitting cluster model") dataname <- list(...)$dataname info <- spatstatClusterModelInfo(clusters) if(verbose) splat("Retrieved cluster model information") isPCP <- info$isPCP isDPP <- inherits(clusters, "detpointprocfamily") default.ctrl <- list(q=if(isDPP) 1/2 else 1/4, p=2, rmin=NULL, rmax=NULL) given.ctrl <- if(missing(ctrl)) list() else ctrl[names(default.ctrl)] given.args <- c(if(missing(q)) NULL else list(q=q), if(missing(p)) NULL else list(p=p), if(missing(rmin)) NULL else list(rmin=rmin), if(missing(rmax)) NULL else list(rmax=rmax)) ctrl <- resolve.defaults(given.args, given.ctrl, default.ctrl) if(verbose) { splat("Algorithm parameters:") print(ctrl) } if(inherits(X, "ppp")){ if(verbose) splat("Using point pattern data") if(is.null(dataname)) dataname <- getdataname(short.deparse(substitute(X), 20), ...) if(is.null(statistic)) statistic <- "K" if(is.null(startpar)) startpar <- info$selfstart(X) stationary <- is.null(lambda) || (is.numeric(lambda) && length(lambda)==1) if(verbose) { splat("Starting parameters:") print(startpar) cat("Calculating summary function...") } if(stationary) { if(is.null(lambda)) lambda <- intensity(X) StatFun <- if(statistic == "K") "Kest" else "pcf" StatName <- if(statistic == "K") "K-function" else "pair correlation function" Stat <- do.call(StatFun, resolve.defaults(list(X=quote(X)), statargs, list(correction="best"))) } else { StatFun <- if(statistic == "K") "Kinhom" else "pcfinhom" StatName <- if(statistic == "K") "inhomogeneous K-function" else "inhomogeneous pair correlation function" Stat <- do.call(StatFun, resolve.defaults(list(X=quote(X), lambda=lambda), statargs, list(correction="best"))) } if(verbose) splat("Done.") } else if(inherits(X, "fv")){ if(verbose) splat("Using the given summary function") Stat <- X stattype <- attr(Stat, "fname") StatFun <- paste0(stattype) StatName <- NULL if(is.null(statistic)){ if(is.null(stattype) || !is.element(stattype[1L], c("K", "pcf"))) stop("Cannot infer the type of summary statistic from argument ", sQuote("X"), " please specify this via argument ", sQuote("statistic")) statistic <- stattype[1L] } if(stattype[1L]!=statistic) stop("Statistic inferred from ", sQuote("X"), " not equal to supplied argument ", sQuote("statistic")) if(is.null(startpar)){ if(isDPP) stop("No rule for starting parameters in this case. Please set ", sQuote("startpar"), " explicitly.") startpar <- info$checkpar(startpar, old=FALSE) startpar[["scale"]] <- mean(range(Stat[[fvnames(Stat, ".x")]])) } } else{ stop("Unrecognised format for argument X") } if(statistic=="pcf"){ if(verbose) splat("Checking g(0)") argu <- fvnames(Stat, ".x") rvals <- Stat[[argu]] if(rvals[1L] == 0 && (is.null(rmin) || rmin == 0)) { if(verbose) splat("Ignoring g(0)") rmin <- rvals[2L] } } changealgorithm <- length(startpar)==1 && algorithm=="Nelder-Mead" if(isDPP){ if(verbose) splat("Invoking dppmFixAlgorithm") alg <- dppmFixAlgorithm(algorithm, changealgorithm, clusters, startpar) algorithm <- alg$algorithm } dots <- info$resolvedots(...) startpar <- info$checkpar(startpar) theoret <- info[[statistic]] desc <- paste("minimum contrast fit of", info$descname) mcargs <- resolve.defaults(list(observed=Stat, theoretical=theoret, startpar=startpar, ctrl=ctrl, method=algorithm, fvlab=list(label="%s[fit](r)", desc=desc), explain=list(dataname=dataname, fname=statistic, modelname=info$modelname), margs=dots$margs, model=dots$model, funaux=info$funaux, pspace=pspace), list(...) ) if(isDPP && algorithm=="Brent" && changealgorithm) mcargs <- resolve.defaults(mcargs, list(lower=alg$lower, upper=alg$upper)) if(verbose) splat("Starting minimum contrast fit") mcfit <- do.call(mincontrast, mcargs) if(verbose) splat("Returned from minimum contrast fit") optpar <- mcfit$par names(optpar) <- names(startpar) mcfit$par <- optpar if(isDPP){ extra <- list(Stat = Stat, StatFun = StatFun, StatName = StatName, modelname = info$modelabbrev, lambda = lambda) attr(mcfit, "info") <- extra if(verbose) splat("Returning from clusterfit (DPP case)") return(mcfit) } mcfit$modelpar <- info$interpret(optpar, lambda) mcfit$internal <- list(model=ifelse(isPCP, clusters, "lgcp")) mcfit$covmodel <- dots$covmodel if(isPCP) { kappa <- mcfit$par[["kappa"]] mu <- lambda/kappa } else { sigma2 <- mcfit$par[["sigma2"]] mu <- log(lambda) - sigma2/2 } mcfit$mu <- mu mcfit$clustpar <- info$checkpar(mcfit$par, old=FALSE) mcfit$clustargs <- info$checkclustargs(dots$margs, old=FALSE) FitFun <- paste0(tolower(clusters), ".est", statistic) extra <- list(FitFun = FitFun, Stat = Stat, StatFun = StatFun, StatName = StatName, modelname = info$modelabbrev, isPCP = isPCP, lambda = lambda, pspace = pspace) attr(mcfit, "info") <- extra if(verbose) splat("Returning from clusterfit") return(mcfit) } kppmComLik <- function(X, Xname, po, clusters, control=list(), stabilize=TRUE, weightfun, rmax, algorithm="Nelder-Mead", DPP=NULL, ..., pspace=NULL) { W <- as.owin(X) if(is.null(rmax)) rmax <- rmax.rule("K", W, intensity(X)) cl <- closepairs(X, rmax, what="ijd") dIJ <- cl$d if(is.function(weightfun)) { wIJ <- weightfun(dIJ) sumweight <- safePositiveValue(sum(wIJ)) } else { npairs <- length(dIJ) wIJ <- rep.int(1, npairs) sumweight <- npairs } dcm <- do.call.matched(as.mask, append(list(w=W), list(...)), sieve=TRUE) M <- dcm$result otherargs <- dcm$otherargs isDPP <- inherits(clusters, "detpointprocfamily") if(stationary <- is.stationary(po)) { lambda <- intensity(X) g <- distcdf(W, delta=rmax/4096) gscale <- npoints(X)^2 } else { lambda <- lambdaM <- predict(po, locations=M) g <- distcdf(M, dW=lambdaM, delta=rmax/4096) gscale <- safePositiveValue(integral.im(lambdaM)^2, default=npoints(X)^2) } isDPP <- !is.null(DPP) if(isDPP){ tmp <- dppmFixIntensity(DPP, lambda, po) clusters <- tmp$clusters lambda <- tmp$lambda po <- tmp$po } g <- g[with(g, .x) <= rmax,] info <- spatstatClusterModelInfo(clusters) pcfun <- info$pcf funaux <- info$funaux selfstart <- info$selfstart isPCP <- info$isPCP parhandler <- info$parhandler modelname <- info$modelname pcfunargs <- list(funaux=funaux) if(is.function(parhandler)) { clustargs <- if("covmodel" %in% names(otherargs)) otherargs[["covmodel"]] else otherargs clargs <- do.call(parhandler, clustargs) pcfunargs <- append(clargs, pcfunargs) } else clargs <- NULL startpar <- selfstart(X) paco <- function(d, par) { do.call(pcfun, append(list(par=par, rvals=d), pcfunargs)) } if(!is.function(weightfun)) { objargs <- list(dIJ=dIJ, sumweight=sumweight, g=g, gscale=gscale, envir=environment(paco), BIGVALUE=1, SMALLVALUE=.Machine$double.eps) obj <- function(par, objargs) { with(objargs, { logprod <- sum(log(safePositiveValue(paco(dIJ, par)))) integ <- unlist(stieltjes(paco, g, par=par)) integ <- pmax(SMALLVALUE, integ) logcl <- 2*(logprod - sumweight * log(integ)) logcl <- safeFiniteValue(logcl, default=-BIGVALUE) return(logcl) }, enclos=objargs$envir) } objargs$BIGVALUE <- bigvaluerule(obj, objargs, startpar) } else { force(weightfun) wpaco <- function(d, par) { y <- do.call(pcfun, append(list(par=par, rvals=d), pcfunargs)) w <- weightfun(d) return(y * w) } objargs <- list(dIJ=dIJ, wIJ=wIJ, sumweight=sumweight, g=g, gscale=gscale, envir=environment(wpaco), BIGVALUE=1, SMALLVALUE=.Machine$double.eps) obj <- function(par, objargs) { with(objargs, { integ <- unlist(stieltjes(wpaco, g, par=par)) integ <- pmax(SMALLVALUE, integ) logcl <- safeFiniteValue( 2*(sum(wIJ * log(safePositiveValue(paco(dIJ, par)))) - sumweight * log(integ)), default=-BIGVALUE) return(logcl) }, enclos=objargs$envir) } objargs$BIGVALUE <- bigvaluerule(obj, objargs, startpar) } if(stabilize) { startval <- obj(startpar, objargs) smallscale <- sqrt(.Machine$double.eps) fnscale <- -max(abs(startval), smallscale) parscale <- pmax(abs(startpar), smallscale) scaling <- list(fnscale=fnscale, parscale=parscale) } else { scaling <- list(fnscale=-1) } control.updated <- resolve.defaults(control, scaling, list(trace=0)) optargs <- list(par=startpar, fn=obj, objargs=objargs, control=control.updated, method=algorithm) changealgorithm <- length(startpar)==1 && algorithm=="Nelder-Mead" if(isDPP){ alg <- dppmFixAlgorithm(algorithm, changealgorithm, clusters, startpar) algorithm <- optargs$method <- alg$algorithm if(algorithm=="Brent" && changealgorithm){ optargs$lower <- alg$lower optargs$upper <- alg$upper } } opt <- do.call(optim, optargs) signalStatus(optimStatus(opt), errors.only=TRUE) optpar <- opt$par names(optpar) <- names(startpar) opt$par <- optpar opt$startpar <- startpar if(!is.null(DPP)){ Fit <- list(method = "clik2", clfit = opt, weightfun = weightfun, rmax = rmax, objfun = obj, objargs = objargs, maxlogcl = opt$value, pspace = pspace) clusters <- update(clusters, as.list(opt$par)) result <- list(Xname = Xname, X = X, stationary = stationary, fitted = clusters, modelname = modelname, po = po, lambda = lambda, Fit = Fit) return(result) } modelpar <- info$interpret(optpar, lambda) if(isPCP) { kappa <- optpar[["kappa"]] mu <- if(stationary) lambda/kappa else eval.im(lambda/kappa) } else { sigma2 <- optpar[["sigma2"]] mu <- if(stationary) log(lambda) - sigma2/2 else eval.im(log(lambda) - sigma2/2) } Fit <- list(method = "clik2", clfit = opt, weightfun = weightfun, rmax = rmax, objfun = obj, objargs = objargs, maxlogcl = opt$value, pspace = pspace) result <- list(Xname = Xname, X = X, stationary = stationary, clusters = clusters, modelname = modelname, isPCP = isPCP, po = po, lambda = lambda, mu = mu, par = optpar, clustpar = info$checkpar(par=optpar, old=FALSE), clustargs = info$checkclustargs(clargs$margs, old=FALSE), modelpar = modelpar, covmodel = clargs, Fit = Fit) return(result) } kppmPalmLik <- function(X, Xname, po, clusters, control=list(), stabilize=TRUE, weightfun, rmax, algorithm="Nelder-Mead", DPP=NULL, ..., pspace=NULL) { W <- as.owin(X) if(is.null(rmax)) rmax <- rmax.rule("K", W, intensity(X)) cl <- closepairs(X, rmax) J <- cl$j dIJ <- cl$d if(is.function(weightfun)) { wIJ <- weightfun(dIJ) } else { npairs <- length(dIJ) wIJ <- rep.int(1, npairs) } dcm <- do.call.matched(as.mask, append(list(w=W), list(...)), sieve=TRUE) M <- dcm$result otherargs <- dcm$otherargs isDPP <- inherits(clusters, "detpointprocfamily") if(stationary <- is.stationary(po)) { lambda <- intensity(X) lambdaJ <- rep(lambda, length(J)) g <- distcdf(X, M, delta=rmax/4096) gscale <- npoints(X)^2 } else { lambdaX <- fitted(po, dataonly=TRUE) lambda <- lambdaM <- predict(po, locations=M) lambdaJ <- lambdaX[J] g <- distcdf(X, M, dV=lambdaM, delta=rmax/4096) gscale <- safePositiveValue(integral.im(lambdaM) * npoints(X), default=npoints(X)^2) } isDPP <- !is.null(DPP) if(isDPP){ tmp <- dppmFixIntensity(DPP, lambda, po) clusters <- tmp$clusters lambda <- tmp$lambda po <- tmp$po } g <- g[with(g, .x) <= rmax,] info <- spatstatClusterModelInfo(clusters) pcfun <- info$pcf funaux <- info$funaux selfstart <- info$selfstart isPCP <- info$isPCP parhandler <- info$parhandler modelname <- info$modelname pcfunargs <- list(funaux=funaux) if(is.function(parhandler)) { clustargs <- if("covmodel" %in% names(otherargs)) otherargs[["covmodel"]] else otherargs clargs <- do.call(parhandler, clustargs) pcfunargs <- append(clargs, pcfunargs) } else clargs <- NULL startpar <- selfstart(X) paco <- function(d, par) { do.call(pcfun, append(list(par=par, rvals=d), pcfunargs)) } if(!is.function(weightfun)) { objargs <- list(dIJ=dIJ, g=g, gscale=gscale, sumloglam=safeFiniteValue(sum(log(lambdaJ))), envir=environment(paco), BIGVALUE=1, SMALLVALUE=.Machine$double.eps) obj <- function(par, objargs) { with(objargs, { integ <- unlist(stieltjes(paco, g, par=par)) integ <- pmax(SMALLVALUE, integ) logplik <- safeFiniteValue( sumloglam + sum(log(safePositiveValue(paco(dIJ, par)))) - gscale * integ, default=-BIGVALUE) return(logplik) }, enclos=objargs$envir) } objargs$BIGVALUE <- bigvaluerule(obj, objargs, startpar) } else { force(weightfun) wpaco <- function(d, par) { y <- do.call(pcfun, append(list(par=par, rvals=d), pcfunargs)) w <- weightfun(d) return(y * w) } objargs <- list(dIJ=dIJ, wIJ=wIJ, g=g, gscale=gscale, wsumloglam=safeFiniteValue( sum(wIJ * safeFiniteValue(log(lambdaJ))) ), envir=environment(wpaco), BIGVALUE=1, SMALLVALUE=.Machine$double.eps) obj <- function(par, objargs) { with(objargs, { integ <- unlist(stieltjes(wpaco, g, par=par)) integ <- pmax(SMALLVALUE, integ) logplik <- safeFiniteValue(wsumloglam + sum(wIJ * log(safePositiveValue(paco(dIJ, par)))) - gscale * integ, default=-BIGVALUE) return(logplik) }, enclos=objargs$envir) } objargs$BIGVALUE <- bigvaluerule(obj, objargs, startpar) } if(stabilize) { startval <- obj(startpar, objargs) smallscale <- sqrt(.Machine$double.eps) fnscale <- -max(abs(startval), smallscale) parscale <- pmax(abs(startpar), smallscale) scaling <- list(fnscale=fnscale, parscale=parscale) } else { scaling <- list(fnscale=-1) } control.updated <- resolve.defaults(control, scaling, list(trace=0)) optargs <- list(par=startpar, fn=obj, objargs=objargs, control=control.updated, method=algorithm) changealgorithm <- length(startpar)==1 && algorithm=="Nelder-Mead" if(isDPP){ alg <- dppmFixAlgorithm(algorithm, changealgorithm, clusters, startpar) algorithm <- optargs$method <- alg$algorithm if(algorithm=="Brent" && changealgorithm){ optargs$lower <- alg$lower optargs$upper <- alg$upper } } opt <- do.call(optim, optargs) signalStatus(optimStatus(opt), errors.only=TRUE) optpar <- opt$par names(optpar) <- names(startpar) opt$par <- optpar opt$startpar <- startpar if(!is.null(DPP)){ Fit <- list(method = "palm", clfit = opt, weightfun = weightfun, rmax = rmax, objfun = obj, objargs = objargs, maxlogcl = opt$value, pspace = pspace) clusters <- update(clusters, as.list(optpar)) result <- list(Xname = Xname, X = X, stationary = stationary, fitted = clusters, modelname = modelname, po = po, lambda = lambda, Fit = Fit) return(result) } modelpar <- info$interpret(optpar, lambda) if(isPCP) { kappa <- optpar[["kappa"]] mu <- if(stationary) lambda/kappa else eval.im(lambda/kappa) } else { sigma2 <- optpar[["sigma2"]] mu <- if(stationary) log(lambda) - sigma2/2 else eval.im(log(lambda) - sigma2/2) } Fit <- list(method = "palm", clfit = opt, weightfun = weightfun, rmax = rmax, objfun = obj, objargs = objargs, maxlogcl = opt$value, pspace = pspace) result <- list(Xname = Xname, X = X, stationary = stationary, clusters = clusters, modelname = modelname, isPCP = isPCP, po = po, lambda = lambda, mu = mu, par = optpar, clustpar = info$checkpar(par=optpar, old=FALSE), clustargs = info$checkclustargs(clargs$margs, old=FALSE), modelpar = modelpar, covmodel = clargs, Fit = Fit) return(result) } kppmCLadap <- function(X, Xname, po, clusters, control, weightfun, rmax=NULL, epsilon=0.01, DPP=NULL, algorithm="Broyden", ..., startpar=NULL, globStrat="dbldog") { if(!requireNamespace("nleqslv", quietly=TRUE)) stop(paste("The package", sQuote("nleqslv"), "is required"), call.=FALSE) W <- as.owin(X) if(is.null(rmax)) rmax <- shortside(Frame(W)) cl <- closepairs(X, rmax) dIJ <- cl$d Rmin <- min(dIJ) indexmin <- which(dIJ==Rmin) dcm <- do.call.matched(as.mask, append(list(w=W), list(...)), sieve=TRUE) M <- dcm$result otherargs <- dcm$otherargs if(stationary <- is.stationary(po)) { lambda <- intensity(X) g <- distcdf(W, delta=rmax/4096) gscale <- npoints(X)^2 } else { lambda <- lambdaM <- predict(po, locations=M) g <- distcdf(M, dW=lambdaM, delta=rmax/4096) gscale <- safePositiveValue(integral.im(lambdaM)^2, default=npoints(X)^2) } isDPP <- !is.null(DPP) if(isDPP){ tmp <- dppmFixIntensity(DPP, lambda, po) clusters <- tmp$clusters lambda <- tmp$lambda po <- tmp$po } info <- spatstatClusterModelInfo(clusters) pcfun <- info$pcf dpcfun <- info$Dpcf funaux <- info$funaux selfstart <- info$selfstart isPCP <- info$isPCP parhandler <- info$parhandler modelname <- info$modelname pcfunargs <- list(funaux=funaux) if(is.function(parhandler)) { clustargs <- if("covmodel" %in% names(otherargs)) otherargs[["covmodel"]] else otherargs clargs <- do.call(parhandler, clustargs) pcfunargs <- append(clargs, pcfunargs) } else clargs <- NULL if(is.null(startpar)) { startpar <- selfstart(X) } else if(!isDPP){ checkpar <- info$checkpar startpar <- checkpar(startpar, old=TRUE) } startparLog <- log(startpar) pcfunLog <- function(par, ...) { pcfun(exp(par), ...) } dpcfunLog <- function(par, ...) { dpcfun(exp(par), ...) } paco <- function(d, par) { do.call(pcfunLog, append(list(par=par, rvals=d), pcfunargs)) } dpaco <- function(d, par) { do.call(dpcfunLog, append(list(par=par, rvals=d), pcfunargs)) } g <- g[with(g, .x) <= rmax,] weight <- function(d, par) { y <- paco(d=d, par=par) M <- 1 if(!isDPP){ M <- abs(paco(d=0, par=par)-1) } return(weightfun(epsilon*M/(y-1))) } wlogcl2score <- function(par, paco, dpaco, dIJ, gscale, epsilon, cdf=g){ p <- length(par) temp <- rep(0, p) if(isDPP){ if(length(par)==1 && is.null(names(par))) names(par) <- clusters$freepar mod <- update(clusters, as.list(exp(par))) if(!valid(mod)){ return(rep(Inf, p)) } } wdIJ <- weight(d=dIJ, par=par) index <- unique(c(which(wdIJ!=0), indexmin)) dIJcurrent <- dIJ[index] for(i in 1:p){ parname <- names(par)[i] dpcfweighted <- function(d, par){ y <- dpaco(d = d, par = par)[parname,]*exp(par[i]) return(y*weight(d = d, par = par)) } temp[i] <- sum(dpcfweighted(d = dIJcurrent, par=par)/paco(d = dIJcurrent, par = par)) - gscale * stieltjes(dpcfweighted,cdf, par=par)$f } return(temp) } opt <- nleqslv::nleqslv(x = startparLog, fn = wlogcl2score, method = algorithm, global = globStrat, control = control, paco=paco, dpaco=dpaco, dIJ=dIJ, gscale=gscale, epsilon=epsilon) optpar <- exp(opt$x) names(optpar) <- names(startpar) opt$par <- optpar opt$startpar <- startpar if(isDPP){ Fit <- list(method = "adapcl", cladapfit = opt, weightfun = weightfun, rmax = rmax, epsilon = epsilon, objfun = wlogcl2score, objargs = control, estfunc = opt$fvec) clusters <- update(clusters, as.list(exp(opt$x))) result <- list(Xname = Xname, X = X, stationary = stationary, fitted = clusters, modelname = modelname, po = po, lambda = lambda, Fit = Fit) return(result) } modelpar <- info$interpret(optpar, lambda) if(isPCP) { kappa <- optpar[["kappa"]] mu <- if(stationary) lambda/kappa else eval.im(lambda/kappa) } else { sigma2 <- optpar[["sigma2"]] mu <- if(stationary) log(lambda) - sigma2/2 else eval.im(log(lambda) - sigma2/2) } Fit <- list(method = "adapcl", cladapfit = opt, weightfun = weightfun, rmax = rmax, epsilon = epsilon, objfun = wlogcl2score, objargs = control, estfunc = opt$fvec) result <- list(Xname = Xname, X = X, stationary = stationary, clusters = clusters, modelname = modelname, isPCP = isPCP, po = po, lambda = lambda, mu = mu, par = optpar, clustpar = info$checkpar(par=optpar, old=FALSE), clustargs = info$checkclustargs(clargs$margs, old=FALSE), modelpar = modelpar, covmodel = clargs, Fit = Fit) return(result) } improve.kppm <- local({ fnc <- function(r, eps, g){ (g(r) - 1)/(g(0) - 1) - eps} improve.kppm <- function(object, type=c("quasi", "wclik1", "clik1"), rmax = NULL, eps.rmax = 0.01, dimyx = 50, maxIter = 100, tolerance = 1e-06, fast = TRUE, vcov = FALSE, fast.vcov = FALSE, verbose = FALSE, save.internals = FALSE) { verifyclass(object, "kppm") type <- match.arg(type) gfun <- pcfmodel(object) X <- object$X win <- as.owin(X) mask <- as.mask(win, dimyx = dimyx) wt <- pixellate(win, W = mask) wt <- wt[mask] Uxy <- rasterxy.mask(mask) U <- ppp(Uxy$x, Uxy$y, window = win, check=FALSE) U <- U[mask] Yu <- pixellate(X, W = mask) Yu <- Yu[mask] po <- object$po Z <- model.images(po, mask) Z <- sapply(Z, "[", i=U) beta0 <- coef(po) if (type != "clik1" && is.null(rmax)) { diamwin <- diameter(win) rmax <- if(fnc(diamwin, eps.rmax, gfun) >= 0) diamwin else uniroot(fnc, lower = 0, upper = diameter(win), eps=eps.rmax, g=gfun)$root if(verbose) splat(paste0("type: ", type, ", ", "dependence range: ", rmax, ", ", "dimyx: ", dimyx, ", g(0) - 1:", gfun(0) -1)) } if (type == "wclik1") Kmax <- 2*pi * integrate(function(r){r * (gfun(r) - 1)}, lower=0, upper=rmax)$value * exp(c(Z %*% beta0)) if (!fast || (vcov && !fast.vcov)){ if (verbose) cat("computing the g(u_i,u_j)-1 matrix ...") gminus1 <- matrix(gfun(c(pairdist(U))) - 1, U$n, U$n) if (verbose) cat("..Done.\n") } if ( (fast && type == "quasi") | fast.vcov ){ if (verbose) cat("computing the sparse G-1 matrix ...\n") cp <- crosspairs(U,U,rmax,what="ijd") if (verbose) cat("crosspairs done\n") Gtap <- (gfun(cp$d) - 1) if(vcov){ if(fast.vcov){ gminus1 <- Matrix::sparseMatrix(i=cp$i, j=cp$j, x=Gtap, dims=c(U$n, U$n)) } else{ if(fast) gminus1 <- matrix(gfun(c(pairdist(U))) - 1, U$n, U$n) } } if (verbose & type!="quasi") cat("..Done.\n") } if (type == "quasi" && fast){ mu0 <- exp(c(Z %*% beta0)) * wt mu0root <- sqrt(mu0) sparseG <- Matrix::sparseMatrix(i=cp$i, j=cp$j, x=mu0root[cp$i] * mu0root[cp$j] * Gtap, dims=c(U$n, U$n)) Rroot <- Matrix::Cholesky(sparseG, perm = TRUE, Imult = 1) if (verbose) cat("..Done.\n") } bt <- beta0 noItr <- 1 repeat { mu <- exp(c(Z %*% bt)) * wt mu.root <- sqrt(mu) ff <- switch(type, clik1 = Z, wclik1= Z/(1 + Kmax), quasi = if(fast){ Matrix::solve(Rroot, mu.root * Z)/mu.root } else{ solve(diag(U$n) + t(gminus1 * mu), Z) } ) uf <- (Yu - mu) %*% ff Jinv <- solve(t(Z * mu) %*% ff) if(maxIter==0){ break } deltabt <- as.numeric(uf %*% Jinv) if (any(!is.finite(deltabt))) { warning(paste("Infinite value, NA or NaN appeared", "in the iterative weighted least squares algorithm.", "Returning the initial intensity estimate unchanged."), call.=FALSE) return(object) } bt <- bt + deltabt if (verbose) splat(paste0("itr: ", noItr, ",\nu_f: ", as.numeric(uf), "\nbeta:", bt, "\ndeltabeta:", deltabt)) if (max(abs(deltabt/bt)) <= tolerance || max(abs(uf)) <= tolerance) break if (noItr > maxIter) stop("Maximum number of iterations reached without convergence.") noItr <- noItr + 1 } out <- object out$po$coef.orig <- beta0 out$po$coef <- bt loc <- if(is.sob(out$lambda)) as.mask(out$lambda) else mask out$lambda <- predict(out$po, locations = loc) out$improve <- list(type = type, rmax = rmax, dimyx = dimyx, fast = fast, fast.vcov = fast.vcov) if(save.internals){ out$improve <- append(out$improve, list(ff=ff, uf=uf, J.inv=Jinv)) } if(vcov){ if (verbose) cat("computing the asymptotic variance ...\n") trans <- if(fast) Matrix::t else t Sig <- trans(ff) %*% (ff * mu) + trans(ff * mu) %*% gminus1 %*% (ff * mu) out$vcov <- as.matrix(Jinv %*% Sig %*% Jinv) } return(out) } improve.kppm }) is.kppm <- function(x) { inherits(x, "kppm")} print.kppm <- print.dppm <- function(x, ...) { isPCP <- x$isPCP isDPP <- inherits(x, "dppm") if(!isDPP && is.null(isPCP)) isPCP <- TRUE terselevel <- spatstat.options('terse') digits <- getOption('digits') splat(if(x$stationary) "Stationary" else "Inhomogeneous", if(isDPP) "determinantal" else if(isPCP) "cluster" else "Cox", "point process model") Xname <- x$Xname if(waxlyrical('extras', terselevel) && nchar(Xname) < 20) { has.subset <- ("subset" %in% names(x$call)) splat("Fitted to", if(has.subset) "(a subset of)" else NULL, "point pattern dataset", sQuote(Xname)) } if(waxlyrical('gory', terselevel)) { switch(x$Fit$method, mincon = { splat("Fitted by minimum contrast") splat("\tSummary statistic:", x$Fit$StatName) }, clik =, clik2 = { splat("Fitted by maximum second order composite likelihood") splat("\trmax =", x$Fit$rmax) if(!is.null(wtf <- x$Fit$weightfun)) { a <- attr(wtf, "selfprint") %orifnull% pasteFormula(wtf) splat("\tweight function:", a) } }, palm = { splat("Fitted by maximum Palm likelihood") splat("\trmax =", x$Fit$rmax) if(!is.null(wtf <- x$Fit$weightfun)) { a <- attr(wtf, "selfprint") %orifnull% pasteFormula(wtf) splat("\tweight function:", a) } }, adapcl = { splat("Fitted by adaptive second order composite likelihood") splat("\tepsilon =", x$Fit$epsilon) if(!is.null(wtf <- x$Fit$weightfun)) { a <- attr(wtf, "selfprint") %orifnull% pasteFormula(wtf) splat("\tweight function:", a) } }, warning(paste("Unrecognised fitting method", sQuote(x$Fit$method))) ) } parbreak(terselevel) if(!(isDPP && is.null(x$fitted$intensity))) print(x$po, what="trend") if(isDPP){ splat("Fitted DPP model:") print(x$fitted) return(invisible(NULL)) } tableentry <- spatstatClusterModelInfo(x$clusters) splat(if(isPCP) "Cluster" else "Cox", "model:", tableentry$printmodelname(x)) cm <- x$covmodel if(!isPCP) { splat("\tCovariance model:", cm$model) margs <- cm$margs if(!is.null(margs)) { nama <- names(margs) tags <- ifelse(nzchar(nama), paste(nama, "="), "") tagvalue <- paste(tags, margs) splat("\tCovariance parameters:", paste(tagvalue, collapse=", ")) } } pa <- x$clustpar if (!is.null(pa)) { splat("Fitted", if(isPCP) "cluster" else "covariance", "parameters:") print(pa, digits=digits) } if(!is.null(mu <- x$mu)) { if(isPCP) { splat("Mean cluster size: ", if(!is.im(mu)) paste(signif(mu, digits), "points") else "[pixel image]") } else { splat("Fitted mean of log of random intensity:", if(!is.im(mu)) signif(mu, digits) else "[pixel image]") } } if(isDPP) { rx <- repul(x) splat(if(is.im(rx)) "(Average) strength" else "Strength", "of repulsion:", signif(mean(rx), 4)) } invisible(NULL) } plot.kppm <- local({ plotem <- function(x, ..., main=dmain, dmain) { plot(x, ..., main=main) } plot.kppm <- function(x, ..., what=c("intensity", "statistic", "cluster"), pause=interactive(), xname) { if(missing(xname)) xname <- short.deparse(substitute(x)) nochoice <- missing(what) what <- pickoption("plot type", what, c(statistic="statistic", intensity="intensity", cluster="cluster"), multi=TRUE) Fit <- x$Fit if(is.null(Fit)) { warning("kppm object is in outdated format") Fit <- x Fit$method <- "mincon" } loc <- list(...)$locations inappropriate <- (nochoice & ((what == "intensity") & (x$stationary))) | ((what == "statistic") & (Fit$method != "mincon")) | ((what == "cluster") & (identical(x$isPCP, FALSE))) | ((what == "cluster") & (!x$stationary) & is.null(loc)) if(!nochoice && !x$stationary && "cluster" %in% what && is.null(loc)) stop("Please specify additional argument ", sQuote("locations"), " which will be passed to the function ", sQuote("clusterfield"), ".") if(any(inappropriate)) { what <- what[!inappropriate] if(length(what) == 0){ message("Nothing meaningful to plot. Exiting...") return(invisible(NULL)) } } pause <- pause && (length(what) > 1) if(pause) opa <- par(ask=TRUE) for(style in what) switch(style, intensity={ plotem(x$po, ..., dmain=c(xname, "Intensity"), how="image", se=FALSE) }, statistic={ plotem(Fit$mcfit, ..., dmain=c(xname, Fit$StatName)) }, cluster={ plotem(clusterfield(x, locations = loc, verbose=FALSE), ..., dmain=c(xname, "Fitted cluster")) }) if(pause) par(opa) return(invisible(NULL)) } plot.kppm }) predict.kppm <- predict.dppm <- function(object, ...) { se <- resolve.1.default(list(se=FALSE), list(...)) interval <- resolve.1.default(list(interval="none"), list(...)) if(se) warning("Standard error calculation assumes a Poisson process") if(interval != "none") warning(paste(interval, "interval calculation assumes a Poisson process")) predict(as.ppm(object), ...) } fitted.kppm <- fitted.dppm <- function(object, ...) { fitted(as.ppm(object), ...) } residuals.kppm <- residuals.dppm <- function(object, ...) { type <- resolve.1.default(list(type="raw"), list(...)) if(type != "raw") warning(paste("calculation of", type, "residuals", "assumes a Poisson process")) residuals(as.ppm(object), ...) } formula.kppm <- formula.dppm <- function(x, ...) { formula(x$po, ...) } terms.kppm <- terms.dppm <- function(x, ...) { terms(x$po, ...) } labels.kppm <- labels.dppm <- function(object, ...) { labels(object$po, ...) } update.kppm <- function(object, ..., evaluate=TRUE, envir=environment(terms(object))) { argh <- list(...) nama <- names(argh) callframe <- object$callframe fmla <- formula(object) jf <- integer(0) if(!is.null(trend <- argh$trend)) { if(!can.be.formula(trend)) stop("Argument \"trend\" should be a formula") fmla <- newformula(formula(object), trend, callframe, envir) jf <- which(nama == "trend") } else if(any(isfo <- sapply(argh, can.be.formula))) { if(sum(isfo) > 1) { if(!is.null(nama)) isfo <- isfo & nzchar(nama) if(sum(isfo) > 1) stop(paste("Arguments not understood:", "there are two unnamed formula arguments")) } jf <- which(isfo) fmla <- argh[[jf]] fmla <- newformula(formula(object), fmla, callframe, envir) } if(!is.null(X <- argh$X)) { if(!inherits(X, c("ppp", "quad"))) stop(paste("Argument X should be a formula,", "a point pattern or a quadrature scheme")) jX <- which(nama == "X") } else if(any(ispp <- sapply(argh, inherits, what=c("ppp", "quad")))) { if(sum(ispp) > 1) { if(!is.null(nama)) ispp <- ispp & nzchar(nama) if(sum(ispp) > 1) stop(paste("Arguments not understood:", "there are two unnamed point pattern/quadscheme arguments")) } jX <- which(ispp) X <- argh[[jX]] } else { X <- object$X jX <- integer(0) } Xexpr <- if(length(jX) > 0) sys.call()[[2L + jX]] else NULL jused <- c(jf, jX) if(length(jused) > 0) { argh <- argh[-jused] nama <- names(argh) } thecall <- getCall(object) methodname <- as.character(thecall[[1L]]) switch(methodname, kppm.formula = { if(!is.null(Xexpr)) { lhs.of.formula(fmla) <- Xexpr } else if(is.null(lhs.of.formula(fmla))) { lhs.of.formula(fmla) <- as.name('.') } oldformula <- as.formula(getCall(object)$X) thecall$X <- newformula(oldformula, fmla, callframe, envir) }, { oldformula <- as.formula(getCall(object)$trend %orifnull% (~1)) fom <- newformula(oldformula, fmla, callframe, envir) if(!is.null(Xexpr)) lhs.of.formula(fom) <- Xexpr if(is.null(lhs.of.formula(fom))) { thecall$trend <- fom if(length(jX) > 0) thecall$X <- X } else { thecall$trend <- NULL thecall$X <- fom } }) knownnames <- unique(c(names(formals(kppm.ppp)), names(formals(mincontrast)), names(formals(optim)))) knownnames <- setdiff(knownnames, c("X", "trend", "observed", "theoretical", "fn", "gr", "...")) ok <- nama %in% knownnames thecall <- replace(thecall, nama[ok], argh[ok]) thecall$formula <- NULL thecall[[1L]] <- as.name("kppm") if(!evaluate) return(thecall) out <- eval(thecall, envir=parent.frame(), enclos=envir) if(length(jX) == 1) { mc <- match.call() Xlang <- mc[[2L+jX]] out$Xname <- short.deparse(Xlang) } return(out) } unitname.kppm <- unitname.dppm <- function(x) { return(unitname(x$X)) } "unitname<-.kppm" <- "unitname<-.dppm" <- function(x, value) { unitname(x$X) <- value if(!is.null(x$Fit$mcfit)) { unitname(x$Fit$mcfit) <- value } else if(is.null(x$Fit)) { warning("kppm object in outdated format") if(!is.null(x$mcfit)) unitname(x$mcfit) <- value } return(x) } as.fv.kppm <- as.fv.dppm <- function(x) { if(x$Fit$method == "mincon") return(as.fv(x$Fit$mcfit)) gobs <- if(is.stationary(x)) pcf(x$X, correction="good") else pcfinhom(x$X, lambda=x, correction="good", update=FALSE) gfit <- (pcfmodel(x))(gobs$r) g <- bind.fv(gobs, data.frame(fit=gfit), "%s[fit](r)", "predicted %s for fitted model") return(g) } coef.kppm <- coef.dppm <- function(object, ...) { return(coef(object$po)) } Kmodel.kppm <- function(model, ...) { Kpcf.kppm(model, what="K") } pcfmodel.kppm <- function(model, ...) { Kpcf.kppm(model, what="pcf") } Kpcf.kppm <- function(model, what=c("K", "pcf", "kernel")) { what <- match.arg(what) clusters <- model$clusters tableentry <- spatstatClusterModelInfo(clusters) if(is.null(tableentry)) stop("No information available for", sQuote(clusters), "cluster model") fun <- tableentry[[what]] if(is.null(fun)) stop("No expression available for", what, "for", sQuote(clusters), "cluster model") par <- model$par funaux <- tableentry$funaux cm <- model$covmodel model <- cm$model margs <- cm$margs f <- function(r) as.numeric(fun(par=par, rvals=r, funaux=funaux, model=model, margs=margs)) return(f) } is.stationary.kppm <- is.stationary.dppm <- function(x) { return(x$stationary) } is.poisson.kppm <- function(x) { switch(x$clusters, Cauchy=, VarGamma=, Thomas=, MatClust={ mu <- x$mu return(!is.null(mu) && (max(mu) == 0)) }, LGCP = { sigma2 <- x$par[["sigma2"]] return(sigma2 == 0) }, return(FALSE)) } as.ppm.kppm <- as.ppm.dppm <- function(object) { object$po } as.owin.kppm <- as.owin.dppm <- function(W, ..., from=c("points", "covariates"), fatal=TRUE) { from <- match.arg(from) as.owin(as.ppm(W), ..., from=from, fatal=fatal) } domain.kppm <- Window.kppm <- domain.dppm <- Window.dppm <- function(X, ..., from=c("points", "covariates")) { from <- match.arg(from) as.owin(X, from=from) } model.images.kppm <- model.images.dppm <- function(object, W=as.owin(object), ...) { model.images(as.ppm(object), W=W, ...) } model.matrix.kppm <- model.matrix.dppm <- function(object, data=model.frame(object, na.action=NULL), ..., Q=NULL, keepNA=TRUE) { if(missing(data)) data <- NULL model.matrix(as.ppm(object), data=data, ..., Q=Q, keepNA=keepNA) } model.frame.kppm <- model.frame.dppm <- function(formula, ...) { model.frame(as.ppm(formula), ...) } logLik.kppm <- logLik.dppm <- function(object, ...) { cl <- object$Fit$maxlogcl if(is.null(cl)) stop(paste("logLik is only available for kppm objects fitted with", "method='palm' or method='clik2'"), call.=FALSE) ll <- logLik(as.ppm(object)) ll[] <- cl return(ll) } AIC.kppm <- AIC.dppm <- function(object, ..., k=2) { cl <- logLik(object) df <- attr(cl, "df") return(- 2 * as.numeric(cl) + k * df) } extractAIC.kppm <- extractAIC.dppm <- function (fit, scale = 0, k = 2, ...) { cl <- logLik(fit) edf <- attr(cl, "df") aic <- - 2 * as.numeric(cl) + k * edf return(c(edf, aic)) } nobs.kppm <- nobs.dppm <- function(object, ...) { nobs(as.ppm(object)) } psib <- function(object) UseMethod("psib") psib.kppm <- function(object) { clus <- object$clusters info <- spatstatClusterModelInfo(clus) if(!info$isPCP) { warning("The model is not a cluster process") return(NA) } g <- pcfmodel(object) p <- 1 - 1/g(0) return(p) }
getVMat.onePhase <- function(Z.Phase1, design.df, var.comp = NA) { v.mat <- lapply(Z.Phase1, function(x) x %*% t(x)) if (all(is.na(var.comp))) { return(v.mat) } else { if (names(v.mat)[1] == "e") { match.names <- match(var.comp, names(v.mat)) if (any(is.na(match.names))) match.names <- match.names[!is.na(match.names)] return(v.mat[c(1, match.names)]) } else { match.names <- match(var.comp, names(v.mat)) if (any(is.na(match.names))) match.names <- match.names[!is.na(match.names)] return(v.mat[match.names]) } } }
qqnorm.rma.uni <- function(y, type="rstandard", pch=19, envelope=TRUE, level=y$level, bonferroni=FALSE, reps=1000, smooth=TRUE, bass=0, label=FALSE, offset=0.3, pos=13, lty, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(y), must="rma.uni", notav="rma.uni.selmodel") na.act <- getOption("na.action") on.exit(options(na.action=na.act), add=TRUE) x <- y type <- match.arg(type, c("rstandard", "rstudent")) if (x$k == 1) stop(mstyle$stop("Stopped because k = 1.")) draw.envelope <- envelope if (label == "out" & !envelope) { envelope <- TRUE draw.envelope <- FALSE } if (length(label) != 1L) stop(mstyle$stop("Argument 'label' should be of length 1.")) if (missing(lty)) { lty <- c("solid", "dotted") } else { if (length(lty) == 1L) lty <- c(lty, lty) } ddd <- list(...) lqqnorm <- function(..., seed) qqnorm(...) labline <- function(..., seed) abline(...) llines <- function(..., seed) lines(...) ltext <- function(..., seed) text(...) if (type == "rstandard") { res <- rstandard(x) not.na <- !is.na(res$z) zi <- res$z[not.na] slab <- res$slab[not.na] ord <- order(zi) slab <- slab[ord] } else { res <- rstudent(x) not.na <- !is.na(res$z) zi <- res$z[not.na] slab <- res$slab[not.na] ord <- order(zi) slab <- slab[ord] } sav <- lqqnorm(zi, pch=pch, bty="l", ...) labline(a=0, b=1, lty=lty[1], ...) if (envelope) { level <- .level(level) if (!is.null(ddd$seed)) set.seed(ddd$seed) dat <- matrix(rnorm(x$k*reps), nrow=x$k, ncol=reps) options(na.action="na.omit") H <- hatvalues(x, type="matrix") options(na.action = na.act) ImH <- diag(x$k) - H ei <- ImH %*% dat ei <- apply(ei, 2, sort) if (bonferroni) { lb <- apply(ei, 1, quantile, (level/2)/x$k) ub <- apply(ei, 1, quantile, 1-(level/2)/x$k) } else { lb <- apply(ei, 1, quantile, (level/2)) ub <- apply(ei, 1, quantile, 1-(level/2)) } temp.lb <- qqnorm(lb, plot.it=FALSE) if (smooth) temp.lb <- supsmu(temp.lb$x, temp.lb$y, bass=bass) if (draw.envelope) llines(temp.lb$x, temp.lb$y, lty=lty[2], ...) temp.ub <- qqnorm(ub, plot.it=FALSE) if (smooth) temp.ub <- supsmu(temp.ub$x, temp.ub$y, bass=bass) if (draw.envelope) llines(temp.ub$x, temp.ub$y, lty=lty[2], ...) } if ((is.character(label) && label=="none") || .isFALSE(label)) return(invisible(sav)) if ((is.character(label) && label=="all") || .isTRUE(label)) label <- x$k if (is.numeric(label)) { label <- round(label) if (label < 1 | label > x$k) stop(mstyle$stop("Out of range value for 'label' argument.")) pos.x <- sav$x[ord] pos.y <- sav$y[ord] dev <- abs(pos.x - pos.y) for (i in seq_len(x$k)) { if (sum(dev > dev[i]) < label) { if (pos <= 4) ltext(pos.x[i], pos.y[i], slab[i], pos=pos, offset=offset, ...) if (pos == 13) ltext(pos.x[i], pos.y[i], slab[i], pos=ifelse(pos.x[i]-pos.y[i] >= 0, 1, 3), offset=offset, ...) if (pos == 24) ltext(pos.x[i], pos.y[i], slab[i], pos=ifelse(pos.x[i]-pos.y[i] <= 0, 2, 4), offset=offset, ...) } } } else { pos.x <- sav$x[ord] pos.y <- sav$y[ord] for (i in seq_len(x$k)) { if (pos.y[i] < temp.lb$y[i] || pos.y[i] > temp.ub$y[i]) { if (pos <= 4) ltext(pos.x[i], pos.y[i], slab[i], pos=pos, offset=offset, ...) if (pos == 13) ltext(pos.x[i], pos.y[i], slab[i], pos=ifelse(pos.x[i]-pos.y[i] >= 0, 1, 3), offset=offset, ...) if (pos == 24) ltext(pos.x[i], pos.y[i], slab[i], pos=ifelse(pos.x[i]-pos.y[i] <= 0, 2, 4), offset=offset, ...) } } } invisible(sav) }
`detail.pick` <- function(y, ex, dt, TIT="") { if(missing(TIT)) { TIT=NULL } labs = c("DONE", "PROJ", "XING", "YMIN", "YMAX", "SAVED", "NONE" ) colabs = rep(1,length(labs)) pchlabs = rep(1,length(labs)) NSEL = 1 N = 0 NLABS = length(labs) NOLAB = NLABS +1000 KSAVE = NULL xsave = NULL ysave = NULL pwink = 0.01*diff(range(ex)) pcol=rgb(1,.5, 0) plot(ex, y, type='n', col=1) abline(h=0, col=1) points(ex, y, col=rgb(0.75,0.75,0.8) ) lines(ex, y, col=1) title(main=TIT) buttons = RPMG::rowBUTTONS(labs, col=colabs, pch=pchlabs) zloc = locator(1, type='p', col=pcol) Nclick = length(zloc$x) if(is.null(zloc$x)) { return(NULL) } K = RPMG::whichbutt(zloc ,buttons) sloc = zloc while(Nclick>0) { xsave = c(xsave, zloc$x) ysave = c(ysave, zloc$y) N = N+1 if(K[Nclick] == match("DONE", labs, nomatch = NOLAB)) { N = N-1 xsave = xsave[1:N] ysave = ysave[1:N] break; } if(K[Nclick] == match("Postscript", labs, nomatch = NOLAB)) { } if(K[Nclick] == match("XING", labs, nomatch = NOLAB)) { N = N-1 xsave = xsave[1:N] ysave = ysave[1:N] LX = xsave[N] LY = ysave[N] rim = findInterval(LX, ex) nflag = seq(from=(rim-5), to=rim+5, by=1) lex = ex[nflag] lwhy = y[nflag] sy = sign(lwhy[1]) ww = which(sign(lwhy) !=sy) x1 = lex[ww[1]-1] y1 = lwhy[ww[1]-1] x2 = lex[ ww[1] ] y2 = lwhy[ww[1]] m = (y2-y1)/(x2-x1) b = y2-m*x2 xingx = -b/m xingy = 0 points(c(x1,x2,xingx), c(y1, y2, xingy), col=2) xsave[N] = xingx ysave[N] = xingy text(xsave[N], ysave[N], labels= N, pos=3) } if(K[Nclick] == match("PROJ", labs, nomatch = NOLAB)) { n = length(xsave) x1 = xsave[n-1] y1 = ysave[n-1] x2 = xsave[n-2] y2 = ysave[n-2] m = (y2-y1)/(x2-x1) b = y2-m*x2 xingx = -b/m xingy = 0 points(c(x1,x2,xingx), c(y1, y2, xingy), col=2) N = N-2 xsave = xsave[1:N] ysave = ysave[1:N] xsave[N] = xingx ysave[N] = xingy text(xsave[N], ysave[N], labels= N, pos=3) } if(K[Nclick] == match("YMAX", labs, nomatch = NOLAB)) { N = N-1 xsave = xsave[1:N] ysave = ysave[1:N] LX = xsave[N] LY = ysave[N] ax = LX flag = ex > (ax-pwink) & ex < (ax+pwink) w1 = which(flag)[1]-1 rim = which.max(y[flag]) abline(v=ex[w1+rim], col=4) xsave[N] = ex[w1+rim] ysave[N] = y[w1+rim] text(xsave[N], ysave[N], labels= N, pos=3) points(xsave[N], ysave[N] , col=3, pch=7) } if(K[Nclick] == match("YMIN", labs, nomatch = NOLAB)) { N = N-1 xsave = xsave[1:N] ysave = ysave[1:N] LX = xsave[N] LY = ysave[N] ax = LX flag = ex > (ax-pwink) & ex < (ax+pwink) w1 = which(flag)[1]-1 points( ex[flag] , y[flag], col=5, pch=7) rim = which.min(y[flag]) abline(v=ex[w1+rim], col=4) xsave[N] = ex[w1+rim] ysave[N] = y[w1+rim] text(xsave[N], ysave[N], labels= N, pos=3) points(xsave[N], ysave[N] , col=3, pch=7) } if(K[Nclick] == match("NONE", labs, nomatch = NOLAB)) { N = 0 KSAVE = NULL xsave = NULL ysave = NULL plot(ex, y, type='n', col=1) abline(h=0, col=1) points(ex, y, col=rgb(0.75,0.75,0.8) ) lines(ex, y, col=1) title(main=TIT) buttons = RPMG::rowBUTTONS(labs, col=colabs, pch=pchlabs) } if(K[Nclick] == match("POINTS", labs, nomatch = NOLAB)) { if(N>1) { N = N-1 xsave = xsave[1:N] ysave = ysave[1:N] } else { N = 0 xsave = NULL ysave = NULL } points(ex, y, col=rgb(0.8,0.8,0.8) ) } if(K[Nclick] == match("SAVED", labs, nomatch = NOLAB)) { points(xsave, ysave, col=rgb(0.5,1, 0.5) ) text(xsave, ysave, labels=1:length(xsave), pos=1) } zloc = locator(1, type='p', col=pcol) Nclick = length(zloc$x) if(is.null(zloc$x)) { return(sloc) } K = RPMG::whichbutt(zloc ,buttons) } KSAVE = list(x=xsave, y=ysave) return(KSAVE) }
xgx_scale_y_percentchangelog10 <- function(breaks = NULL, minor_breaks = NULL, labels = NULL, accuracy = 1, n_breaks = 7, ...) { if (is.null(breaks)){ breaks <- function(data_range) { r <- range(log2(data_range + 1)) breaks <- 2^(labeling::extended(r[1], r[2], m = n_breaks, Q = c(1,2,4,8))) - 1 return(breaks) } } if (is.null(minor_breaks)) { minor_breaks <- function(x) xgx_minor_breaks_log10(x + 1) - 1 } percentchangelog <- scales::trans_new( name = "percentchangelog", transform = function(x) log10(x + 1), inverse = function(x) 10^(x) - 1) if (is.null(labels)) { labels = scales::percent_format(accuracy = accuracy) } ggplot2::scale_y_continuous(trans = percentchangelog, labels = labels, minor_breaks = minor_breaks, breaks = breaks, ...) } xgx_scale_x_percentchangelog10 <- function(breaks = NULL, minor_breaks = NULL, labels = NULL, accuracy = 1, n_breaks = 7, ...) { if (is.null(breaks)){ breaks <- function(data_range) { r <- range(log2(data_range + 1)) breaks <- 2^(labeling::extended(r[1], r[2], m = n_breaks, Q = c(1,2,4,8))) - 1 return(breaks) } } if (is.null(minor_breaks)) { minor_breaks <- function(x) xgx_minor_breaks_log10(x + 1) - 1 } percentchangelog <- scales::trans_new( name = "percentchangelog", transform = function(x) log10(x + 1), inverse = function(x) 10^(x) - 1) if (is.null(labels)) { labels = scales::percent_format(accuracy = accuracy) } ggplot2::scale_x_continuous(trans = percentchangelog, labels = labels, minor_breaks = minor_breaks, breaks = breaks, ...) }
fitacis2 <- function(data, group1, group2 = NA, group3 = NA, gm25 = 0.08701, Egm = 47.650, K25 = 718.40, Ek = 65.50828, Gstar25 = 42.75, Egamma = 37.83, fitmethod = "default", fitTPU = TRUE, Tcorrect = FALSE, useRd = FALSE, citransition = NULL, alphag = 0, PPFD = NULL, Tleaf = NULL, alpha = 0.24, theta = 0.85, varnames = list(ALEAF = "Photo", Tleaf = "Tleaf", Ci = "Ci", PPFD = "PARi", Rd = "Rd", Press = "Press"), ...) { data$group1 <- data[, group1] data$Press <- data[, varnames$Press] if (!is.na(group2)) { data$group2 <- data[, group2] } if (!is.na(group3)) { data$group3 <- data[, group3] } if (!is.na(group2) & !is.na(group3)) { data <- unite(data, col = "group", c("group1", "group2", "group3"), sep = "_") } else { if (!is.na(group2) & is.na(group3)) { data <- unite(data, col = "group", c("group1", "group2"), sep = "_") } else { data$group <- data$group1 } } data <- split(data, data$group) fits <- as.list(1:length(data)) for (i in 1:length(data)) { gmeso <- gm25 * exp(Egm * (mean(data[[i]]$Tleaf + 273.15) - 298.15) / (298.15 * mean(data[[i]]$Tleaf + 273.15) * 0.008314)) Km <- K25 * exp(Ek * (mean(data[[i]]$Tleaf + 273.15) - 298.15) / (298.15 * mean(data[[i]]$Tleaf + 273.15) * 0.008314)) Patm <- mean(data[[i]]$Press) GammaStar <- Gstar25 * exp(Egamma * (mean(data[[i]]$Tleaf + 273.15) - 298.15) / (298.15 * mean(data[[i]]$Tleaf + 273.15) * 0.008314)) fits[[i]] <- tryCatch(fitaci(data[[i]], Patm = Patm, varnames = varnames, fitmethod = fitmethod, Tcorrect = Tcorrect, fitTPU = fitTPU, gmeso = gmeso, Km = Km, GammaStar = GammaStar, useRd = useRd, citransition = citransition, alphag = alphag, PPFD = PPFD, Tleaf = Tleaf, alpha = alpha, theta = theta, ...), error = function(e) paste("Failed")) names(fits)[i] <- data[[i]]$group[1] } return(fits) }
convert_creat_unit <- function( value = NULL, unit_in = "mg/dL") { if(class(value) == "list" && !is.null(value$value) && !is.null(value$unit)) { unit_in <- value$unit value <- value$value } if(!tolower(unit_in) %in% c("mg/dl", "micromol/l", "mumol/l")) { stop("Input unit needs to be either mg/dL or micromol/L.") } if(tolower(unit_in) == "mg/dl") { out <- list( value = value * 88.42, unit = "micromol/L" ) } else { out <- list( value = value / 88.42, unit = "mg/dL" ) } return(out) }
tex_build <- function(tex_lines, stem = "tex_temp", tex_message, fileDir = tex_opts$get('fileDir'), engine = tex_opts$get('engine'), ...){ cwd <- getwd() on.exit({setwd(cwd)},add = TRUE) setwd(fileDir) interaction_mode <- ifelse(tex_message, "nonstopmode", "batchmode") temp_tex <- sprintf("%sDoc.tex",stem) temp_log <- sprintf('%sDoc.log',stem) temp_out <- sprintf('%s_stdout.txt',stem) temp_err <- sprintf('%s_stderr.txt',stem) tex_args <- c('-synctex=1', sprintf('-interaction=%s',interaction_mode), '--halt-on-error', temp_tex) writeLines(tex_lines, con = temp_tex) system2(engine, args = tex_args, stdout = temp_out, stderr = temp_err,...) log_lines <- readLines(temp_log) attr(log_lines,'error') <- grepl('error',log_lines[length(log_lines)]) log_lines }
generate_shinyinput <- function(use_mbmodel = FALSE, mbmodel = NULL, use_doc = FALSE, model_file = NULL, model_function = NULL, otherinputs = NULL, packagename = NULL) { myclassfct = function (x) { tags$div(class="myinput", x) } if (use_mbmodel) { if (!is.list(mbmodel)) {return("Please provide a valid mbmodel list structure.")} allv = lapply(1:length(mbmodel$var), function(n) { myclassfct(numericInput(mbmodel$var[[n]]$varname, paste0(mbmodel$var[[n]]$vartext,' (',mbmodel$var[[n]]$varname,')'), value = mbmodel$var[[n]]$varval, min = 0,step = mbmodel$var[[n]]$varval/100) ) }) allp = lapply(1:length(mbmodel$par), function(n) { myclassfct(numericInput(mbmodel$par[[n]]$parname, paste0(mbmodel$par[[n]]$partext,' (',mbmodel$par[[n]]$parname,')'), value = mbmodel$par[[n]]$parval, min = 0, step = mbmodel$par[[n]]$parval/100) ) }) allt = lapply(1:length(mbmodel$time), function(n) { myclassfct(numericInput(mbmodel$time[[n]]$timename, paste0(mbmodel$time[[n]]$timetext,' (',mbmodel$time[[n]]$timename,')'), value = mbmodel$time[[n]]$timeval, min = 0, step = mbmodel$time[[n]]$timeval/100) ) }) modelargs = c(allv,allp,allt) if ( (packagename == "DSAIDE") && grepl("_stochastic",model_function) ) { stochasticui <- shiny::tagList( shiny::numericInput("nreps", "Number of simulations", min = 1, max = 100, value = 1, step = 1), shiny::numericInput("rngseed", "Random number seed", min = 1, max = 1000, value = 123, step = 1) ) stochasticui = lapply(stochasticui,myclassfct) modelargs = c(modelargs,stochasticui) } } else if (use_doc) { if (!file.exists(model_file)) {return("Please provide path to a valid model R file.")} x = readLines(model_file) x2 = grep('@param', x, value = TRUE) pattern = ".*[:](.+)[:].*" x3 = gsub(pattern, "\\1",x2) x3 = substr(x3,2,nchar(x3)-1); ip = formals(model_function) ip = ip[unlist(lapply(ip,is.numeric))] modelargs = lapply(1:length(ip), function(n) { iplabel = paste0(names(ip[n]),', ', x3[n]) myclassfct( shiny::numericInput(names(ip[n]), label = iplabel, value = ip[n][[1]], step = 0.01*ip[n][[1]]) ) }) } else { if (is.null(model_function)) {return("Please provide a valid model function name.")} ip = unlist(formals(model_function)) modelargs = lapply(1:length(ip), function(n) { myclassfct( shiny::numericInput(names(ip[n]), label = names(ip[n]), value = ip[n][[1]], step = 0.01*ip[n][[1]]) ) }) } otherargs = shiny::tagList( shiny::selectInput("plotscale", "Log-scale for plot",c("none" = "none", 'x-axis' = "x", 'y-axis' = "y", 'both axes' = "both")), shiny::selectInput("plotengine", "Plot engine",c("ggplot" = "ggplot", "plotly" = "plotly")) ) otherargs = lapply(otherargs,myclassfct) if (!is.null(otherinputs) && nchar(otherinputs)>1) { moreargs = lapply(eval(str2expression(otherinputs)),myclassfct) otherargs = c(moreargs,otherargs) } if (packagename == "modelbuilder") { standardui <- shiny::tagList( shiny::selectInput("modeltype", "Model to run",c("ODE" = "ode", 'stochastic' = 'stochastic', 'discrete time' = 'discrete'), selected = 'ode'), shiny::selectInput("plotscale", "Log-scale for plot",c("none" = "none", 'x-axis' = "x", 'y-axis' = "y", 'both axes' = "both")), shiny::selectInput("plotengine", "Plot engine",c("ggplot" = "ggplot", "plotly" = "plotly")) ) standardui = lapply(standardui,myclassfct) stochasticui <- shiny::tagList( shiny::numericInput("nreps", "Number of simulations", min = 1, max = 500, value = 1, step = 1), shiny::numericInput("rngseed", "Random number seed", min = 1, max = 1000, value = 123, step = 1) ) stochasticui = lapply(stochasticui,myclassfct) scanparui <- shiny::tagList( shiny::selectInput("scanparam", "Scan parameter", c("No" = 0, "Yes" = 1)), shiny::selectInput("partoscan", "Parameter to scan", sapply(mbmodel$par, function(x) x[[1]]) ), shiny::numericInput("parmin", "Lower value of parameter", min = 0, max = 1000, value = 1, step = 1), shiny::numericInput("parmax", "Upper value of parameter", min = 0, max = 1000, value = 10, step = 1), shiny::numericInput("parnum", "Number of samples", min = 1, max = 1000, value = 10, step = 1), shiny::selectInput("pardist", "Spacing of parameter values", c('linear' = 'lin', 'logarithmic' = 'log')) ) scanparui = lapply(scanparui,myclassfct) otherargs = tagList(otherargs, standardui, p('Settings for stochastic model:'), stochasticui, p('Settings for optional parameter scan for ODE/discrete models:'), scanparui) } modelinputs <- tagList( p( shiny::actionButton("submitBtn", "Run Simulation", class = "submitbutton"), shiny::actionButton(inputId = "reset", label = "Reset Inputs", class = "submitbutton"), align = 'center'), modelargs, otherargs ) return(modelinputs) }
context("JAGS marginal likelihood functions") test_that("JAGS model functions work (simple)", { skip_if_not_installed("rjags") all_priors <- list( p1 = prior("normal", list(0, 1)), p2 = prior("normal", list(0, 1), list(1, Inf)), p3 = prior("lognormal", list(0, .5)), p4 = prior("t", list(0, .5, 5)), p5 = prior("Cauchy", list(1, 0.1), list(-10, 0)), p6 = prior("gamma", list(2, 1)), p7 = prior("invgamma", list(3, 2), list(1, 3)), p8 = prior("exp", list(1.5)), p9 = prior("beta", list(3, 2)), p10 = prior("uniform", list(1, 5)), PET = prior_PET("normal", list(0, 1)), PEESE = prior_PEESE("gamma", list(1, 1)) ) log_posterior <- function(parameters, data){ return(0) } for(i in seq_along(all_priors)){ prior_list <- all_priors[i] model_syntax <- JAGS_add_priors("model{}", prior_list) monitor <- JAGS_to_monitor(prior_list) inits <- JAGS_get_inits(prior_list, chains = 2, seed = 1) set.seed(1) model <- rjags::jags.model(file = textConnection(model_syntax), inits = inits, n.chains = 2, quiet = TRUE) samples <- rjags::coda.samples(model = model, variable.names = monitor, n.iter = 5000, quiet = TRUE, progress.bar = "none") marglik <- JAGS_bridgesampling(samples, prior_list = prior_list, data = list(), log_posterior = log_posterior) expect_equal(marglik$logml, 0, tolerance = 1e-2) } }) test_that("JAGS model functions work (weightfunctions)", { skip_if_not_installed("rjags") all_priors <- list( prior_weightfunction("one.sided", list(c(.05), c(1, 1))), prior_weightfunction("one.sided", list(c(.05, 0.10), c(1, 2, 3))), prior_weightfunction("one.sided", list(c(.05, 0.60), c(1, 1), c(1, 5))), prior_weightfunction("two.sided", list(c(.05), c(1, 1))) ) log_posterior <- function(parameters, data){ return(0) } for(i in seq_along(all_priors)){ prior_list <- all_priors[i] model_syntax <- JAGS_add_priors("model{}", prior_list) monitor <- JAGS_to_monitor(prior_list) inits <- JAGS_get_inits(prior_list, chains = 2, seed = 1) set.seed(1) model <- rjags::jags.model(file = textConnection(model_syntax), inits = inits, n.chains = 2, quiet = TRUE) samples <- rjags::coda.samples(model = model, variable.names = monitor, n.iter = 5000, quiet = TRUE, progress.bar = "none") marglik <- JAGS_bridgesampling(samples, prior_list = prior_list, data = list(), log_posterior = log_posterior) expect_equal(marglik$logml, 0, tolerance = 1e-2) } }) test_that("JAGS model functions work (complex scenario)", { skip_if_not_installed("rjags") set.seed(1) data <- list( x = rnorm(50, 0, .5), N = 50 ) priors1 <- list( m = prior("normal", list(0, 1)), s = prior("normal", list(0, 1), list(0, Inf)) ) priors2 <- list( m = prior("normal", list(0, 1)), s = prior("spike", list(1)) ) log_posterior <- function(parameters, data, return3){ if(return3){ return(3) }else{ return(sum(stats::dnorm(data$x, mean = parameters[["m"]], sd = parameters[["s"]], log = TRUE))) } } model_syntax <- "model{ for(i in 1:N){ x[i] ~ dnorm(m, pow(s, -2)) } }" model1 <- rjags::jags.model( file = textConnection(JAGS_add_priors(model_syntax, priors1)), inits = JAGS_get_inits(priors1, chains = 2, seed = 1), n.chains = 2, data = data, quiet = TRUE) samples1 <- rjags::jags.samples( model = model1, variable.names = JAGS_to_monitor(priors1), data = data, n.iter = 5000, quiet = TRUE, progress.bar = "none") marglik1 <- JAGS_bridgesampling( samples1, prior_list = priors1, data = data, log_posterior = log_posterior, return3 = FALSE) runjags::runjags.options(silent.jags = TRUE, silent.runjags = TRUE) fit2 <- runjags::run.jags( model = JAGS_add_priors(model_syntax, priors2), data = data, inits = JAGS_get_inits(priors2, chains = 2, seed = 1), monitor = JAGS_to_monitor(priors2), n.chains = 2, sample = 5000, burnin = 1000, adapt = 500, summarise = FALSE ) marglik2 <- JAGS_bridgesampling( fit2, data = data, prior_list = priors2, log_posterior = log_posterior, return3 = FALSE) marglik3 <- JAGS_bridgesampling( fit2, data = data, prior_list = priors2, log_posterior = log_posterior, return3 = TRUE) expect_equal(marglik1$logml, -31.944, tolerance = 1e-2) expect_equal(marglik2$logml, -52.148, tolerance = 1e-2) expect_equal(marglik3$logml, 1.489, tolerance = 1e-2) })
corrHLfit_body <- function(processed, init.corrHLfit=list(), ranFix=list(), lower=list(),upper=list(), control.corrHLfit=list(), nb_cores=NULL, ... ) { dotlist <- list(...) if (is.list(processed)) { proc1 <- processed[[1L]] } else proc1 <- processed verbose <- proc1$verbose HLnames <- (c(names(formals(HLCor)),names(formals(HLfit)), names(formals(mat_sqrt)),names(formals(make_scaled_dist)))) good_dotnames <- intersect(names(dotlist),HLnames) if (length(good_dotnames)) { HLCor.args <- dotlist[good_dotnames] } else HLCor.args <- list() if ( is.list(processed)) { pnames <- names(processed[[1]]) } else pnames <- names(processed) for (st in pnames) HLCor.args[st] <- NULL optim.scale <- control.corrHLfit$optim.scale if (is.null(optim.scale)) optim.scale="transformed" sparse_precision <- proc1$is_spprec user_init_optim <- init.corrHLfit optim_blob <- .calc_optim_args(proc_it=proc1, processed=processed, user_init_optim=init.corrHLfit, fixed=ranFix, lower=lower, upper=upper, verbose=verbose, optim.scale=optim.scale, For="corrHLfit") init.corrHLfit <- NaN init.optim <- optim_blob$inits$`init.optim` init.HLfit <- optim_blob$inits$`init.HLfit` fixed <- optim_blob$fixed corr_types <- optim_blob$corr_types LUarglist <- optim_blob$LUarglist moreargs <- LUarglist$moreargs LowUp <- optim_blob$LowUp lower <- LowUp$lower upper <- LowUp$upper HLCor.args$ranPars <- fixed control.dist <- vector("list",length(moreargs)) for (nam in names(moreargs)) control.dist[[nam]] <- moreargs[[nam]]$control.dist HLCor.args$control.dist <- control.dist processedHL1 <- proc1$HL[1] if (!is.null(processedHL1) && processedHL1=="SEM" && length(lower)) { optimMethod <- "iterateSEMSmooth" if (is.null(proc1$SEMargs$control_pmvnorm$maxpts)) { .assignWrapper(processed,"SEMargs$control_pmvnorm$maxpts <- quote(250L*nobs)") } } else optimMethod <- ".new_locoptim" HLCor.args$processed <- processed anyHLCor_obj_args <- HLCor.args initvec <- unlist(init.optim) anyHLCor_obj_args$skeleton <- structure(init.optim, moreargs=moreargs, type=relist(rep("fix",length(initvec)),init.optim), moreargs=moreargs) .assignWrapper(anyHLCor_obj_args$processed, paste0("return_only <- \"",proc1$objective,"APHLs\"")) if (optimMethod=="iterateSEMSmooth") { loclist <- list(anyHLCor_obj_args=anyHLCor_obj_args, LowUp=LowUp,init.corrHLfit=user_init_optim, control.corrHLfit=control.corrHLfit, verbose=verbose[["iterateSEM"]], nb_cores=nb_cores) optr <- .probitgemWrap("iterateSEMSmooth",arglist=loclist, pack="probitgem") optPars <- relist(optr$par,init.optim) if (!is.null(optPars)) attr(optPars,"method") <-"optimthroughSmooth" } else { if (identical(verbose["getCall"][[1L]],TRUE)) { optPars <- init.optim } else { optPars <- .new_locoptim(init.optim, LowUp=LowUp,anyHLCor_obj_args=anyHLCor_obj_args, objfn_locoptim=.objfn_locoptim, control=control.corrHLfit, user_init_optim=user_init_optim, verbose=verbose[["TRACE"]]) } } if (!is.null(optPars)) { ranPars_in_refit <- structure(.modify_list(HLCor.args$ranPars,optPars), type=.modify_list(relist(rep("fix",length(unlist(HLCor.args$ranPars))),HLCor.args$ranPars), relist(rep("outer",length(unlist(optPars))),optPars)), moreargs=moreargs) } else { ranPars_in_refit <- structure(HLCor.args$ranPars, type = relist(rep("fix", length(unlist(HLCor.args$ranPars))), HLCor.args$ranPars)) } ranPars_in_refit <- .expand_hyper(ranPars_in_refit, processed$hyper_info, moreargs=moreargs) HLCor.args$ranPars <- ranPars_in_refit .assignWrapper(HLCor.args$processed,"return_only <- NULL") .assignWrapper(HLCor.args$processed,"verbose['warn'] <- TRUE") hlcor <- do.call("HLCor",HLCor.args) if (is.call(hlcor)) { return(hlcor[]) } attr(hlcor,"optimInfo") <- list(LUarglist=LUarglist, optim.pars=optPars, objective=proc1$objective) if ( ! is.null(optPars)) { locoptr <- attr(optPars,"optr") if (attr(optPars,"method")=="nloptr") { if (locoptr$status<0L) hlcor$warnings$optimMessage <- paste0("nloptr() message: ", locoptr$message," (status=",locoptr$status,")") } else if ( attr(optPars,"method")=="optim" ) { if (locoptr$convergence) hlcor$warnings$optimMessage <- paste0("optim() message: ",locoptr$message, " (convergence=",locoptr$convergence,")") } else if ( attr(optPars,"method")== "optimthroughSmooth") { logLapp <- optr$value attr(logLapp,"method") <- " logL (smoothed)" hlcor$APHLs$logLapp <- logLapp } hlcor$warnings$suspectRho <- .check_suspect_rho(corr_types, ranPars_in_refit, LowUp) if ( ! is.null(PQLdivinfo <- processed$envir$PQLdivinfo)) { hlcor$divinfo <- PQLdivinfo hlcor$warnings$divinfo <- "Numerical issue detected; see div_info(<fit object>) for more information." warning(hlcor$warnings$divinfo) } } lsv <- c("lsv",ls()) rm(list=setdiff(lsv,"hlcor")) return(hlcor) }
NULL percent_weight <- function(){labs(W="Wt.%")} weight_percent <- percent_weight percent_atomic <- function(){labs(W="At.%")} atomic_percent <- percent_atomic percent_custom <- function(x){ if(class(x) == 'character'){ x = gsub("%","%",x) x = gsub('([[:punct:]])\\1+', '\\1', x) } labs(W=x) } custom_percent <- percent_custom
music.basic = function(Y, X, S, Sigma, iter.max, nu, eps){ k = ncol(X) lm.D = nnls(X, Y) r = resid(lm.D); weight.gene = 1/(nu + r^2 + colSums( (lm.D$x*S)^2*t(Sigma) )) Y.weight = Y*sqrt(weight.gene) D.weight = sweep(X, 1, sqrt(weight.gene), '*') lm.D.weight = nnls(D.weight, Y.weight) p.weight = lm.D.weight$x/sum(lm.D.weight$x) p.weight.iter = p.weight r = resid(lm.D.weight) for(iter in 1:iter.max){ weight.gene = 1/(nu + r^2 + colSums( (lm.D.weight$x*S)^2*t(Sigma) )) Y.weight = Y*sqrt(weight.gene) D.weight = X * as.matrix(sqrt(weight.gene))[,rep(1,k)] lm.D.weight = nnls(D.weight, Y.weight ) p.weight.new = lm.D.weight$x/sum(lm.D.weight$x) r.new = resid(lm.D.weight) if(sum(abs(p.weight.new - p.weight)) < eps){ p.weight = p.weight.new; r = r.new R.squared = 1 - var(Y - X%*%as.matrix(lm.D.weight$x))/var(Y) fitted = X%*%as.matrix(lm.D.weight$x) var.p = diag(solve(t(D.weight)%*%D.weight)) * mean(r^2)/sum(lm.D.weight$x)^2 return(list(p.nnls = (lm.D$x)/sum(lm.D$x), q.nnls = lm.D$x, fit.nnls = fitted(lm.D), resid.nnls = resid(lm.D), p.weight = p.weight, q.weight = lm.D.weight$x, fit.weight = fitted, resid.weight = Y - X%*%as.matrix(lm.D.weight$x), weight.gene = weight.gene, converge = paste0('Converge at ', iter), rsd = r, R.squared = R.squared, var.p = var.p)); } p.weight = p.weight.new; r = r.new; } fitted = X%*%as.matrix(lm.D.weight$x) R.squared = 1 - var(Y - X%*%as.matrix(lm.D.weight$x))/var(Y) var.p = diag(solve(t(D.weight)%*%D.weight)) * mean(r^2)/sum(lm.D.weight$x)^2 return(list(p.nnls = (lm.D$x)/sum(lm.D$x), q.nnls = lm.D$x, fit.nnls = fitted(lm.D), resid.nnls = resid(lm.D), p.weight = p.weight, q.weight = lm.D.weight$x, fit.weight = fitted, resid.weight = Y - X%*%as.matrix(lm.D.weight$x), weight.gene = weight.gene, converge = 'Reach Maxiter', rsd = r, R.squared = R.squared, var.p = var.p)) } music.iter = function(Y, D, S, Sigma, iter.max = 1000, nu = 0.0001, eps = 0.01, centered = FALSE, normalize = FALSE){ if(length(S)!=ncol(D)){ common.cell.type = intersect(colnames(D), names(S)) if(length(common.cell.type)<=1){ stop('Not enough cell types!') } D = D[,match(common.cell.type, colnames(D))] S = S[match(common.cell.type, names(S))] } if(ncol(Sigma) != ncol(D)){ common.cell.type = intersect(colnames(D), colnames(Sigma)) if(length(common.cell.type)<=1){ stop('Not enough cell type!') } D = D[, match(common.cell.type, colnames(D))] Sigma = Sigma[, match(common.cell.type, colnames(Sigma))] S = S[match(common.cell.type, names(S))] } k = ncol(D); common.gene = intersect(names(Y), rownames(D)) if(length(common.gene)< 0.1*min(length(Y), nrow(D))){ stop('Not enough common genes!') } Y = Y[match(common.gene, names(Y))]; D = D[match(common.gene, rownames(D)), ] Sigma = Sigma[match(common.gene, rownames(Sigma)), ] X = D if(centered){ X = X - mean(X) Y = Y - mean(Y) } if(normalize){ X = X/sd(as.vector(X)); S = S*sd(as.vector(X)); Y = Y/sd(Y) }else{ Y = Y*100 } lm.D = music.basic(Y, X, S, Sigma, iter.max = iter.max, nu = nu, eps = eps) return(lm.D) } weight.cal.ct = function(Sp, Sigma.ct){ nGenes = ncol(Sigma.ct); n.ct = length(Sp); weight = sapply(1:nGenes, function(g){ sum(Sp%*%t(Sp)*matrix(Sigma.ct[,g], n.ct)) }) return(weight) } Weight_cal <- function(p, M.S, Sigma){ Sigma%*%(M.S * t(p))^2 } music.basic.ct = function(Y, X, S, Sigma.ct, iter.max, nu, eps){ k = ncol(X) lm.D = nnls(X, Y) r = resid(lm.D); weight.gene = 1/(nu + r^2 + weight.cal.ct(lm.D$x*S, Sigma.ct)) Y.weight = Y*sqrt(weight.gene) D.weight = sweep(X, 1, sqrt(weight.gene), '*') lm.D.weight = nnls(D.weight, Y.weight) p.weight = lm.D.weight$x/sum(lm.D.weight$x) p.weight.iter = p.weight r = resid(lm.D.weight) for(iter in 1:iter.max){ weight.gene = 1/(nu + r^2 + weight.cal.ct(lm.D$x*S, Sigma.ct)) Y.weight = Y*sqrt(weight.gene) D.weight = X * as.matrix(sqrt(weight.gene))[,rep(1,k)] lm.D.weight = nnls(D.weight, Y.weight ) p.weight.new = lm.D.weight$x/sum(lm.D.weight$x) r.new = resid(lm.D.weight) if(sum(abs(p.weight.new - p.weight)) < eps){ p.weight = p.weight.new; r = r.new R.squared = 1 - var(Y - X%*%as.matrix(lm.D.weight$x))/var(Y) fitted = X%*%as.matrix(lm.D.weight$x) var.p = diag(solve(t(D.weight)%*%D.weight)) * mean(r^2)/sum(lm.D.weight$x)^2 return(list(p.nnls = (lm.D$x)/sum(lm.D$x), q.nnls = lm.D$x, fit.nnls = fitted(lm.D), resid.nnls = resid(lm.D), p.weight = p.weight, q.weight = lm.D.weight$x, fit.weight = fitted, resid.weight = Y - X%*%as.matrix(lm.D.weight$x), weight.gene = weight.gene, converge = paste0('Converge at ', iter), rsd = r, R.squared = R.squared, var.p = var.p)); break; } p.weight = p.weight.new; r = r.new; } fitted = X%*%as.matrix(lm.D.weight$x) R.squared = 1 - var(Y - X%*%as.matrix(lm.D.weight$x))/var(Y) var.p = diag(solve(t(D.weight)%*%D.weight)) * mean(r^2)/sum(lm.D.weight$x)^2 return(list(p.nnls = (lm.D$x)/sum(lm.D$x), q.nnls = lm.D$x, fit.nnls = fitted(lm.D), resid.nnls = resid(lm.D), p.weight = p.weight, q.weight = lm.D.weight$x, fit.weight = fitted, resid.weight = Y - X%*%as.matrix(lm.D.weight$x), weight.gene = weight.gene, converge = 'Reach Maxiter', rsd = r, R.squared = R.squared, var.p = var.p)) } music.iter.ct = function(Y, D, S, Sigma.ct, iter.max = 1000, nu = 0.0001, eps = 0.01, centered = FALSE, normalize = FALSE){ if(length(S)!=ncol(D)){ common.cell.type = intersect(colnames(D), names(S)) if(length(common.cell.type)<=1){ stop('Not enough cell types!') } D = D[,match(common.cell.type, colnames(D))] S = S[match(common.cell.type, names(S))] } k = ncol(D); common.gene = intersect(names(Y), rownames(D)) common.gene = intersect(common.gene, colnames(Sigma.ct)) if(length(common.gene)< 0.1*min(length(Y), nrow(D), ncol(Sigma.ct))){ stop('Not enough common genes!') } Y = Y[match(common.gene, names(Y))]; D = D[match(common.gene, rownames(D)), ] Sigma.ct = Sigma.ct[, match(common.gene, colnames(Sigma.ct))] X = D if(centered){ X = X - mean(X) Y = Y - mean(Y) } if(normalize){ X = X/sd(as.vector(X)); S = S*sd(as.vector(X)); Y = Y/sd(Y) }else{ Y = Y*100 } lm.D = music.basic.ct(Y, X, S, Sigma.ct, iter.max = iter.max, nu = nu, eps = eps) return(lm.D) }
mz_place <- function(ids, ..., api_key = NULL) UseMethod("mz_place") build_place_url <- function(ids, api_key = NULL) { ids <- string_array(ids) query <- list( ids = ids, api_key = api_key ) do.call(search_url, c(endpoint = "place", query)) } mz_place.character <- function(ids, ..., api_key = NULL) { search_get(build_place_url(ids, api_key = api_key)) } mz_place.mapzen_geo_list <- function(ids, ..., gid = "gid", api_key = NULL) { geolist <- ids getgid <- function(feature) { feature$properties[[gid]] } ids <- vapply(geolist$features, getgid, FUN.VALUE = character(1)) search_get(build_place_url(ids, api_key)) }
expected <- eval(parse(text="c(2, 3, 4, 5, 6, 7, 8, 9, 11)")); test(id=0, code={ argv <- eval(parse(text="list(c(2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 11))")); do.call(`floor`, argv); }, o=expected);
test_that("Validate GetDashboards using legacy credentials", { skip_on_cran() SCAuth(Sys.getenv("USER", ""), Sys.getenv("SECRET", "")) dash <- GetDashboards("zwitchdev") expect_is(dash, "data.frame") })
require(testthat) require(Rdiagnosislist) require(bit64) require(data.table) context('SNOMED codelists') test_that('Checking conversion of SNOMED concepts in data.table and data.frame', { myconcepts <- SNOMEDconcept('Heart failure', SNOMED = sampleSNOMED()) frame <- data.frame(conceptId = myconcepts) expect_equal(names(frame), 'conceptId') expect_equal(class(frame[[1]]), 'integer64') frame_int64 <- data.frame(conceptId = bit64::as.integer64(myconcepts)) expect_equal(names(frame_int64), 'conceptId') expect_equal(class(frame_int64[[1]]), 'integer64') frame_concept <- data.frame(conceptId = as.SNOMEDconcept(myconcepts)) expect_equal(names(frame_concept), 'conceptId') expect_equal(class(frame_concept[[1]]), 'integer64') table <- data.table(conceptId = myconcepts) expect_equal(names(table), 'conceptId') expect_equal(class(table[[1]]), c('SNOMEDconcept', 'integer64')) table_int64 <- data.table(conceptId = bit64::as.integer64(myconcepts)) expect_equal(names(table_int64), 'conceptId') expect_equal(class(table_int64[[1]]), 'integer64') table_concept <- data.table(conceptId = as.SNOMEDconcept(myconcepts)) expect_equal(names(table_concept), 'conceptId') expect_equal(class(table_concept[[1]]), c('SNOMEDconcept', 'integer64')) }) test_that('Creating codelists from concept IDs or tables', { myconcepts <- SNOMEDconcept('Heart failure', SNOMED = sampleSNOMED()) concept_codelist <- SNOMEDcodelist(myconcepts, SNOMED = sampleSNOMED(), include_desc = TRUE) table_codelist <- as.SNOMEDcodelist(data.frame(conceptId = myconcepts, include_desc = TRUE), SNOMED = sampleSNOMED()) table_codelist3 <- as.SNOMEDcodelist(data.table(conceptId = myconcepts, include_desc = TRUE), SNOMED = sampleSNOMED()) table_codelist4 <- as.SNOMEDcodelist(data.table(conceptId = myconcepts, nice = 1, include_desc = TRUE), SNOMED = sampleSNOMED()) expect_equal(all.equal(concept_codelist, table_codelist), TRUE) expect_equal(all.equal(concept_codelist, table_codelist3), TRUE) expect_equal(all.equal( concept_codelist[, .(conceptId, term)], table_codelist4[, .(conceptId, term)]), TRUE) expect_error(table_codelist <- as.SNOMEDcodelist( data.frame(x = myconcepts, include_desc = TRUE), SNOMED = sampleSNOMED())) }) test_that('Codelist with missing descriptions', { my_codelist <- SNOMEDcodelist('1234', SNOMED = sampleSNOMED()) expect_equal(nrow(my_codelist), 1) expect_equal(my_codelist$conceptId, as.SNOMEDconcept('1234')) expect_equal(my_codelist$term, as.character(NA)) }) test_that('Expand and contract codelists', { my_concepts <- SNOMEDconcept('Heart failure', SNOMED = sampleSNOMED()) orig <- SNOMEDcodelist(data.frame(conceptId = my_concepts, include_desc = TRUE), SNOMED = sampleSNOMED(), format = 'simple')[1:50] e1 <- expandSNOMED(orig, SNOMED = sampleSNOMED()) e2 <- SNOMEDcodelist(orig, format = 'tree', SNOMED = sampleSNOMED(), show_excluded_descendants = TRUE) e3 <- SNOMEDcodelist(orig, format = 'exptree', SNOMED = sampleSNOMED(), show_excluded_descendants = TRUE) e4 <- contractSNOMED(e2, SNOMED = sampleSNOMED()) e5 <- contractSNOMED(e3, SNOMED = sampleSNOMED()) e1a <- SNOMEDcodelist(e1, format = 'simple', SNOMED = sampleSNOMED()) e2a <- SNOMEDcodelist(e2, format = 'simple', SNOMED = sampleSNOMED()) e3a <- SNOMEDcodelist(e3, format = 'simple', SNOMED = sampleSNOMED()) e4a <- SNOMEDcodelist(e4, format = 'simple', SNOMED = sampleSNOMED()) e5a <- SNOMEDcodelist(e5, format = 'simple', SNOMED = sampleSNOMED()) expect_equal(all.equal(e4, e5), TRUE) expect_equal(all.equal(orig, e1a), TRUE) expect_equal(all.equal(orig, e2a), TRUE) expect_equal(all.equal(orig, e3a), TRUE) expect_equal(all.equal(orig, e4a), TRUE) expect_equal(all.equal(orig, e5a), TRUE) }) test_that('Related concepts for a NULL list', { my_concepts <- as.SNOMEDconcept('0')[-1] related_concepts <- relatedConcepts(my_concepts, SNOMED = sampleSNOMED()) expect_equal(my_concepts, related_concepts) expect_equal(my_concepts, parents(related_concepts)) expect_equal(my_concepts, children(related_concepts)) expect_equal(my_concepts, ancestors(related_concepts)) expect_equal(my_concepts, descendants(related_concepts)) }) test_that('Expand codelist with nothing to expand', { my_concepts <- as.SNOMEDconcept( c('Heart failure', 'Acute heart failure'), SNOMED = sampleSNOMED()) my_codelist <- SNOMEDcodelist(data.frame(conceptId = my_concepts, include_desc = FALSE), SNOMED = sampleSNOMED(), format = 'tree') expanded_codelist <- expandSNOMED(my_codelist, SNOMED = sampleSNOMED()) roundtrip_codelist <- contractSNOMED(expanded_codelist, SNOMED = sampleSNOMED()) data.table::setindex(my_codelist, NULL) data.table::setindex(roundtrip_codelist, NULL) expect_equal(all.equal(my_codelist, roundtrip_codelist), TRUE) data.table::setattr(expanded_codelist, 'format', 'tree') data.table::setindex(my_codelist, NULL) data.table::setindex(expanded_codelist, NULL) expect_equal(all.equal(my_codelist, expanded_codelist), TRUE) }) test_that('Safely contract codelist', { my_codelist <- as.SNOMEDcodelist(data.frame( conceptId = SNOMEDconcept(c('Heart failure', 'Is a'), SNOMED = sampleSNOMED()), include_desc = c(TRUE, NA)), format = 'tree', SNOMED = sampleSNOMED()) expanded_codelist <- expandSNOMED(my_codelist, SNOMED = sampleSNOMED()) roundtrip_codelist <- contractSNOMED(expanded_codelist, SNOMED = sampleSNOMED()) data.table::setindex(my_codelist, NULL) data.table::setindex(roundtrip_codelist, NULL) expect_equal(all.equal(my_codelist, roundtrip_codelist), TRUE) }) test_that('Codelist with some concepts not in dictionary', { myconcepts <- SNOMEDconcept(c('78408007', '78643003', '9999999999')) expect_equal(nrow(SNOMEDcodelist(myconcepts, SNOMED = sampleSNOMED())), 3) })
setGeneric(name = 'hm_plot', def = function(obj, slot_name, col_name, interactive = FALSE, line_type = NULL, line_color = NULL, line_size = NULL, line_alpha = NULL, x_lab = 'date', y_lab = 'y', title_lab = NULL, legend_lab = NULL, dual_yaxis = NULL, from = NULL, to = NULL, scatter = NULL) { standardGeneric('hm_plot') }) setMethod(f = 'hm_plot', signature = 'hydromet_station', definition = function(obj, slot_name, col_name, interactive = FALSE, line_type = NULL, line_color = NULL, line_size = NULL, line_alpha = NULL, x_lab = 'date', y_lab = 'y', title_lab = NULL, legend_lab = NULL, dual_yaxis = NULL, from = NULL, to = NULL, scatter = NULL) { check_class(argument = obj, target = 'hydromet_station', arg_name = 'obj') check_class(argument = slot_name, target = 'character', arg_name = 'slot_name') check_string(argument = slot_name, target = slotNames(x = 'hydromet_station')[1:23], arg_name = 'slot_name') check_class(argument = col_name, target = c('list'), arg_name = 'col_name') col_name_vect <- unlist(col_name) check_class(argument = col_name_vect, target = 'character', arg_name = 'col_name internal arguments') column_names <- list() for(i in 1:length(slot_name)){ column_names[[i]] <- colnames( hm_get(obj = obj, slot_name = slot_name[i]) )[-1] } check_string(argument = col_name_vect, target = unlist(column_names), arg_name = 'col_name') check_class(argument = interactive, target = 'logical', arg_name = 'interactive') check_length(argument = interactive, max_allow = 1, arg_name = 'interactive') if( is.null(scatter) ){ check_class(argument = line_type, target = 'character', arg_name = 'line_type') if(interactive == FALSE){ check_string(argument = line_type, target = c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank'), arg_name = 'line_type') } else{ check_string(argument = line_type, target = c('lines', 'lines+markers', 'markers'), arg_name = 'line_type') } check_cross(ref_arg = col_name_vect, eval_arg = line_type, arg_names = c('col_name', 'line_type') ) } else{ check_class(argument = line_type, target = 'numeric', arg_name = 'line_type (point shape)') check_numeric(argument = line_type, target = 0:24, arg_name = 'line_type (point shape)') check_length(argument = line_type, max_allow = 1, arg_name = 'line_type (point shape)') } check_class(argument = line_color, target = 'character', arg_name = 'line_color') check_string(argument = line_color, target = colors(), arg_name = 'line_color') if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_color, arg_names = c('col_name', 'line_color')) } else{ check_length(argument = line_color, max_allow = 1, arg_name = 'line_color (scatter)') } check_class(argument = line_size, target = c('numeric', 'integer'), arg_name = 'line_size') check_values <- sum( which(line_size < 0) ) if(check_values != 0){ stop('line_size argument(s) shuld be greater than 0!', call. = FALSE) } if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_size, arg_names = c('col_name', 'line_size')) } else{ check_length(argument = line_size, max_allow = 1, arg_name = 'line_size (scatter)') } check_class(argument = line_alpha, target = 'numeric', arg_name = 'line_alpha') check_values <- sum( which(line_alpha < 0 | line_alpha > 1 ) ) if(check_values != 0){ stop('line_alpha argument(s) shuld be between 0 and 1!', call. = FALSE) } if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_alpha, arg_names = c('col_name', 'line_alpha')) } else{ check_length(argument = line_alpha, max_allow = 1, arg_name = 'line_alpha (scatter)') } check_class(argument = x_lab, target = 'character', arg_name = 'x_lab') check_length(argument = x_lab, max_allow = 1, arg_name = 'x_lab') check_class(argument = y_lab, target = 'character', arg_name = 'y_lab') if( is.null(dual_yaxis) ){ check_length(argument = y_lab, max_allow = 1, arg_name = 'y_lab') } else{ check_length(argument = y_lab, max_allow = 2, arg_name = 'y_lab') } check_class(argument = title_lab, target = 'character', arg_name = 'title_lab') check_length(argument = title_lab, max_allow = 1, arg_name = 'title_lab') check_class(argument = legend_lab, target = 'character', arg_name = 'legend_lab') check_cross(ref_arg = col_name_vect, eval_arg = legend_lab, arg_names = c('col_name', 'legend_lab')) check_class(argument = dual_yaxis, target = 'character', arg_name = 'dual_yaxis') check_string(argument = dual_yaxis, target = c('left', 'right'), arg_name = 'dual_yaxis') check_cross(ref_arg = col_name_vect, eval_arg = dual_yaxis, arg_names = c('col_name', 'dual_yaxis')) check_class(argument = from, target = c('character', 'POSIXct'), arg_name = 'from') check_length(argument = from, max_allow = 1, arg_name = 'from') check_class(argument = to, target = c('character', 'POSIXct'), arg_name = 'to') check_length(argument = to, max_allow = 1, arg_name = 'to') check_class(argument = scatter, target = 'character', arg_name = 'scatter') check_string(argument = scatter, target = c('x', 'y'), arg_name = 'scatter') check_cross(ref_arg = col_name_vect, eval_arg = scatter, arg_names = 'scatter') if( is.null(line_type) ){ if( is.null(scatter) ){ if(interactive == FALSE){ line_type <- rep('solid', length(col_name_vect)) } else { line_type <- rep('lines', length(col_name_vect)) } } else{ line_type <- 16 } } if( is.null(line_color) ){ if( is.null(scatter) ){ line_color <- heat.colors(n = length(col_name_vect) ) } else{ line_color <- 'dodgerblue' } } if( is.null(line_size) ){ if( is.null(scatter) ){ line_size <- rep(0.8, length(col_name_vect) ) } else{ line_size <- 1 } } if( is.null(line_alpha) ){ if( is.null(scatter) ){ line_alpha <- rep(1, length(col_name_vect) ) } else{ line_alpha <- 1 } } if( !is.null(dual_yaxis) ){ if( length(y_lab) != 2){ y_lab <- c('y', 'y2') } } c_table <- build_table(hm_obj = obj, slot_name = slot_name, col_name = col_name, from = from, to = to) if(interactive == FALSE){ if( is.null(scatter) == TRUE ) { if( is.null(dual_yaxis) == TRUE ){ gg_table <- ggplot_table(df = c_table, l_color = line_color, l_type = line_type, l_size = line_size, l_legend = legend_lab) gg_out <- ggplot(data = gg_table, aes_string(x = 'date', y = 'series', group = 'group') ) + geom_line( aes_string(size = 'group', linetype = 'group', color = 'group', alpha = 'group') ) + scale_color_manual( values = line_color ) + scale_linetype_manual(values = line_type ) + scale_size_manual(values = line_size ) + scale_alpha_manual(values = line_alpha) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } else{ index_left <- which(dual_yaxis == 'left') index_right <- which(dual_yaxis == 'right') nm_table <- colnames(c_table)[-1] left_names <- nm_table[index_left] right_names <- nm_table[index_right] dual_list <- dual_y_table(df = c_table, y_left = left_names, y_right = right_names) dual_table <- dual_list[['table']] gg_table <- ggplot_table(df = dual_table, l_color = line_color, l_type = line_type, l_size = line_size, l_legend = legend_lab) a <- as.numeric( dual_list[['coefficients']][1] ) b <- as.numeric( dual_list[['coefficients']][2] ) sf <- as.numeric( dual_list[['coefficients']][3] ) trans <- dual_list[['transformation']] gg_out <- ggplot(data = gg_table, aes_string(x = 'date', y = 'series', group = 'group') ) + geom_line( aes_string(size = 'group', linetype = 'group', color = 'group', alpha = 'group') ) + scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]) ) + scale_color_manual( values = line_color ) + scale_linetype_manual(values = line_type ) + scale_size_manual(values = line_size ) + scale_alpha_manual(values = line_alpha) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } } else { index_x <- which(scatter == 'x') index_y <- which(scatter == 'y') nm_table <- colnames(c_table)[-1] x_name <- nm_table[index_x] y_name <- nm_table[index_y] gg_out <- ggplot(data = c_table, aes(x = c_table[ , x_name], y = c_table[ , y_name]) ) + geom_point(size = line_size, color = line_color, alpha = line_alpha, shape = line_type ) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } } else{ if( is.null(scatter) == TRUE ){ if( is.null(dual_yaxis) == TRUE ){ ppout <- plot_ly(c_table, x = ~date) n_plots <- ncol(c_table) - 1 for(i in 1:n_plots){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i] ) } ppout <- ppout %>% layout(title = title_lab, xaxis = list(title = x_lab), yaxis = list(title = y_lab) ) return(ppout) } else { ppout <- plot_ly(c_table, x = ~date) n_plots <- ncol(c_table) - 1 for(i in 1:n_plots){ if(dual_yaxis[i] == 'left'){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i] ) } else if (dual_yaxis[i] == 'right'){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i], yaxis = 'y2') } } ppout <- ppout %>% layout(title = title_lab, xaxis = list(title = x_lab), yaxis = list(title = y_lab[1]), yaxis2 = list(title = y_lab[2], overlaying = 'y', side = 'right') ) return(ppout) } } else { index_x <- which(scatter == 'x') index_y <- which(scatter == 'y') nm_table <- colnames(c_table)[-1] x_name <- nm_table[index_x] y_name <- nm_table[index_y] gg_out <- ggplot(data = c_table, aes(x = c_table[ , x_name], y = c_table[ , y_name]) ) + geom_point(size = line_size, color = line_color, alpha = line_alpha, shape = line_type ) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) pp_out <- ggplotly( gg_out ) return(pp_out) } } }) setMethod(f = 'hm_plot', signature = 'hydromet_compact', definition = function(obj, slot_name, col_name, interactive = FALSE, line_type = NULL, line_color = NULL, line_size = NULL, line_alpha = NULL, x_lab = 'date', y_lab = 'y', title_lab = NULL, legend_lab = NULL, dual_yaxis = NULL, from = NULL, to = NULL, scatter = NULL) { check_class(argument = obj, target = 'hydromet_compact', arg_name = 'obj') check_class(argument = slot_name, target = 'character', arg_name = 'slot_name') check_string(argument = slot_name, target = 'compact', arg_name = 'slot_name') check_class(argument = col_name, target = c('list'), arg_name = 'col_name') col_name_vect <- unlist(col_name) check_class(argument = col_name_vect, target = 'character', arg_name = 'col_name internal arguments') column_names <- list() for(i in 1:length(slot_name)){ column_names[[i]] <- colnames( hm_get(obj = obj, slot_name = slot_name[i]) )[-1] } check_string(argument = col_name_vect, target = unlist(column_names), arg_name = 'col_name') check_class(argument = interactive, target = 'logical', arg_name = 'interactive') check_length(argument = interactive, max_allow = 1, arg_name = 'interactive') if( is.null(scatter) ){ check_class(argument = line_type, target = 'character', arg_name = 'line_type') if(interactive == FALSE){ check_string(argument = line_type, target = c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank'), arg_name = 'line_type') } else{ check_string(argument = line_type, target = c('lines', 'lines+markers', 'markers'), arg_name = 'line_type') } check_cross(ref_arg = col_name_vect, eval_arg = line_type, arg_names = c('col_name', 'line_type') ) } else{ check_class(argument = line_type, target = 'numeric', arg_name = 'line_type (point shape)') check_numeric(argument = line_type, target = 0:24, arg_name = 'line_type (point shape)') check_length(argument = line_type, max_allow = 1, arg_name = 'line_type (point shape)') } check_class(argument = line_color, target = 'character', arg_name = 'line_color') check_string(argument = line_color, target = colors(), arg_name = 'line_color') if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_color, arg_names = c('col_name', 'line_color')) } else{ check_length(argument = line_color, max_allow = 1, arg_name = 'line_color (scatter)') } check_class(argument = line_size, target = c('numeric', 'integer'), arg_name = 'line_size') check_values <- sum( which(line_size < 0) ) if(check_values != 0){ stop('line_size argument(s) shuld be greater than 0!', call. = FALSE) } if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_size, arg_names = c('col_name', 'line_size')) } else{ check_length(argument = line_size, max_allow = 1, arg_name = 'line_size (scatter)') } check_class(argument = line_alpha, target = 'numeric', arg_name = 'line_alpha') check_values <- sum( which(line_alpha < 0 | line_alpha > 1 ) ) if(check_values != 0){ stop('line_alpha argument(s) shuld be between 0 and 1!', call. = FALSE) } if( is.null(scatter) ){ check_cross(ref_arg = col_name_vect, eval_arg = line_alpha, arg_names = c('col_name', 'line_alpha')) } else{ check_length(argument = line_alpha, max_allow = 1, arg_name = 'line_alpha (scatter)') } check_class(argument = x_lab, target = 'character', arg_name = 'x_lab') check_length(argument = x_lab, max_allow = 1, arg_name = 'x_lab') check_class(argument = y_lab, target = 'character', arg_name = 'y_lab') if( is.null(dual_yaxis) ){ check_length(argument = y_lab, max_allow = 1, arg_name = 'y_lab') } else{ check_length(argument = y_lab, max_allow = 2, arg_name = 'y_lab') } check_class(argument = title_lab, target = 'character', arg_name = 'title_lab') check_length(argument = title_lab, max_allow = 1, arg_name = 'title_lab') check_class(argument = legend_lab, target = 'character', arg_name = 'legend_lab') check_cross(ref_arg = col_name_vect, eval_arg = legend_lab, arg_names = c('col_name', 'legend_lab')) check_class(argument = dual_yaxis, target = 'character', arg_name = 'dual_yaxis') check_string(argument = dual_yaxis, target = c('left', 'right'), arg_name = 'dual_yaxis') check_cross(ref_arg = col_name_vect, eval_arg = dual_yaxis, arg_names = c('col_name', 'dual_yaxis')) check_class(argument = from, target = c('character', 'POSIXct'), arg_name = 'from') check_length(argument = from, max_allow = 1, arg_name = 'from') check_class(argument = to, target = c('character', 'POSIXct'), arg_name = 'to') check_length(argument = to, max_allow = 1, arg_name = 'to') check_class(argument = scatter, target = 'character', arg_name = 'scatter') check_string(argument = scatter, target = c('x', 'y'), arg_name = 'scatter') check_cross(ref_arg = col_name_vect, eval_arg = scatter, arg_names = 'scatter') if( is.null(line_type) ){ if( is.null(scatter) ){ if(interactive == FALSE){ line_type <- rep('solid', length(col_name_vect)) } else { line_type <- rep('lines', length(col_name_vect)) } } else{ line_type <- 16 } } if( is.null(line_color) ){ if( is.null(scatter) ){ line_color <- heat.colors(n = length(col_name_vect) ) } else{ line_color <- 'dodgerblue' } } if( is.null(line_size) ){ if( is.null(scatter) ){ line_size <- rep(0.8, length(col_name_vect) ) } else{ line_size <- 1 } } if( is.null(line_alpha) ){ if( is.null(scatter) ){ line_alpha <- rep(1, length(col_name_vect) ) } else{ line_alpha <- 1 } } if( !is.null(dual_yaxis) ){ if( length(y_lab) != 2){ y_lab <- c('y', 'y2') } } c_table <- build_table(hm_obj = obj, slot_name = slot_name, col_name = col_name, from = from, to = to) if(interactive == FALSE){ if( is.null(scatter) == TRUE ) { if( is.null(dual_yaxis) == TRUE ){ gg_table <- ggplot_table(df = c_table, l_color = line_color, l_type = line_type, l_size = line_size, l_legend = legend_lab) gg_out <- ggplot(data = gg_table, aes_string(x = 'date', y = 'series', group = 'group') ) + geom_line( aes_string(size = 'group', linetype = 'group', color = 'group', alpha = 'group') ) + scale_color_manual( values = line_color ) + scale_linetype_manual(values = line_type ) + scale_size_manual(values = line_size ) + scale_alpha_manual(values = line_alpha) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } else{ index_left <- which(dual_yaxis == 'left') index_right <- which(dual_yaxis == 'right') nm_table <- colnames(c_table)[-1] left_names <- nm_table[index_left] right_names <- nm_table[index_right] dual_list <- dual_y_table(df = c_table, y_left = left_names, y_right = right_names) dual_table <- dual_list[['table']] gg_table <- ggplot_table(df = dual_table, l_color = line_color, l_type = line_type, l_size = line_size, l_legend = legend_lab) a <- as.numeric( dual_list[['coefficients']][1] ) b <- as.numeric( dual_list[['coefficients']][2] ) sf <- as.numeric( dual_list[['coefficients']][3] ) trans <- dual_list[['transformation']] gg_out <- ggplot(data = gg_table, aes_string(x = 'date', y = 'series', group = 'group') ) + geom_line( aes_string(size = 'group', linetype = 'group', color = 'group', alpha = 'group') ) + scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]) ) + scale_color_manual( values = line_color ) + scale_linetype_manual(values = line_type ) + scale_size_manual(values = line_size ) + scale_alpha_manual(values = line_alpha) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } } else { index_x <- which(scatter == 'x') index_y <- which(scatter == 'y') nm_table <- colnames(c_table)[-1] x_name <- nm_table[index_x] y_name <- nm_table[index_y] gg_out <- ggplot(data = c_table, aes(x = c_table[ , x_name], y = c_table[ , y_name]) ) + geom_point(size = line_size, color = line_color, alpha = line_alpha, shape = line_type ) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) return(gg_out) } } else{ if( is.null(scatter) == TRUE ){ if( is.null(dual_yaxis) == TRUE ){ ppout <- plot_ly(c_table, x = ~date) n_plots <- ncol(c_table) - 1 for(i in 1:n_plots){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i] ) } ppout <- ppout %>% layout(title = title_lab, xaxis = list(title = x_lab), yaxis = list(title = y_lab) ) return(ppout) } else { ppout <- plot_ly(c_table, x = ~date) n_plots <- ncol(c_table) - 1 for(i in 1:n_plots){ if(dual_yaxis[i] == 'left'){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i] ) } else if (dual_yaxis[i] == 'right'){ ppout <- ppout %>% add_trace(y = c_table[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), line = list( width = line_size[i]), opacity = line_alpha[i], yaxis = 'y2') } } ppout <- ppout %>% layout(title = title_lab, xaxis = list(title = x_lab), yaxis = list(title = y_lab[1]), yaxis2 = list(title = y_lab[2], overlaying = 'y', side = 'right') ) return(ppout) } } else { index_x <- which(scatter == 'x') index_y <- which(scatter == 'y') nm_table <- colnames(c_table)[-1] x_name <- nm_table[index_x] y_name <- nm_table[index_y] gg_out <- ggplot(data = c_table, aes(x = c_table[ , x_name], y = c_table[ , y_name]) ) + geom_point(size = line_size, color = line_color, alpha = line_alpha, shape = line_type ) + theme(legend.title = element_blank()) + ggtitle(label = title_lab) + xlab(x_lab) + ylab(y_lab) pp_out <- ggplotly( gg_out ) return(pp_out) } } })
gc() unlink(.temp_dir_to_use, recursive = TRUE)
context("ggdend") test_that("as.ggdend.dendrogram works", { dend <- 1:3 %>% dist() %>% hclust() %>% as.dendrogram() %>% set("branches_k_color", k = 2) %>% set("branches_lwd", c(1.5, 1, 1.5)) %>% set("branches_lty", c(1, 1, 3, 1, 1, 2)) %>% set("labels_colors") %>% set("labels_cex", c(.9, 1.2)) %>% set("nodes_pch", 19) %>% set("nodes_col", c("orange", "black", "NA")) gg1 <- as.ggdend(dend) should_be <- structure(list( segments = structure(list(x = c( 1.75, 1, 1.75, 2.5, 2.5, 2, 2.5, 3 ), y = c(2, 2, 2, 2, 1, 1, 1, 1), xend = c( 1, 1, 2.5, 2.5, 2, 2, 3, 3 ), yend = c(2, 0, 2, 1, 1, 0, 1, 0), col = c( " " " ), lwd = c(1, 1, 1.5, 1.5, 1.5, 1.5, 1, 1), lty = c( 1, 1, 3, 3, 1, 1, 1, 1 )), .Names = c( "x", "y", "xend", "yend", "col", "lwd", "lty" ), row.names = c(NA, 8L), class = "data.frame"), labels = structure(list(x = c(1, 2, 3), y = c(0, 0, 0), label = structure(1:3, .Label = c( "3", "1", "2" ), class = "factor"), col = c( " " ), cex = c(0.9, 1.2, 0.9)), .Names = c( "x", "y", "label", "col", "cex" ), row.names = c(NA, 3L), class = "data.frame"), nodes = structure(list(x = c(1.75, 1, 2.5, 2, 3), y = c( 2, 0, 1, 0, 0 ), pch = c(19, 19, 19, 19, 19), cex = c( NA, NA, NA, NA, NA ), col = c("orange", "black", "NA", "orange", "black"), members = c(3L, 1L, 2L, 1L, 1L), midpoint = c( 0.75, NA, 0.5, NA, NA ), height = c(2, 0, 1, 0, 0), leaf = c( NA, TRUE, NA, TRUE, TRUE )), .Names = c( "x", "y", "pch", "cex", "col", "members", "midpoint", "height", "leaf" ), row.names = c( NA, -5L ), class = "data.frame") ), .Names = c( "segments", "labels", "nodes" ), class = "ggdend") expect_identical(gg1, should_be) dend <- 1:3 %>% dist() %>% hclust() %>% as.dendrogram() gg2 <- as.ggdend(dend) should_be <- structure(list(segments = structure(list(x = c( 1.75, 1, 1.75, 2.5, 2.5, 2, 2.5, 3 ), y = c(2, 2, 2, 2, 1, 1, 1, 1), xend = c( 1, 1, 2.5, 2.5, 2, 2, 3, 3 ), yend = c(2, 0, 2, 1, 1, 0, 1, 0), col = c( NA, NA, NA, NA, NA, NA, NA, NA ), lwd = c( NA, NA, NA, NA, NA, NA, NA, NA ), lty = c(NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c( "x", "y", "xend", "yend", "col", "lwd", "lty" ), row.names = c( NA, 8L ), class = "data.frame"), labels = structure(list(x = c( 1, 2, 3 ), y = c(0, 0, 0), label = structure(1:3, .Label = c( "3", "1", "2" ), class = "factor"), col = c(NA, NA, NA), cex = c( NA, NA, NA )), .Names = c("x", "y", "label", "col", "cex"), row.names = c( NA, 3L ), class = "data.frame"), nodes = structure(list( x = c( 1.75, 1, 2.5, 2, 3 ), y = c(2, 0, 1, 0, 0), pch = c( NA, NA, NA, NA, NA ), cex = c(NA, NA, NA, NA, NA), col = c(NA, NA, NA, NA, NA), members = c(3L, 1L, 2L, 1L, 1L), midpoint = c( 0.75, NA, 0.5, NA, NA ), height = c(2, 0, 1, 0, 0), leaf = c( NA, TRUE, NA, TRUE, TRUE ) ), .Names = c( "x", "y", "pch", "cex", "col", "members", "midpoint", "height", "leaf" ), row.names = c(NA, -5L), class = "data.frame")), .Names = c( "segments", "labels", "nodes" ), class = "ggdend") expect_identical(gg2, should_be) }) test_that("ggplot doesn't have warnings for dendrograms", { library(ggplot2) library(dendextend) g <- ggplot(as.dendrogram(hclust(dist(mtcars)))) expect_warning(ggplot_build(g), NA) })
library(animation) saveHTML({ extList = c('http://i.imgur.com/rJ7xF.jpg', 'http://i.imgur.com/Lyr9o.jpg', 'http://i.imgur.com/18Qrb.jpg') for (i in 1:length(extList)) { download.file(url = extList[i], destfile = sprintf(ani.options('img.fmt'), i), mode = 'wb') } }, use.dev = FALSE, ani.width = 640, ani.height = 480, ani.type = 'jpg', interval = 2, single.opts = "'dwellMultiplier': 1")
test_that("bd handles strange data", { expect_error(band_depth(dt = list()), "Argument \"dt\" must be a nonempty numeric matrix or dataframe.") dta <- data.frame() expect_error(band_depth(dt = data.frame())) expect_error(band_depth(dt = matrix(NA, nrow = 1, ncol = 3))) expect_error(band_depth(dt = matrix(c(1:2, NA), nrow = 1, ncol = 3))) }) test_that("bd gives correct result", { dt1 <- simulation_model1(seed = 50) bdd <- band_depth(dt1$data) expect_equal(order(bdd)[1:10], c(20, 43, 53, 70, 9, 6, 14, 36, 93, 8)) expect_equal(order(bdd)[90:100], c(17, 54, 15, 34, 83, 74, 25, 24, 23, 47, 90)) })
is_constant <- function(x, nThread = getOption("hutilscpp.nThread", 1L)) { if (!is.atomic(x)) { stop("`x` was not atomic. ", "Such objects are not supported.") } nThread <- check_omp(nThread) ans <- .Call("Cis_constant", x, nThread, PACKAGE = packageName) if (is.null(ans)) { return(identical(rep_len(x[1], length(x)), x)) } ans } isntConstant <- function(x) { if (!is.atomic(x)) { stop("`x` was not atomic. ", "Such objects are not supported.") } if (length(x) <= 1L) { return(0L) } x1 <- x[1L] if (is.logical(x)) { wmin <- which.min(x) if (anyNA(x1)) { if (length(wmin)) { wmax <- which.max(x[seq_len(wmin)]) return(min(wmax, wmin)) } else { return(0L) } } else { if (wmin == 1L) { wmax <- which.max(x) if (wmax == 1L) { return(0L) } else { return(wmax) } } else { return(wmin) } } } ans <- .Call("Cisnt_constant", x, PACKAGE = packageName) if (is.null(ans)) { x1 <- x[1L] for (i in seq_along(ans)) { if (x[i] != x1) { return(i) } } return(0L) } ans }
context("Very basic tests of sequencing output") dir <- tempdir(check = TRUE) ref <- create_genome(5, 100) tr <- ape::rcoal(4) haps <- create_haplotypes(ref, haps_phylo(tr), sub = sub_JC69(0.1)) test_that("no weirdness with Illumina single-end reads on ref. genome", { illumina(ref, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = FALSE, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) fasta <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) expect_length(fasta, 400L) expect_true(all(grepl("^@", fasta[seq(1, 400, 4)]))) expect_identical(fasta[seq(3, 400, 4)], rep("+", 100)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) }) test_that("no weirdness with Illumina paired-end reads on ref. genome", { illumina(ref, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = TRUE, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) expect_true(sprintf("%s_R2.fq", "test") %in% list.files(dir)) fasta1 <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) fasta2 <- readLines(sprintf("%s/%s_R2.fq", dir, "test")) expect_length(fasta1, 200L) expect_length(fasta2, 200L) expect_true(all(grepl("^@", fasta1[seq(1, 200, 4)]))) expect_true(all(grepl("^@", fasta2[seq(1, 200, 4)]))) expect_identical(fasta1[seq(3, 200, 4)], rep("+", 50)) expect_identical(fasta2[seq(3, 200, 4)], rep("+", 50)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) file.remove(sprintf("%s/%s_R2.fq", dir, "test")) }) profile_df <- expand.grid(nucleo = c("T", "C", "A", "G"), pos = 0:99, qual = c(255L, 1000L), stringsAsFactors = FALSE) profile_df <- profile_df[order(profile_df$nucleo, profile_df$pos, profile_df$qual),] write.table(profile_df, file = sprintf("%s/%s", dir, "test_prof.txt"), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) test_that("proper pairs created with Illumina paired-end reads on ref. genome", { chrom <- paste(c(rep('C', 25), rep('N', 150), rep('T', 25)), collapse = "") poss_pairs <- c(paste(c(rep('C', 25), rep('N', 75)), collapse = ""), paste(c(rep('A', 25), rep('N', 75)), collapse = "")) rg <- ref_genome$new(jackalope:::make_ref_genome(chrom)) illumina(rg, out_prefix = paste0(dir, "/test"), n_reads = 10e3, read_length = 100, paired = TRUE, matepair = FALSE, frag_len_min = 200, frag_len_max = 200, ins_prob1 = 0, del_prob1 = 0, ins_prob2 = 0, del_prob2 = 0, profile1 = paste0(dir, "/test_prof.txt"), profile2 = paste0(dir, "/test_prof.txt"), overwrite = TRUE) fq1 <- readLines(paste0(dir, "/test_R1.fq")) fq2 <- readLines(paste0(dir, "/test_R2.fq")) reads1 <- fq1[seq(2, length(fq1), 4)] reads2 <- fq2[seq(2, length(fq2), 4)] expect_identical(sort(unique(reads1)), sort(poss_pairs)) expect_identical(sort(unique(reads2)), sort(poss_pairs)) }) test_that("proper pairs created with Illumina mate-pair reads on ref. genome", { chrom <- paste(c(rep('C', 25), rep('N', 150), rep('T', 25)), collapse = "") poss_pairs <- c(paste(c(rep('N', 75), rep('T', 25)), collapse = ""), paste(c(rep('N', 75), rep('G', 25)), collapse = "")) rg <- ref_genome$new(jackalope:::make_ref_genome(chrom)) illumina(rg, out_prefix = paste0(dir, "/test"), n_reads = 10e3, read_length = 100, paired = TRUE, matepair = TRUE, frag_len_min = 200, frag_len_max = 200, ins_prob1 = 0, del_prob1 = 0, ins_prob2 = 0, del_prob2 = 0, profile1 = paste0(dir, "/test_prof.txt"), profile2 = paste0(dir, "/test_prof.txt"), overwrite = TRUE) fq1 <- readLines(paste0(dir, "/test_R1.fq")) fq2 <- readLines(paste0(dir, "/test_R2.fq")) reads1 <- fq1[seq(2, length(fq1), 4)] reads2 <- fq2[seq(2, length(fq2), 4)] expect_identical(sort(unique(reads1)), sort(poss_pairs)) expect_identical(sort(unique(reads2)), sort(poss_pairs)) }) test_that("no weirdness with Illumina single-end reads on haplotypes", { illumina(haps, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = FALSE, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) fasta <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) expect_length(fasta, 400L) expect_true(all(grepl("^@", fasta[seq(1, 400, 4)]))) expect_identical(fasta[seq(3, 400, 4)], rep("+", 100)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) }) test_that("no weirdness with Illumina single-end reads on haplotypes w/ sep. files", { illumina(haps, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = FALSE, overwrite = TRUE, sep_files = TRUE) fns <- sprintf("%s_%s_R1.fq", "test", haps$hap_names()) expect_true(all(fns %in% list.files(dir))) fns <- paste0(dir, "/", fns) fastas <- lapply(fns, readLines) expect_identical(sum(sapply(fastas, length)), 400L) expect_true(all(sapply(fastas, function(fa) all(grepl("^@", fa[seq(1, length(fa), 4)]))))) expect_identical(do.call(c, lapply(fastas, function(fa) fa[seq(3, length(fa), 4)])), rep("+", 100)) file.remove(fns) }) test_that("no weirdness with Illumina paired-end reads on haplotypes", { illumina(haps, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = TRUE, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) expect_true(sprintf("%s_R2.fq", "test") %in% list.files(dir)) fasta1 <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) fasta2 <- readLines(sprintf("%s/%s_R2.fq", dir, "test")) expect_length(fasta1, 200L) expect_length(fasta2, 200L) expect_true(all(grepl("^@", fasta1[seq(1, 200, 4)]))) expect_true(all(grepl("^@", fasta2[seq(1, 200, 4)]))) expect_identical(fasta1[seq(3, 200, 4)], rep("+", 50)) expect_identical(fasta2[seq(3, 200, 4)], rep("+", 50)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) file.remove(sprintf("%s/%s_R2.fq", dir, "test")) }) test_that("no weirdness with Illumina paired-end reads on haplotypes w/ sep. files", { illumina(haps, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, read_length = 100, paired = TRUE, overwrite = TRUE, sep_files = TRUE) fns <- lapply(haps$hap_names(), function(x) sprintf("%s_%s_R%i.fq", "test", x, 1:2)) expect_true(all(unlist(fns) %in% list.files(dir))) fns <- lapply(fns, function(x) paste0(dir, "/", x)) fastas <- lapply(fns, function(x) lapply(x, readLines)) expect_true(all(sapply(fastas, function(x) length(x[[1]]) == length(x[[2]])))) fastas <- unlist(fastas, recursive = FALSE) expect_length(unlist(fastas), 400L) expect_true(all(sapply(fastas, function(fa) all(grepl("^@", fa[seq(1, length(fa), 4)]))))) expect_identical(do.call(c, lapply(fastas, function(fa) fa[seq(3, length(fa), 4)])), rep("+", 100)) file.remove(unlist(fns)) }) test_that("no weirdness with PacBio reads on ref. genome", { pacbio(ref, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) fasta <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) expect_length(fasta, 400L) expect_true(all(grepl("^@", fasta[seq(1, 400, 4)]))) expect_identical(fasta[seq(3, 400, 4)], rep("+", 100)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) }) test_that("no weirdness with PacBio reads on haplotypes", { pacbio(haps, out_prefix = sprintf("%s/%s", dir, "test"), n_reads = 100, overwrite = TRUE) expect_true(sprintf("%s_R1.fq", "test") %in% list.files(dir)) fasta <- readLines(sprintf("%s/%s_R1.fq", dir, "test")) expect_length(fasta, 400L) expect_true(all(grepl("^@", fasta[seq(1, 400, 4)]))) expect_identical(fasta[seq(3, 400, 4)], rep("+", 100)) file.remove(sprintf("%s/%s_R1.fq", dir, "test")) })
context("build(hp) - ResNet") source("utils.R") test_succeeds("Can run hyper_class", { library(keras) library(dplyr) library(kerastuneR) cifar <- dataset_cifar10() hypermodel = HyperResNet(input_shape = list(300L, 300L, 3L), classes = 10L) hypermodel2 = HyperXception(input_shape = list(300L, 300L, 3L), classes = 10L) testthat::expect_match(hypermodel %>% capture.output(),'keras_tuner.applications.resnet.HyperResNet') tuner = Hyperband( hypermodel = hypermodel, objective = 'val_accuracy', max_epochs = 1, directory = 'my_dir', project_name='helloworld') testthat::expect_match(tuner %>% capture.output(),'keras_tuner.tuners.hyperband.Hyperband') train_data = cifar$train$x[1:30,1:32,1:32,1:3] test_data = cifar$train$y[1:30,1] %>% as.matrix() rm(cifar) os = switch(Sys.info()[['sysname']], Windows= {paste("win")}, Linux = {paste("lin")}, Darwin = {paste("mac")}) if (os %in% 'win') { print('Done') } else { print('Done') } })
addObservations <- function(formLatticeOutput, observations){ if(class(formLatticeOutput) != "formLatticeOutput"){ stop("Should be the output from the function formLattice") } nodes <- formLatticeOutput$nodes n_observ <- nrow(observations) n_nodes <- nrow(nodes) temp <- sp::bbox(rbind(observations, nodes)) bound_vect <- c(temp[1,1],temp[1,2],temp[2,1],temp[2,2]) X <- spatstat.geom::as.ppp(observations, W=bound_vect) Y <- spatstat.geom::as.ppp(nodes, W=bound_vect) closest <- spatstat.geom::nncross(X,Y)$which out <- list(init_prob = tabulate(closest,nbins=n_nodes)/n_observ, which_nodes = closest) class(out) <- "initProbObject" return(out) }
partition_roots <- function(roots, rtsize){ if(length(rtsize) > 1 && length(rtsize) == length(roots)){ threshold <- .002 epsilon <- .0005 rtsize_thresh_idx <- which.min(sapply(rtsize-threshold,abs)) rtsize_thresh <- rtsize[rtsize_thresh_idx] if(abs(rtsize_thresh-threshold) > epsilon){ PEcAn.logger::logger.error(paste("Closest rtsize to fine root threshold of", threshold, "m (", rtsize_thresh, ") is greater than", epsilon, "m off; fine roots can't be partitioned. Please improve rtsize dimensions.")) return(NULL) } else{ fine.roots <- sum(roots[1:rtsize_thresh_idx-1]) coarse.roots <- sum(roots) - fine.roots if(fine.roots >= 0 && coarse.roots >= 0){ PEcAn.logger::logger.info("Using partitioned root values", fine.roots, "for fine and", coarse.roots, "for coarse.") return(list(fine.roots = fine.roots, coarse.roots = coarse.roots)) } else{ PEcAn.logger::logger.error("Roots could not be partitioned (fine or coarse is less than 0).") return(NULL) } } } else { PEcAn.logger::logger.error("Inadequate or incorrect number of levels of rtsize associated with roots; please ensure roots and rtsize lengths match and are greater than 1.") return(NULL) } }
DarkWrap <- function(obj){ require(Dark) P<- Start(obj, 5000) MSC<-ModelSelect(obj,P) MSC$AIC[3]<-MSC$AIC[3] + 1000 MSC$AIC[5]<-MSC$AIC[5] + 1000 MSC$AIC[6]<-MSC$AIC[6] + 1000 MSC$AIC[7]<-MSC$AIC[7] + 00 obj<-BestFit(obj,MSC) obj<-MultiStart(obj,repeats = 50) obj<-BootDark(obj,R = 200) obj }
library(ggplot2) load('output/result-model7-4.RData') ms <- rstan::extract(fit) qua <- apply(ms$y_new, 2, quantile, prob=c(0.025, 0.25, 0.5, 0.75, 0.975)) d_est <- data.frame(X=Time_new, t(qua), check.names=FALSE) p <- ggplot() + theme_bw(base_size=18) + geom_ribbon(data=d_est, aes(x=X, ymin=`2.5%`, ymax=`97.5%`), fill='black', alpha=1/6) + geom_ribbon(data=d_est, aes(x=X, ymin=`25%`, ymax=`75%`), fill='black', alpha=2/6) + geom_line(data=d_est, aes(x=X, y=`50%`), size=0.5) + geom_point(data=d, aes(x=Time, y=Y), size=3) + labs(x='Time (hour)', y='Y') + scale_x_continuous(breaks=d$Time, limit=c(0, 24)) + ylim(-2.5, 16) ggsave(file='output/fig7-6-right.png', plot=p, dpi=300, w=4, h=3)
with.datlist <- function( data, expr, fun, ... ) { pf<-parent.frame() if (!is.null(match.call()$expr)){ expr<-substitute(expr) results<-lapply(data, function(dataset) eval(expr, dataset, enclos=pf)) } else { results<-lapply(data, fun,...) } if (all(sapply(results, inherits, what="imputationResult"))){ class(results)<-"imputationResultList" results$call<-sys.call(-1) } else { attr(results,"call")<-sys.call(-1) } return(results) }
context("dose response model functions") ud <- function(x) unname(drop(x)) test_that("betaMod does not produce NaN for large delta1, delta2", { expect_equal(betaMod(100, 1, 2, 10, 10, 200), 3) expect_equal(betaMod(100, 1, 2, 150, 150, 200), 3) expect_equal(betaMod(100, 1, 2, 100, 50, 200), 1.000409) expect_equal(betaMod(0, 1, 2, 50, 50, 200), 1) expect_equal(betaMod(0, 1, 2, 75, 75, 200), 1) expect_equal(ud(betaModGrad(100, 2, 50, 50, 200)), c(1, 1, 0, 0)) expect_equal(ud(betaModGrad(100, 2, 150, 150, 200)), c(1, 1, 0, 0)) expect_equal(ud(betaModGrad(0, 2, 50, 50, 200)), c(1, 0, 0, 0)) expect_equal(ud(betaModGrad(0, 2, 100, 100, 200)), c(1, 0, 0, 0)) }) test_that("sigEmax does not produce NaN for large dose and large h", { expect_equal(sigEmax(100, 1, 1, 50, 2), 1.8) expect_equal(sigEmax(100, 1, 1, 50, 150), 2) expect_equal(sigEmax(150, 1, 1, 50, 150), 2) expect_equal(sigEmax(0, 1, 1, 50, 10), 1) expect_equal(sigEmax(0, 1, 1, 50, 400), 1) expect_equal(sigEmax(c(50, 150), 1, 1, 50, 0), c(1.5, 1.5)) expect_equal(ud(sigEmaxGrad(100, 1, 50, 10)), c(1, 0.999024390243902, -0.000194931588340274, 0.000675581404300663)) expect_equal(ud(sigEmaxGrad(100, 1, 50, 150)), c(1, 1, 0, 0)) expect_equal(ud(sigEmaxGrad(150, 1, 50, 150)), c(1, 1, 0, 0)) expect_equal(ud(sigEmaxGrad(0, 1, 50, 0)), c(1, 0.5, 0, 0)) expect_equal(ud(sigEmaxGrad(0, 1, 50, 150)), c(1, 0, 0, 0)) expect_equal(sigEmax(0, 1, 1, 0, 5), NaN) })
library(network) net<-network.initialize(100000) net<-add.edges(net,1:99999,2:100000) set.edge.attribute(net,'LETTERS',LETTERS) data(emon) subG4<-get.inducedSubgraph(emon$MtStHelens,eid=which(emon$MtStHelens%e%'Frequency'==4)) if(network.size(subG4)!=24){ stop('wrong size eid induced subgraph') } if (any(subG4%e%'Frequency'!=4)){ stop('bad edges in eid induced subgraph') } set.edge.attribute(network.initialize(3),"test","a") set.vertex.attribute(network.initialize(0),'foo','bar') x2<-network.initialize(3) x2[1,2]<-NA if(is.na.network(x2)[1,2]!=1){ stop('problem iwth is.na.netowrk') } mat <- matrix(rbinom(200, 1, 0.2), nrow = 20) naIndices <- sample(1:200, 20) mat[naIndices] <- NA nw <- network(mat) net<-network.initialize(2,loops=TRUE,directed=FALSE) net[1,1]<-1 net[1,2]<-1 net[2,2]<-1 if(get.edgeIDs(net,v=1,alter=1)!=1){ stop("problem with get.edgeIDs on undirected network with loops") } if(get.edgeIDs(net,v=2,alter=2)!=3){ stop("problem with get.edgeIDs on undirected network with loops") } net<-network.initialize(2,loops=TRUE,directed=FALSE) net[1,2]<-1 if(length(get.edgeIDs(net,v=2,alter=2))>0){ stop("problem with get.edgeIDs on undirected network with loops") } result1 <- as.matrix.network.edgelist(network.initialize(5),as.sna.edgelist = TRUE) if (nrow(result1) != 0){ stop('as.matrix.network.edgelist did not return correct value for net with zero edges') } result1a <- tibble::as_tibble(network.initialize(5)) if (nrow(result1a) != 0){ stop('as_tibble.network did not return correct value for net with zero edges') } result2<-as.matrix.network.adjacency(network.initialize(5)) if(nrow(result2) != 5 & ncol(result2) != 5){ stop('as.matrix.network.adjacency did not return matrix with correct dimensions') } result3<-as.matrix.network.adjacency(network.initialize(0)) if(nrow(result3) != 0 & ncol(result3) != 0){ stop('as.matrix.network.adjacency did not return matrix with correct dimensions') } result4<-as.matrix.network.incidence(network.initialize(5)) if(nrow(result4) != 5 & ncol(result4) != 0){ stop('as.matrix.network.incidence did not return matrix with correct dimensions') } result5<-as.matrix.network.incidence(network.initialize(0)) if(nrow(result5) != 0 & ncol(result5) != 0){ stop('as.matrix.network.incidence did not return matrix with correct dimensions') }
lists_subscribers <- function(list_id = NULL, slug = NULL, owner_user = NULL, n = 20, cursor = "-1", parse = TRUE, retryonratelimit = NULL, verbose = TRUE, token = NULL) { params <- lists_params( list_id = list_id, slug = slug, owner_user = owner_user ) r <- TWIT_paginate_cursor(token, "/1.1/lists/subscribers", params, n = n, cursor = cursor, retryonratelimit = retryonratelimit, verbose = verbose, page_size = 5000, get_id = function(x) x$users$id_str ) if (parse) { r <- parse_lists_users(r) } r } parse_lists_users <- function(x) { users <- lapply(x, function(x) x$users) dfs <- lapply(users, wrangle_into_clean_data, type = "user") dfs <- lapply(dfs, tibble::as_tibble) df <- do.call("rbind", dfs) copy_cursor(df, x) }
"adjust.linear.bayes" <- function(lbo,ana.obj=lbo$call$ana.obj,...) { this.call <- match.call(expand.dots=TRUE) specs <- lbo$specs cl.1 <- lbo$hk$call cl.1[[1]]<-cl.1$varcov<-cl.1$ana.obj<-NULL cl.2 <- lbo$varcov.call cl.2[[1]]<-cl.2$x<-cl.2$ana.obj<-NULL one.gene.expr <- call("bqtl",reg.formula=lbo$varcov.call$x, ana.obj=ana.obj) extra.args <- unique(c(names(cl.1),names(cl.2))) if (length(extra.args)!=0){ dummy.call <- expression("$<-"(one.gene.expr,arg.2,arg.3))[[1]] for ( i in extra.args ){ dummy.call[[3]] <- dummy.call[[4]] <- i eval(dummy.call) one.gene.expr[[i]]<-lbo$call[[i]] } } one.gene.smry.expr <- call("summary.adj",adj.obj=as.name("one.gene.models"), n.loc=1,coef.znames="",mode.names=NULL,imp.denom="") one.gene.smry.expr$coef.znames <- call("$",ana.obj,"reg.names") mf.expr <- call("$",ana.obj,"map.frame") prior.expr <- call("$",mf.expr,"prior") one.gene.smry.expr$imp.denom <- call("/",1,prior.expr) if ( any(specs$gene.number == 1) ) { one.gene.models <- eval(one.gene.expr) one.gene.smry <- eval(one.gene.smry.expr) } else { one.gene.smry <- NULL } swap.gene.expr <- one.gene.expr swaps.expr <- expression( configs( uniq.config(lbo$swaps[[1]])$uniq ) )[[1]] swaps.expr[[2]][[2]][[2]][[2]][[2]] <- as.name(this.call$lbo) n.gene.smry.expr <- one.gene.smry.expr n.gene.smry.expr$adj.obj <- as.name("swaps.adj") n.gene.smry.expr$imp.denom <- NULL n.gene <- vector("list",length(lbo$swaps)) n.swap <- specs$gene.number[specs$n.cycles != 0] for( i in n.swap ){ swaps.expr[[2]][[2]][[2]][[3]] <- i swap.gene.expr$reg.formula[[3]] <- swaps.expr swaps.adj <- eval(swap.gene.expr) n.gene.smry.expr$n.loc <- i n.gene.smry.expr$swap.obj <- swaps.expr[[2]][[2]][[2]] n.gene[[i]] <- c( eval(n.gene.smry.expr), list(swaps=swaps.adj)) } if ( is.null(lbo$odds) ){ odds <- loc.posterior <- coefs <- NULL } else if ( any(specs$gene.number == 1) ){ odds <- lbo$odds*cumprod(c(one.gene.smry$adj, sapply(n.gene[n.swap],"[[","adj"))) post.pr <- odds/sum(odds) loc.posterior <- cbind(one.gene.smry$loc,sapply(n.gene[n.swap],"[[","loc")) %*% ( post.pr* c(1,n.swap)) coefs <- cbind(one.gene.smry$coef,sapply(n.gene[n.swap],"[[","coef")) %*% post.pr } else { odds <- lbo$odds*cumprod( sapply(n.gene[n.swap],"[[","adj") )/ n.gene[n.swap][[1]]$adj post.pr <- odds/sum(odds) loc.posterior <- sapply(n.gene[n.swap],"[[","loc") %*% ( post.pr * n.swap ) coefs <- sapply(n.gene[n.swap],"[[","coef") %*% post.pr } res <- list(odds=odds,loc.posterior=loc.posterior,coefficients=coefs, one.gene.adj=one.gene.smry,n.gene.adj=n.gene, call=this.call) class(res) <- "adjust.linear.bayes" res }
predictive.distribution <- function (document_sums, topics, alpha, eta) { smoothed.topics <- (topics + eta)/rowSums(topics + eta) apply(document_sums, 2, function(x) { props <- (x + alpha)/sum(x + alpha) colSums(props * smoothed.topics) }) }
qfrac<-function(x,s,k,i,data,assumption,prop){ dig<-getOption("digits") on.exit(options(digits = dig)) options(digits = 15) if(assumption=="UDD"){ if(x==(nrow(data)-1)){ prop<-1 } Q<-((1/k)*data[x+1,2]*prop)/(1-(s/k)*data[x+1,2]*prop) }else if(assumption=="constant"){ if(x==(nrow(data)-1)){ prop<-1 } ik<-Rate_converter(i,"i",1,"i",k,"frac") p<-((1+i)^(s/k))*(1-(s/k)*(1-E(x,1,i,data,prop,"none",1))) q.<-((1+i)^(s/k))*((1/k)*(1-E(x,1,i,data,prop,"none",1))*((s+1)*ik+1)-ik) Q<-q./p } else{ stop("Check assumption") } return(as.numeric(Q)) }
corc <- function(dataframe,varnames,subsampsize,nbsafe=5,mixties=FALSE,nthreads=2) { obs=dataframe[varnames] obs=subset(obs,apply(is.na(obs),1,sum)==0) nnm=length(obs[,1]) dimension=length(varnames) obs=as.numeric(unlist(obs)) u=runif(1)*(2^31-1) nboot=nbsafe*subsampsize^dimension cop=corc0( obs, nnm, dimension, subsampsize, nboot, u, mixties, nthreads=nthreads ) nbootreel=cop[subsampsize^dimension+2] ties=cop[subsampsize^dimension+1] cop=cop[1:subsampsize^dimension] cop=array(cop, rep(subsampsize,dimension)) cop=aperm(cop,dimension:1) cop=cop/((nbootreel-ties)*subsampsize) return(list(cop=cop,ties=ties,nsubsampreal=nbootreel,varnames=varnames,nnm=nnm)) }
tagsDivPlot.l_graph<- function(loon.grob, tabPanelName, loonWidgetsInfo, linkingGroup, displayedPanel) { tagsDivPlot.l_plot(loon.grob, tabPanelName, loonWidgetsInfo, linkingGroup, displayedPanel) }
knitr::opts_chunk$set( echo = TRUE, root.dir = "C:/Users/Dragos/Desktop/projects", collapse = TRUE, comment = " out.width = "100%", tidy.opts = list(width.cutoff = 120), tidy = TRUE, if (any(!requireNamespace("data.table", quietly = TRUE))) { knitr::opts_chunk$set(eval = FALSE) } ) pks = c('data.table', 'knitr', 'kableExtra', 'replacer') if(!any(pks %in% search())) { invisible(lapply(pks, require, character.only = TRUE)) } ll = lapply(c('data_id_vig.csv', 'lookup_id_vig.csv', 'outData.csv'), fread) dat = ll[[1]]; orderDat = names(copy(dat)) lk = ll[[2]]; orderLk = names(copy(lk)) odat = ll[[3]]; orderOdat = names(copy(odat)) dat$Rw = seq_len(nrow(dat)); setcolorder(dat, neworder = c('Rw', orderDat)) lk$Rw = seq_len(nrow(lk)); setcolorder(lk, neworder = c('Rw', orderLk)) odat$Rw = seq_len(nrow(odat)); setcolorder(odat, neworder = c('Rw', orderOdat)) options(knitr.kable.NA = "") kable_styling(kable(dat, format = 'html', caption = '*In-Data*', escape = TRUE, digits = 1), 'bordered', full_width = FALSE, position = 'float_left', font_size = 10) kable_styling(kable(lk, format = 'html', caption = 'Lookup', escape = TRUE, digits = 1), 'bordered', full_width = FALSE, position = 'float_left', font_size = 10) kable_styling(kable(odat, format = 'html', caption = '*Out-Data*', escape = TRUE, digits = 1), 'bordered', full_width = FALSE, position = 'float_left', font_size = 10) dir = system.file('extdata', package = 'replacer') inData = list.files(dir) inData = inData[grep('.csv', inData)] inData = inData[-grep('chile_id|chile_nadup|lookup', inData)] lData = lapply(inData, function(i) paste0(dir,'/', i)) data = lapply(lData, fread, na.strings = c(NA_character_, '')) n.chile = data$chile[, lapply(.SD, function(i) {sum(duplicated(i))/length(i)})] names(data) = unlist(strsplit(inData, split = '.csv', fixed = TRUE)) ldup = lapply(data, function(i) whichDups(i)[length(i) > 0]) ldup$chile = sample(ldup$chile, size = 4, prob = n.chile) nams = names(ldup) = names(data) DUPS = lapply(nams, function(n) {kable(t(ldup[[n]]) , format = 'html' , align='c' , caption = 'Duplicated') }) NAS = lapply(nams, function(n) {kable(t(data[[n]][, colSums(is.na(.SD))]) , format = 'html' , align='c' , caption = 'Missing') }) names(DUPS) = paste0(nams, 'DUP') names(NAS) = paste0(nams, 'NA') cat(c('<table><tr valign="top"><td>', DUPS$data_idDUP , '</td><td>', NAS$data_idNA, '</td><tr></table>'), sep = '') cat(c('<table><tr valign="top"><td>', DUPS$chileDUP , '</td><td>', NAS$chileNA, '</td><tr></table>'), sep = '') cat(c('<table><tr valign="top"><td>', DUPS$dataDUP , '</td><td>', NAS$dataNA, '</td><tr></table>'), sep = '') cat(c('<table><tr valign="top"><td>', DUPS$data_uniqueDUP , '</td><td>', NAS$data_uniqueNA, '</td><tr></table>'), sep = '') sessionInfo() knitr::write_bib(file = 'citation.bib')
ghypCheckPars <- function(param) { param <- as.numeric(param) mu <- param[1] delta <- param[2] alpha <- param[3] beta <- param[4] lambda <- param[5] case <- "" errMessage <- "" if (length(param) != 5) { case <- "error" errMessage <- "param vector must contain 5 values" } else { if (alpha < 0) { case <- "error" errMessage <- "alpha must not be less than zero" } else { if (lambda == 0) { if (abs(beta) >= alpha) { case <- "error" errMessage <- "absolute value of beta must be less than alpha when lambda = 0" } if (delta <= 0) { case <- "error" errMessage <- "delta must be greater than zero when lambda = 0" } if (abs(beta) >= alpha & delta <= 0) { case <- "error" errMessage <- "absolute value of beta must be less than alpha and delta must be greater than zero when lambda = 0" } } if (lambda > 0) { if (abs(beta) >= alpha) { case <- "error" errMessage <- "absolute value of beta must be less than alpha when lambda > 0" } if (delta < 0) { case <- "error" errMessage <- "delta must be non-negative when lambda > 0" } if (abs(beta) >= alpha & delta < 0) { case <- "error" errMessage <- "absolute value of beta must be less than alpha and delta must be less than zero when lambda > 0" } if (case != "error") { if (lambda == 1) { if (alpha > 0 & abs(beta) < abs(alpha) & delta == 0) case <- "skew laplace" if (alpha > 0 & beta == 0 & delta == 0) case <- "laplace" if (alpha > 0 & abs(beta) < abs(alpha) & delta > 0) case <- "hyperbolic" } else { if (alpha > 0 & abs(beta) < abs(alpha) & delta == 0) case <- "variance gamma" } } } if (lambda < 0) { if (abs(beta) > alpha) { case <- "error" errMessage <- "absolute value of beta must be less than or equal to alpha when lambda < 0" } if (delta <= 0) { case <- "error" errMessage <- "delta must be greater than zero when lambda < 0" } if (abs(beta) > alpha & delta <= 0) { case <- "error" errMessage <- "absolute value of beta must be less than or equal to alpha and delta must be greater than zero when lambda < 0" } if (case != "error") { if (lambda == -1/2) { if (alpha == 0 & beta == 0 & delta > 0) case <- "cauchy" if (alpha > 0 & abs(beta) < abs(alpha) & delta > 0) case <- "normal inverse gaussian" } else { if (abs(alpha - abs(beta)) < 0.001 & beta >= 0 & delta > 0) case <- "skew hyperbolic" if (alpha == 0 & beta == 0 & delta > 0) case <- "student's t" } } } } } if (case == "") case <- "normal" result <- list(case = case, errMessage = errMessage) return(result) }
test_that("distance matrix creation works", { num_cells <- 10 ras <- raster(nrows = num_cells, ncols = num_cells, vals = 1+runif(num_cells*num_cells)) coords <- rasterToPoints(ras)[, c("x", "y")] tr <- transition(ras, function(x){1/x[1]}, 8, symm = FALSE) co <- geoCorrection(tr, "c", multpl = TRUE) gdist_m <- costDistance(tr*co, coords, coords) landscapes <- stack_landscapes(list("r1" = list(ras)), 1) h_mask <- get_habitable_mask(NULL, landscapes, 1) local_distance <- get_local_distances(landscapes, h_mask, function(src, h_src, dest, h_dest){src},8, NULL) dist_m <- get_distance_matrix(habitable_cells = 1:prod(dim(ras)), num_cells = prod(dim(ras)), dist_p = local_distance@p, dist_i = local_distance@i, dist_x = local_distance@x, max_distance = Inf ) expect_true(isTRUE(all.equal(unname(dist_m), gdist_m))) expect_false(is.null(rownames(dist_m))) expect_false(is.null(colnames(dist_m))) })