code
stringlengths 1
13.8M
|
---|
utils::globalVariables(c(".", "moduleName"))
setGeneric("ganttStatus", function(eventType) {
standardGeneric("ganttStatus")
})
setMethod("ganttStatus",
signature(eventType = "character"),
definition = function(eventType) {
status <- lapply(eventType, function(x) {
if (x == "init") {
"done"
} else if (x == "plot") {
"crit"
} else {
"active"
}
})
return(unlist(status))
})
setGeneric(".sim2gantt", function(sim, n, startDate, width) {
standardGeneric(".sim2gantt")
})
setMethod(
".sim2gantt",
signature(sim = "simList", n = "numeric", startDate = "character", width = "numeric"),
definition = function(sim, n, startDate, width) {
DT <- tail(completed(sim), n)
modules <- unique(DT$moduleName)
width <- 4500 / as.numeric(width)
ts <- sim@simtimes[["timeunit"]] %>%
inSeconds(envir = [email protected]) %>%
convertTimeunit("day", envir = [email protected]) %>%
as.numeric()
out <- lapply(modules, function(x) {
data.frame(
task = DT[moduleName == x]$eventType,
status = ganttStatus(DT[moduleName == x]$eventType),
pos = paste0(x, 1:nrow(DT[moduleName == x])),
start = as.Date(
DT[moduleName == x]$eventTime * ts, origin = startDate
),
end = as.Date(
DT[moduleName == x]$eventTime * ts + width, origin = startDate
)
)
})
names(out) <- modules
return(out)
})
setGeneric("eventDiagram", function(sim, n, startDate, ...) {
standardGeneric("eventDiagram")
})
setMethod(
"eventDiagram",
signature(sim = "simList", n = "numeric", startDate = "character"),
definition = function(sim, n, startDate, ...) {
needInstall("DiagrammeR", minVersion = "0.8.2",
messageStart = "Please install DiagrammeR: ")
dots <- list(...)
dots$width <- if (any(grepl(pattern = "width", names(dots)))) {
as.numeric(dots$width)
} else {
1000
}
ll <- .sim2gantt(sim, n, startDate, dots$width)
ll <- ll[names(ll) != "progress"]
if (length(ll)) {
dots$height <- if (any(grepl(pattern = "height", names(dots)))) {
as.numeric(dots$height)
} else {
sapply(ll, NROW) %>% sum() %>% `*`(., 26L)
}
diagram <- paste0(
"gantt", "\n",
"dateFormat YYYY-MM-DD", "\n",
"title SpaDES event diagram", "\n",
paste("section ", names(ll), "\n", lapply(ll, function(df) {
paste0(df$task, ":", df$status, ",", df$pos, ",",
df$start, ",", df$end, collapse = "\n")
}), collapse = "\n"), "\n"
)
do.call(DiagrammeR::mermaid, args = append(diagram, dots))
} else {
stop("Unable to create eventDiagram for a simulation that hasn't been run.\n",
"Run your simulation using `mySim <- spades(mySim)` and try again.")
}
})
setMethod(
"eventDiagram",
signature(sim = "simList", n = "missing", startDate = "character"),
definition = function(sim, startDate, ...) {
eventDiagram(sim = sim, n = NROW(completed(sim)), startDate = startDate, ...)
})
setMethod(
"eventDiagram",
signature(sim = "simList", n = "missing", startDate = "missing"),
definition = function(sim, startDate, ...) {
d <- as.Date(start(sim), format(Sys.time(), "%Y-%m-%d")) %>% as.character()
eventDiagram(sim = sim, n = NROW(completed(sim)), startDate = d, ...)
})
setGeneric("objectDiagram", function(sim, ...) {
standardGeneric("objectDiagram")
})
setMethod(
"objectDiagram",
signature(sim = "simList"),
definition = function(sim, ...) {
dt <- depsEdgeList(sim, FALSE)
needInstall("DiagrammeR", minVersion = "0.8.2",
messageStart = "Please install DiagrammeR: ")
DiagrammeR::mermaid(...,
paste0(
"sequenceDiagram", "\n",
paste(dt$from, "->>", dt$to, ":", dt$objName, collapse = "\n"),
"\n"
)
)
})
setGeneric("moduleDiagram", function(sim, type, showParents, ...) {
standardGeneric("moduleDiagram")
})
setMethod(
"moduleDiagram",
signature = c(sim = "simList", type = "character", showParents = "logical"),
definition = function(sim, type, showParents, ...) {
if (type == "rgl") {
rglplot(depsGraph(sim, TRUE), ...)
} else if (type == "tk") {
tkplot(depsGraph(sim, TRUE), ...)
} else {
moduleDiagram(sim)
}
})
setMethod(
"moduleDiagram",
signature = c(sim = "simList", type = "missing"),
definition = function(sim, ...) {
modDia <- depsGraph(sim, TRUE)
dots <- list(...)
nDots <- names(dots)
if (missing(showParents)) showParents <- FALSE
if (showParents) {
moduleGraph(sim = sim, ...)
} else {
PlotRemovingDots <- function(modDia, plotFn, axes, ...,
vertex.color,
vertex.size,
vertex.size2,
vertex.shape,
vertex.label.cex,
vertex.label.family,
layout,
rescale,
xlim, ylim, asp) {
namesModDia <- names(V(modDia))
vcol <- if (!("vertex.color" %in% nDots)) {
sapply(namesModDia, function(v) {
ifelse(v == "_INPUT_", "orange", "lightblue")
})
} else {
"lightblue"
}
vertexSize <- if (!("vertex.size" %in% nDots)) {
c(nchar(namesModDia)^0.8 * 10)
} else {
dots$vertex.size
}
vertexSize2 <- if (!("vertex.size2" %in% nDots)) {
25
} else {
dots$vertex.size2
}
vertexLabelCex <- if (!("vertex.label.cex" %in% nDots)) {
1.7
} else {
dots$vertex.label.cex
}
vertexLabelFamily <- if (!("vertex.label.family" %in% nDots)) {
"sans"
} else {
dots$vertex.label.family
}
vertexShape <- if (!("vertex.shape" %in% nDots)) {
"rectangle"
} else {
dots$vertex.shape
}
layout2 <- if (!("layout" %in% nDots)) {
if ("_INPUT_" %in% V(modDia)) {
igraph::layout_as_star(modDia, center = "_INPUT_")
} else {
igraph::layout_in_circle(modDia)
}
} else {
dots$layout
}
rescale2 <- if (!("rescale" %in% nDots)) FALSE else dots$rescale
xlim2 <- if (!("xlim" %in% nDots)) c(-1.7, 1.7) else dots$xlim
ylim2 <- if (!("ylim" %in% nDots)) c(-1.1, 1.1) else dots$ylim
asp2 <- if (!("asp" %in% nDots)) 0 else dots$asp
Plot(modDia, plotFn = "plot", axes = FALSE,
vertex.color = vcol,
vertex.size = vertexSize,
vertex.size2 = vertexSize2,
vertex.shape = vertexShape,
vertex.label.cex = vertexLabelCex,
vertex.label.family = vertexLabelFamily,
layout = layout2,
rescale = rescale2,
xlim = xlim2, ylim = ylim2, asp = asp2, ...)
}
if ("title" %in% nDots) {
PlotRemovingDots(modDia = modDia, plotFn = "plot", axes = FALSE, ...)
} else {
PlotRemovingDots(modDia = modDia, plotFn = "plot", axes = FALSE,
title = "Module Diagram", ...)
}
}
})
setGeneric("moduleGraph", function(sim, plot, ...) {
standardGeneric("moduleGraph")
})
setMethod(
"moduleGraph",
signature(sim = "simList", plot = "logical"),
definition = function(sim, plot, ...) {
msgMissingGLPK <- paste("GLPK not found on this system.\n",
"igraph is used internally and requires a GLPK installation.\n")
msgInstallDarwin <- paste("It can be installed using, e.g., `brew install glpk`.\n")
msgInstallLinux <- paste("It can be installed using, e.g., `apt install libglpk-dev`.\n")
msgReinstallIgraph <- paste("If GLPK is installed you should reinstall igraph from source using:\n",
"`install.packages('igraph', type = 'source')`\n",
"For more info see https://github.com/igraph/rigraph/issues/273.")
if (Sys.which("glpsol") == "") {
if (Sys.info()[['sysname']] == "Darwin") {
message(msgMissingGLPK, msgInstallDarwin, msgReinstallIgraph)
} else if (Sys.info()[['sysname']] == "Linux") {
message(msgMissingGLPK, msgInstallLinux, msgReinstallIgraph)
}
return(invisible(NULL))
} else {
mg <- attr(sim@modules, "modulesGraph")
mg[["from"]] <- basename(mg[["from"]])
mg[["to"]] <- basename(mg[["to"]])
parents <- unique(mg[, "from"]) %>% basename()
deps <- depsEdgeList(sim)[, list(from, to)]
el <- rbind(mg, deps)
if (NROW(deps) == 0) deps <- mg
grph <- graph_from_data_frame(el, directed = TRUE)
grps <- try(cluster_optimal(grph))
if (is(grps, "try-error")) {
msgIgraphNoGLPK <- paste("Unable to create moduleGraph.",
"Likely reason: igraph not compiled with GLPK support.\n")
message(msgIgraphNoGLPK, msgReinstallIgraph)
return(invisible(NULL))
} else {
membership <- as.numeric(as.factor(mg[match(names(V(grph)), mg[, 2]), 1]))
membership[is.na(membership)] <- 1
membership[which(names(V(grph)) == "_INPUT_")] <- max(membership, na.rm = TRUE) + 1
grps$membership <- membership
el1 <- lapply(parents, function(par) data.frame(el["from" == par]))
el1 <- rbindlist(el1)
e <- apply(el1, 1, paste, collapse = "|")
e <- edges(e)
if (plot) {
vs <- c(15, 0)[(names(V(grph)) %in% parents) + 1]
dots <- list(...)
if ("title" %in% names(dots)) {
Plot(grps, grph - e, vertex.size = vs, plotFn = "plot", axes = FALSE, ...)
} else {
Plot(grps, grph - e, vertex.size = vs, plotFn = "plot", axes = FALSE,
title = "Module Graph", ...)
}
}
return(invisible(list(graph = grph, communities = grps)))
}
}
})
setMethod("moduleGraph",
signature(sim = "simList", plot = "missing"),
definition = function(sim, ...) {
return(moduleGraph(sim, TRUE, ...))
}) |
get_coauthors <- function(id, n_coauthors = 5, n_deep = 1) {
stopifnot(is.numeric(n_coauthors), length(n_coauthors) >= 1, n_coauthors != 0)
all_coauthors <- list_coauthors(id, n_coauthors)
all_coauthors <- all_coauthors[setdiff(1:nrow(all_coauthors),
grep("Sort by ", all_coauthors$coauthors)),]
empty_network <- replicate(n_deep, list())
if(n_deep == 0){
empty_network[[1]] <- clean_network(grab_id(all_coauthors$coauthors_url),
25)
}else{
for (i in seq_len(n_deep)) {
if (i == 1) {
empty_network[[i]] <- clean_network(grab_id(all_coauthors$coauthors_url),
n_coauthors)
} else {
empty_network[[i]] <- clean_network(grab_id(empty_network[[i - 1]]$coauthors_url),
n_coauthors)
}
}
}
final_network <- rbind(all_coauthors, Reduce(rbind, empty_network))
final_network <- final_network[setdiff(1:nrow(final_network),
grep("Sort by ", final_network$coauthors)),]
final_network$author <- stringr::str_to_title(final_network$author)
final_network$coauthors <- stringr::str_to_title(final_network$coauthors)
if(n_deep == 0) {
final_network <- final_network[final_network$coauthors %in% final_network$author,]
}
res <- final_network[c("author", "coauthors")]
res <- res[!res$coauthors %in% c("Sort By Year", "Sort By Title", "Sort By Citations"), ]
return(res)
}
plot_coauthors <- function(network, size_labels = 5) {
graph <- tidygraph::as_tbl_graph(network) %>%
mutate(closeness = suppressWarnings(tidygraph::centrality_closeness())) %>%
filter(name != "")
ggraph::ggraph(graph, layout = 'kk') +
ggraph::geom_edge_link(ggplot2::aes_string(alpha = 1/2, color = as.character('from')), alpha = 1/3, show.legend = FALSE) +
ggraph::geom_node_point(ggplot2::aes_string(size = 'closeness'), alpha = 1/2, show.legend = FALSE) +
ggraph::geom_node_text(ggplot2::aes_string(label = 'name'), size = size_labels, repel = TRUE, check_overlap = TRUE) +
ggplot2::labs(title = paste0("Network of coauthorship of ", network$author[1])) +
ggraph::theme_graph(title_size = 16, base_family = "sans")
}
list_coauthors <- function(id, n_coauthors) {
site <- getOption("scholar_site")
url_template <- paste0(site, "/citations?hl=en&user=%s")
url <- compose_url(id, url_template)
if (id == "" | is.na(id)) {
return(
data.frame(author = character(),
author_href = character(),
coauthors = character(),
coauthors_url = character()
)
)
}
resp <- get_scholar_resp(url, 5)
google_scholar <- httr::content(resp)
author_name <-
xml2::xml_text(
xml2::xml_find_all(google_scholar,
xpath = "//div[@id = 'gsc_prf_in']")
)
coauthors <- xml2::xml_find_all(google_scholar,
xpath = "//a[@tabindex = '-1']")
subset_coauthors <- if (n_coauthors > length(coauthors)) TRUE else seq_len(n_coauthors)
coauthor_href <- xml2::xml_attr(coauthors[subset_coauthors], "href")
coauthors <- xml2::xml_text(coauthors)[subset_coauthors]
if (length(coauthor_href) == 0) {
coauthors <- ""
coauthor_href <- ""
}
coauthor_urls <-
vapply(
grab_id(coauthor_href),
compose_url,
url_template,
FUN.VALUE = character(1)
)
data.frame(
author = author_name,
author_url = url,
coauthors = coauthors,
coauthors_url = coauthor_urls,
stringsAsFactors = FALSE,
row.names = NULL
)
}
clean_network <- function(network, n_coauthors) {
Reduce(rbind, lapply(network, list_coauthors, n_coauth = n_coauthors))
} |
"summary.psgc" <-
function(object,...){
qC<-qM.sM(object$C.psamp)
qR<-qM.sM(sR.sC(object$C.psamp))
p<-dim(qC)[1]
nsamp<-dim(object$C.psamp)[3]
vn<-colnames(qC[,,1])
ACF<-QC<-QR<-NULL
rnamesC<-rnamesR<-NULL
for(l1 in 1:p) {
for(l2 in (1:p)[-l1]) {
QR<-rbind(QR, c(qR[l1,l2,1:3]) )
rnamesR<-c(rnamesR,paste(vn[l1],vn[l2],sep="~") )
if(l1<l2) {
QC<-rbind(QC, c(qC[l1,l2,1:3]) )
ACF<-rbind(ACF,acf(object$C.psamp[l1,l2,],lag.max=round(nsamp/20),plot=FALSE)[[1]][-1] )
rnamesC<-c(rnamesC, paste(vn[l1],vn[l2],sep="*") )
}
}}
rownames(QC)<-rownames(ACF)<-rnamesC
rownames(QR)<-rnamesR
Kappa<-1+2*apply(ACF,1,sum)
ESS<-nsamp/Kappa
ACR.lag1<-matrix(0,p,p)
ACR.lag1[upper.tri(ACR.lag1)]<-ACF[1:choose(p,2),1]
ACR.lag1<-ACR.lag1+t(ACR.lag1)
diag(ACR.lag1)<-NA
nsamp<-dim(object$C.psamp)[3]
SUM<-list(QC=QC,QR=QR,nsamp=nsamp,ACR.lag1=ACR.lag1,ESS=ESS)
structure(SUM,class="sum.psgc")
} |
cleanUp <- function() {
existZWMat <- dir(tempdir(), pattern = "^\\d+(z|w)mat\\d{10}\\.RData$")
unlink(paste0(tempdir(), "/", existZWMat))
}
loadActual <- function() {
existWMat <- dir(tempdir(), pattern = "^\\d+wmat\\d{10}\\.RData$")
get(load(paste0(tempdir(), "/", existWMat)))
}
testCase1 <- function() {
cleanUp()
phasePortrait("(2-z)^2*(-1i+z)^3*(4-3i-z)/((2+2i+z)^4)",
xlim = c(-4, 4), ylim = c(-4, 4),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase001.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase2 <- function() {
cleanUp()
phasePortrait("(2-z)^2*(-1i+z)^3*(4-3i-z)/((2+2i+z)^4)",
xlim = c(-4, 4), ylim = c(-4, 4),
invertFlip = TRUE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase002.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase3 <- function() {
jacobiTheta_1 <- function(z, tau = 1i, nIter = 30) {
k <- c(1:nIter)
q <- exp(pi*1i*tau)
g <- exp(2*pi*1i*z)
return(1 + sum(q^(k^2)*g^k + q^(k^2)*(1/g)^k))
}
cleanUp()
phasePortrait(jacobiTheta_1,
xlim = c(-2, 2), ylim = c(-2, 2),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase003.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase4 <- function() {
jacobiTheta_1 <- function(z, tau = 1i, nIter = 30) {
k <- c(1:nIter)
q <- exp(pi*1i*tau)
g <- exp(2*pi*1i*z)
return(1 + sum(q^(k^2)*g^k + q^(k^2)*(1/g)^k))
}
cleanUp()
phasePortrait(jacobiTheta_1,
moreArgs = list(tau = 1i/2 - 1/4, nIter = 30),
xlim = c(-2, 2), ylim = c(-2, 2),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE,
autoDereg = TRUE)
referenceWmat <- get(load("1wmatCase004.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase5 <- function() {
cleanUp()
phasePortraitBw("(2-z)^2*(-1i+z)^3*(4-3i-z)/((2+2i+z)^4)",
xlim = c(-4, 4), ylim = c(-4, 4),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase005.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase6 <- function() {
cleanUp()
phasePortraitBw("(2-z)^2*(-1i+z)^3*(4-3i-z)/((2+2i+z)^4)",
xlim = c(-4, 4), ylim = c(-4, 4),
invertFlip = TRUE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase006.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase7 <- function() {
jacobiTheta_1 <- function(z, tau = 1i, nIter = 30) {
k <- c(1:nIter)
q <- exp(pi*1i*tau)
g <- exp(2*pi*1i*z)
return(1 + sum(q^(k^2)*g^k + q^(k^2)*(1/g)^k))
}
cleanUp()
phasePortraitBw(jacobiTheta_1,
xlim = c(-2, 2), ylim = c(-2, 2),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE)
referenceWmat <- get(load("1wmatCase007.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
testCase8 <- function() {
jacobiTheta_1 <- function(z, tau = 1i, nIter = 30) {
k <- c(1:nIter)
q <- exp(pi*1i*tau)
g <- exp(2*pi*1i*z)
return(1 + sum(q^(k^2)*g^k + q^(k^2)*(1/g)^k))
}
cleanUp()
phasePortrait(jacobiTheta_1,
moreArgs = list(tau = 1i/2 - 1/4, nIter = 30),
xlim = c(-2, 2), ylim = c(-2, 2),
invertFlip = FALSE,
blockSizePx = 2250000,
res = 150,
tempDir = NULL,
deleteTempFiles = FALSE,
noScreenDevice = TRUE,
nCores = 2,
verbose = FALSE,
autoDereg = TRUE)
referenceWmat <- get(load("1wmatCase008.RData"))
actualWmat <- loadActual()
cleanUp()
rslt <- all.equal(referenceWmat, actualWmat)
rm(referenceWmat, actualWmat)
return(rslt)
}
test_that("phasePortrait produces correct numerical output", {
expect_true(testCase1())
expect_true(testCase2())
expect_true(testCase3())
expect_true(testCase4())
})
test_that("phasePortraitBw produces correct numerical output", {
expect_true(testCase5())
expect_true(testCase6())
expect_true(testCase7())
expect_true(testCase8())
}) |
pool_propdiff_ac <- function(object,
conf.level=0.95,
dfcom=NULL)
{
if(all(class(object)!="mistats"))
stop("object must be of class 'mistats'")
if(!is.list(object$statistics))
stop("object must be a list")
ra <- data.frame(do.call("rbind", object$statistics))
colnames(ra) <- c("est", "se", "dfcom")
if(is_empty(dfcom)){
dfcom <- ra$dfcom[1]
} else {
dfcom <- dfcom
}
pool_est <- pool_scalar_RR(est=ra$est, se=ra$se,
logit_trans=FALSE,
conf.level = conf.level, dfcom=dfcom)
low <-
pool_est$pool_est - pool_est$t * pool_est$pool_se
high <-
pool_est$pool_est + pool_est$t * pool_est$pool_se
output <-
matrix(c(pool_est$pool_est, low, high), 1, 3)
colnames(output) <-
c("Prop diff AC",
c(paste(conf.level*100, "CI low"),
paste(conf.level*100, "CI high")))
class(output) <- 'mipool'
return(output)
} |
geo_amenity <- function(bbox,
amenity,
lat = "lat",
long = "lon",
limit = 1,
full_results = FALSE,
return_addresses = TRUE,
verbose = FALSE,
custom_query = list(),
strict = FALSE) {
if (limit > 50) {
message(paste(
"Nominatim provides 50 results as a maximum. ",
"Your query may be incomplete"
))
limit <- min(50, limit)
}
all_res <- NULL
for (i in seq_len(length(amenity))) {
if (amenity[i] %in% all_res$query) {
if (verbose) {
message(
amenity[i],
" already cached.\n",
"Skipping download."
)
}
res_single <- dplyr::filter(
all_res,
.data$query == amenity[i],
.data$nmlite_first == 1
)
res_single$nmlite_first <- 0
} else {
res_single <- geo_amenity_single(
bbox = bbox,
amenity = amenity[i],
lat,
long,
limit,
full_results,
return_addresses,
verbose,
custom_query
)
res_single <- dplyr::bind_cols(res_single, nmlite_first = 1)
}
all_res <- dplyr::bind_rows(all_res, res_single)
}
all_res <- dplyr::select(all_res, -.data$nmlite_first)
if (strict) {
strict <- all_res[lat] >= bbox[2] &
all_res[lat] <= bbox[4] &
all_res[long] >= bbox[1] &
all_res[long] <= bbox[3]
strict <- as.logical(strict)
all_res <- all_res[strict, ]
}
return(all_res)
}
geo_amenity_single <- function(bbox,
amenity,
lat = "lat",
long = "lon",
limit = 1,
full_results = TRUE,
return_addresses = TRUE,
verbose = FALSE,
custom_query = list()) {
bbox_txt <- paste0(bbox, collapse = ",")
api <- "https://nominatim.openstreetmap.org/search?"
url <- paste0(
api, "viewbox=",
bbox_txt,
"&q=[",
amenity,
"]&format=json&limit=", limit
)
if (full_results) {
url <- paste0(url, "&addressdetails=1")
}
if (length(custom_query) > 0) {
opts <- NULL
for (i in seq_len(length(custom_query))) {
nlist <- names(custom_query)[i]
val <- paste0(custom_query[[i]], collapse = ",")
opts <- paste0(opts, "&", nlist, "=", val)
}
url <- paste0(url, opts)
}
if (!"bounded" %in% names(custom_query)) {
url <- paste0(url, "&bounded=1")
}
json <- tempfile(fileext = ".json")
res <- api_call(url, json, isFALSE(verbose))
if (isFALSE(res)) {
message(url, " not reachable.")
result_out <- tibble::tibble(query = amenity, a = NA, b = NA)
names(result_out) <- c("query", lat, long)
return(invisible(result_out))
}
result <- tibble::as_tibble(jsonlite::fromJSON(json, flatten = TRUE))
if (nrow(result) > 0) {
result$lat <- as.double(result$lat)
result$lon <- as.double(result$lon)
}
nmes <- names(result)
nmes[nmes == "lat"] <- lat
nmes[nmes == "lon"] <- long
names(result) <- nmes
if (nrow(result) == 0) {
message("No results for query ", amenity)
result_out <- tibble::tibble(query = amenity, a = NA, b = NA)
names(result_out) <- c("query", lat, long)
return(invisible(result_out))
}
names(result) <- gsub("address.", "", names(result))
names(result) <- gsub("namedetails.", "", names(result))
names(result) <- gsub("display_name", "address", names(result))
result_out <- tibble::tibble(query = amenity)
result_out <- cbind(result_out, result[lat], result[long])
if (return_addresses || full_results) {
disp_name <- result["address"]
result_out <- cbind(result_out, disp_name)
}
if (full_results) {
rest_cols <- result[, !names(result) %in% c(long, lat, "address")]
result_out <- cbind(result_out, rest_cols)
}
result_out <- tibble::as_tibble(result_out)
return(result_out)
} |
seqeformat <- function(data,from="TSE",to="seqe",
id=NULL,timestamp=NULL,event=NULL,
var=NULL,start=1,alphabet=NULL,states=NULL,
labels=NULL,weighted=TRUE,
weights=NULL,tevent="transition",
obs.intervals=NULL)
{
if (!is.null(obs.intervals)) {
if (id!="id"&is.character(id)) {
id <- which(colnames(obs.intervals)==id)
colnames(obs.intervals)[id] <- "id"
}
if (sum(c("id","time.start","time.end")%in%
colnames(obs.intervals))!=3) {
warning(" [!] Invalid observation interval declaration. Ignore.")
obs.intervals <- NULL
}
}
if (from=="TSE") {
if (id!="id"&is.character(id)) {
id <- which(colnames(data)==id)
colnames(data)[id] <- "id"
}
data$id <- factor(data$id)
if (timestamp!="timestamp"&is.character(timestamp)) {
timestamp <- which(colnames(data)==timestamp)
colnames(data)[timestamp] <- "timestamp"
}
if (event!="event"&is.character(event)) {
event <- which(colnames(data)==event)
colnames(data)[event] <- "event"
}
data$event <- factor(data$event)
}
if ((from=="TSE")&(to=="TSE")) {
if (!is.factor(data$id)) {
data$id <- factor(data$id) }
if (!is.factor(data$event)) {
data$event <- factor(data$event) }
data <- data[order(data$id,data$timestamp,data$event),]
rownames(data) <- 1:nrow(data)
ret <- data
}
if ((from=="TSE")&(to=="seqe")) {
ret <- seqecreate(data=data,id=id,timestamp=timestamp,
event=event,weighted=weighted)
}
if ((from=="TSE")&(to=="both")) {
if (!is.factor(data$id)) {
data$id <- factor(data$id) }
if (!is.factor(data$event)) {
data$event <- factor(data$event) }
data <- data[order(data$id,data$timestamp,data$event),]
rownames(data) <- 1:nrow(data)
ret <- list()
ret$TSE <- data
ret$eseq <- seqecreate(data=data,id=id,timestamp=timestamp,
event=event,weighted=weighted)
}
if (from=="STS") {
if (is.null(id)) {seqid <- 1:nrow(data)} else {seqid <- data[,id]}
data <- data[order(seqid),]
seqid <- sort(seqid)
if (!inherits(data,"stslist")) {
if (is.null(states)&!is.null(labels)) {
states <- LETTERS[1:length(labels)]
seq <- seqdef(data=data,var=var,informat="STS",
alphabet=alphabet,states=states,
id=seqid,labels=labels,weights=weights,
start=start)
}
if (is.null(states)) {
seq <- seqdef(data=data,var=var,informat="STS",
alphabet=alphabet,
id=seqid,labels=labels,weights=weights,
start=start)
}
if (!exists("seq")) {
seq <- seqdef(data=data,var=var,informat="STS",
alphabet=alphabet,states=states,
id=seqid,labels=labels,weights=weights,
start=start)
}
} else {
seq <- data
}
}
if ((from=="STS")&(to=="seqe")) {
ret <- seqecreate(data=seq,weighted=weighted,
tevent=tevent)
}
if ((from=="STS")&(to=="TSE")) {
m <- seqetm(seq=seq,method=tevent)
ret <- seqformat(seq, from = "STS", to = "TSE", tevent = m)
names(ret)[2] <- "timestamp"
ret$timestamp <- ret$timestamp+start
ret$id <- factor(rownames(seq)[ret$id],levels=rownames(seq))
if (tevent=="period") {
which.end <- grep(pattern="end",x=levels(ret$event))
which.start <- which(!1:nlevels(ret$event)%in%which.end)
ind <- rep(c(1,1+length(which.start)),
length(which.start))+
rep(seq(0,length(which.start)-1),each=2)
order <- c(which.start,which.end)[ind]
ret$event <- factor(ret$event,levels=levels(ret$event)[order])
}
if (!inherits(data,"stslist")) {
lockedvars <- which(colnames(data)%in%c("id","event","timestamp"))
cov <- seq(1,ncol(data))[-var]
if (length(cov)>1) {
ret[,colnames(data)[cov]] <- data[ret$id,cov]
}
}
}
if ((from=="STS")&(to=="both")) {
ret <- list()
m <- seqetm(seq=seq,method=tevent)
ret$TSE <- seqformat(seq, from = "STS", to = "TSE", tevent = m)
names(ret$TSE)[2] <- "timestamp"
ret$TSE$timestamp <- ret$TSE$timestamp+start
ret$TSE$id <- factor(rownames(seq)[ret$TSE$id],levels=rownames(seq))
ret$eseq <- seqecreate(data=seq,weighted=weighted,tevent=tevent)
if (tevent=="period") {
which.end <- grep(pattern="end",x=levels(ret$TSE$event))
which.start <- which(!1:nlevels(ret$TSE$event)%in%which.end)
ind <- rep(c(1,1+length(which.start)),
length(which.start))+
rep(seq(0,length(which.start)-1),each=2)
order <- c(which.start,which.end)[ind]
ret$TSE$event <- factor(ret$TSE$event,
levels=levels(ret$TSE$event)[order])
}
if (!inherits(data,"stslist")) {
lockedvars <- which(colnames(data)%in%c("id","event","timestamp"))
cov <- seq(1,ncol(data))[-c(var,lockedvars)]
if (length(cov)>1) {
ret$TSE[,colnames(data)[cov]] <- data[ret$TSE$id,cov]
}
}
}
if ((from=="seqe")&(to=="TSE")|
(from=="seqe")&(to=="both"))
{
seqe.string <- as.character(data)
split.seqe.string <- function(x){unlist(strsplit(x=x,split="-"))}
seqe.decomp <- lapply(X=seqe.string,FUN=split.seqe.string)
event <- vector("list",length(seqe.decomp))
gaps <- vector("list",length(seqe.decomp))
time <- vector("list",length(seqe.decomp))
timerange <- vector("list",length(seqe.decomp))
for (i in 1:length(seqe.decomp)) {
if (substr(x=seqe.string[i],start=1,stop=1)=="(") {
seqe.decomp[[i]] <- c("0",seqe.decomp[[i]])
}
event[[i]] <-
seqe.decomp[[i]][seq(from=2,to=length(seqe.decomp[[i]]),by=2)]
event[[i]] <- sub(pattern="(",replacement="",
x=event[[i]],fixed=TRUE)
event[[i]] <- sub(pattern=")",replacement="",
x=event[[i]],fixed=TRUE)
gaps[[i]] <-
as.numeric(seqe.decomp[[i]][seq(from=1,
to=length(seqe.decomp[[i]]),
by=2)])
timerange[[i]] <- c(gaps[[i]][1],sum(gaps[[i]]))
if (length(gaps[[i]])>length(event[[i]]))
{
gaps[[i]] <- gaps[[i]][-length(gaps[[i]])]
}
time[[i]] <- cumsum(gaps[[i]])
extract.simultanevents <- function(x){strsplit(x=x,split=",")}
event[[i]] <- sapply(X=event[[i]],FUN=extract.simultanevents,
USE.NAMES=FALSE)
}
f.id <- function(x){length(unlist(x))}
f.time <- function(x){unlist(lapply(X=x,FUN=length))}
ret <- data.frame(id=factor(rep(1:length(event),
unlist(lapply(X=event,FUN=f.id)))),
timestamp=rep(unlist(time),
unlist(lapply(X=event,FUN=f.time))),
event=factor(unlist(event)))
}
if ((from=="seqe")&(to=="both"))
{
ret <- list(TSE=ret,
seqe=data)
}
if ((!is.null(obs.intervals))&(to=="both"))
{
obs.intervals <- obs.intervals[obs.intervals$id%in%
levels(ret$TSE$id),]
obs.intervals$id <- factor(obs.intervals$id,
levels=levels(ret$TSE$id))
ret$obs.intervals <- obs.intervals[order(obs.intervals$id),]
}
if (to=="both")
{
class(ret) <- c("seqelist","list")
}
return(ret)
} |
fit_BBMV_multiple_clades_different_V_different_sig2 <-
function(trees,traits,bounds,a=NULL,b=NULL,c=NULL,Npts=50,method='Nelder-Mead',init.optim=NULL){
if (length(trees)!=length(traits)){stop('The list of trees and the list of traits differ in length.')}
if (length(trees)==1){stop('There is only one tree and trait vector: use the function lnl_BBMV instead')}
lnls=ks=rep(NA,length(trees))
fits=list()
for (i in 1:length(trees)){
lnl_temp=lnL_BBMV(trees[[i]],traits[[i]],bounds=bounds,a=a,b=b,c=c,Npts=Npts)
fit_temp=find.mle_FPK(model=lnl_temp,method=method,init.optim=init.optim)
fits[[i]]=fit_temp ; names(fits)[i]=paste('fit_clade_',i,sep='')
lnls[i]=fit_temp$lnL ; ks[i]=fit_temp$k
}
return(list(lnL=sum(lnls),aic=2*(sum(ks)-sum(lnls)),k=sum(ks),fits=fits))
} |
source("ESEUR_config.r")
library("survival")
pal_col=rainbow(2)
API=read.csv(paste0(ESEUR_dir, "survival/ETP/Survival-ETP-API.csv.xz"),
header=FALSE, as.is=TRUE)
nonAPI=read.csv(paste0(ESEUR_dir, "survival/ETP/Survival-ETP-nonAPI.csv.xz"),
header=FALSE, as.is=TRUE)
gen_dead_list=function(cohort, API_status, start_year, end_year)
{
dead_list=NULL
for (y in 1:7)
{
new_row=data.frame(start_year, end_year[y], API_status, 0)
names(new_row)=c("year_start", "year_end", "API", "survived")
dead_list=rbind(dead_list, new_row[rep(1, cohort[y]), ])
}
new_row=data.frame(start_year, 2010, API_status, 1)
names(new_row)=c("year_start", "year_end", "API", "survived")
dead_list=rbind(dead_list, new_row[rep(1, cohort[8]), ])
return(dead_list)
}
gen_surv_list=function(app_info, API_status)
{
end_year=app_info[1, ]
app_status=NULL
for (y in 2:nrow(app_info))
app_status=rbind(app_status, gen_dead_list(app_info[y, ], API_status,
app_info[1, y-1]-1, end_year))
return(app_status)
}
app_API=gen_surv_list(API, 1)
app_nonAPI=gen_surv_list(nonAPI, 0)
all_api=rbind(app_API, app_nonAPI)
write.csv(all_api, paste0(ESEUR_dir, "survival/ETP/ETP-all-rel.csv.xz"),
row.names=FALSE)
write.csv(all_api, paste0(ESEUR_dir, "survival/ETP/ETP-all-bld.csv.xz"),
row.names=FALSE)
api_surv=Surv(app_API$year_end-app_API$year_start,
event=app_API$survived == 0, type="right")
api_mod=survfit(api_surv ~ 1)
nonapi_surv=Surv(app_nonAPI$year_end-app_nonAPI$year_start,
event=app_nonAPI$survived == 0, type="right")
nonapi_mod=survfit(nonapi_surv ~ 1)
plot(api_mod, xlim=c(0,7), xlab="Years", col=pal_col[1])
lines(nonapi_mod, col=pal_col[2])
api_diff=survdiff(Surv(year_end-year_start,
event=survived == 0, type="right") ~ API, data=all_api) |
if(FALSE)
invisible( "~/R/D/r-devel/R/src/nmath/qpois.c" )
doSearch_poi <- function(y, z, p, lambda, incr,
lower.tail=TRUE, log.p=FALSE, trace = 0)
{
formatI <- function(x) format(x, scientific = 16)
if(y < 0) y <- 0
iStr <- if(incr != 1) sprintf(" incr = %s", formatI(incr)) else ""
left <- if(lower.tail) (z >= p) else (z < p)
it <- 0L
if(left) {
if(trace) cat(sprintf("doSearch() to the left (ppois(y=%g, *) = z = %g %s p=%g):%s\n",
y,z, if(lower.tail) ">=" else "<", p, iStr))
repeat {
it <- it + 1L
if(y > 0)
newz <- ppois(y - incr, lambda, lower.tail=lower.tail, log.p=log.p)
else if(y < 0)
y <- 0
if(y == 0 || is.na(newz) ||
if(lower.tail) (newz < p) else (newz >= p)) {
if(trace >= 2) cat(sprintf(
" new y=%.15g, ppois(y-incr,*) %s p; ==> doSearch() returns prev z=%g after %d iter.\n",
y, if(lower.tail) "<" else ">=", z, it))
return(list(y=y, poi.y = z, iter = it))
}
y <- max(0, y - incr)
z <- newz
}
}
else {
if(trace) cat(sprintf("doSearch() to the right (ppois(y=%g, *) = z = %g %s p=%g):%s\n",
y,z, if(lower.tail) "<" else ">=", p, iStr))
repeat {
it <- it + 1L
y <- y + incr
z <- ppois(y, lambda, lower.tail=lower.tail, log.p=log.p)
if(is.na(z) ||
if(lower.tail) z >= p else z < p) {
if(trace >= 2) cat(sprintf(
" new y=%.15g, z=%g = ppois(y,*) %s p ==> doSearch() returns after %d iter.\n",
y, z, if(lower.tail) ">=" else "<", it))
return(list(y=y, poi.y = z, iter = it))
}
}
}
}
qpoisR1 <- function(p, lambda, lower.tail=TRUE, log.p=FALSE,
yLarge = 4096,
incF = 1/64,
iShrink = 8,
relTol = 1e-15,
pfEps.n = 8,
pfEps.L = 2,
fpf = 4,
trace = 0)
{
stopifnot(length(p) == 1, length(lambda) == 1)
if (is.na(p) || is.na(lambda))
return(p + lambda)
if (lambda == 0) return(0)
if (lambda < 0) {
warning("returning NaN because of lambda < 0 is out of range")
return(NaN)
}
if(log.p) {
if(p == -Inf) return(if(lower.tail) Inf else 0)
if(p == 0 ) return(if(lower.tail) 0 else Inf)
if(p > 0) { warning("p > 0 -> returning NaN"); return(NaN) }
} else {
if (p == 0 || p == 1) return(if(lower.tail) p else 1-p)
if(p < 0 || p > 1) {
warning("p out of [0,1] -> returning NaN"); return(NaN) }
}
mu <- lambda
sigma <- sqrt(lambda);
gamma <- 1.0/sigma;
if(trace) {
cat(sprintf("qpois(p=%.12g, lambda=%.15g, l.t.=%d, log=%d):\n
mu=%g, sigma=%g, gamma=%g;\n",
p, lambda, lower.tail, log.p, mu, sigma, gamma))
}
if(!lower.tail || log.p) {
p_n <- .DT_qIv(p, lower.tail, log.p)
if (p_n == 0) message("p_n=0: NO LONGER return(0)\n")
if (p_n == 1) message("p_n=1: NO LONGER return(Inf)\n")
} else
p_n <- p
if (p_n + 1.01*.Machine$double.eps >= 1.) {
if(trace)
cat("p__n + 1.01 * c_eps >= 1 ; (1-p = ",format(1-p),
") ==> NOW LONGER returning Inf (Hack -- FIXME ?)\n", sep="")
}
z <- qnorm(p, lower.tail=lower.tail, log.p=log.p)
y <- round(mu + sigma * (z + gamma * (z*z - 1) / 6))
if(trace) cat(sprintf("Cornish-Fisher: initial z=%g, y=%g; ", z,y))
if(y < 0) y <- 0.;
z <- ppois(y, lambda, lower.tail=lower.tail, log.p=log.p)
if(trace) cat(sprintf(" then: y=%g, z= ppois(y,*) = %g\n", y,z))
c.eps <- .Machine$double.eps
if(log.p) {
e <- pfEps.L * c.eps
if(lower.tail && p > -.Machine$x.max)
p <- p * (1 + e)
else if(p < - .Machine$x.min)
p <- p * (1 - e)
} else {
e <- pfEps.n * c.eps
if(lower.tail)
p <- p * (1 - e)
else if(1 - p > fpf*e)
p <- p * (1 + e)
}
if(y < yLarge) {
doSearch_poi(y=y, z=z, p=p, lambda=lambda, incr = 1,
lower.tail=lower.tail, log.p=log.p, trace=trace)$ y
} else {
incr <- floor(y * incF)
if(trace) cat(sprintf("large y: --> use larger increments than 1: incr=%s\n",
format(incr, scientific=16)))
qIt <- totIt <- 0L
repeat {
oldincr <- incr
yz <- doSearch_poi(y=y, z=z, p=p, lambda=lambda, incr = incr,
lower.tail=lower.tail, log.p=log.p, trace=trace)
y <- yz$y
z <- yz$poi.y
totIt <- totIt + yz$iter
qIt <- qIt + 1L
incr <- max(1, floor(incr/iShrink));
if(oldincr <= 1 || incr <= y * relTol)
break
}
if(trace) cat(sprintf(" \\--> %s; needed %d doSearch() calls, total %d iterations\n",
if(oldincr == 1) "oldincr=1"
else sprintf("oldincr = %s, incr = %s < %.11g = y * relTol",
format(oldincr, scientific = 9),
format(incr, scientific = 9), y*relTol),
qIt, totIt))
y
}
}
qpoisR <- Vectorize(qpoisR1, c("p", "lambda"))
|
numericindex <- function (x, i, n = names (x)){
if (is.character (i))
match (i, n)
else if (is.logical (i))
seq_along (x) [i]
else if (is.numeric (i))
i
else
stop ("i must be numeric, logical, or character")
}
.test (numericindex) <- function (){
checkEquals (numericindex (v, c("b", "a", "x")), c (2L, 1L, NA))
checkEquals (numericindex (v, c(TRUE, FALSE, TRUE)), c(1L, 3L))
checkEquals (numericindex (v, TRUE), 1 : 3)
checkEquals (numericindex (v, FALSE), integer (0L))
checkEquals (numericindex (v, c(TRUE, FALSE)), c(1L, 3L))
checkEquals (numericindex (v, 1L), 1L)
} |
combine.date.and.time <- function(date, time){
if (is.list(time))
datetime <- strptime(paste(as.character(date), " ", time$hrs, ":",
time$mins, ":", time$secs, sep=""),
format="%Y-%m-%d %H:%M:%S", tz="GMT")
else
datetime <- strptime(paste(as.character(date), " ", time, sep=""),
format="%Y-%m-%d %H:%M:%S", tz="GMT")
return(datetime)
} |
ccmean <- function(x, L = max(x$surv), addInterPol = 0) {
if( !("id" %in% names(x)) | !("cost" %in% names(x)) | !("delta" %in% names(x)) | !("surv" %in% names(x)) )
stop('Rename colums to: "id", "cost", "delta" and "surv"')
maxsurv <- max(x$surv)
if( ("start" %in% names(x)) & ("stop" %in% names(x)) ) {
x$delta[x$surv >= L] <- 1
x$surv <- pmin(x$surv, L)
x <- subset(x, x$start <= L)
x <- x %>%
mutate(cost = ifelse(.data$stop > .data$surv,
.data$cost * ((.data$surv - .data$start + addInterPol)/(.data$stop - .data$start + addInterPol)),
.data$cost),
stop = pmin(.data$stop, L)) %>%
arrange(.data$surv, .data$delta)
xf <- x %>%
group_by(.data$id) %>%
summarize(cost = sum(.data$cost, na.rm = TRUE),
delta = last(.data$delta),
surv = first(.data$surv))
} else if (length(x$id) > length(unique(x$id))) {
stop('No cost history but non-unique id tags')
} else {
message('No cost history found, can be set by: "start" and "stop"')
xf <- x %>%
mutate(cost = ifelse(.data$surv > L,
.data$cost * ((L + addInterPol)/(.data$surv + addInterPol)),
.data$cost),
delta = as.numeric(.data$surv >= L | .data$delta == 1),
surv = pmin(.data$surv, L)) %>%
arrange(.data$surv, .data$delta)
}
AS <- mean(xf$cost)
AS_var <- var(xf$cost) / nrow(xf)
AS_full <- c(AS,
AS_var,
sqrt(AS_var),
AS - 1.96 * sqrt(AS_var),
AS + 1.96 * sqrt(AS_var))
CC <- mean(xf$cost[xf$delta == 1])
CC_var <- var(xf$cost[xf$delta == 1]) / sum(xf$delta)
CC_full <- c(CC,
CC_var,
sqrt(CC_var),
CC - 1.96 * sqrt(CC_var),
CC + 1.96 * sqrt(CC_var))
sc <- summary(survfit(Surv(xf$surv, xf$delta == 0) ~ 1), times = xf$surv)
sct <- data.frame(sc$time, sc$surv)
sct$sc.surv[sct$sc.surv == 0] <- min(sct$sc.surv[sct$sc.surv != 0])
sct <- unique(sct)
s <- summary(survfit(Surv(xf$surv, xf$delta) ~ 1), times = xf$surv)
st <- data.frame(s$time, s$surv)
st <- unique(st)
t <- merge(xf, sct, by.x = "surv", by.y = "sc.time", all.x = T)
t <- merge(t, st, by.x = "surv", by.y = "s.time", all.x = T)
BT <- mean((t$cost * t$delta) / t$sc.surv)
n <- length(t$cost)
t$GA <- rep(0, n)
t$GB <- rep(0, n)
for(i in 1:n){
if(t$delta[i] == 1) next
t2 <- subset(t, surv >= t$surv[i])
t$GA[i] <- (1 / (n*t$s.surv[i])) * sum(t2$delta * t2$cost^2 / t2$sc.surv)
t$GB[i] <- (1 / (n*t$s.surv[i])) * sum(t2$delta * t2$cost / t2$sc.surv)
}
BT_var <- 1 / n * (mean(t$delta * (t$cost-BT)^2 / t$sc.surv) +
mean(((1 - t$delta) / t$sc.surv^2 ) * (t$GA - t$GB^2)))
BT_full <- c(BT,
BT_var,
sqrt(BT_var),
BT - 1.96 * sqrt(BT_var),
BT + 1.96 * sqrt(BT_var))
if( ("start" %in% names(x)) & ("stop" %in% names(x)) ) {
runCostMatrix <- matrix(0, nrow = nrow(t), ncol = nrow(t))
t$mcostlsurv <- 0
t$mcostlsurvSq <- 0
setDTthreads(1)
surv <- NULL
start <- NULL
cost <- NULL
for(i in 1:nrow(t)){
if(t$delta[i] == 1){
next
} else {
DT <- data.table::as.data.table(x)[start <= t$surv[i]]
DT <- DT[,cost := ifelse(stop > t$surv[i], (cost/(stop - start + addInterPol)) * (t$surv[i] - start + addInterPol), cost)]
t_data2 <- DT[, list(cost = sum(cost), surv = first(surv)), by = list(id)]
idIndex <- t$id %in% t_data2$id
ids <- t$id[idIndex]
runCost <- t_data2$cost
names(runCost) <- t_data2$id
runCostMatrix[idIndex, i] <- runCost[as.character(ids)]
t$mcostlsurv[i] <- mean(t_data2$cost[t_data2$surv >= t$surv[i]])
t$mcostlsurvSq[i] <- mean(t_data2$cost[t_data2$surv >= t$surv[i]]^2)
}
}
ZT <- BT + mean(((1 - t$delta) * ((t$cost - t$mcostlsurv) / t$sc.surv)), na.rm = TRUE)
n <- nrow(t)
t$gm <- rep(0,n)
t$gmm <- rep(0,n)
for(i in 1:n){
if(t$delta[i] == 1) next
t$gm[i] <- (1 / (n * t$s.surv[i])) * sum(as.numeric(t$surv >= t$surv[i]) * t$delta * runCostMatrix[,i] / t$sc.surv)
t$gmm[i] <- (1 / (n * t$s.surv[i])) * sum(as.numeric(t$surv >= t$surv[i]) * t$delta * t$cost * runCostMatrix[,i] / t$sc.surv)
}
ZT_var <- BT_var - (2 / n^2) * sum(((1 - t$delta) / t$sc.surv^2) * (t$gmm - t$GB * t$gm)) +
(1 / n^2) * sum(((1 - t$delta) / t$sc.surv^2) * (t$mcostlsurvSq - t$mcostlsurv^2))
ZT_full <- c(ZT,
ZT_var,
sqrt(ZT_var),
ZT - 1.96 * sqrt(ZT_var),
ZT + 1.96 * sqrt(ZT_var))
} else {
ZT <- NA
ZT_full <- rep(NA,5)
}
svl1 <- survival::survfit(Surv(xf$surv, xf$delta == 1) ~ 1)
svl2 <- summary(svl1)[["table"]]
results <- list(Text = c("ccostr - Estimates of mean cost with censored data"),
Data = data.frame("Observations" = nrow(x),
"Individuals" = nrow(xf),
"FullyObserved" = sum(xf$delta == 1),
"Limits" = L,
"TotalTime" = sum(xf$surv),
"MaxSurvival" = maxsurv,
row.names = "N"),
First = data.frame(AS, CC, BT, ZT),
Estimates = data.frame("AS" = AS_full,
"CC" = CC_full,
"BT" = BT_full,
"ZT" = ZT_full,
row.names = c("Estimate", "Variance", "SE", "0.95LCL", "0.95UCL")),
Survival = svl2
)
class(results) <- "ccobject"
results
} |
context("Test outbreaker config")
test_that("test: settings are processed fine", {
data(toy_outbreak_short)
x <- toy_outbreak_short
dt_cases <- x$cases
dt_cases <- dt_cases[order(dt_cases$Date), ]
dt_regions <- x$dt_regions
all_dist <- geosphere::distGeo(matrix(c(rep(dt_regions$long, nrow(dt_regions)),
rep(dt_regions$lat, nrow(dt_regions))),
ncol = 2),
matrix(c(rep(dt_regions$long, each = nrow(dt_regions)),
rep(dt_regions$lat, each = nrow(dt_regions))),
ncol = 2))
dist_mat <- matrix(all_dist/1000, nrow = nrow(dt_regions))
pop_vect <- dt_regions$population
names(pop_vect) <- rownames(dist_mat) <- colnames(dist_mat) <- dt_regions$region
w <- dnorm(x = 1:100, mean = 11.7, sd = 2.0)
f <- dgamma(x = 1:100, scale = 0.43, shape = 27)
data <- outbreaker_data(dates = dt_cases$Date, age_group = dt_cases$age_group,
region = dt_cases$Cens_tract, population = pop_vect,
distance = dist_mat, a_dens = x$age_contact,
f_dens = f, w_dens = w)
expect_is(create_config(), "list")
expect_is(create_config(data = data), "list")
expect_equal(create_config(data = data, init_tree = c(NA, rep(1, data$N - 1)))$init_alpha,
create_config(data = data, init_tree = c(NA, rep(1, data$N - 1)))$init_tree)
expect_error(create_config(data = data, init_tree = rep(1, data$N)),
"There should be an ancestor in the initial tree")
expect_equal(create_config(data = data, init_kappa = c(NA, rep(1, data$N - 1)))$init_kappa,
c(NA, rep(1, data$N - 1)))
expect_error(create_config(fakearg = 2), "Additional invalid options: fakearg")
expect_error(create_config(spatial_method = "invalid"),
"invalid value for spatial_method, spatial_method is either exponential, or power-law.")
expect_error(create_config(gamma = "1"), "gamma is not numeric")
expect_error(create_config(gamma = NA), "gamma is NA")
expect_error(create_config(gamma = -1), "gamma is below 0")
expect_error(create_config(delta = -1), "delta is below 0")
expect_error(create_config(delta = "1"), "delta is not numeric")
expect_error(create_config(delta = NA), "delta is NA")
expect_error(create_config(init_kappa = 0), "init_kappa has values smaller than 1")
expect_error(create_config(init_kappa = "1"), "init_kappa is not a numeric value")
expect_error(create_config(init_pi = -1), "init_pi is negative")
expect_error(create_config(init_pi = 2), "init_pi is greater than 1")
expect_error(create_config(init_pi = "1"), "init_pi is not a numeric value")
expect_error(create_config(init_pi = Inf), "init_pi is infinite or NA")
expect_error(create_config(init_a = -1), "init_a is negative")
expect_error(create_config(init_a = Inf), "init_a is infinite or NA")
expect_error(create_config(init_a = "1"), "init_a is not a numeric value")
expect_error(create_config(init_b = -1), "init_b is negative")
expect_error(create_config(init_b = Inf), "init_b is infinite or NA")
expect_error(create_config(init_b = "1"), "init_b is not a numeric value")
expect_error(create_config(move_alpha = "TRUE"), "move_alpha is not a logical")
expect_error(create_config(move_alpha = NA), "move_alpha is NA")
expect_error(create_config(move_swap_cases = "TRUE"), "move_swap_cases is not a logical")
expect_error(create_config(move_swap_cases = NA), "move_swap_cases is NA")
expect_error(create_config(move_t_inf = "TRUE"), "move_t_inf is not a logical")
expect_error(create_config(move_t_inf = NA), "move_t_inf has NA")
expect_error(create_config(move_kappa = "TRUE"), "move_kappa is not a logical")
expect_error(create_config(move_kappa = NA), "move_kappa has NA")
expect_error(create_config(move_pi = "TRUE"), "move_pi is not a logical")
expect_error(create_config(move_pi = NA), "move_pi is NA")
expect_error(create_config(move_pi = "TRUE"), "move_pi is not a logical")
expect_error(create_config(move_pi = NA), "move_pi is NA")
expect_error(create_config(move_a = "TRUE"), "move_a is not a logical")
expect_error(create_config(move_a = NA), "move_a is NA")
expect_error(create_config(move_b = "TRUE"), "move_b is not a logical")
expect_error(create_config(move_b = NA), "move_b is NA")
expect_warning(create_config(init_kappa = 8), "values of init_kappa greater than max_kappa have been set to max_kappa")
expect_error(create_config(data = data, init_tree = c(-NA, 1)),
"length of init_alpha or init_tree incorrect")
expect_warning(create_config(move_a = TRUE, max_kappa = 10),
"If spatial kernel parameters are estimated, max_kappa is set to 2")
expect_error(create_config(n_iter = 0),
"n_iter is smaller than 2")
expect_error(create_config(sample_every = 0),
"sample_every is smaller than 1")
})
test_that("test: initial tree does not mix genotypes", {
data(toy_outbreak_short)
x <- toy_outbreak_short
dt_cases <- x$cases
dt_cases <- dt_cases[order(dt_cases$Date), ]
dt_regions <- x$dt_regions
all_dist <- geosphere::distGeo(matrix(c(rep(dt_regions$long, nrow(dt_regions)),
rep(dt_regions$lat, nrow(dt_regions))),
ncol = 2),
matrix(c(rep(dt_regions$long, each = nrow(dt_regions)),
rep(dt_regions$lat, each = nrow(dt_regions))),
ncol = 2))
dist_mat <- matrix(all_dist/1000, nrow = nrow(dt_regions))
pop_vect <- dt_regions$population
names(pop_vect) <- rownames(dist_mat) <- colnames(dist_mat) <- dt_regions$region
w <- dnorm(x = 1:100, mean = 11.7, sd = 2.0)
f <- dgamma(x = 1:100, scale = 0.43, shape = 27)
data <- outbreaker_data(dates = dt_cases$Date, age_group = dt_cases$age_group,
region = dt_cases$Cens_tract, population = pop_vect,
distance = dist_mat, a_dens = x$age_contact,
f_dens = f, w_dens = w, genotype = dt_cases$Genotype)
config <- create_config(data = data)
tree_ances <- config$init_alpha
while(any(!is.na(tree_ances[tree_ances])))
tree_ances[!is.na(tree_ances[tree_ances])] <-
tree_ances[tree_ances][!is.na(tree_ances[tree_ances])]
tree_ances[is.na(tree_ances)] <- which(is.na(tree_ances))
genotype_tree <- numeric(length(unique(tree_ances)))
nb_gen_rep_per_tree <- sapply(unique(tree_ances), function(X) {
gens <- unique(data$genotype[which(tree_ances == X)])
return(length(gens[gens != "Not attributed"]))
})
expect_true(all(nb_gen_rep_per_tree < 2))
expect_error(create_config(data = data, init_tree = c(NA, rep(1, data$N - 1))),
"There should be one reported genotype per tree at most.")
}) |
context("rptProportion")
suppressWarnings(RNGversion("3.5.0"))
set.seed(23)
data(BeetlesMale)
BeetlesMale$Dark <- BeetlesMale$Colour
BeetlesMale$Reddish <- (BeetlesMale$Colour-1)*-1
md <- aggregate(cbind(Dark, Reddish) ~ Population + Container, data=BeetlesMale, FUN=sum)
R_est_1 <- rptProportion(cbind(Dark, Reddish) ~ (1|Population), grname=c("Population"), data=md,
nboot=0, npermut=0)
test_that("rpt estimation works for one random effect, no boot, no permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$R["R_org", ],0.1853997, tolerance = 0.001)
expect_equal(R_est_1$R["R_link", ], 0.1879315, tolerance = 0.001)
})
test_that("LRT works", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$P$LRT_P, 5.81e-09, tolerance = 0.001)
})
R_est_2 <- rptProportion(cbind(Dark, Reddish) ~ (1|Population), grname=c("Population"), data=md,
nboot=2, npermut=0)
test_that("rpt estimation works for one random effect, boot, no permut, no parallelisation, logit link", {
expect_equal(as.numeric(R_est_2$CI_emp$CI_org["2.5%"]), 0.1587981, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org["97.5%"]), 0.1896277, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link["2.5%"]), 0.1602279, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link["97.5%"]), 0.1923845, tolerance = 0.001)
})
R_est_3 <- rptProportion(cbind(Dark, Reddish) ~ (1|Population), grname=c("Population"), data=md,
nboot=0, npermut=2)
test_that("rpt estimation works for one random effect, no boot, permut, no parallelisation, logit link", {
expect_equal(R_est_3$P$P_permut_org, 0.5, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_link, 0.5, tolerance = 0.001)
})
R_est_1 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Container) + (1|Population), grname=c("Container", "Population", "Residual"), data = md,
nboot=0, npermut=0))
test_that("rpt estimation works for two random effect, no boot, no permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$R["R_org", 1], 3.030087e-11, tolerance = 0.001)
expect_equal(R_est_1$R["R_link", 1], 4.686765e-11 , tolerance = 0.001)
expect_equal(R_est_1$R["R_org", 2], 0.1854017, tolerance = 0.001)
expect_equal(R_est_1$R["R_link", 2], 0.1879334, tolerance = 0.001)
})
test_that("LRTs works", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$P[1, "LRT_P"], 1, tolerance = 0.001)
expect_equal(R_est_1$P[2, "LRT_P"], 5.81e-09, tolerance = 0.001)
})
test_that("random effect components sum to up to one", {
expect_equal(sum(R_est_1$R["R_link", ]), 1)
})
R_est_2 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Container) + (1|Population), grname=c("Container", "Population"), data = md,
nboot=2, npermut=0))
test_that("rpt estimation works for two random effect, boot, no permut, no parallelisation, logit link", {
expect_equal(as.numeric(R_est_2$CI_emp$CI_org[1, "2.5%"]), 0.0001784753, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org[1, "97.5%"]), 0.006960535, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org[2, "2.5%"]), 0.1085067 , tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org[2, "97.5%"]), 0.1204242, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link[1, "2.5%"]), 0.0001784753, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link[1, "97.5%"]),0.006960535, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link[2, "2.5%"]), 0.1085067, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link[2, "97.5%"]), 0.1204242, tolerance = 0.001)
})
R_est_3 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Container) + (1|Population), grname=c("Container", "Population"), data = md,
nboot=0, npermut=5))
test_that("rpt estimation works for two random effect, no boot, permut, no parallelisation, logit link", {
expect_equal(R_est_3$P$P_permut_org[1], 1, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_org[2], 0.2, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_link[1], 1, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_link[2], 0.2, tolerance = 0.001)
})
R_est_4 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Container) + (1|Population),
grname=c("Container", "Population", "Overdispersion", "Residual"), data = md,
nboot=0, npermut=0))
test_that("repeatabilities are equal for grouping factors independent of residual and overdispersion specification", {
expect_false(any(R_est_3$R$Container == R_est_4$R$Container) == FALSE)
expect_false(any(R_est_3$R$Population == R_est_4$R$Population) == FALSE)
})
R_est_5 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Container) + (1|Population),
grname=c("Population", "Container"), data = md,
nboot=0, npermut=0))
test_that("repeatabilities are equal for different sequence in grname argument", {
expect_false(any(R_est_3$R$Container == R_est_5$R$Container) == FALSE)
expect_false(any(R_est_3$R$Population == R_est_5$R$Population) == FALSE)
})
test_that("LRTs are equal for different different sequence in grname argument", {
expect_equal(R_est_3$P["Container", "LRT_P"], R_est_5$P["Container", "LRT_P"])
expect_equal(R_est_3$P["Population", "LRT_P"], R_est_5$P["Population", "LRT_P"])
})
R_est_6 <- suppressWarnings(rptProportion(cbind(Dark, Reddish) ~ (1|Population) + (1|Container),
grname=c("Container", "Population"), data = md,
nboot=0, npermut=0))
test_that("repeatabilities are equal for different sequence in formula argument", {
expect_false(any(R_est_3$R$Container == R_est_6$R$Container) == FALSE)
expect_false(any(R_est_3$R$Population == R_est_6$R$Population) == FALSE)
})
test_that("LRTs are equal for different order in formula argument", {
expect_equal(R_est_3$P["Container", "LRT_P"], R_est_6$P["Container", "LRT_P"])
expect_equal(R_est_3$P["Population", "LRT_P"], R_est_6$P["Population", "LRT_P"])
}) |
"_PACKAGE" |
expected <- eval(parse(text="structure(c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), .Dim = c(20L, 20L), .Dimnames = list(c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_)))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), .Dim = c(20L, 20L), .Dimnames = list(c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_))))"));
.Internal(t.default(argv[[1]]));
}, o=expected); |
expfunction.nl <- function(par=c(0.3,0.4,0.5,0.6),
x=10*rep(1,3))
{
alpha=par[1]
beta=par[-1]
U1 = ( x[1]^(-1./(alpha*beta[1]) ) +
x[2]^(-1./(alpha*beta[1]) ) )^(beta[1])
U2 = ( x[1]^(-1./(alpha*beta[2]) ) +
x[3]^(-1./(alpha*beta[2]) ) )^(beta[2])
U3 = ( x[2]^(-1./(alpha*beta[3]) ) +
x[3]^(-1./(alpha*beta[3]) ) )^(beta[3])
return( 2^(-alpha) * ( (U1 + U2 + U3)^(alpha) ) )
}
excessProb.condit.nl <- function(par=c(0.3,0.4,0.5,0.6),
thres=rep(100,3))
{
expfun <- expfunction.nl
zeros <- which(thres==0)
if(length(zeros)==3)
stop(" x must have at least one positive element")
if(length(zeros)==2)
{
x <- thres
x[zeros] <- Inf
return(expfun(par=par, x=x))
}
if(length(zeros)==1)
{
nonzeros <- c(1,2,3)[-zeros]
x <- thres
x[zeros] <- Inf
T0 <- expfun(par=par,x=x)
x1 <- x
x1[nonzeros[1]] <- Inf
T1 <- expfun(par=par, x=x1)
x2 <- x
x2[nonzeros[2]] <- Inf
T2 <- expfun(par=par, x=x2)
return( T1 + T2 - T0 )
}
T1 <- expfun(par=par,x=thres)
T2 <- expfun(par=par,x=c(thres[1], Inf,Inf)) +
expfun(par=par,x=c(Inf, thres[2],Inf)) +
expfun(par=par,x=c(Inf, Inf, thres[3]))
T3 <- expfun(par=par,x=c(thres[1], thres[2],Inf)) +
expfun(par=par,x=c(thres[1], Inf, thres[3])) +
expfun(par=par,x=c(Inf, thres[2], thres[3]))
return( T1 + T2 - T3 )
}
excessProb.nl <- function(post.sample,
from=NULL,to=NULL, thin=100,
thres=rep(100,3),
known.par= FALSE,
true.par,
displ=FALSE)
{
reslist <- posteriorMean(post.sample=post.sample,
from=from,to=to, thin=thin,
FUN=excessProb.condit.nl,
displ=FALSE,
thres=thres
)
res <- as.vector(reslist$values)
N <- length(res)
cummean <- cumsum(res)/(1:N)
estsd <- sqrt(cumsum((res-cummean)^2)/(1:N))
esterr <- estsd/sqrt(1:N)
ymax= max(res)
ymin=min(res)
if(displ){
plot(1:N, cummean, ylim=range(res), type="l", lwd=2)
polygon(c(1:N, N:1),
c(cummean+qnorm(0.9)*estsd,
rev(cummean-qnorm(0.9)*estsd)), col=gray(0.8))
lines(1:N, cummean, lwd=2)
}
if(known.par)
{
true <- excessProb.condit.nl ( par=true.par,
thres=thres
)
if(displ)
abline(h=true, col="red", lwd=2 )
}
else
true <- NULL
sorted <-
sort(res, decreasing=TRUE)
upquant <- sorted[ceiling(10/100*N)]
lowquant <- sorted[floor(90/100*N)]
if(displ){
abline(h=lowquant, col="blue", lwd=2)
abline(h=upquant, col="blue", lwd=2)
if(known.par)
{
legend("topright", legend=c("true", "posterior mean",
"posterior 0.1/0.9 quantiles",
"posterior 0.1/0.9 Gaussian quantiles" ),
lwd=c(2,2,2,3),
col=c("red", "black", "blue", gray(0.5))
)
}
else
{
legend("topright", legend=c( "posterior mean",
"posterior 0.1/0.9 quantiles",
"posterior 0.1/0.9 Gaussian quantiles" ),
lwd=c(2,2,4),
col=c( "black", "blue", gray(0.5))
)
}
}
return(list(whole=res, mean=cummean[N], esterr=esterr[N],
estsd=estsd[N],
lowquant= lowquant,
upquant=upquant,
true=true))
} |
get.taxa <- function (taxa, replace.synonyms = TRUE, suggest.names = TRUE,
life.form = FALSE, habitat = FALSE, vegetation.type = FALSE, vernacular = FALSE, states = FALSE,
establishment = FALSE, domain = FALSE, endemism = FALSE, drop = c("authorship", "genus", "specific.epiteth",
"infra.epiteth", "name.status"),
suggestion.distance = 0.9, parse = FALSE)
{
taxa <- trim(taxa)
taxa <- taxa[nzchar(taxa)]
if (length(taxa) == 0L)
stop("No valid names provided.")
original.search <- taxa
ncol.taxa <- ncol(all.taxa.accepted)
res <- data.frame(matrix(vector(), length(taxa), ncol.taxa +
1, dimnames = list(c(), c(names(all.taxa.accepted), "notes"))),
stringsAsFactors = FALSE)
minus.notes <- seq_len(ncol.taxa)
index <- 0
for (taxon in taxa) {
notes <- NULL
index <- index + 1
if (parse) {
url <- "http://api.gbif.org/v1/parser/name"
request <- try(POST(url, body = list(taxon), encode = "json"))
if (inherits(request, "try-error")) {
warning("Couldn't connect with the GBIF data servers. Check your internet connection or try again later.")
} else {
warn_for_status(request)
taxon <- content(request)[[1]]$canonicalName
}
}
taxon <- fixCase(taxon)
uncertain <- regmatches(taxon, regexpr("[a|c]f+\\.",
taxon))
if (length(uncertain) != 0L) {
taxon <- gsub("\\s[a|c]f+\\.", "", taxon)
}
ident <- regmatches(taxon, regexpr("\\s+sp\\.+\\w*",
taxon))
if (length(ident) != 0L) {
split.name <- unlist(strsplit(taxon, " "))
taxon <- split.name[1]
infra <- split.name[2]
}
found <- length(with(all.taxa.accepted, {
which(search.str == taxon)
})) > 0L
if (!found) {
found <- length(with(all.taxa.synonyms, {
which(search.str == taxon)
})) > 0L
}
if (!found) {
if (suggest.names) {
taxon <- suggest.names(taxon, max.distance = suggestion.distance)
}
else {
res[index, "notes"] <- "not found"
next
}
if (is.na(taxon)) {
res[index, "notes"] <- "not found"
next
}
else {
notes <- "was misspelled"
}
}
accepted <- all.taxa.accepted[with(all.taxa.accepted, {
which(search.str == taxon)
}), ]
if (nrow(accepted) > 0) {
if (nrow(accepted) == 1L) {
res[index, minus.notes] <- accepted
}
else {
notes <- c(notes, "check +1 accepted")
}
res[index, "notes"] <- paste(notes, collapse = "|")
if (length(ident) != 0L) res[index, "search.str"] <- paste(res[index, "search.str"], infra)
next
}
synonym <- all.taxa.synonyms[with(all.taxa.synonyms, {
which(search.str == taxon)
}), ]
nrow.synonym <- nrow(synonym)
if (nrow.synonym > 0L) {
if (replace.synonyms) {
related <- relationships[with(relationships, {which(related.id %in% synonym$id)}), ]
accepted <- all.taxa.accepted[with(all.taxa.accepted, {
which(id %in% related$id)
}), ]
nrow.accepted <- nrow(accepted)
if (nrow.accepted == 0L) {
if (nrow.synonym == 1L) {
notes <- c(notes, "check no accepted name")
res[index, minus.notes] <- synonym
}
if (nrow.synonym > 1L) {
notes <- c(notes, "check no accepted +1 synonyms")
}
}
if (nrow.accepted == 1L) {
notes <- c(notes, "replaced synonym")
res[index, minus.notes] <- accepted
}
if (nrow.accepted > 1L) {
notes <- c(notes, "check +1 accepted")
if (nrow.synonym == 1L) {
res[index, minus.notes] <- synonym
}
}
}
else {
if (nrow(synonym) == 1L) {
res[index, minus.notes] <- synonym
}
else {
notes <- c(notes, "check +1 entries")
}
}
res[index, "notes"] <- paste(notes, collapse = "|")
if (length(ident) != 0L) res[index, "search.str"] <- paste(res[index, "search.str"], infra)
next
}
undefined <- all.taxa.undefined[with(all.taxa.undefined, {
which(search.str == taxon)
}), ]
nrow.undefined <- nrow(undefined)
if (nrow.undefined == 0L) {
notes <- c(notes, "check undefined status")
}
if (nrow.undefined == 1L) {
notes <- c(notes, "check undefined status")
res[index, minus.notes] <- undefined
}
if (nrow.undefined > 1L) {
notes <- c(notes, "check undefined status")
}
res[index, "notes"] <- paste(notes, collapse = "|")
if (length(ident) != 0L) res[index, "search.str"] <- paste(taxa, infra)
}
if (is.null(drop)) {
res <- data.frame(res, original.search, stringsAsFactors = FALSE)
}
else {
res <- data.frame(res[, !names(res) %in% drop], original.search,
stringsAsFactors = FALSE)
}
if (life.form) {
res <- dplyr::left_join(res, species.profiles[, c("id", "life.form")],
by = "id")
}
if (habitat) {
res <- dplyr::left_join(res, species.profiles[, c("id", "habitat")],
by = "id")
}
if (vegetation.type) {
res <- dplyr::left_join(res, species.profiles[, c("id", "vegetation.type")],
by = "id")
}
if (vernacular) {
res <- dplyr::left_join(res, vernacular.names[, c("id", "vernacular.name")],
by = "id")
}
if (states) {
res <- dplyr::left_join(res, distribution[, c("id", "occurrence")],
by = "id")
}
if (establishment) {
res <- dplyr::left_join(res, distribution[, c("id", "establishment")],
by = "id")
}
if (domain) {
res <- dplyr::left_join(res, distribution[, c("id", "domain")],
by = "id")
}
if (endemism) {
res <- dplyr::left_join(res, distribution[, c("id", "endemism")],
by = "id")
}
res
} |
library(testthat)
library(CNAIM)
context("Future Probability of Failure for 10-20kV cable, PEX")
test_that("pof_future_cables_20_10_04kv", {
res <- pof_future_cables_20_10_04kv(hv_lv_cable_type = "10-20kV cable, PEX",
sub_division = "Aluminium sheath - Aluminium conductor",
utilisation_pct = 100,
operating_voltage_pct = 106,
sheath_test = "Default",
partial_discharge = "Default",
fault_hist = "Default",
reliability_factor = "Default",
age = 30,
simulation_end_year = 100)
expect_equal(res$PoF[which(res$year == 65)], 0.029754193)
}) |
moead <- function(preset = NULL,
problem = NULL,
decomp = NULL,
aggfun = NULL,
neighbors = NULL,
variation = NULL,
update = NULL,
constraint = NULL,
scaling = NULL,
stopcrit = NULL,
showpars = NULL,
seed = NULL,
...)
{
moead.input.pars <- as.list(sys.call())[-1]
if ("save.env" %in% names(moead.input.pars)) {
if (moead.input.pars$save.env == TRUE) saveRDS(as.list(environment()),
"moead_env.rds")
}
if (!is.null(preset)) {
if (is.null(problem)) problem = preset$problem
if (is.null(decomp)) decomp = preset$decomp
if (is.null(aggfun)) aggfun = preset$aggfun
if (is.null(neighbors)) neighbors = preset$neighbors
if (is.null(variation)) variation = preset$variation
if (is.null(update)) update = preset$update
if (is.null(scaling)) scaling = preset$scaling
if (is.null(stopcrit)) stopcrit = preset$stopcrit
}
if (is.null(seed)) {
if (!exists(".Random.seed")) stats::runif(1)
seed <- .Random.seed
} else {
assertthat::assert_that(assertthat::is.count(seed))
set.seed(seed)
}
nfe <- 0
time.start <- Sys.time()
iter.times <- numeric(10000)
if(is.null(update$UseArchive)){
update$UseArchive <- FALSE
}
W <- generate_weights(decomp = decomp,
m = problem$m)
X <- create_population(N = nrow(W),
problem = problem)
YV <- evaluate_population(X = X,
problem = problem,
nfe = nfe)
Y <- YV$Y
V <- YV$V
nfe <- YV$nfe
keep.running <- TRUE
iter <- 0
while(keep.running){
iter <- iter + 1
if ("save.iters" %in% names(moead.input.pars)) {
if (moead.input.pars$save.iters == TRUE) saveRDS(as.list(environment()),
"moead_env.rds")
}
BP <- define_neighborhood(neighbors = neighbors,
v.matrix = switch(neighbors$name,
lambda = W,
x = X),
iter = iter)
B <- BP$B
P <- BP$P
Xt <- X
Yt <- Y
Vt <- V
Xv <- do.call(perform_variation,
args = as.list(environment()))
X <- Xv$X
ls.args <- Xv$ls.args
nfe <- nfe + Xv$var.nfe
YV <- evaluate_population(X = X,
problem = problem,
nfe = nfe)
Y <- YV$Y
V <- YV$V
nfe <- YV$nfe
normYs <- scale_objectives(Y = Y,
Yt = Yt,
scaling = scaling)
bigZ <- scalarize_values(normYs = normYs,
W = W,
B = B,
aggfun = aggfun)
sel.indx <- order_neighborhood(bigZ = bigZ,
B = B,
V = V,
Vt = Vt,
constraint = constraint)
XY <- do.call(update_population,
args = as.list(environment()))
X <- XY$X
Y <- XY$Y
V <- XY$V
Archive <- XY$Archive
elapsed.time <- as.numeric(difftime(time1 = Sys.time(),
time2 = time.start,
units = "secs"))
iter.times[iter] <- ifelse(iter == 1,
yes = as.numeric(elapsed.time),
no = as.numeric(elapsed.time) - sum(iter.times))
keep.running <- check_stop_criteria(stopcrit = stopcrit,
call.env = environment())
print_progress(iter.times, showpars)
}
X <- denormalize_population(X, problem)
colnames(Y) <- paste0("f", 1:ncol(Y))
colnames(W) <- paste0("f", 1:ncol(W))
if(!is.null(Archive)) {
Archive$X <- denormalize_population(Archive$X, problem)
colnames(Archive$Y) <- paste0("f", 1:ncol(Archive$Y))
Archive$W <- W
colnames(Archive$W) <- paste0("f", 1:ncol(Archive$W))
}
out <- list(X = X,
Y = Y,
V = V,
W = W,
Archive = Archive,
ideal = apply(Y, 2, min),
nadir = apply(Y, 2, max),
nfe = nfe,
n.iter = iter,
time = difftime(Sys.time(), time.start, units = "secs"),
seed = seed,
inputConfig = moead.input.pars)
class(out) <- c("moead", "list")
return(out)
} |
define_signif_tumor_subclusters_via_random_smooothed_trees <- function(infercnv_obj, p_val, hclust_method, cluster_by_groups, window_size=101,
max_recursion_depth=3, min_cluster_size_recurse=10) {
infercnv_copy = infercnv_obj
flog.info(sprintf("define_signif_tumor_subclusters(p_val=%g", p_val))
infercnv_obj <- subtract_ref_expr_from_obs(infercnv_obj, inv_log=TRUE)
tumor_groups = list()
if (cluster_by_groups) {
tumor_groups <- c(infercnv_obj@observation_grouped_cell_indices, infercnv_obj@reference_grouped_cell_indices)
}
else {
tumor_groups <- c(list(all_observations=unlist(infercnv_obj@observation_grouped_cell_indices, use.names=FALSE)), infercnv_obj@reference_grouped_cell_indices)
}
res = list()
for (tumor_group in names(tumor_groups)) {
flog.info(sprintf("define_signif_tumor_subclusters(), tumor: %s", tumor_group))
tumor_group_idx <- tumor_groups[[ tumor_group ]]
names(tumor_group_idx) = colnames([email protected])[tumor_group_idx]
tumor_expr_data <- [email protected][,tumor_group_idx]
tumor_subcluster_info <- .single_tumor_subclustering_smoothed_tree(tumor_group, tumor_group_idx, tumor_expr_data, p_val, hclust_method, window_size,
max_recursion_depth, min_cluster_size_recurse)
res$hc[[tumor_group]] <- tumor_subcluster_info$hc
res$subclusters[[tumor_group]] <- tumor_subcluster_info$subclusters
}
infercnv_copy@tumor_subclusters <- res
if (! is.null([email protected])) {
flog.info("-mirroring for hspike")
[email protected] <- define_signif_tumor_subclusters_via_random_smooothed_trees([email protected], p_val, hclust_method,
window_size, max_recursion_depth, min_cluster_size_recurse)
}
return(infercnv_copy)
}
.single_tumor_subclustering_smoothed_tree <- function(tumor_name, tumor_group_idx, tumor_expr_data, p_val, hclust_method, window_size,
max_recursion_depth, min_cluster_size_recurse) {
tumor_subcluster_info = list()
sm_tumor_expr_data = apply(tumor_expr_data, 2, caTools::runmean, k=window_size)
sm_tumor_expr_data = .center_columns(sm_tumor_expr_data, 'median')
hc <- hclust(parallelDist(t(sm_tumor_expr_data), threads=infercnv.env$GLOBAL_NUM_THREADS), method=hclust_method)
tumor_subcluster_info$hc = hc
heights = hc$height
grps <- .partition_by_random_smoothed_trees(tumor_name, tumor_expr_data, hclust_method, p_val, window_size,
max_recursion_depth, min_cluster_size_recurse)
tumor_subcluster_info$subclusters = list()
ordered_idx = tumor_group_idx[hc$order]
s = split(grps,grps)
flog.info(sprintf("cut tree into: %g groups", length(s)))
start_idx = 1
for (split_subcluster in names(s)) {
flog.info(sprintf("-processing %s,%s", tumor_name, split_subcluster))
split_subcluster_cell_names = names(s[[split_subcluster]])
if (! all(split_subcluster_cell_names %in% names(tumor_group_idx)) ) {
stop("Error: .single_tumor_subclustering_smoothed_tree(), not all subcluster cell names were in the tumor group names")
}
subcluster_indices = tumor_group_idx[ which(names(tumor_group_idx) %in% split_subcluster_cell_names) ]
tumor_subcluster_info$subclusters[[ split_subcluster ]] = subcluster_indices
}
return(tumor_subcluster_info)
}
.partition_by_random_smoothed_trees <- function(tumor_name, tumor_expr_data, hclust_method, p_val, window_size,
max_recursion_depth, min_cluster_size_recurse) {
grps <- rep(sprintf("%s.%d", tumor_name, 1), ncol(tumor_expr_data))
names(grps) <- colnames(tumor_expr_data)
grps <- .single_tumor_subclustering_recursive_random_smoothed_trees(tumor_expr_data, hclust_method, p_val, grps, window_size,
max_recursion_depth, min_cluster_size_recurse)
return(grps)
}
.single_tumor_subclustering_recursive_random_smoothed_trees <- function(tumor_expr_data, hclust_method, p_val, grps.adj, window_size,
max_recursion_depth,
min_cluster_size_recurse,
recursion_depth=1) {
if (recursion_depth > max_recursion_depth) {
flog.warn("-not exceeding max recursion depth.")
return(grps.adj)
}
tumor_clade_name = unique(grps.adj[names(grps.adj) %in% colnames(tumor_expr_data)])
message("unique tumor clade name: ", tumor_clade_name)
if (length(tumor_clade_name) > 1) {
stop("Error, found too many names in current clade")
}
rand_params_info = .parameterize_random_cluster_heights_smoothed_trees(tumor_expr_data, hclust_method, window_size)
h_obs = rand_params_info$h_obs
h = h_obs$height
max_height = rand_params_info$max_h
max_height_pval = 1
if (max_height > 0) {
e = rand_params_info$ecdf
max_height_pval = 1- e(max_height)
}
if (max_height_pval <= p_val) {
cut_height = mean(c(h[length(h)], h[length(h)-1]))
flog.info(sprintf("cutting at height: %g", cut_height))
grps = cutree(h_obs, h=cut_height)
print(grps)
uniqgrps = unique(grps)
message("unique grps: ", paste0(uniqgrps, sep=",", collapse=","))
if (all(sapply(uniqgrps, function(grp) {
(sum(grps==grp) < min_cluster_size_recurse)
} ))) {
flog.warn("none of the split subclusters exceed min cluster size. Not recursing here.")
return(grps.adj)
}
for (grp in uniqgrps) {
grp_idx = which(grps==grp)
message(sprintf("grp: %s contains idx: %s", grp, paste(grp_idx,sep=",", collapse=",")))
df = tumor_expr_data[,grp_idx,drop=FALSE]
subset_cell_names = colnames(df)
subset_clade_name = sprintf("%s.%d", tumor_clade_name, grp)
message(sprintf("subset_clade_name: %s", subset_clade_name));
grps.adj[names(grps.adj) %in% subset_cell_names] <- subset_clade_name
if (length(grp_idx) >= min_cluster_size_recurse) {
grps.adj <- .single_tumor_subclustering_recursive_random_smoothed_trees(tumor_expr_data=df,
hclust_method=hclust_method,
p_val=p_val,
grps.adj=grps.adj,
window_size=window_size,
max_recursion_depth=max_recursion_depth,
min_cluster_size_recurse=min_cluster_size_recurse,
recursion_depth = recursion_depth + 1 )
} else {
flog.warn(sprintf("%s size of %d is too small to recurse on", subset_clade_name, length(grp_idx)))
}
}
} else {
message("No cluster pruning: ", tumor_clade_name)
}
return(grps.adj)
}
.parameterize_random_cluster_heights_smoothed_trees <- function(expr_matrix, hclust_method, window_size, plot=FALSE) {
sm_expr_data = apply(expr_matrix, 2, caTools::runmean, k=window_size)
sm_expr_data = .center_columns(sm_expr_data, 'median')
d = parallelDist(t(sm_expr_data), threads=infercnv.env$GLOBAL_NUM_THREADS)
h_obs = hclust(d, method=hclust_method)
permute_col_vals <- function(df) {
num_cells = nrow(df)
for (i in seq(ncol(df) ) ) {
df[, i] = df[sample(x=seq_len(num_cells), size=num_cells, replace=FALSE), i]
}
df
}
flog.info(sprintf("random trees, using %g parallel threads", infercnv.env$GLOBAL_NUM_THREADS))
if (infercnv.env$GLOBAL_NUM_THREADS > future::availableCores()) {
flog.warn(sprintf("not enough cores available, setting to num avail cores: %g", future::availableCores()))
infercnv.env$GLOBAL_NUM_THREADS <- future::availableCores()
}
registerDoParallel(cores=infercnv.env$GLOBAL_NUM_THREADS)
num_rand_iters=100
max_rand_heights <- foreach (i=seq_len(num_rand_iters)) %dopar% {
rand.tumor.expr.data = t(permute_col_vals( t(expr_matrix) ))
sm.rand.tumor.expr.data = apply(rand.tumor.expr.data, 2, caTools::runmean, k=window_size)
sm.rand.tumor.expr.data = .center_columns(sm.rand.tumor.expr.data, 'median')
rand.dist = parallelDist(t(sm.rand.tumor.expr.data), threads=infercnv.env$GLOBAL_NUM_THREADS)
h_rand <- hclust(rand.dist, method=hclust_method)
max_rand_height <- max(h_rand$height)
max_rand_height
}
max_rand_heights <- as.numeric(max_rand_heights)
h = h_obs$height
max_height = max(h)
message(sprintf("Lengths for original tree branches (h): %s", paste(h, sep=",", collapse=",")))
message(sprintf("Max height: %g", max_height))
message(sprintf("Lengths for max heights: %s", paste(max_rand_heights, sep=",", collapse=",")))
e = ecdf(max_rand_heights)
pval = 1- e(max_height)
message(sprintf("pval: %g", pval))
params_list <- list(h_obs=h_obs,
max_h=max_height,
rand_max_height_dist=max_rand_heights,
ecdf=e
)
if (plot) {
.plot_tree_height_dist(params_list)
}
return(params_list)
}
.plot_tree_height_dist <- function(params_list, plot_title='tree_heights') {
mf = par(mfrow=(c(2,1)))
rand_height_density = density(params_list$rand_max_height_dist)
xlim=range(params_list$max_h, rand_height_density$x)
ylim=range(rand_height_density$y)
plot(rand_height_density, xlim=xlim, ylim=ylim, main=paste(plot_title, "density"))
abline(v=params_list$max_h, col='red')
h_obs = params_list$h_obs
h_obs$labels <- NULL
plot(h_obs)
par(mf)
}
.get_tree_height_via_ecdf <- function(p_val, params_list) {
h = quantile(params_list$ecdf, probs=1-p_val)
return(h)
}
find_DE_stat_significance <- function(normal_matrix, tumor_matrix) {
run_t_test<- function(idx) {
vals1 = unlist(normal_matrix[idx,,drop=TRUE])
vals2 = unlist(tumor_matrix[idx,,drop=TRUE])
res = try(t.test(vals1, vals2), silent=TRUE)
if (is(res, "try-error")) return(NA) else return(res$p.value)
}
pvals = sapply(seq(nrow(normal_matrix)), run_t_test)
return(pvals)
} |
context("Checking syllable_sum")
test_that("syllable_count, gives the desired output",{
x1 <- syllable_count("Robots like Dason lie.")
x2 <- syllable_count("Robots like Dason lie.", algorithm.report = TRUE)
x1_c <- structure(list(words = c("robots", "like", "dason", "lie"), syllables = c(2,
1, 2, 1), in.dictionary = c("-", "-", "NF", "-")), class = "data.frame", row.names = c(NA,
-4L))
x2_c <- list(`ALGORITHM REPORT` = structure(list(words = "dason", syllables = 2,
in.dictionary = "NF"), row.names = 3L, class = "data.frame"),
`SYLLABLE DATAFRAME` = structure(list(words = c("robots",
"like", "dason", "lie"), syllables = c(2, 1, 2, 1), in.dictionary = c("-",
"-", "NF", "-")), class = "data.frame", row.names = c(NA,
-4L)))
expect_equivalent(x1, x1_c)
expect_equivalent(x2, x2_c)
})
test_that("syllable_sum, gives the desired output",{
x3 <- syllable_sum(DATA$state)
x3_c <- structure(c(8, 5, 4, 5, 6, 6, 4, 4, 7, 6, 9), class = c("syllable_sum",
"syllable_freq", "numeric"), wc = c(6L, 5L, 4L, 4L, 5L, 5L, 4L,
3L, 5L, 6L, 6L), type = "Syllable")
expect_true(all(x3 == x3_c))
})
test_that("polysyllable_sum, gives the desired output",{
x4 <- polysyllable_sum(DATA$state)
x4_c <- structure(c(1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L),
class = c("polysyllable_sum", "syllable_freq", "integer"),
wc = c(6L, 5L, 4L, 4L, 5L, 5L, 4L, 3L, 5L, 6L, 6L),
type = "Pollysyllable")
expect_true(all(x4 == x4_c))
})
test_that("combo_syllable_sum, gives the desired output",{
x5 <- combo_syllable_sum(DATA$state)
x5_c <- structure(list(syllable.count = c(8, 5, 4, 5, 6, 6, 4, 4, 7,
6, 9), polysyllable.count = c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
)), .Names = c("syllable.count", "polysyllable.count"), row.names = c(NA,
11L), class = c("combo_syllable_sum", "data.frame"), text.var = c("Computer is fun. Not too fun.",
"No it's not, it's dumb.", "What should we do?", "You liar, it stinks!",
"I am telling the truth!", "How can we be certain?", "There is no way.",
"I distrust you.", "What are you talking about?", "Shall we move on? Good then.",
"I'm hungry. Let's eat. You already?"), wc = c(6L, 5L, 4L,
4L, 5L, 5L, 4L, 3L, 5L, 6L, 6L))
expect_equivalent(x5, x5_c)
})
test_that("cumulative methods for syllable_freq, gives the desired output",{
x3_cum <- cumulative(syllable_sum(DATA$state))
x4_cum <- cumulative(polysyllable_sum(DATA$state) )
expect_true(is.data.frame(x3_cum))
expect_true(all(colnames(x3_cum) == c("cumave", "Time")))
expect_true(is.data.frame(x4_cum))
expect_true(all(colnames(x4_cum) == c("cumave", "Time")))
}) |
data_biplot <-
function(X,sX=TRUE,axeh=1,axev=2,cex.lab=1) {
X<- scale(X, center=T, scale=sX)
p <- dim(X)[2]
n <- dim(X)[1]
A<-max(axeh,axev)
if (n<p) {
reseig<-eigen(X%*%t(X)/n)
valp<-100*reseig$values[1:A]/sum(reseig$values)
coordvar<-t(X)%*%reseig$vectors[,1:A]/sqrt(n)
coordind<-reseig$vectors[,1:A]%*%diag(sqrt(reseig$values[1:A]))
} else {
reseig<-eigen(t(X)%*%X/(n))
valp<-100*reseig$values[1:A]/sum(reseig$values)
coordvar<-reseig$vectors[,1:A]%*%diag(sqrt(reseig$values[1:A]))
coordind<-X%*%reseig$vectors[,1:A]/sqrt(n)
}
for (a in 1:A) {
if (sign(mean(coordvar[,a]))==(-1)) {
coordvar[,a]=coordvar[,a]*(-1)
coordind[,a]=coordind[,a]*(-1)
}
}
par(pty="s")
vp<-(coordind[,axeh]^2+coordind[,axev]^2)
lp=max(vp)
vv<-(coordvar[,axeh]^2+coordvar[,axev]^2)
lv=max(vv)
f=sqrt(lp/lv)
plot(c(coordvar[,axeh]*f,coordind[,axeh]),c(coordvar[,axev]*f,coordind[,axev]),type="n",
xlab=paste("Dim ",axeh,"(",round(valp[axeh],2),"%)"),
ylab=paste("Dim ",axev,"(",round(valp[axev],2),"%)"),
main="PCA biplot")
arrows(0,0,coordvar[,axeh]*f,coordvar[,axev]*f,length=0.1,angle=10,lwd=0.5,col="gray")
posi=rep(1,n)
posi[which(coordind[,axeh]>max(c(coordvar[,axeh]*f,coordind[,axeh]))*0.8)]=2
posi[which(coordind[,axeh]<min(c(coordvar[,axeh]*f,coordind[,axeh]))*0.8)]=4
posi[which(coordind[,axev]>max(c(coordvar[,axev]*f,coordind[,axev]))*0.8)]=1
posi[which(coordind[,axev]<min(c(coordvar[,axev]*f,coordind[,axev]))*0.8)]=3
text(coordind[,axeh],coordind[,axev],labels=rownames(X),pos=posi,cex=cex.lab)
abline(h=0,v=0)
par(pty="m")
} |
require(OpenMx)
require(numDeriv)
set.seed(1)
mat1 <- mxMatrix("Full", rnorm(1), free=TRUE, nrow=1, ncol=1, labels="m1", name="mat1")
mu <- 0
sigma <- 2
Scale <- -2
obj <- mxAlgebra(Scale * -.5 * (log(2*pi) + log(sigma) + (mat1[1,1] - mu)^2/sigma), name = "obj")
grad <- mxAlgebra(Scale * -(mat1[1,1] - mu)/sigma, name = "grad", dimnames=list("m1", NULL))
hess <- mxAlgebra(Scale * -1/sigma, name = "hess", dimnames=list("m1", "m1"))
model2 <- mxModel("model2", mat1, obj, grad, hess,
mxFitFunctionAlgebra("obj"))
omxCheckError(mxRun(mxModel(model2, mxComputeOnce('fitfunction', 'hessian')), silent=TRUE),
"Hessian requested but not available")
model1 <- mxModel("model1", mat1, obj, grad, hess,
mxFitFunctionAlgebra("obj", gradient="grad", hessian="hess"),
mxComputeSequence(list(
mxComputeOnce('fitfunction', c('fit', 'gradient', 'hessian', 'ihessian')),
mxComputeReportDeriv()
)))
got <- omxCheckWarning(mxRun(model1, silent=TRUE, useOptimizer=FALSE),
"mxRun(..., useOptimizer=FALSE) ignored due to custom compute plan")
omxCheckCloseEnough(got$output$fit, -2 * log(dnorm(got$output$estimate, sd=sqrt(sigma))), 1e-4)
omxCheckCloseEnough(got$output$gradient, 2*(mat1$values[1]-mu)/sigma, 1e-4)
omxCheckCloseEnough(got$output$hessian, 2/sigma)
omxCheckCloseEnough(got$output$ihessian, sigma/2)
numer <- mxModel(model1, mxComputeSequence(list(
mxComputeNumericDeriv(checkGradient = FALSE),
mxComputeReportDeriv())))
got <- mxRun(numer, silent=TRUE)
omxCheckCloseEnough(got$output$hessian, 1, 1e-3)
model3 <- mxModel(model1, mxComputeNewtonRaphson())
model3 <- mxRun(model3, silent=TRUE)
omxCheckCloseEnough(model3$output$estimate, 0, 1e-4)
omxCheckCloseEnough(model3$output$status$code, 0)
omxCheckCloseEnough(model3$output$iterations, 2L)
model3 <- mxModel(model3, mxComputeSequence(list(
mxComputeOnce('fitfunction', 'information', 'hessian'),
mxComputeReportDeriv())))
model3 <- mxRun(model3)
omxCheckCloseEnough(model3$output$hessian, 1, 1e-3)
mat1 <- mxMatrix("Full", rnorm(1), free=TRUE, nrow=1, ncol=1, labels="m1", name="mat1")
obj <- mxAlgebra(abs(mat1) + mat1^2, name = "obj")
grad <- mxAlgebra(mat1/abs(mat1) + 2 * mat1, name = "grad", dimnames=list("m1", NULL))
hess <- mxAlgebra(2, name = "hess", dimnames=list("m1", "m1"))
code6 <- mxModel("code6", mat1, obj, grad, hess,
mxFitFunctionAlgebra("obj", gradient="grad", hessian="hess"))
m1 <- mxRun(mxModel(code6, mxComputeSequence(list(
mxComputeNumericDeriv(checkGradient=FALSE),
mxComputeReportDeriv()
))))
m2 <- mxRun(mxModel(code6, mxComputeSequence(list(
mxComputeOnce('fitfunction', c('fit','gradient','hessian')),
mxComputeReportDeriv()
))))
omxCheckCloseEnough(c(m1$output$gradient), c(m2$output$gradient), 1e-6)
omxCheckCloseEnough(c(m1$output$hessian), c(m2$output$hessian), 1e-5)
code6 <- mxRun(mxModel(code6, mxComputeSequence(list(
mxComputeNewtonRaphson(),
mxComputeReportDeriv()
))), suppressWarnings = TRUE)
omxCheckEquals(code6$output$status$code, 6)
omxCheckCloseEnough(code6$output$estimate, 0, 1e-6)
omxCheckCloseEnough(abs(code6$output$gradient), 1, 1e-6)
mat2 <- mxMatrix("Full", c(50,50), free=TRUE, nrow=2, ncol=1, labels=paste("x",1:2,sep=""), name="x")
obj <- mxAlgebra(x[1,1]^2 + x[2,1]^2 + sin(x[1,1]+x[2,1]) + x[1,1] - x[2,1], name = "obj")
grad <- mxAlgebra(rbind(2*cos(2*x[1,1]+x[2,1])+2*x[1,1]+1,
cos(2*x[1,1]+x[2,1])+4*x[2,1]-1),
dimnames=list(paste("x",1:2,sep=""),c()), name = "grad")
hess <- mxAlgebra(rbind(cbind(2-4*sin(2*x[1,1]+x[2,1]), -2*sin(2*x[1,1]+x[2,1])),
cbind(-2*sin(2*x[1,1]+x[2,1]), 4-sin(2*x[1,1]+x[2,1]))), name = "hess",
dimnames=list(paste("x",1:2,sep=""), paste("x",1:2,sep="")))
mv1 <- mxModel("mv1", mat2, obj, grad, hess,
mxFitFunctionAlgebra("obj", gradient="grad", hessian="hess"),
mxComputeSequence(list(
mxComputeOnce('fitfunction', c('gradient', 'hessian', 'ihessian')),
mxComputeReportDeriv())))
mv1.fit <- mxRun(mv1, silent=TRUE)
omxCheckCloseEnough(mv1.fit$output$gradient, c(102.4, 199.7), .1)
omxCheckCloseEnough(c(mv1.fit$output$hessian), c(4.86, 1.43, 1.43, 4.71), .01)
omxCheckCloseEnough(mv1.fit$output$hessian, solve(mv1.fit$output$ihessian), 1e-2)
mv2 <- mxModel(mv1, mxComputeNewtonRaphson())
mv2.fit <- mxRun(mv2, silent=TRUE, suppressWarnings = TRUE)
omxCheckEquals(mv2.fit$output$status$code, 6)
omxCheckCloseEnough(mv2.fit$output$estimate, rep(0, 2), 1) |
add_extra_to_libpath <- function() {
extra_lib <- file.path(get_wspace_dir(), basename(tempfile()))
original_libPaths <- .libPaths()
dir.create(extra_lib, recursive = T)
.libPaths(c(original_libPaths, extra_lib))
on_test_exit(function() {
.libPaths(original_libPaths)
unlink(extra_lib, recursive = T, force = T)
})
new_libPaths <- .libPaths()
stopifnot(extra_lib %in% new_libPaths)
return(new_libPaths)
} |
P5c <- function(a, X) {
x <- .GlobalEnv$x
y <- .GlobalEnv$y
if (missing(X)) {
if (length(a) == 1) {
list(Pn = 5L, Mod = "P5c")
} else {
Yest <- a[1] + a[2] * exp(-x / a[3]) + a[4] * (x - a[5]) * H(x, 10, a[5])
sum((y - Yest) ^ 2)
}
} else {
a[1] + a[2] * exp(-X / a[3]) + a[4] * (X - a[5]) * H(X, 10, a[5])
}
} |
wild.boot <- function(x, design = "fixed", distr = "rademacher", n.ahead = 20,
nboot = 500, nc = 1, dd = NULL, signrest = NULL, signcheck = TRUE, itermax = 300,
steptol = 200, iter2 = 50, rademacher = "deprecated"){
if(x$method == "Cramer-von Mises distance" & is.null(dd)){
dd <- copula::indepTestSim(x$n, x$K, verbose=F)
}
sqrt.f <- function(Pstar, Sigma_u_star){
yy <- suppressMessages(sqrtm(Sigma_u_hat_old))%*%solve(suppressMessages(sqrtm(Sigma_u_star)))%*%Pstar
return(yy)
}
if(!inherits(x$y, c("matrix", "ts"))){
y = as.matrix(x$y)
}else{
y <- x$y
}
p <- x$p
obs <- x$n
k <- x$K
B <- x$B
restriction_matrix = x$restriction_matrix
restriction_matrix <- get_restriction_matrix(restriction_matrix, k)
restrictions <- length(restriction_matrix[!is.na(restriction_matrix)])
if(length(signrest) > k){
stop('too many sign restrictions')
}
A <- x$A_hat
Z <- t(YLagCr(y, p))
if(x$type == 'const'){
Z <- rbind(rep(1, ncol(Z)), Z)
}else if(x$type == 'trend'){
Z <- rbind(seq(p + 1, ncol(Z)+ p), Z)
}else if(x$type == 'both'){
Z <- rbind(rep(1, ncol(Z)), seq(p + 1, ncol(Z) + p), Z)
}else{
Z <- Z
}
u <- t(y[-c(1:p),]) - A %*% Z
Sigma_u_hat_old <- tcrossprod(u)/(obs - 1 - k * p)
ub <- u
errors <- list()
if(rademacher != "deprecated"){
if(rademacher == "TRUE"){
warning("The argument 'rademacher' is deprecated and may not be supported in the future. Please use the argument 'distr' to decide upon a distribution.",
call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL)
} else if(rademacher == "FALSE"){
distr <- "gaussian"
warning("The argument 'rademacher' is deprecated and may not be supported in the future. Please use the argument 'distr' to decide upon a distribution.",
call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL)
} else{
warning("Invalid use of deprecated argument 'rademacher'. Please use the argument 'distr' to decide upon a distribution!",
call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL)
}
}
for(i in 1:nboot){
ub <- u
if (distr == "rademacher") {
my <- rnorm(n = ncol(u))
my <- (my > 0) - (my < 0)
} else if (distr == "mammen") {
cu <- (sqrt(5)+1)/(2*sqrt(5))
my <- rep(1,ncol(u))*(-(sqrt(5)-1)/2)
uni <- runif(n = ncol(u), min = 0, max = 1)
my[uni > cu] <- (sqrt(5)+1)/2
} else if (distr == "gaussian") {
my <- rnorm(n = ncol(u))
}
errors[[i]] <- ub* my
}
bootf <- function(Ustar1){
if(design == "fixed"){
Ystar <- t(A %*% Z + Ustar1)
Bstar <- t(Ystar) %*% t(Z) %*% solve(Z %*% t(Z))
Ustar <- Ystar - t(Bstar %*% Z)
Sigma_u_star <- crossprod(Ustar)/(ncol(Ustar1) - 1 - k * p)
varb <- list(y = Ystar,
coef_x = Bstar,
residuals = Ustar,
p = p,
type = x$type)
class(varb) <- 'var.boot'
if(x$method == "Non-Gaussian maximum likelihood"){
temp <- id.ngml_boot(varb, stage3 = x$stage3, Z = Z, restriction_matrix = x$restriction_matrix)
}else if(x$method == "Changes in Volatility"){
temp <- tryCatch(id.cv_boot(varb, SB = x$SB, SB2 = x$SB2, Z = Z, restriction_matrix = x$restriction_matrix),
error = function(e) NULL)
}else if(x$method == "Cramer-von Mises distance"){
temp <- id.cvm(varb, itermax = itermax, steptol = steptol, iter2 = iter2, dd)
}else if(x$method == "Distance covariances"){
temp <- id.dc(varb, PIT=x$PIT)
}else if(x$method == "GARCH"){
temp <- tryCatch(id.garch(varb, restriction_matrix = x$restriction_matrix, max.iter = x$max.iter,
crit = x$crit),
error = function(e) NULL)
}else if(x$method == "Cholesky"){
temp <- id.chol(varb, order_k = x$order_k)
}else{
temp <- tryCatch(id.st_boot(varb, c_fix = x$est_c, transition_variable = x$transition_variable, restriction_matrix = x$restriction_matrix,
gamma_fix = x$est_g, max.iter = x$iteration, crit = 0.01, Z = Z),
error = function(e) NULL)
}
} else if (design == "recursive") {
Ystar <- matrix(0, nrow(y), k)
Ystar[1:p,] <- y[1:p,]
if (x$type == 'const' | x$type == 'trend') {
for (i in (p + 1):nrow(y)) {
for (j in 1:k) {
Ystar[i, j] <- A[j, 1] + A[j, -1] %*% c(t(Ystar[(i - 1):(i - p), ])) + Ustar1[j, (i - p)]
}
}
} else if (x$type == 'both') {
for (i in (p + 1):nrow(y)) {
for (j in 1:k) {
Ystar[i, j] <- A[j, 1] + A[j, 2] + A[j, -c(1, 2)] %*% c(t(Ystar[(i - 1):(i - p),])) + Ustar1[j, (i - p)]
}
}
}else if (x$type == 'none') {
for (i in (p + 1):nrow(y)) {
for (j in 1:k) {
Ystar[i, j] <- A[j, ] %*% c(t(Ystar[(i - 1):(i - p), ])) + Ustar1[j, (i - p)]
}
}
}
Ystar <- Ystar[-c(1:p), ]
varb <- suppressWarnings(VAR(Ystar, p = x$p, type = x$type))
Ustar <- residuals(varb)
Sigma_u_star <- crossprod(Ustar)/(obs - 1 - k * p)
if(x$method == "Non-Gaussian maximum likelihood"){
temp <- id.ngml_boot(varb, stage3 = x$stage3, restriction_matrix = x$restriction_matrix)
}else if(x$method == "Changes in Volatility"){
if (length(x$SB) > 3) {
SB <- x$SB[-c(1:p)]
} else {
SB <- x$SB
}
temp <- tryCatch(id.cv_boot(varb, SB = SB, SB2 = x$SB2, restriction_matrix = x$restriction_matrix),
error = function(e) NULL)
}else if(x$method == "Cramer-von Mises distance"){
temp <- id.cvm(varb, itermax = itermax, steptol = steptol, iter2 = iter2, dd)
}else if(x$method == "Distance covariances"){
temp <- id.dc(varb, PIT=x$PIT)
}else if(x$method == "Smooth transition"){
temp <- id.st(varb, c_fix = x$est_c, transition_variable = x$transition_variable, restriction_matrix = x$restriction_matrix,
gamma_fix = x$est_g, max.iter = x$iteration, crit = 0.01)
}else if(x$method == "GARCH"){
temp <- tryCatch(id.garch(varb, restriction_matrix = x$restriction_matrix, max.iter = x$max.iter,
crit = x$crit),
error = function(e) NULL)
}else if(x$method == "Cholesky"){
temp <- id.chol(varb, order_k = x$order_k)
}
}
if(!is.null(temp)){
Pstar <- temp$B
if (x$method != "Cholesky") {
if(!is.null(x$restriction_matrix)){
Pstar1 <- Pstar
frobP <- frobICA_mod(Pstar1, B, standardize=TRUE)
}else{
Pstar1 <- sqrt.f(Pstar, Sigma_u_star)
diag_sigma_root <- diag(diag(suppressMessages(sqrtm(Sigma_u_hat_old))))
frobP <- frobICA_mod(t(solve(diag_sigma_root)%*%Pstar1), t(solve(diag_sigma_root)%*%B), standardize=TRUE)
}
Pstar <- Pstar1%*%frobP$perm
temp$B <- Pstar
}
ip <- irf(temp, n.ahead = n.ahead)
return(list(ip, Pstar, temp$A_hat))
}else{
return(NA)
}
}
bootstraps <- pblapply(errors, bootf, cl = nc)
delnull <- function(x){
x[unlist(lapply(x, length) != 0)]
}
bootstraps <- lapply(bootstraps, function (x)x[any(!is.na(x))])
bootstraps <- delnull(bootstraps)
Bs <- array(0, c(k,k,length(bootstraps)))
ipb <- list()
Aboot <- array(0, c(nrow(A), ncol(A),length(bootstraps)))
for(i in 1:length(bootstraps)){
Bs[,,i] <- bootstraps[[i]][[2]]
ipb[[i]] <- bootstraps[[i]][[1]]
Aboot[, , i] <- bootstraps[[i]][[3]]
}
A_hat_boot <- matrix(Aboot, ncol = nrow(A)*ncol(A), byrow = TRUE)
A_hat_boot_mean <- matrix(colMeans(A_hat_boot), nrow(A), ncol(A))
v.b <- matrix(Bs, ncol = k^2, byrow = TRUE)
cov.bs <- cov(v.b)
SE <- matrix(sqrt(diag(cov.bs)),k,k)
rownames(SE) <- rownames(x$B)
boot.mean <- matrix(colMeans(v.b),k,k)
rownames(boot.mean) <- rownames(x$B)
if (signcheck == TRUE) {
if(restrictions > 0 | x$method == 'Cholesky'){
if(!is.null(signrest)){
cat('Testing signs only possible for unrestricted model \n')
}
sign.part <- NULL
sign.complete <- NULL
}else{
if(is.null(signrest)){
sign.mat <- matrix(FALSE, nrow = k, ncol = k)
sign.complete <- 0
sign.part <- rep(0, times = k)
for(i in 1:length(bootstraps)){
pBs <- permutation(Bs[,,i])
sign.mat <-lapply(pBs, function(z){sapply(1:k, function(ii){all(z[,ii]/abs(z[,ii]) == x$B[,ii]/abs(x$B[,ii])) | all(z[,ii]/abs(z[,ii]) == x$B[,ii]/abs(x$B[,ii])*(-1))})})
if(any(unlist(lapply(sign.mat, function(sign.mat)all(sign.mat == TRUE))))){
sign.complete <- sign.complete + 1
}
for(j in 1:k){
check <- rep(FALSE, k)
for(l in 1:k){
check[l] <- any(all(pBs[[1]][,l]/abs(pBs[[1]][,l]) == x$B[,j]/abs(x$B)[,j]) | all(pBs[[1]][,l]/abs(pBs[[1]][,l]) == x$B[,j]/abs(x$B)[,j]*(-1)))
}
if(sum(check) == 1){
sign.part[[j]] <- sign.part[[j]] + 1
}
}
}
}else{
nrest <- length(signrest)
sign.part <- rep(list(0), nrest )
sign.complete <- 0
for(j in 1:length(bootstraps)){
check.full <- 0
for(i in 1:nrest){
check <- rep(FALSE, length(signrest[[i]][!is.na(signrest[[i]])]))
for(l in 1:k){
check[l] <- any(all(Bs[!is.na(signrest[[i]]),l,j]/abs(Bs[!is.na(signrest[[i]]),l,j]) == signrest[[i]][!is.na(signrest[[i]])]) |
all(Bs[!is.na(signrest[[i]]),l,j]/abs(Bs[!is.na(signrest[[i]]),l,j]) == signrest[[i]][!is.na(signrest[[i]])]*(-1)))
}
if(sum(check) == 1){
sign.part[[i]] <- sign.part[[i]] + 1
check.full <- check.full + 1
}
}
if(check.full == nrest){
sign.complete <- sign.complete + 1
}
}
names(sign.part) <- names(signrest)
}
}
} else {
sign.part <- NULL
sign.complete <- NULL
}
ip <- irf(x, n.ahead = n.ahead)
result <- list(true = ip,
bootstrap = ipb,
SE = SE,
nboot = nboot,
distr = distr,
point_estimate = x$B,
boot_mean = boot.mean,
signrest = signrest,
sign_complete = sign.complete,
sign_part = sign.part,
cov_bs = cov.bs,
A_hat = x$A_hat,
design = design,
A_hat_boot_mean = A_hat_boot_mean,
Omodel = x,
boot_B = Bs,
rest_mat = restriction_matrix,
method = 'Wild bootstrap',
VAR = x$VAR,
signcheck = signcheck)
class(result) <- 'sboot'
return(result)
} |
test_that("fredr_category_children()", {
skip_if_no_key()
ctg <- fredr_category_children(category_id = 0)
expect_s3_class(ctg, c("tbl_df", "tbl", "data.frame"))
expect_true(ncol(ctg) == 3)
expect_true(nrow(ctg) == 8)
})
test_that("input is validated", {
expect_error(fredr_category_children(category_id = NULL))
expect_error(fredr_category_children(category_id = "a"))
expect_error(fredr_category_children(category_id = 1:2))
}) |
library(circlize)
library(ComplexHeatmap)
library(GetoptLong)
set.seed(123)
lt = list(a = sample(letters, 10),
b = sample(letters, 15),
c = sample(letters, 20))
m = make_comb_mat(lt)
t(m)
set_name(m)
comb_name(m)
set_size(m)
comb_size(m)
lapply(comb_name(m), function(x) extract_comb(m, x))
draw(UpSet(m))
draw(UpSet(m, comb_col = c(rep(2, 3), rep(3, 3), 1)))
draw(UpSet(t(m)))
set_name(t(m))
comb_name(t(m))
set_size(t(m))
comb_size(t(m))
lapply(comb_name(t(m)), function(x) extract_comb(t(m), x))
m = make_comb_mat(lt, mode = "intersect")
lapply(comb_name(m), function(x) extract_comb(m, x))
draw(UpSet(m))
m = make_comb_mat(lt, mode = "union")
lapply(comb_name(m), function(x) extract_comb(m, x))
draw(UpSet(m))
f = system.file("extdata", "movies.csv", package = "UpSetR")
if(file.exists(f)) {
movies <- read.csv(system.file("extdata", "movies.csv", package = "UpSetR"), header = T, sep = ";")
m = make_comb_mat(movies, top_n_sets = 6)
t(m)
set_name(m)
comb_name(m)
set_size(m)
comb_size(m)
lapply(comb_name(m), function(x) extract_comb(m, x))
set_name(t(m))
comb_name(t(m))
set_size(t(m))
comb_size(t(m))
lapply(comb_name(t(m)), function(x) extract_comb(t(m), x))
draw(UpSet(m))
draw(UpSet(t(m)))
m = make_comb_mat(movies, top_n_sets = 6, mode = "intersect")
m = make_comb_mat(movies, top_n_sets = 6, mode = "union")
}
library(circlize)
library(GenomicRanges)
lt = lapply(1:4, function(i) generateRandomBed())
lt = lapply(lt, function(df) GRanges(seqnames = df[, 1], ranges = IRanges(df[, 2], df[, 3])))
names(lt) = letters[1:4]
m = make_comb_mat(lt)
if(file.exists(f)) {
movies <- read.csv(f, header = T, sep = ";")
genre = c("Action", "Romance", "Horror", "Children", "SciFi", "Documentary")
rate = cut(movies$AvgRating, c(0, 1, 2, 3, 4, 5))
m_list = tapply(seq_len(nrow(movies)), rate, function(ind) {
make_comb_mat(movies[ind, genre, drop = FALSE])
})
m_list2 = normalize_comb_mat(m_list)
lapply(m_list2, set_name)
lapply(m_list2, set_size)
lapply(m_list2, comb_name)
lapply(m_list2, comb_size)
lapply(1:length(m_list), function(i) {
n1 = comb_name(m_list[[i]])
x1 = comb_size(m_list[[i]])
n2 = comb_name(m_list2[[i]])
x2 = comb_size(m_list2[[i]])
l = n2 %in% n1
x2[!l]
})
} |
plot.ped = function(x, marker = NULL, sep = "/", missing = "-", showEmpty = FALSE,
labs = labels(x), title = NULL, col = 1, aff = NULL, carrier = NULL,
hatched = NULL, shaded = NULL, deceased = NULL,
starred = NULL, twins = NULL, textInside = NULL, textAbove = NULL,
hints = NULL, fouInb = "autosomal",
margins = c(0.6, 1, 4.1, 1), keep.par = FALSE, ...) {
if(hasSelfing(x))
stop2("Plotting of pedigrees with selfing is not yet supported")
nInd = pedsize(x)
if(is.function(labs))
labs = labs(x)
if(identical(labs, "num"))
labs = setNames(labels(x), 1:nInd)
text = rep("", nInd)
mtch = match(labels(x), labs, nomatch = 0L)
showIdx = mtch > 0
showLabs = labs[mtch]
if(!is.null(nms <- names(labs))) {
newnames = nms[mtch]
goodIdx = newnames != "" & !is.na(newnames)
showLabs[goodIdx] = newnames[goodIdx]
}
text[showIdx] = showLabs
if(is.function(starred))
starred = starred(x)
starred = internalID(x, starred, errorIfUnknown = FALSE)
starred = starred[!is.na(starred)]
text[starred] = paste0(text[starred], "*")
if (length(marker) > 0) {
if (is.marker(marker))
mlist = list(marker)
else if (is.markerList(marker))
mlist = marker
else if (is.numeric(marker) || is.character(marker) || is.logical(marker))
mlist = getMarkers(x, markers = marker)
else
stop2("Argument `marker` must be either:\n",
" * a n object of class `marker`\n",
" * a list of `marker` objects\n",
" * a character vector (names of attached markers)\n",
" * an integer vector (indices of attached markers)",
" * a logical vector of length `nMarkers(x)`")
checkConsistency(x, mlist)
gg = do.call(cbind, lapply(mlist, format, sep = sep, missing = missing))
geno = apply(gg, 1, paste, collapse = "\n")
if (!showEmpty)
geno[rowSums(do.call(cbind, mlist)) == 0] = ""
text = if (!any(nzchar(text))) geno else paste(text, geno, sep = "\n")
}
opar = par(mar = margins)
if(!keep.par)
on.exit(par(opar))
if(is.list(col)) {
cols = rep(1, nInd)
for(cc in names(col)) {
thiscol = col[[cc]]
if(is.function(thiscol))
idscol = thiscol(x)
else
idscol = intersect(labels(x), thiscol)
cols[internalID(x, idscol)] = cc
}
}
else {
cols = rep(col, length = nInd)
}
if(!is.null(shaded)) {
message("The argument `shaded` has been renamed to `hatched`; please use this instead.")
hatched = shaded
shaded = NULL
}
if(is.function(aff))
aff = aff(x)
if(is.function(hatched))
hatched = hatched(x)
if(!is.null(aff) && !is.null(hatched))
stop2("Both `aff` and `hatched` cannot both be used")
if(!is.null(aff)) {
density = -1
angle = 90
}
else if(!is.null(hatched)) {
aff = hatched
density = 25
angle = 45
} else {
density = angle = NULL
}
if(is.vector(twins))
twins = data.frame(id1 = twins[1], id2 = twins[2], code = as.integer(twins[3]))
pedigree = as_kinship2_pedigree(x, deceased = deceased, aff = aff,
twins = twins, hints = hints)
pdat = kinship2::plot.pedigree(pedigree, id = text, col = cols, mar = margins,
density = density, angle = angle, keep.par = keep.par, ...)
dotArgs.uneval = match.call(expand.dots = FALSE)$`...`
dotArgs = lapply(dotArgs.uneval, eval.parent, n = 2L)
cex = dotArgs[['cex']]
fam = dotArgs[['family']]
if (!is.null(title))
title(title, cex.main = dotArgs$cex.main %||% cex, col.main = dotArgs$col.main,
font.main = dotArgs$font.main, fam = fam, xpd = NA)
if(is.function(carrier))
carrier = carrier(x)
carrier = internalID(x, carrier, errorIfUnknown = FALSE)
points(pdat$x[carrier], pdat$y[carrier] + pdat$boxh/2, pch = 16, cex = cex, col = cols[carrier])
if(!is.null(textInside)) {
text(pdat$x, pdat$y + pdat$boxh/2, labels = textInside, cex = cex, col = cols,
font = dotArgs[['font']], fam = fam)
}
if(!is.null(textAbove)) {
text(pdat$x, pdat$y, labels = textAbove, cex = cex, col = cols,
font = dotArgs[['font']], fam = fam, adj = c(0.5, -0.5), xpd = TRUE)
}
else if(!is.null(fouInb) && hasInbredFounders(x)) {
finb = founderInbreeding(x, chromType = fouInb, named = TRUE)
finb = finb[finb > 0]
idx = internalID(x, names(finb))
finb.txt = sprintf("f = %.4g", finb)
text(pdat$x[idx], pdat$y[idx], labels = finb.txt, cex = cex, font = 3,
fam = fam, adj = c(0.5, -0.5), xpd = TRUE)
}
invisible(pdat)
}
plot.singleton = function(x, marker = NULL, sep = "/", missing = "-", showEmpty = FALSE,
labs = labels(x), title = NULL, col = 1, aff = NULL,
carrier = NULL, hatched = NULL, shaded = NULL,
deceased = NULL, starred = NULL,
textInside = NULL, textAbove = NULL, fouInb = "autosomal",
margins = c(8, 0, 0, 0), yadj = 0, ...) {
if(is.function(labs))
labs = labs(x)
if(identical(labs, "num"))
labs = c(`1` = labels(x))
if(is.function(aff))
aff = aff(x)
if(is.function(carrier))
carrier = carrier(x)
if(!is.null(shaded)) {
hatched = shaded
shaded = NULL
}
if(is.function(hatched))
hatched = hatched(x)
if(is.function(starred))
starred = starred(x)
if(!is.null(textInside))
textInside = c("", "", textInside)
if(!is.null(textAbove))
textAbove = c("", "", textAbove)
if(!is.null(fouInb) && hasInbredFounders(x))
finb = founderInbreeding(x, chromType = fouInb)
else
finb = NULL
if (length(marker) == 0)
mlist = NULL
else if (is.marker(marker))
mlist = list(marker)
else if (is.markerList(marker))
mlist = marker
else if (is.numeric(marker) || is.character(marker))
mlist = getMarkers(x, markers = marker)
else
stop2("Argument `marker` must be either:\n",
" * an object of class `marker`\n",
" * a list of `marker` objects\n",
" * a character vector (names of attached markers)\n",
" * an integer vector (indices of attached markers)")
x = setMarkers(x, mlist)
y = suppressMessages(addParents(x, labels(x)[1], father = "__FA__", mother = "__MO__",
verbose = FALSE))
pdat = plot.ped(y, marker = y$MARKERS, sep = sep, missing = missing,
showEmpty = showEmpty, labs = labs,
title = title, col = col, aff = aff, carrier = carrier,
hatched = hatched, shaded = shaded, deceased = deceased,
starred = starred, textInside = textInside, textAbove = textAbove,
margins = c(margins[1], 0, 0, 0), keep.par = TRUE, ...)
usr = par("usr")
rect(usr[1] - 0.1, pdat$y[3] - yadj, usr[2] + 0.1, usr[4], border = NA, col = "white")
dotArgs.uneval = match.call(expand.dots = FALSE)$`...`
dotArgs = lapply(dotArgs.uneval, eval.parent, n = 2L)
cex = dotArgs[['cex']]
fam = dotArgs$family
if (!is.null(title))
title(title, cex.main = dotArgs$cex.main %||% cex, col.main = dotArgs$col.main, line = -2.8,
font.main = dotArgs$font.main, family = fam, xpd = NA)
if(!is.null(textAbove)) {
text(pdat$x, pdat$y, labels = textAbove, cex = cex, col = col,
font = dotArgs[['font']], family = fam, adj = c(0.5, -0.5), xpd = TRUE)
}
else if(!is.null(finb)) {
finb.txt = sprintf("f = %.4g", finb)
idx = 3
text(pdat$x[idx], pdat$y[idx], labels = finb.txt, family = fam,
cex = cex, font = 3, adj = c(0.5, -0.5), xpd = TRUE)
}
invisible(pdat)
}
as_kinship2_pedigree = function(x, deceased = NULL, aff = NULL, twins = NULL, hints = NULL) {
ped = as.data.frame(x)
ped$sex[ped$sex == 0] = 3
affected = ifelse(ped$id %in% aff, 1, 0)
status = ifelse(ped$id %in% deceased, 1, 0)
arglist = list(id = ped$id, dadid = ped$fid, momid = ped$mid,
sex = ped$sex, affected = affected,
status = status, missid = 0)
if(!is.null(twins))
arglist$relation = twins
kinped = suppressWarnings(do.call(kinship2::pedigree, arglist))
kinped$hints = hints
kinped
}
plot.pedList = function(x, ...) {
plotPedList(x, frames = FALSE, ...)
}
plotPedList = function(plots, widths = NULL, groups = NULL, titles = NULL,
frames = TRUE, fmar = NULL, frametitles = NULL,
source = NULL, dev.height = NULL, dev.width = NULL,
newdev = !is.null(dev.height) || !is.null(dev.width),
verbose = FALSE, ...) {
if(!is.null(frametitles)) {
message("Argument `frametitles` is deprecated; use `titles` instead")
titles = frametitles
}
if(!(isTRUE(frames) || isFALSE(frames))) {
message("`frames` must be either TRUE or FALSE; use `groups` to specify framing groups")
groups = frames
frames = TRUE
}
if(!is.null(source)) {
srcPed = plots[[source]]
if(is.null(srcPed))
stop2("Unknown source pedigree: ", source)
if(nMarkers(srcPed) == 0)
stop2("The source pedigree has no attached markers")
plots = lapply(plots, transferMarkers, from = srcPed)
}
deduceGroups = is.null(groups)
if (deduceGroups) {
groups = list()
k = 0
}
flatlist = list()
for (p in plots) {
if (is.ped(p))
newpeds = list(list(p))
else if (is.pedList(p))
newpeds = lapply(p, list)
else {
if (!is.ped(p[[1]]))
stop2("First element must be a `ped` object", p[[1]])
newpeds = list(p)
}
flatlist = c(flatlist, newpeds)
if (deduceGroups) {
groups = c(groups, list(k + seq_along(newpeds)))
k = k + length(newpeds)
}
}
N = length(flatlist)
NG = length(groups)
for (v in groups)
if (!is.numeric(v) || !isTRUE(all.equal.numeric(v, v[1]:v[length(v)])))
stop2("Each element of `groups` must consist of consecutive integers: ", v)
dup = anyDuplicated.default(unlist(groups))
if (dup > 0)
stop2("Plot occurring twice in `groups`: ", dup)
grouptitles = titles %||% names(plots)
if (!is.null(grouptitles) && length(grouptitles) != NG)
stop2(sprintf("Length of `titles` (%d) does not equal number of groups (%d)",
length(grouptitles), NG))
finalTitles = grouptitles %||% sapply(flatlist, function(p) p$title %||% "")
hasTitles = any(nchar(finalTitles) > 0)
if (is.null(widths))
widths = vapply(flatlist, function(p) ifelse(is.singleton(p[[1]]), 1, 2.5), 1)
else {
if(!is.numeric(widths) && !length(widths) %in% c(1,N))
stop2("`widths` must be a numeric of length either 1 or the total number of objects")
widths = rep_len(widths, N)
}
maxGen = max(vapply(flatlist, function(arglist) generations(arglist[[1]]), 1))
extra.args = list(...)
defaultmargins = if (N > 2) c(0, 4, 0, 4) else c(0, 2, 0, 2)
plotlist = lapply(flatlist, function(arglist) {
names(arglist)[1] = "x"
for (parname in setdiff(names(extra.args), names(arglist)))
arglist[[parname]] = extra.args[[parname]]
arglist$title = NULL
arglist$margins = arglist$margins %||% {
g = generations(arglist$x)
addMar = 2 * (maxGen - g + 1)
defaultmargins + c(addMar, 0, addMar, 0)
}
arglist
})
if (newdev) {
dev.height = dev.height %||% {max(3, 1 * maxGen) + 0.3 * as.numeric(hasTitles)}
dev.width = dev.width %||% {3 * N}
dev.new(height = dev.height, width = dev.width, noRStudioGD = TRUE)
}
new.oma = if (hasTitles) c(0, 0, 3, 0) else c(0, 0, 0, 0)
opar = par(oma = new.oma, xpd = NA)
on.exit(par(opar))
if(verbose) {
message("Group structure: ", toString(groups))
message("Relative widths: ", toString(widths))
message("Default margins: ", toString(defaultmargins))
message("Indiv. margins:")
for(p in plotlist) message(" ", toString(p$margins))
message("Input width/height: ", toString(c(dev.width, dev.height)))
message("Actual dimensions: ", toString(round(dev.size(),3)))
}
layout(rbind(1:N), widths = widths)
for (arglist in plotlist)
do.call(plot, arglist)
ratios = c(0, cumsum(widths)/sum(widths))
grStartIdx = sapply(groups, function(v) v[1])
grStopIdx = sapply(groups, function(v) v[length(v)])
grStart = ratios[grStartIdx]
grStop = ratios[grStopIdx + 1]
if(frames) {
fmar = fmar %||% min(0.05, 0.25/dev.size()[2])
margPix = grconvertY(0, from = "ndc", to = "device") * fmar
margXnorm = grconvertX(margPix, from = "device", to = "ndc")
frame_start = grconvertX(grStart + margXnorm, from = "ndc")
frame_stop = grconvertX(grStop - margXnorm, from = "ndc")
rect(xleft = frame_start,
ybottom = grconvertY(1 - fmar, from = "ndc"),
xright = frame_stop,
ytop = grconvertY(fmar, from = "ndc"), xpd = NA)
}
if(hasTitles) {
midpoints = if(!is.null(grouptitles)) (grStart + grStop)/2 else ratios[1:N] + diff(ratios)/2
cex.title = extra.args$cex.main %||% NA
mtext(finalTitles, outer = TRUE, at = midpoints, cex = cex.title)
}
} |
chi2cub1cov <-function(m,ordinal,covar,pai,gama){
covar<-as.matrix(covar)
n<-length(ordinal)
elle<-as.numeric(sort(unique(covar)))
kappa<-length(elle)
matfrel<-matrix(NA,nrow=kappa,ncol=m)
matprob<-matrix(NA,nrow=kappa,ncol=m)
chi2<-0
dev<-0
j<-1
while(j<=kappa){
quali<-which(covar==elle[j])
Wquali<-covar[quali]
qualiord<-ordinal[quali]
nk<- length(qualiord)
matfrel[j,]=tabulate(qualiord,nbins=m)/nk
nonzero<-which(matfrel[j,]!=0)
paij<-pai
csij<-1/(1+ exp(-gama[1]-gama[2]*elle[j]))
matprob[j,]<-t(probcub00(m,paij,csij))
chi2<-chi2+nk*sum(((matfrel[j,]-matprob[j,])^2)/matprob[j,])
dev<- dev + 2*nk*sum(matfrel[j,nonzero]*log(matfrel[j,nonzero]/matprob[j,nonzero]))
j<-j+1
}
df<- kappa*(m-1)-(length(gama)+1)
cat("Degrees of freedom ==> df =",df, "\n")
cat("Pearson Fitting measure ==> X^2 =",chi2,"(p-val.=",1-pchisq(chi2,df),")","\n")
cat("Deviance ==> Dev =",dev,"(p-val.=",1-pchisq(dev,df),")","\n")
results<-list('chi2'=chi2,'df'=df,'dev'=dev)
} |
svc <- paws::route53resolver()
test_that("list_resolver_dnssec_configs", {
expect_error(svc$list_resolver_dnssec_configs(), NA)
})
test_that("list_resolver_dnssec_configs", {
expect_error(svc$list_resolver_dnssec_configs(MaxResults = 20), NA)
})
test_that("list_resolver_endpoints", {
expect_error(svc$list_resolver_endpoints(), NA)
})
test_that("list_resolver_endpoints", {
expect_error(svc$list_resolver_endpoints(MaxResults = 20), NA)
})
test_that("list_resolver_query_log_config_associations", {
expect_error(svc$list_resolver_query_log_config_associations(), NA)
})
test_that("list_resolver_query_log_config_associations", {
expect_error(svc$list_resolver_query_log_config_associations(MaxResults = 20), NA)
})
test_that("list_resolver_query_log_configs", {
expect_error(svc$list_resolver_query_log_configs(), NA)
})
test_that("list_resolver_query_log_configs", {
expect_error(svc$list_resolver_query_log_configs(MaxResults = 20), NA)
})
test_that("list_resolver_rule_associations", {
expect_error(svc$list_resolver_rule_associations(), NA)
})
test_that("list_resolver_rule_associations", {
expect_error(svc$list_resolver_rule_associations(MaxResults = 20), NA)
})
test_that("list_resolver_rules", {
expect_error(svc$list_resolver_rules(), NA)
})
test_that("list_resolver_rules", {
expect_error(svc$list_resolver_rules(MaxResults = 20), NA)
}) |
NULL
parse_dataset <- function(dataset, project_id = NULL) {
.Deprecated("bq_dataset", package = "bigrquery")
assert_that(is.string(dataset), is.null(project_id) || is.string(project_id))
first_split <- rsplit_one(dataset, ":")
dataset_id <- first_split$right
project_id <- first_split$left %||% project_id
list(project_id = project_id, dataset_id = dataset_id)
}
format_dataset <- function(project_id, dataset) {
.Deprecated("bq_dataset", package = "bigrquery")
if (!is.null(project_id)) {
dataset <- paste0(project_id, ":", dataset)
}
dataset
}
parse_table <- function(table, project_id = NULL) {
.Deprecated("bq_table", package = "bigrquery")
assert_that(is.string(table), is.null(project_id) || is.string(project_id))
dataset_id <- NULL
first_split <- rsplit_one(table, ".")
table_id <- first_split$right
project_and_dataset <- first_split$left
if (!is.null(project_and_dataset)) {
second_split <- rsplit_one(project_and_dataset, ":")
dataset_id <- second_split$right
project_id <- second_split$left %||% project_id
}
list(project_id = project_id, dataset_id = dataset_id, table_id = table_id)
}
format_table <- function(project_id, dataset, table) {
if (!is.null(project_id)) {
dataset <- paste0(project_id, ":", dataset)
}
table <- paste0(dataset, ".", table)
table
}
rsplit_one <- function(str, sep) {
assert_that(is.string(str), is.string(sep))
parts <- strsplit(str, sep, fixed = TRUE)[[1]]
right <- parts[length(parts)]
if (length(parts) > 1) {
left <- paste0(parts[-length(parts)], collapse = sep)
} else {
left <- NULL
}
list(left = left, right = right)
} |
asVPC.distanceW<-function(orig.data,sim.data,n.timebin,n.sim,n.hist,
q.list=c(0.05,0.5,0.95),
conf.level=0.95,
X.name="TIME",Y.name="DV",
opt.DV.point=FALSE,
weight.flag=FALSE,
Y.min=NULL,
Y.max=NULL,
only.med=FALSE,
plot.flag=TRUE){
SIM.CIarea.1<-NULL
SIM.CIarea.2<-NULL
SIM.CIarea.3<-NULL
DV.point<-NULL
DV.quant<-NULL
SIM.quant<-NULL
ID<-NULL;G<-NULL
bintot.N<-n.timebin*n.hist
time.bin<-makeCOVbin(orig.data[,X.name],N.covbin=bintot.N)
alpha<-1-conf.level
Q.CI<-vector("list",3)
orig.Q<-NULL
bintot.N<-nrow(time.bin$COV.bin.summary)
for(i in 1:bintot.N){
if(i<n.hist){
sel.id<-which(as.numeric(time.bin$COV.bin)<=i+n.hist-1)
sel.id1<-which(as.numeric(time.bin$COV.bin)==i)
mid.point<-median(orig.data[sel.id1,X.name])
low.point<-time.bin$COV.bin.summary$lower.COV[i]
upper.point<-time.bin$COV.bin.summary$upper.COV[i]
} else if(i >(bintot.N-n.hist+1)){
sel.id<-which(as.numeric(time.bin$COV.bin)>=i-(n.hist-1))
sel.id1<-which(as.numeric(time.bin$COV.bin)==i)
mid.point<-median(orig.data[sel.id1,X.name])
low.point<-time.bin$COV.bin.summary$lower.COV[i]
upper.point<-time.bin$COV.bin.summary$upper.COV[i]
} else{
sel.id<-which(as.numeric(time.bin$COV.bin)>i-n.hist &
as.numeric(time.bin$COV.bin)<i+n.hist)
sel.id1<-which(as.numeric(time.bin$COV.bin)==i)
mid.point<-median(orig.data[sel.id1,X.name])
low.point<-time.bin$COV.bin.summary$lower.COV[i]
upper.point<-time.bin$COV.bin.summary$upper.COV[i]
}
if(bintot.N<length(table(orig.data$TIME))){
dist.temp<-abs(orig.data$TIME[sel.id]-mid.point)
temp.weight<-(max(dist.temp)-dist.temp)/diff(range(dist.temp))
} else{
A<-as.numeric(time.bin$COV.bin[sel.id])
temp<-abs(A-median(range(A)))
temp.weight<-(max(temp)+1)-temp
temp.weight<-temp.weight/max(temp.weight)
}
if(weight.flag){
temp.quantile<-t(apply(sim.data[sel.id,],2,function(x)
Hmisc::wtd.quantile(x,weight=temp.weight,
prob=q.list,na.rm=TRUE)))
temp.orig.q<-Hmisc::wtd.quantile(orig.data[,Y.name][sel.id],
weight=temp.weight,prob=q.list,na.rm=TRUE)
} else{
temp.quantile<-t(apply(sim.data[sel.id,],2,function(x)
quantile(x,prob=q.list,na.rm=TRUE)))
temp.orig.q<-quantile(orig.data[,Y.name][sel.id],
prob=q.list,na.rm=TRUE)
}
orig.Q<-rbind(orig.Q,c(mid.point,temp.orig.q))
temp<-t(apply(temp.quantile,2,function(x)
quantile(x,prob=c(alpha/2,0.5,1-alpha/2),na.rm=TRUE)))
for(j in 1:length(q.list))
Q.CI[[j]]<-rbind(Q.CI[[j]],c(mid.point,low.point,upper.point,temp[j,]))
}
keep.name<-NULL
for(j in 1:length(q.list)){
keep.name<-c(keep.name,paste("Q",round(q.list[j]*100),"th",sep=""))
colnames(Q.CI[[j]])<-c("mid","Lower","upper",colnames(Q.CI[[j]])[4:6])
}
names(Q.CI)<-keep.name
colnames(orig.Q)<-c("mid","Y1","Y2","Y3")
orig.Q<-data.frame(orig.Q)
plot.data<-data.frame(orig.data,X=orig.data[,X.name],Y=orig.data[,Y.name])
if(is.null(Y.min)) Y.min<-min(c(plot.data$Y,Q.CI[[1]][,4]),na.rm=T)
if(is.null(Y.max)) Y.max<-max(c(plot.data$Y,Q.CI[[length(Q.CI)]][,6]),na.rm=T)
P.temp<-ggplot(plot.data,aes(x=X,y=Y))+ylim(Y.min,Y.max)+
labs(x=X.name,y=Y.name)+theme_bw()+
theme(panel.grid.major=element_line(colour="white"))+
theme(panel.grid.minor=element_line(colour="white"))
test.LU<-Q.CI[[1]][,2:3]
test.data.tot<-Q.CI
X.temp<-c(test.LU[,1],test.LU[nrow(test.LU),2])
n.temp<-nrow(test.LU)
X<-c(test.LU[1,1],rep(test.LU[2:n.temp,1],each=2),test.LU[n.temp,2])
X<-c(X,X[length(X):1])
if(!only.med){
test.data<-test.data.tot[[1]]
Y<-c(rep(test.data[,4],each=2),rep(test.data[(n.temp:1),6],each=2))
SIM.CIarea.1<-data.frame(X=X,Y=Y,ID=1)
P.temp<-P.temp+geom_polygon(data= SIM.CIarea.1,
aes(x=X,y=Y,group=ID,fill=ID),
fill="gray80",colour="gray80")
test.data<-test.data.tot[[3]]
Y<-c(rep(test.data[,4],each=2),rep(test.data[(n.temp:1),6],each=2))
SIM.CIarea.3<-data.frame(X=X,Y=Y,ID=1)
P.temp<-P.temp+geom_polygon(data= SIM.CIarea.3,
aes(x=X,y=Y,group=ID,fill=ID),
fill="gray80",colour="gray80")
}
test.data<-test.data.tot[[2]]
Y<-c(rep(test.data[,4],each=2),rep(test.data[(n.temp:1),6],each=2))
SIM.CIarea.2<-data.frame(X=X,Y=Y,ID=1)
P.temp<-P.temp+geom_polygon(data= SIM.CIarea.2,
aes(x=X,y=Y,group=ID,fill=ID),
fill="gray50",colour="gray50")
if(opt.DV.point==TRUE){
P.temp<-P.temp+geom_point(,color="grey30",size=2,alpha=0.5)
DV.point<-data.frame(X=orig.data[,X.name],Y=orig.data[,Y.name])
}
DV.quant<-data.frame(X=rep(orig.Q$mid,length(q.list)),
G=factor(rep(paste("Q",round(q.list*100),"th",sep=""),
each=nrow(orig.Q))),
Y=unlist(orig.Q[,-1]))
P.temp<-P.temp+geom_line(data=DV.quant[DV.quant$G!="Q50th",],
aes(x=X,y=Y,group=G),linetype=2,
size=1,color="black")+
geom_line(data=DV.quant[DV.quant$G=="Q50th",],
aes(x=X,y=Y,group=G),linetype=1,
size=1,color="black")
colnames(orig.Q)<-c("X.mid",paste("Q",round(q.list*100),"th",sep=""))
if(plot.flag){
P.temp
} else{
return(list(SIM.CIarea.1=SIM.CIarea.1,SIM.CIarea.2=SIM.CIarea.2,
SIM.CIarea.3=SIM.CIarea.3,DV.point=DV.point,
DV.quant=DV.quant,SIM.quant=SIM.quant))
}
} |
context("S4Types")
test_that("Type with defaults", {
Test(x = 1, y = list(z = 1, a = list(1, 3))) %type% {
stopifnot(.Object@x > 0)
.Object
}
expect_error(Test(x = 0))
expect_true(Test()@x == 1)
expect_true(Test(2)@x == 2)
expect_true(identical(Test()@y$z, 1))
expect_true(typeof(Test()) == "S4")
removeClass("Test", environment())
})
test_that("Type with ANY", {
Test(x = numeric(), y = NULL) %type% .Object
expect_true(is.null(Test()@y))
expect_true(is.numeric(Test()@x))
x <- Test()
x@y <- Test()
expect_true(is(x@y, "Test"))
removeClass("Test", environment())
})
test_that("Class without slot", {
setClass("Empty", prototype = prototype(), where = environment())
Empty : Test() %type% .Object
expect_true(is(Test(), "Test"))
removeClass("Test", environment())
})
test_that("Type inheritance", {
Test4(x = 1, y = list()) %type% {
stopifnot(.Object@x > 0)
.Object
}
Test4:Child(z = " ") %type% {
stopifnot(nchar(.Object@z) > 0)
.Object
}
expect_error(Child(x = 0))
expect_true(Child()@x == 1)
expect_true(identical(Child()@y, list()))
expect_true(typeof(Test4()) == "S4")
expect_true(is(Child(), "Child"))
expect_true(inherits(Child(), "Test4"))
expect_true(identical(Child(z = "char")@z, "char"))
expect_error(Child(z = ""))
expect_equal(Child(x = 5)@x, 5)
removeClass("Child", environment())
Test2(z = "") %type% .Object
Test4 : Test2 : Child() %type% .Object
expect_true(Child()@x == 1)
expect_true(identical(Child()@y, list()))
expect_true(inherits(Child(), "Test4"))
expect_true(inherits(Child(), "Test2"))
expect_true(identical(Child(z = "char")@z, "char"))
removeClass("Test2", environment())
removeClass("Test4", environment())
removeClass("Child", environment())
})
test_that("Types can inherit S3 classes", {
numeric : Test(x = 1, .Data = 2) %type% {
.Object
}
expect_true(Test() == 2)
expect_true(Test(4, 3) == 3)
numeric : Test(x = 1) %type% .Object
expect_equal(Test()@.Data, numeric())
expect_true(Test(4, 3) == 3)
removeClass("Test", environment())
})
test_that("Type with VIRTUAL", {
VIRTUAL:Type() %type% .Object
names.Type <- function(x) {
slotNames(x)
}
Type:Test(x = 1) %type% .Object
expect_true(names(Test(x = 2)) == "x")
expect_true(inherits(Test(), "Type"))
expect_error(new("Type"))
removeClass("Test", environment())
removeClass("Type", environment())
})
test_that("Type with quoted class names", {
'character' : "Test6"(names = character()) %type% .Object
expect_true(inherits(Test6(), "character"))
expect_is(Test6(), "Test6")
removeClass("Test6", environment())
})
test_that("Type with explicit class names", {
Test7(x ~ numeric, y = list(), z) %type% .Object
expect_error(Test7(x = 0))
expect_true(Test7(1, list(), NULL)@x == 1)
expect_true(identical(Test7(1, list(), NULL)@y, list()))
expect_true(typeof(Test7(1, list(), NULL)) == "S4")
removeClass("Test7", environment())
})
test_that("Types can deal with class unions", {
'numeric | character' : Test5(
x ~ 'numeric | character | list'
) %type% .Object
expect_is(Test5(1, 2)@x, "numeric")
expect_is(Test5("", "")@x, "character")
expect_is(Test5(list())@x, "list")
}) |
make_vectorized_smoof <- function(prob.name, ...){
if(!("smoof" %in% rownames(utils::installed.packages()))){
stop("Please install package 'smoof' to continue")
} else {
my.args <- as.list(sys.call())[-1]
my.args$prob.name <- NULL
if (length(my.args) == 0) my.args <- list()
myfun <- do.call(utils::getFromNamespace(x = paste0("make",
toupper(prob.name),
"Function"),
ns = "smoof"),
args = my.args)
myfun2 <- function(X, ...){
t(apply(X,
MARGIN = 1,
FUN = myfun))
}
return(myfun2)
}
} |
library(LearnBayes)
data(birdextinct)
attach(birdextinct)
logtime=log(time)
plot(nesting,logtime)
out = (logtime > 3)
text(nesting[out], logtime[out], label=species[out], pos = 2)
S=readline(prompt="Type <Return> to continue : ")
windows()
plot(jitter(size),logtime,xaxp=c(0,1,1))
S=readline(prompt="Type <Return> to continue : ")
windows()
plot(jitter(status),logtime,xaxp=c(0,1,1))
fit=lm(logtime~nesting+size+status,data=birdextinct,x=TRUE,y=TRUE)
summary(fit)
theta.sample=blinreg(fit$y,fit$x,5000)
S=readline(prompt="Type <Return> to continue : ")
windows()
par(mfrow=c(2,2))
hist(theta.sample$beta[,2],main="NESTING",
xlab=expression(beta[1]))
hist(theta.sample$beta[,3],main="SIZE",
xlab=expression(beta[2]))
hist(theta.sample$beta[,4],main="STATUS",
xlab=expression(beta[3]))
hist(theta.sample$sigma,main="ERROR SD",
xlab=expression(sigma))
apply(theta.sample$beta,2,quantile,c(.05,.5,.95))
quantile(theta.sample$sigma,c(.05,.5,.95))
S=readline(prompt="Type <Return> to continue : ")
cov1=c(1,4,0,0)
cov2=c(1,4,1,0)
cov3=c(1,4,0,1)
cov4=c(1,4,1,1)
X1=rbind(cov1,cov2,cov3,cov4)
mean.draws=blinregexpected(X1,theta.sample)
c.labels=c("A","B","C","D")
windows()
par(mfrow=c(2,2))
for (j in 1:4)
hist(mean.draws[,j],
main=paste("Covariate set",c.labels[j]),xlab="log TIME")
S=readline(prompt="Type <Return> to continue : ")
cov1=c(1,4,0,0)
cov2=c(1,4,1,0)
cov3=c(1,4,0,1)
cov4=c(1,4,1,1)
X1=rbind(cov1,cov2,cov3,cov4)
pred.draws=blinregpred(X1,theta.sample)
c.labels=c("A","B","C","D")
windows()
par(mfrow=c(2,2))
for (j in 1:4)
hist(pred.draws[,j],
main=paste("Covariate set",c.labels[j]),xlab="log TIME")
S=readline(prompt="Type <Return> to continue : ")
pred.draws=blinregpred(fit$x,theta.sample)
pred.sum=apply(pred.draws,2,quantile,c(.05,.95))
par(mfrow=c(1,1))
ind=1:length(logtime)
windows()
matplot(rbind(ind,ind),pred.sum,type="l",lty=1,col=1,
xlab="INDEX",ylab="log TIME")
points(ind,logtime,pch=19)
out=(logtime>pred.sum[2,])
text(ind[out], logtime[out], label=species[out], pos = 4)
S=readline(prompt="Type <Return> to continue : ")
prob.out=bayesresiduals(fit,theta.sample,2)
windows()
par(mfrow=c(1,1))
plot(nesting,prob.out)
out = (prob.out > 0.35)
text(nesting[out], prob.out[out], label=species[out], pos = 4) |
options(warn=2)
library(sensitivityPStrat)
data(vaccine.trial)
vaccine.trial$followup.yearsPreART <- runif(2000, 0.5, 3)
vaccine.trial.withNA <- vaccine.trial
set.seed(12345)
for(i in seq_len(20))
vaccine.trial.withNA[sample(nrow(vaccine.trial), size=1, replace=TRUE),
sample(ncol(vaccine.trial), size=1)] <- NA
set.seed(12345)
sens.analysis<-with(vaccine.trial,
sensitivitySGD(z=treatment, s=hiv.outcome, y=followup.yearsART,
d=ARTinitiation, beta0=c(0,-.25,-.5),
beta1=c(0, -.25, -.5), phi=c(0.95, 0.90, 1), tau=3,
time.points=c(2,3), selection="infected",
trigger="initiated ART",
groupings=c("placebo","vaccine"), ci=.95,
ci.method="bootstrap", N.boot=50)
)
stopifnot(is.list(sens.analysis))
stopifnot(inherits(sens.analysis,"sensitivity"))
stopifnot(inherits(sens.analysis,"sensitivity.1d"))
stopifnot(all(c("Fas0", "Fas1", "beta0", "alphahat0", "beta1", "alphahat1") %in% names(sens.analysis)))
stopifnot(is.numeric(sens.analysis$alphahat0))
stopifnot(is.numeric(sens.analysis$beta0))
stopifnot(is.numeric(sens.analysis$alphahat1))
stopifnot(is.numeric(sens.analysis$beta1))
stopifnot(with(sens.analysis,
Fas0[1, 1](2) - Fas1[1, 1](2) == SCE[1,1,1,1]))
sens.analysis
set.seed(12345)
sens.analysis<-with(vaccine.trial.withNA,
sensitivitySGD(z=treatment, s=hiv.outcome, y=followup.yearsART,
d=ARTinitiation, beta0=c(0,-.25,-.5),
beta1=c(0, -.25, -.5), phi=c(0.95, 0.90, 1), tau=3,
time.points=c(2,3), selection="infected",
trigger="initiated ART",
groupings=c("placebo","vaccine"), ci=.95, na.rm=TRUE,
ci.method="bootstrap", N.boot=50)
)
sens.analysis
set.seed(12345)
sens.analysis<-with(vaccine.trial,
sensitivitySGD(z=treatment, s=hiv.outcome, y=followup.yearsART,
v=followup.yearsPreART, d=ARTinitiation,
beta0=c(0,-.25,-.5),
beta1=c(0, -.25, -.5), phi=c(0.95, 0.90, 1), tau=3,
followup.time=2.5,
time.points=c(2,3), selection="infected",
trigger="initiated ART",
groupings=c("placebo","vaccine"), ci=.95,
ci.method="bootstrap", N.boot=50)
)
sens.analysis
set.seed(12345)
sens.analysis<-with(vaccine.trial.withNA,
sensitivitySGD(z=treatment, s=hiv.outcome, y=followup.yearsART,
v=followup.yearsPreART, d=ARTinitiation,
beta0=c(0,-.25,-.5),
beta1=c(0, -.25, -.5), phi=c(0.95, 0.90, 1), tau=3,
followup.time=2.5,
time.points=c(2,3), selection="infected",
trigger="initiated ART",
groupings=c("placebo","vaccine"), ci=.95,
ci.method="bootstrap", N.boot=50, na.rm=TRUE)
)
sens.analysis
set.seed(12345)
sens.analysis<-with(vaccine.trial,
sensitivitySGD(z=treatment, s=hiv.outcome, y=followup.yearsART,
d=ARTinitiation, beta0=c(0,-.25,-.5),
beta1=c(0, -.25, -.5), phi=c(1), tau=3,
time.points=c(2,3), selection="infected",
trigger="initiated ART",
groupings=c("placebo","vaccine"), ci=.95,
ci.method="")
)
sens.analysis |
implFSSEM = function(data = NULL, method = c("CV", "BIC")) {
method = match.arg(method)
gamma = cv.multiRegression(
data$Data$X,
data$Data$Y,
data$Data$Sk,
ngamma = 50,
nfold = 5,
data$Vars$n,
data$Vars$p,
data$Vars$k
)
fit = multiRegression(
data$Data$X,
data$Data$Y,
data$Data$Sk,
gamma,
data$Vars$n,
data$Vars$p,
data$Vars$k,
trans = FALSE
)
Xs = data$Data$X
Ys = data$Data$Y
Sk = data$Data$Sk
if (method == "CV") {
cvfitc <-
cv.multiFSSEMiPALM(
Xs = Xs,
Ys = Ys,
Bs = fit$Bs,
Fs = fit$Fs,
Sk = Sk,
sigma2 = fit$sigma2,
nlambda = 10,
nrho = 10,
nfold = 5,
p = data$Vars$p,
q = data$Vars$k,
wt = T
)
fitc <-
multiFSSEMiPALM(
Xs = Xs,
Ys = Ys,
Bs = fit$Bs,
Fs = fit$Fs,
Sk = Sk,
sigma2 = fit$sigma2,
lambda = cvfitc$lambda,
rho = cvfitc$rho,
Wl = inverseB(fit$Bs),
Wf = flinvB(fit$Bs),
p = data$Vars$p,
maxit = 100,
threshold = 1e-5,
sparse = T,
verbose = T,
trans = T,
strict = T
)
} else {
opt = opt.multiFSSEMiPALM(
Xs = Xs,
Ys = Ys,
Bs = fit$Bs,
Fs = fit$Fs,
Sk = Sk,
sigma2 = fit$sigma2,
nlambda = 10,
nrho = 10,
p = data$Vars$p,
q = data$Vars$k,
wt = T
)
fitc = opt$fit
}
TPR4GRN = (TPR(fitc$B[[1]], data$Vars$B[[1]], PREC = 1e-3) + TPR(fitc$B[[2]], data$Vars$B[[2]], PREC = 1e-3)) / 2
FDR4GRN = (FDR(fitc$B[[1]], data$Vars$B[[1]], PREC = 1e-3) + FDR(fitc$B[[2]], data$Vars$B[[2]], PREC = 1e-3)) / 2
TPR4DiffGRN = TPR(fitc$B[[1]] - fitc$B[[2]], data$Vars$B[[1]] - data$Vars$B[[2]], PREC = 1e-3)
FDR4DiffGRN = FDR(fitc$B[[1]] - fitc$B[[2]], data$Vars$B[[1]] - data$Vars$B[[2]], PREC = 1e-3)
data.frame(
TPR = TPR4GRN,
FDR = FDR4GRN,
TPRofDiffGRN = TPR4DiffGRN,
FDRofDiffGRN = FDR4DiffGRN
)
}
transx = function(data) {
Sk = data$Data$Sk
X = data$Data$X
lapply(Sk, function(s) { X[s, ] })
} |
library(RobStatTM)
options(digits=4)
trimean<-function(x,alfa) {
n=length(x); m=floor(n*alfa)
xs=sort(x); mu=mean(xs[(m+1):(n-m)])
xs=xs-mu; A=m*xs[m]^2 +m*xs[n-m+1]^2 +sum(xs[(m+1):(n-m)]^2)
mu.std=A/(n-2*m); mu.std=sqrt(mu.std/n)
return(list(mu=mu, mu.std=mu.std))
}
n=24; qn=qnorm(0.975)
data(flour)
x = as.vector(flour[,1])
resu = locScaleM(x,eff = 0.95)
muM=resu$mu; muMst=resu$std.mu; h=muMst*qn
interM=c(muM-h, muM+h)
xbar=mean(x); smed=sd(x)/sqrt(n); h=smed*qn
intermean=c(xbar-h,xbar+h)
resu=trimean(x,0.25)
mu25=resu$mu; ss25=resu$mu.std; h=ss25*qn
inter25=c(mu25-h,mu25+h)
print("Mean, bisquare M- estimator, and 25% trimmed mean")
print(c(xbar,muM,mu25))
print("Their estimated standard deviations")
print(c(smed, muMst, ss25))
print("Their 0.95 confidence intervals")
print(rbind(intermean, interM, inter25)) |
cluster_groups <- function(data,
cols,
group_cols = NULL,
scale_min_fn = function(x) {
quantile(x, 0.025)
},
scale_max_fn = function(x) {
quantile(x, 0.975)
},
keep_centroids = FALSE,
multiplier = 0.05,
suffix = "_clustered",
keep_original = TRUE,
overwrite = FALSE) {
assert_collection <- checkmate::makeAssertCollection()
checkmate::assert_data_frame(data, add = assert_collection)
checkmate::assert_character(
cols,
min.len = 1,
min.chars = 1,
unique = TRUE,
add = assert_collection
)
checkmate::assert_character(
group_cols,
min.len = 1,
min.chars = 1,
unique = TRUE,
null.ok = TRUE,
add = assert_collection
)
checkmate::assert_function(scale_min_fn, add = assert_collection)
checkmate::assert_function(scale_max_fn, add = assert_collection)
checkmate::assert_flag(keep_centroids, add = assert_collection)
checkmate::assert_number(multiplier, add = assert_collection)
checkmate::assert_flag(keep_original, add = assert_collection)
checkmate::assert_string(suffix, add = assert_collection)
checkmate::reportAssertions(assert_collection)
checkmate::assert_names(colnames(data),
must.include = c(cols, group_cols),
add = assert_collection
)
checkmate::reportAssertions(assert_collection)
if (!is.null(group_cols) &&
length(intersect(group_cols, cols)) > 0) {
assert_collection$push("'group_cols' cannot contain a column from 'cols'.")
checkmate::reportAssertions(assert_collection)
}
if (!dplyr::is_grouped_df(data) && is.null(group_cols)) {
assert_collection$push("when 'group_cols' is 'NULL', 'data' should be grouped.")
checkmate::reportAssertions(assert_collection)
}
if (dplyr::is_grouped_df(data) && !is.null(group_cols)) {
assert_collection$push("'data' is already grouped but 'group_cols' is not 'NULL'")
checkmate::reportAssertions(assert_collection)
}
checkmate::reportAssertions(assert_collection)
if (!isTRUE(overwrite)) {
purrr::map(.x = cols, .f = ~ {
check_overwrite_(data = data,
nm = paste0(.x, suffix),
overwrite = overwrite)
})
}
if (!dplyr::is_grouped_df(data)) {
data <- dplyr::group_by(data, !!!rlang::syms(group_cols))
} else {
group_cols <- colnames(dplyr::group_keys(data))
}
expanded <- expand_distances(
data = data,
cols = cols,
multiplier = multiplier,
origin_fn = centroid,
suffix = "",
overwrite = TRUE,
keep_original = keep_original,
mult_col_name = NULL,
origin_col_name = NULL
)
scaled <- plyr::llply(cols, function(cl) {
min_max_scale(
x = expanded[[cl]],
new_min = scale_min_fn(data[[cl]]),
new_max = scale_max_fn(data[[cl]])
)
}) %>%
setNames(cols) %>%
dplyr::bind_cols()
clustered <- dplyr::bind_cols(
scaled,
expanded[, colnames(expanded) %ni% cols, drop = FALSE]
)
if (isTRUE(keep_centroids)) {
clustered <-
transfer_centroids(
to_data = clustered,
from_data = data,
cols = cols,
group_cols = group_cols
)
}
if (suffix != "") {
colnames(clustered) <-
purrr::map_chr(.x = colnames(clustered), .f = ~ {
ifelse(.x %in% cols, paste0(.x, suffix), .x)
})
if (isTRUE(keep_original)) {
clustered <- dplyr::bind_cols(
data[, cols, drop = FALSE],
clustered
)
}
} else if (!isTRUE(keep_original)) {
exclude <- setdiff(colnames(data), colnames(clustered))
if (length(exclude) > 0) {
clustered <- clustered[, colnames(clustered) %ni% exclude, drop = FALSE]
}
}
clustered %>%
dplyr::as_tibble()
} |
library(wikilake)
data(milakes)
res_df <- milakes
library(sp)
coordinates(res_df) <- ~ Lon + Lat
map("state", region = "michigan", mar = c(0, 0, 0, 0))
points(res_df, col = "red", pch = 19)
hist(log(res_df$`Max. depth`), main = "", xlab = "Max depth (log(m))") |
req_template <- function(req, template, ..., .env = parent.frame()) {
check_request(req)
check_string(template, "`template`")
pieces <- strsplit(template, " ")[[1]]
if (length(pieces) == 1) {
template <- pieces[[1]]
} else if (length(pieces) == 2) {
req <- req_method(req, pieces[[1]])
template <- pieces[[2]]
} else {
abort(c(
"Can't parse template `template`",
i = "Should have form like 'GET /a/b/c' or 'a/b/c/'"
))
}
dots <- list2(...)
if (length(dots) > 0 && !is_named(dots)) {
abort("All elements of ... must be named")
}
path <- template_process(template, dots, .env)
req_url_path(req, path)
}
template_process <- function(template, dots = list(), env = parent.frame()) {
type <- template_type(template)
vars <- template_vars(template, type)
vals <- map_chr(vars, template_val, dots = dots, env = env)
for (i in seq_along(vars)) {
pattern <- switch(type,
colon = paste0(":", vars[[i]]),
uri = paste0("{", vars[[i]], "}")
)
template <- gsub(pattern, vals[[i]], template, fixed = TRUE)
}
template
}
template_val <- function(name, dots, env) {
if (has_name(dots, name)) {
val <- dots[[name]]
} else if (env_has(env, name, inherit = TRUE)) {
val <- env_get(env, name, inherit = TRUE)
} else {
abort(glue("Can't find template variable '{name}'"))
}
if (!is.atomic(val) || length(val) != 1) {
abort(glue("Template variable '{name}' is not a simple scalar value"))
}
as.character(val)
}
template_vars <- function(x, type) {
if (type == "none") return(character())
pattern <- switch(type,
colon = ":([a-zA-Z0-9_]+)",
uri = "\\{(\\w+?)\\}"
)
loc <- gregexpr(pattern, x, perl = TRUE)[[1]]
start <- attr(loc, "capture.start")
end <- start + attr(loc, "capture.length") - 1
substring(x, start, end)
}
template_type <- function(x) {
if (grepl(":", x)) {
"colon"
} else if (grepl("\\{\\w+?\\}", x)) {
"uri"
} else {
"none"
}
} |
SRMPInferenceApprox <- function(performanceTable, criteriaMinMax, maxProfilesNumber, preferencePairs, indifferencePairs = NULL, alternativesIDs = NULL, criteriaIDs = NULL, timeLimit = 60, populationSize = 20, mutationProb = 0.1){
if (!(is.matrix(performanceTable) || is.data.frame(performanceTable)))
stop("performanceTable should be a matrix or a data frame")
if(is.null(colnames(performanceTable)))
stop("performanceTable columns should be named")
if (!is.matrix(preferencePairs) || is.data.frame(preferencePairs))
stop("preferencePairs should be a matrix or a data frame")
if (!(is.null(indifferencePairs) || is.matrix(indifferencePairs) || is.data.frame(indifferencePairs)))
stop("indifferencePairs should be a matrix or a data frame")
if (!(is.vector(criteriaMinMax)))
stop("criteriaMinMax should be a vector")
if(!all(sort(colnames(performanceTable)) == sort(names(criteriaMinMax))))
stop("criteriaMinMax should be named as the columns of performanceTable")
if (!(is.numeric(maxProfilesNumber)))
stop("maxProfilesNumber should be numberic")
maxProfilesNumber <- as.integer(maxProfilesNumber)
if (!(is.null(timeLimit)))
{
if(!is.numeric(timeLimit))
stop("timeLimit should be numeric")
if(timeLimit <= 0)
stop("timeLimit should be strictly positive")
}
if (!(is.null(populationSize)))
{
if(!is.numeric(populationSize))
stop("populationSize should be numeric")
if(populationSize < 10)
stop("populationSize should be at least 10")
}
if (!(is.null(mutationProb)))
{
if(!is.numeric(mutationProb))
stop("mutationProb should be numeric")
if(mutationProb < 0 || mutationProb > 1)
stop("mutationProb should be between 0 and 1")
}
if (!(is.null(alternativesIDs) || is.vector(alternativesIDs)))
stop("alternativesIDs should be a vector")
if (!(is.null(criteriaIDs) || is.vector(criteriaIDs)))
stop("criteriaIDs should be a vector")
if(dim(preferencePairs)[2] != 2)
stop("preferencePairs should have two columns")
if(!is.null(indifferencePairs))
if(dim(indifferencePairs)[2] != 2)
stop("indifferencePairs should have two columns")
if (!(maxProfilesNumber > 0))
stop("maxProfilesNumber should be strictly pozitive")
if (!is.null(alternativesIDs)){
performanceTable <- performanceTable[alternativesIDs,]
preferencePairs <- preferencePairs[(preferencePairs[,1] %in% alternativesIDs) & (preferencePairs[,2] %in% alternativesIDs),]
if(dim(preferencePairs)[1] == 0)
preferencePairs <- NULL
if(!is.null(indifferencePairs))
{
indifferencePairs <- indifferencePairs[(indifferencePairs[,1] %in% alternativesIDs) & (indifferencePairs[,2] %in% alternativesIDs),]
if(dim(indifferencePairs)[1] == 0)
indifferencePairs <- NULL
}
}
if (!is.null(criteriaIDs)){
performanceTable <- performanceTable[,criteriaIDs]
criteriaMinMax <- criteriaMinMax[criteriaIDs]
}
if (is.null(dim(performanceTable)))
stop("less than 2 criteria or 2 alternatives")
if (is.null(dim(preferencePairs)))
stop("preferencePairs is empty or the provided alternativesIDs have filtered out everything from within")
numAlt <- dim(performanceTable)[1]
numCrit <- dim(performanceTable)[2]
minEvaluations <- apply(performanceTable, 2, min)
maxEvaluations <- apply(performanceTable, 2, max)
outranking <- function(alternativePerformances1, alternativePerformances2, profilePerformances, criteriaWeights, lexicographicOrder, criteriaMinMax){
for (k in lexicographicOrder)
{
weightedSum1 <- 0
weightedSum2 <- 0
for (i in 1:numCrit)
{
if (criteriaMinMax[i] == "min")
{
if (alternativePerformances1[i] %<=% profilePerformances[k,i])
weightedSum1 <- weightedSum1 + criteriaWeights[i]
if (alternativePerformances2[i] %<=% profilePerformances[k,i])
weightedSum2 <- weightedSum2 + criteriaWeights[i]
}
else
{
if (alternativePerformances1[i] %>=% profilePerformances[k,i])
weightedSum1 <- weightedSum1 + criteriaWeights[i]
if (alternativePerformances2[i] %>=% profilePerformances[k,i])
weightedSum2 <- weightedSum2 + criteriaWeights[i]
}
}
if(weightedSum1 > weightedSum2)
return(1)
else if(weightedSum1 < weightedSum2)
return(-1)
}
return(0)
}
InitializePopulation <- function()
{
population <- list()
for(i in 1:populationSize)
{
values <- c(0,sort(runif(numCrit-1,0,1)),1)
weights <- sapply(1:numCrit, function(i) return(values[i+1]-values[i]))
names(weights) <- colnames(performanceTable)
profilesNumber <- sample(1:maxProfilesNumber, 1)
profiles <- NULL
for(j in 1:numCrit)
{
if(criteriaMinMax[j] == 'max')
profiles <- cbind(profiles,sort(runif(profilesNumber,minEvaluations[j],maxEvaluations[j])))
else
profiles <- cbind(profiles,sort(runif(profilesNumber,minEvaluations[j],maxEvaluations[j]), decreasing = TRUE))
}
colnames(profiles) <- colnames(performanceTable)
lexicographicOrder <- sample(1:profilesNumber, profilesNumber)
population[[length(population)+1]] <- list(criteriaWeights = weights, referenceProfilesNumber = profilesNumber, referenceProfiles = profiles, lexicographicOrder = lexicographicOrder)
}
return(population)
}
Fitness <- function(individual)
{
total <- 0
ok <- 0
for (i in 1:dim(preferencePairs)[1]){
comparison <- outranking(performanceTable[preferencePairs[i,1],],performanceTable[preferencePairs[i,2],],individual$referenceProfiles, individual$criteriaWeights, individual$lexicographicOrder, criteriaMinMax)
if(comparison == 1)
ok <- ok + 1
total <- total + 1
}
if(!is.null(indifferencePairs))
for (i in 1:dim(indifferencePairs)[1]){
comparison <- outranking(performanceTable[indifferencePairs[i,1],],performanceTable[indifferencePairs[i,2],],individual$referenceProfiles, individual$criteriaWeights, individual$lexicographicOrder, criteriaMinMax)
if(comparison == 0)
ok <- ok + 1
total <- total + 1
}
return(ok/total)
}
Reproduce <- function(parents)
{
children <- list()
for(k in 1:maxProfilesNumber)
{
kParents <- Filter(function(element){if(element$referenceProfilesNumber == k) return(TRUE) else return(FALSE)}, parents)
if(!is.null(kParents))
{
numPairs <- as.integer(length(kParents)/2)
if(numPairs > 0)
{
pairings <- matrix(sample(1:length(kParents),numPairs*2),numPairs,2)
for(i in 1:numPairs)
{
parent1 <- kParents[[pairings[i,1]]]
parent2 <- kParents[[pairings[i,2]]]
criteria <- sample(colnames(performanceTable), numCrit)
pivot <- runif(1,1,numCrit - 1)
profiles1 <- matrix(rep(0,numCrit*k),k,numCrit)
profiles2 <- matrix(rep(0,numCrit*k),k,numCrit)
colnames(profiles1) <- colnames(performanceTable)
colnames(profiles2) <- colnames(performanceTable)
for(l in 1:k)
for(j in 1:numCrit)
{
if(j <= pivot)
{
profiles1[l,criteria[j]] <- parent1$referenceProfiles[l,criteria[j]]
profiles2[l,criteria[j]] <- parent2$referenceProfiles[l,criteria[j]]
}
else
{
profiles1[l,criteria[j]] <- parent2$referenceProfiles[l,criteria[j]]
profiles2[l,criteria[j]] <- parent1$referenceProfiles[l,criteria[j]]
}
}
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent1$referenceProfiles, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent2$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent2$referenceProfiles, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent2$referenceProfiles, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent2$referenceProfiles, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles1, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles2, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent2$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles1, lexicographicOrder = parent1$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent2$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles2, lexicographicOrder = parent1$lexicographicOrder)
if(!all(parent1$lexicographicOrder == parent2$lexicographicOrder))
{
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent2$referenceProfiles, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = parent2$referenceProfiles, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles1, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent1$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles2, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent2$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles1, lexicographicOrder = parent2$lexicographicOrder)
children[[length(children)+1]] <- list(criteriaWeights = parent2$criteriaWeights, referenceProfilesNumber = k, referenceProfiles = profiles2, lexicographicOrder = parent2$lexicographicOrder)
}
}
}
if(length(kParents)%%2 == 1)
children[[length(children)+1]] <- kParents[[length(kParents)]]
}
}
numChildren <- length(children)
for(i in 1:numChildren)
{
if(runif(1,0,1) < mutationProb)
{
if(sample(c(FALSE,TRUE), 1) && !(children[[i]]$referenceProfilesNumber == maxProfilesNumber))
{
children[[i]]$referenceProfilesNumber <- children[[i]]$referenceProfilesNumber + 1
k <- sample(1:children[[i]]$referenceProfilesNumber, 1)
minVals <- minEvaluations
maxVals <- maxEvaluations
if(k < children[[i]]$referenceProfilesNumber)
{
for(criterion in colnames(performanceTable))
{
if(criteriaMinMax[criterion] == 'max')
maxVals[criterion] <- children[[i]]$referenceProfiles[k,criterion]
else
minVals[criterion] <- children[[i]]$referenceProfiles[k,criterion]
}
}
if(k > 1)
{
for(criterion in colnames(performanceTable))
{
if(criteriaMinMax[criterion] == 'max')
minVals[criterion] <- children[[i]]$referenceProfiles[k-1,criterion]
else
maxVals[criterion] <- children[[i]]$referenceProfiles[k-1,criterion]
}
}
newProfile <- matrix(sapply(1:numCrit, function(j){return(runif(1,minVals[j],maxVals[j]))}), nrow = 1, ncol = numCrit)
colnames(newProfile) <- colnames(performanceTable)
if(k == 1)
children[[i]]$referenceProfiles <- rbind(newProfile , children[[i]]$referenceProfiles)
else if(k == children[[i]]$referenceProfilesNumber)
children[[i]]$referenceProfiles <- rbind(children[[i]]$referenceProfiles, newProfile)
else
children[[i]]$referenceProfiles <- rbind(children[[i]]$referenceProfiles[1:(k-1),], newProfile , children[[i]]$referenceProfiles[k:(children[[i]]$referenceProfilesNumber-1),])
children[[i]]$lexicographicOrder <- sapply(children[[i]]$lexicographicOrder, function(val){if(val >= k) return(val + 1) else return(val)})
i1 <- sample(1:children[[i]]$referenceProfilesNumber, 1)
if(i1 == 1)
children[[i]]$lexicographicOrder <- c(k,children[[i]]$lexicographicOrder)
else if(i1 == children[[i]]$referenceProfilesNumber)
children[[i]]$lexicographicOrder <- c(children[[i]]$lexicographicOrder,k)
else
children[[i]]$lexicographicOrder <- c(children[[i]]$lexicographicOrder[1:(i1-1)],k,children[[i]]$lexicographicOrder[i1:(children[[i]]$referenceProfilesNumber-1)])
}
else if(!(children[[i]]$referenceProfilesNumber == 1))
{
children[[i]]$referenceProfilesNumber <- children[[i]]$referenceProfilesNumber - 1
k <- sample(1:(children[[i]]$referenceProfilesNumber + 1), 1)
children[[i]]$referenceProfiles <- children[[i]]$referenceProfiles[-k,,drop=FALSE]
children[[i]]$lexicographicOrder <- children[[i]]$lexicographicOrder[children[[i]]$lexicographicOrder != k]
children[[i]]$lexicographicOrder <- sapply(children[[i]]$lexicographicOrder, function(val){if(val > k) return(val - 1) else return(val)})
}
}
for(k in 1:children[[i]]$referenceProfilesNumber)
{
for(criterion in colnames(performanceTable))
{
if(runif(1,0,1) < mutationProb)
{
maxVal <- maxEvaluations[criterion]
minVal <- minEvaluations[criterion]
if(k < children[[i]]$referenceProfilesNumber)
{
if(criteriaMinMax[criterion] == 'max')
maxVal <- children[[i]]$referenceProfiles[k+1,criterion]
else
minVal <- children[[i]]$referenceProfiles[k+1,criterion]
}
if(k > 1)
{
if(criteriaMinMax[criterion] == 'max')
minVal <- children[[i]]$referenceProfiles[k-1,criterion]
else
maxVal <- children[[i]]$referenceProfiles[k-1,criterion]
}
children[[i]]$referenceProfiles[k,criterion] <- runif(1,minVal,maxVal)
}
}
}
for(j1 in 1:(numCrit-1))
{
for(j2 in (j1+1):numCrit)
{
if(runif(1,0,1) < mutationProb)
{
criteria <- c(colnames(performanceTable)[j1],colnames(performanceTable)[j2])
minVal <- 0 - children[[i]]$criteriaWeights[criteria[1]]
maxVal <- children[[i]]$criteriaWeights[criteria[2]]
tradeoff <- runif(1,minVal,maxVal)
children[[i]]$criteriaWeights[criteria[1]] <- children[[i]]$criteriaWeights[criteria[1]] + tradeoff
children[[i]]$criteriaWeights[criteria[2]] <- children[[i]]$criteriaWeights[criteria[2]] - tradeoff
}
}
}
if(runif(1,0,1) < mutationProb && children[[i]]$referenceProfilesNumber > 1)
{
i1 <- sample(1:children[[i]]$referenceProfilesNumber, 1)
adjacent <- NULL
if(i1 > 1)
adjacent <- c(adjacent, i1 - 1)
if(i1 < children[[i]]$referenceProfilesNumber)
adjacent <- c(adjacent, i1 + 1)
i2 <- sample(adjacent, 1)
temp <- children[[i]]$lexicographicOrder[i1]
children[[i]]$lexicographicOrder[i1] <- children[[i]]$lexicographicOrder[i2]
children[[i]]$lexicographicOrder[i2] <- temp
}
}
return(children)
}
startTime <- Sys.time()
population <- InitializePopulation()
bestIndividual <- list(fitness = 0)
ct <- 0
while(as.double(difftime(Sys.time(), startTime, units = 'secs')) < timeLimit)
{
evaluations <- unlist(lapply(population, Fitness))
maxFitness <- max(evaluations)
if(maxFitness > bestIndividual$fitness)
{
bestIndividual <- population[[match(maxFitness,evaluations)]]
bestIndividual$fitness <- maxFitness
}
if(as.double(difftime(Sys.time(), startTime, units = 'secs')) / 5 > ct)
{
ct <- ct + 1
}
if(bestIndividual$fitness == 1)
break
if(length(population) > populationSize)
{
evaluations <- evaluations^2
newPopulation <- list()
i <- 1
while(length(newPopulation) < populationSize)
{
if(runif(1,0,1) <= evaluations[i])
{
evaluations[i] <- -1
newPopulation[[length(newPopulation)+1]] <- population[[i]]
}
i <- i + 1
if(i > length(population))
i <- 1
}
population <- newPopulation
}
population <- Reproduce(population)
}
return(bestIndividual)
} |
skew.ratio = function(x){
skew(x)/se.skew(x)
} |
plot_imb_1 <- function(df_plot, df_names, text_labels, label_angle = NULL,
label_color, label_size, col_palette){
nudge <- max(df_plot$pcnt) / 50
df_plot <- df_plot %>%
mutate(col_name = factor(col_name, levels = as.character(col_name))) %>%
mutate(label = paste0(value, " - ", round(pcnt, 1), "%")) %>%
mutate(value = case_when(is.na(value) ~ "NA", TRUE ~ value))
plt <- df_plot %>%
ggplot(aes(x = col_name, y = pcnt, fill = col_name, label = value)) +
geom_bar(stat = "identity") +
labs(x = '', y = "% of values",
title = paste0("df::", df_names$df1, " most common levels by column")) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
scale_fill_manual(values = user_colours(nrow(df_plot), col_palette)) +
guides(fill = 'none')
if(text_labels){
x = df_plot$col_name
y = df_plot$pcnt
z = paste0(df_plot$value, ': ', round(df_plot$pcnt, 2))
z[nchar(z) == 0] <- NA
big_bar <- 0.2 * max(y, na.rm = T)
label_df <- tibble(col_name = x, pcnt = y , label = z)
label_df$fill <- NA
label_white <- label_df %>% filter(pcnt > big_bar)
max_lab <- ifelse(all(is.na(label_white$pcnt)), NA, max(label_white$pcnt, na.rm = T))
label_grey <- label_df %>%
filter(pcnt <= big_bar, pcnt > 0) %>%
mutate(ymax = pcnt + 0.5 * max_lab)
label_zero <- label_df %>% filter(pcnt == 0)
if(nrow(label_white) > 0){
plt <- plt +
annotate(
'text',
x = label_white$col_name,
y = label_white$pcnt - nudge,
label = label_white$label,
color = ifelse(is.null(label_color), "white", label_color),
angle = ifelse(is.null(label_angle), 90, label_angle),
size = ifelse(is.null(label_size), 3.5, label_size),
hjust = 1
)
}
if(nrow(label_grey) > 0){
plt <- plt +
annotate(
'text',
x = label_grey$col_name,
y = label_grey$pcnt + nudge,
label = label_grey$label,
color = ifelse(is.null(label_color), "gray50", label_color),
angle = ifelse(is.null(label_angle), 90, label_angle),
size = ifelse(is.null(label_size), 3.5, label_size),
hjust = 0
)
}
if(nrow(label_zero) > 0){
plt <- plt +
annotate(
'text',
x = label_zero$col_name,
y = nudge,
label = 0,
color = ifelse(is.null(label_color), "gray50", label_color),
angle = ifelse(is.null(label_angle), 90, label_angle),
size = ifelse(is.null(label_size), 3.5, label_size),
hjust = 0
)
}
}
plt
}
plot_imb_2 <- function(df_plot, df_names, alpha, text_labels, col_palette){
df_plot <- df_plot %>%
mutate(col_name = paste0(col_name, "\n(", value, ")"))
na_tab <- df_plot
df_plot <- df_plot %>%
select(-starts_with("cnt")) %>%
gather(key = "data_frame", value = "pcnt", -col_name, -p_value, -value) %>%
mutate(data_frame = as.integer(gsub("pcnt_", "", data_frame))) %>%
mutate(col_name = factor(col_name, levels = as.character(na_tab$col_name))) %>%
mutate(data_frame = unlist(df_names)[data_frame])
df_plot <- df_plot[nrow(df_plot):1, ]
p_val_tab <- df_plot %>%
mutate(is_sig = as.integer(p_value < alpha) + 2, index = 1:nrow(df_plot)) %>%
replace_na(list(is_sig = 1)) %>%
select(is_sig, index)
yrange <- abs(diff(range(df_plot$pcnt, na.rm = TRUE)))
df_plot <- df_plot %>%
group_by(col_name) %>%
arrange(data_frame) %>%
mutate(nudge = as.integer((abs(diff(pcnt)) / yrange) < 0.02)) %>%
ungroup
df_plot$nudge[(df_plot$data_frame == unique(df_plot$data_frame)[1]) & (df_plot$nudge == 1)] <- -1
nudge_vec <- df_plot$nudge
nudge_vec[is.na(nudge_vec)] <- 0
df_plot_col_name <- df_plot$col_name
plt <- df_plot %>%
ggplot(aes(x = factor(col_name, levels = unique(df_plot_col_name)),
y = pcnt,
colour = data_frame)) +
geom_blank() + theme_bw() +
theme(panel.border = element_blank(), panel.grid.major = element_blank()) +
geom_rect(
fill = c(NA, "gray50", user_colours(9, col_palette)[9])[p_val_tab$is_sig], alpha = 0.2,
xmin = p_val_tab$index - 0.4, xmax = p_val_tab$index + 0.4,
ymin = -100, ymax = 200, linetype = "blank") +
geom_hline(yintercept = 0, linetype = "dashed", color = "lightsteelblue4") +
geom_point(size = 3.7, color = "black", na.rm = TRUE, position = position_nudge(x = -0.15 * nudge_vec)) +
geom_point(size = 3, na.rm = TRUE, position = position_nudge(x = -0.15 * nudge_vec)) +
coord_flip() +
scale_colour_manual(values = get_best_pair(col_palette), name = "Data frame")
ttl <- paste0("Comparison of most common levels")
sttl <- bquote("Color/gray stripes mean different/equal imbalance")
plt <- plt +
labs(x = "", title = ttl, subtitle = sttl) +
guides(color = guide_legend(override.aes = list(fill = NA))) +
labs(y = "% of column", x = "")
plt
}
plot_imb_grouped <- function(df_plot, df_names, text_labels, col_palette, plot_type){
group_name <- colnames(df_plot)[1]
if(plot_type == 1){
col_ord <- df_plot %>%
ungroup %>%
group_by(col_name) %>%
summarize(md_pcnt = median(pcnt, na.rm = T)) %>%
arrange(md_pcnt) %>%
.$col_name
out <- df_plot %>%
ungroup %>%
mutate(col_name = factor(col_name, levels = col_ord)) %>%
arrange(col_name)
jitter_width <- ifelse(length(unique(out$col_name)) > 10, 0, 0.25)
plt <- out %>%
ggplot(aes_string(x = 'col_name', y = 'pcnt', col = 'col_name', group = group_name)) +
geom_jitter(alpha = 0.5, width = jitter_width, height = 0, size = 1.8) +
theme(legend.position='none') +
coord_flip() +
ylab("Imbalance by group") +
xlab("")
} else {
plt <- plot_grouped(
df = df_plot,
value = "pcnt",
series = "col_name",
group = group_name,
plot_type = plot_type,
col_palette = col_palette,
text_labels = text_labels,
ylab = "% imbalance"
)
}
plt
} |
check_prediction_data.PredictionDataRegr = function(pdata) {
pdata$row_ids = assert_row_ids(pdata$row_ids)
n = length(pdata$row_ids)
if (!is.null(pdata$response)) {
pdata$response = assert_numeric(unname(pdata$response))
assert_prediction_count(length(pdata$response), n, "response")
}
if (!is.null(pdata$se)) {
pdata$se = assert_numeric(unname(pdata$se), lower = 0)
assert_prediction_count(length(pdata$se), n, "se")
}
if (!is.null(pdata$distr)) {
assert_class(pdata$distr, "VectorDistribution")
if (is.null(pdata$response)) {
pdata$response = unname(pdata$distr$mean())
}
if (is.null(pdata$se)) {
pdata$se = unname(pdata$distr$stdev())
}
}
pdata
}
is_missing_prediction_data.PredictionDataRegr = function(pdata) {
miss = logical(length(pdata$row_ids))
if (!is.null(pdata$response)) {
miss = is.na(pdata$response)
}
if (!is.null(pdata$se)) {
miss = miss | is.na(pdata$se)
}
pdata$row_ids[miss]
}
c.PredictionDataRegr = function(..., keep_duplicates = TRUE) {
dots = list(...)
assert_list(dots, "PredictionDataRegr")
assert_flag(keep_duplicates)
if (length(dots) == 1L) {
return(dots[[1L]])
}
predict_types = names(mlr_reflections$learner_predict_types$regr)
predict_types = map(dots, function(x) intersect(names(x), predict_types))
if (!every(predict_types[-1L], setequal, y = predict_types[[1L]])) {
stopf("Cannot combine predictions: Different predict types")
}
elems = c("row_ids", "truth", intersect(predict_types[[1L]], c("response", "se")))
tab = map_dtr(dots, function(x) x[elems], .fill = FALSE)
if (!keep_duplicates) {
tab = unique(tab, by = "row_ids", fromLast = TRUE)
}
result = as.list(tab)
if ("distr" %in% predict_types[[1L]]) {
require_namespaces("distr6")
result$distr = do.call(c, map(dots, "distr"))
}
new_prediction_data(result, "regr")
}
filter_prediction_data.PredictionDataRegr = function(pdata, row_ids) {
keep = pdata$row_ids %in% row_ids
pdata$row_ids = pdata$row_ids[keep]
pdata$truth = pdata$truth[keep]
if (!is.null(pdata$response)) {
pdata$response = pdata$response[keep]
}
if (!is.null(pdata$se)) {
pdata$se = pdata$se[keep]
}
pdata
} |
aemet_normal_clim <- function(station = NULL,
verbose = FALSE,
return_sf = FALSE) {
if (is.null(station)) {
stop("Station can't be missing")
}
stopifnot(is.logical(return_sf))
stopifnot(is.logical(verbose))
station <- as.character(station)
final_result <- NULL
for (i in seq_len(length(station))) {
apidest <-
paste0(
"/api/valores/climatologicos/normales/estacion/",
station[i]
)
final_result <-
dplyr::bind_rows(
final_result,
get_data_aemet(apidest, verbose)
)
}
final_result <- dplyr::distinct(final_result)
if (verbose) {
message("\nGuessing fields...")
}
final_result <-
aemet_hlp_guess(final_result, "indicativo", dec_mark = ".")
if (return_sf) {
sf_stations <-
aemet_stations(verbose, return_sf = FALSE)
sf_stations <-
sf_stations[c("indicativo", "latitud", "longitud")]
final_result <- dplyr::left_join(final_result,
sf_stations,
by = "indicativo"
)
final_result <-
aemet_hlp_sf(final_result, "latitud", "longitud", verbose)
}
return(final_result)
}
aemet_normal_clim_all <- function(verbose = FALSE,
return_sf = FALSE) {
stations <- aemet_stations(verbose = verbose)
data_all <-
aemet_normal_clim(
stations$indicativo,
verbose = verbose,
return_sf = return_sf
)
return(data_all)
} |
diffinv <- function (x, ...) { UseMethod("diffinv") }
diffinv.vector <- function (x, lag = 1L, differences = 1L, xi, ...)
{
if (!is.vector(x)) stop ("'x' is not a vector")
lag <- as.integer(lag); differences <- as.integer(differences)
if (lag < 1L || differences < 1L) stop ("bad value for 'lag' or 'differences'")
if(missing(xi)) xi <- rep(0., lag*differences)
if (length(xi) != lag*differences)
stop("'xi' does not have the right length")
if (differences == 1L) {
x <- as.double(x)
xi <- as.double(xi)
n <- as.integer(length(x))
if(is.na(n)) stop(gettextf("invalid value of %s", "length(x)"), domain = NA)
.Call(C_intgrt_vec, x, xi, lag)
}
else
diffinv.vector(diffinv.vector(x, lag, differences-1L,
diff(xi, lag=lag, differences=1L)),
lag, 1L, xi[1L:lag])
}
diffinv.default <- function (x, lag = 1, differences = 1, xi, ...)
{
if (is.matrix(x)) {
n <- nrow(x)
m <- ncol(x)
y <- matrix(0, nrow = n+lag*differences, ncol = m)
if(m >= 1) {
if(missing(xi)) xi <- matrix(0.0, lag*differences, m)
if(NROW(xi) != lag*differences || NCOL(xi) != m)
stop("incorrect dimensions for 'xi'")
for (i in 1L:m)
y[,i] <- diffinv.vector(as.vector(x[,i]), lag, differences,
as.vector(xi[,i]))
}
}
else if (is.vector(x))
y <- diffinv.vector(x, lag, differences, xi)
else
stop ("'x' is not a vector or matrix")
y
}
diffinv.ts <- function (x, lag = 1, differences = 1, xi, ...)
{
y <- diffinv.default(if(is.ts(x) && is.null(dim(x))) as.vector(x) else
as.matrix(x), lag, differences, xi)
ts(y, frequency = frequency(x), end = end(x))
}
toeplitz <- function (x)
{
if(!is.vector(x)) stop("'x' is not a vector")
n <- length(x)
A <- matrix(raw(), n, n)
matrix(x[abs(col(A) - row(A)) + 1L], n, n)
} |
intraCMM <-
function(d,n,l=0, B=0, DB=c(0,0), JC=FALSE,CI_Boot,type="bca", plot=FALSE){
if(is.numeric(d)){d=d}else{stop("d is not numeric")}
if(is.numeric(n)){n=n}else{stop("n is not numeric")}
if(B==0&& plot==TRUE){stop("please select a number of bootstrap repititions for the plot")}
if(B%%1==0){B=B}else{stop("B is not an integer")}
if(DB[1]%%1==0 && DB[2]%%1==0 ){DB=DB}else{stop("At least one entry in DB is not an integer")}
if(length(d)==length(n)){}else{stop("Input vectors do not have the same length")}
d1=d/n
CI=0
estimate=function(X,CI){
if(CI==0){
pd_mean=1/length(X)*sum(X)
var_dat= 1/length(X)*sum((X^2-X/n))
foo=function(rho){
corr=matrix(c(1,rho,rho,1),2)
prob=pmvnorm(lower=c(-Inf,-Inf),upper=c(qnorm(pd_mean),qnorm(pd_mean)),mean=c(0,0),corr=corr)
return(prob-var_dat)
}
Res<-uniroot(foo,c(0,1))$root
s=qnorm(pd_mean)
ABL1<- 1/(2*pi*sqrt(1-Res^2))*exp(-(s^2/(1+Res)))
ABL2<- ((s^2+ Res*(1-2*s^2) + s^2*Res^2 -Res^3)/(2*pi*(1-Res^2)^(5/2)))*exp(-(s^2/(1+Res)))
Time<-length(X)
if(l>0){
tryCatch(AC<-(acf(X^2, plot = FALSE, type = "covariance")$acf)[(1:l),1,1], error = function(e) 0)
Sum=NULL
for (z in 1:l){
Sum[z]<-(1-z/Time)*AC[z]
}
AB=sum(Sum)} else{AB=0}
nX=X^2
nM=1/length(X)*sum(nX)
var2=var(nX)
Res2=(Res +(ABL2/(Time*ABL1^3))*(var2/2 + AB))
Est<-list(Original =(Res +(ABL2/(Time*ABL1^3))*(var2/2 + AB)))
}else{
pd_mean=1/length(X)*sum(X)
var_dat= 1/length(X)*sum((X^2-X/n))
foo=function(rho){
corr=matrix(c(1,rho,rho,1),2)
prob=pmvnorm(lower=c(-Inf,-Inf),upper=c(qnorm(pd_mean),qnorm(pd_mean)),mean=c(0,0),corr=corr)
return(prob-var_dat)
}
Res<-uniroot(foo,c(0,1))$root
s=qnorm(pd_mean)
ABL1<- 1/(2*pi*sqrt(1-Res^2))*exp(-(s^2/(1+Res)))
ABL2<- ((s^2+ Res*(1-2*s^2) + s^2*Res^2 -Res^3)/(2*pi*(1-Res^2)^(5/2)))*exp(-(s^2/(1+Res)))
Time<-length(X)
if(l>0){
tryCatch(AC<-(acf(X^2, plot = FALSE, type = "covariance")$acf)[(1:l),1,1], error = function(e) 0)
Sum=NULL
for (z in 1:l){
Sum[z]<-(1-z/Time)*AC[z]
}
AB=sum(Sum)} else{AB=0}
nX=X^2
nM=1/length(X)*sum(nX)
var2=var(nX)
Res2=(Res +(ABL2/(Time*ABL1^3))*(var2/2 + AB))
Est<-list(Original =Res2, CI=c(Res2-(qt(1-(1-CI)/2,Time-1)*abs(1/ABL1))/sqrt(Time)*sqrt(var2+2*(AB)),Res2+(qt(1-(1-CI)/2,Time-1)*abs(1/ABL1))/sqrt(Time)*sqrt(var2+2*(AB))))
}
}
Estimate_Standard<- estimate(d1,CI)
if(DB[1]!=0){
IN=DB[1]
OUT=DB[2]
theta1=NULL
theta2=matrix(ncol = OUT, nrow=IN)
for(i in 1:OUT){
N<-length(d1)
Ib<-sample(N,N,replace=TRUE)
Db<-d1[Ib]
try(theta1[i]<-estimate(Db,CI)$Original, silent = TRUE)
for(c in 1:IN){
Ic<-sample(N,N,replace=TRUE)
Dc<-Db[Ic]
try( theta2[c,i]<-estimate(Dc,CI)$Original, silent = TRUE)
}
}
Boot1<- mean(theta1, na.rm = TRUE)
Boot2<- mean(theta2, na.rm = TRUE)
BC<- 2*Estimate_Standard$Original -Boot1
DBC<- (3*Estimate_Standard$Original-3*Boot1+Boot2)
Estimate_DoubleBootstrap<-list(Original = Estimate_Standard$Original, Bootstrap=BC, Double_Bootstrap=DBC, oValues=theta1, iValues=theta2)
}
if(B>0){
N<-length(n)
D<- matrix(ncol=1, nrow=N,d1)
BCA=function(data, indices){
d <- data[indices,]
tryCatch(estimate(d,CI)$Original,error=function(e)NA)
}
boot1<- boot(data = D, statistic = BCA, R=B)
Estimate_Bootstrap<-list(Original = boot1$t0, Bootstrap=2*boot1$t0 - mean(boot1$t,na.rm = TRUE),bValues=boot1$t )
if(missing(CI_Boot)){Estimate_Bootstrap=Estimate_Bootstrap}else{
if(type=="norm"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type)$normal[2:3])}
if(type=="basic"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type)$basic[4:5])}
if(type=="perc"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))$percent[4:5]}
if(type=="bca"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))$bca[4:5]}
if(type=="all"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))}
CI=CI_Boot
pd_mean=mean(d1)
var_dat= 1/length(d1)*sum((d1^2-d1/n))
foo=function(rho){
corr=matrix(c(1,rho,rho,1),2)
prob=pmvnorm(lower=c(-Inf,-Inf),upper=c(qnorm(pd_mean),qnorm(pd_mean)),mean=c(0,0),corr=corr)
return(prob-var_dat)
}
Res<-uniroot(foo,c(0,1))$root
s=qnorm(pd_mean)
ABL1<- 1/(2*pi*sqrt(1-Res^2))*exp(-(s^2/(1+Res)))
ABL2<- ((s^2+ Res*(1-2*s^2) + s^2*Res^2 -Res^3)/(2*pi*(1-Res^2)^(5/2)))*exp(-(s^2/(1+Res)))
nX=d1^2
nM=1/length(d1^2)*sum(d1^2)
var2=1/length(d1)*sum(nX^2-nM^2)
if(l>0){
tryCatch(AC<-(acf(d1^2, plot = FALSE, type = "covariance")$acf)[(1:l),1,1], error = function(e) 0)
Sum=NULL
for (z in 1:l){
Sum[z]<-(1-z/N)*AC[z]
}
AB=sum(Sum)} else{AB=0}
Res2=(Res +(ABL2/(N*ABL1^3))*(var2/2 + AB))
CI=c(Res2-(qt(1-(1-CI)/2,N-1)/abs(ABL1))/sqrt(N)*sqrt(var2+2*(AB)),Res2+(qt(1-(1-CI)/2,N-1)/abs(ABL1))/sqrt(N)*sqrt(var2+2*(AB)))
Estimate_Bootstrap<-list(Original = boot1$t0, Bootstrap=2*boot1$t0 - mean(boot1$t,na.rm = TRUE),CI=CI,CI_Boot=Conf,bValues=boot1$t )
}
if(plot==TRUE){
Dens<-density(boot1$t, na.rm = TRUE)
XY<-cbind(Dens$x,Dens$y)
label<-data.frame(rep("Bootstrap density",times=length(Dens$x)))
Plot<-cbind(XY,label)
colnames(Plot)<-c("Estimate","Density","Label")
SD<-cbind(rep(boot1$t0,times=length(Dens$x)), Dens$y,rep("Standard estimate",times=length(Dens$x)))
colnames(SD)<-c("Estimate","Density","Label")
BC<-cbind(rep(Estimate_Bootstrap$Bootstrap,times=length(Dens$x)), Dens$y,rep("Bootstrap corrected estimate",times=length(Dens$x)))
colnames(BC)<-c("Estimate","Density","Label")
Plot<-rbind(Plot,SD, BC)
Plot$Estimate<-as.numeric(Plot$Estimate)
Plot$Density<- as.numeric(Plot$Density)
Estimate<-Plot$Estimate
Density<-Plot$Density
Label<-Plot$Label
P<-ggplot()
P<-P+with(Plot, aes(x=Estimate, y=Density, colour=Label)) +
geom_line()+
scale_colour_manual(values = c("black", "red", "orange"))+
theme_minimal(base_size = 15) +
ggtitle("Bootstrap Density" )+
theme(plot.title = element_text(hjust = 0.5),legend.position="bottom",legend.text = element_text(size = 12),legend.title = element_text( size = 12), legend.justification = "center",axis.text.x= element_text(face = "bold", size = 12))
print(P)
}
}
if(JC==TRUE){
N=length(d1)
Test=NULL
for(v in 1:N){
d2<-d1[-v]
try(Test[v]<-estimate(d2,CI)$Original)
}
Estimate_Jackknife<-list(Original = Estimate_Standard$Original, Jackknife=(N*Estimate_Standard$Original-(N-1)*mean(Test)))
}
if(B>0){return(Estimate_Bootstrap)}
if(JC==TRUE){return(Estimate_Jackknife)}
if(DB[1]!=0){return(Estimate_DoubleBootstrap)}
if(B==0 && JC==FALSE && DB[1]==0){return(Estimate_Standard)}
} |
msc.pca <- function(clustmatrix, samples, groups, n = 20, labels = TRUE, title = NULL) {
if (!is.factor(groups)) stop("ERROR: groups should be a factor")
if (length(samples) != length(groups)) stop("ERROR: samples and groups are not of equal length")
if (length(samples) != ncol(clustmatrix)) {
answer <- utils::menu(c("Yes", "No"),
title="WARNING: You entered a subset of your samples.\nDo you wish to procede?")
if (answer!=1) stop("Function stopped")
}
pca <- FactoMineR::PCA(t(clustmatrix[,samples]),scale.unit=F, ncp=3, graph = F)
if (labels == F) {
plt <- factoextra::fviz_pca_ind(pca, geom.ind='point', col.ind = groups,
addEllipses = F, legend.title="", alpha.ind = 0.8,
pointsize = 4, invisible = "quali", title = title)
} else {
plt <- factoextra::fviz_pca_ind(pca, col.ind = groups, labelsize=3,
addEllipses = F, legend.title="", alpha.ind = 0.8,
pointsize = 4, invisible = "quali",
repel = TRUE, title = title)
}
contr <- factoextra::get_pca_var(pca)$contrib
cl_index <- unique(order(contr[,1], decreasing = T)[1:n],
order(contr[,2], decreasing = T)[1:n],
order(contr[,3], decreasing = T)[1:n])
cl_names <- rownames(clustmatrix[cl_index,samples])
results <- list("plot" = plt,
"eigenvalues" = factoextra::fviz_eig(pca, addlabels = TRUE),
"clustnames" = cl_names)
return(results)
} |
`fun.RMFMKL.ml` <-
function (data, fmkl.init = c(-0.25, 1.5), leap = 3, FUN = "runif.sobol",no=10000)
{
RMFMKL <- fun.fit.gl.v3(a=fmkl.init[1], b=fmkl.init[2], data=data, fun=fun.auto.mm.fmkl, no=no,
leap = leap, FUN = FUN)$unique.optim.result
RMFMKL <- fun.fit.gl.v3a(RMFMKL[1], RMFMKL[2], RMFMKL[3],
RMFMKL[4], data, "fmkl")
return(RMFMKL)
} |
print.reduced <-
function (x, ...)
{
x = x["reduc"]
NextMethod()
} |
word_ref <- function(idx) paste(idx$index, idx$src)
copy_src <- function(x, y)
{
attr(x, "row") <- attr(y, "row")
attr(x, "col") <- attr(y, "col")
attr(x, "subrow") <- attr(y, "subrow")
attr(x, "subcol") <- attr(y, "subcol")
x
}
key <- function(x, id)
{
if(is.null(attr(x, "row")) || is.null(attr(x, "col"))) return(NULL)
row <- attr(x, "row")
col <- attr(x, "col")
subrow <- attr(x, "subrow")
subcol <- attr(x, "subcol")
rv <- if(is.null(subrow)) row else paste0(row, '[',subrow,']')
cv <- if(is.null(subcol)) col else paste0(col, '[',subcol,']')
paste0(id, ":", rv,":",cv)
}
index <- function(object, ...)
{
UseMethod("index", object)
}
index.tangram <- function(object, id="tangram", key.len=4, ...)
{
nrows <- rows(object)
ncols <- cols(object)
result<-
unlist(sapply(1:nrows, simplify=FALSE, FUN=function(row) {
unlist(sapply(1:ncols, simplify=FALSE, FUN=function(col) {
c(index(object[[row]][[col]], id, key.len=key.len))
}))
}))
names(result) <- NULL
result <- matrix(result, ncol=3, byrow=TRUE)
colnames(result) <- c("key", "src", "value")
result
}
index.default <- function(object, id="tangram", name=NULL, key.len=4, ...)
{
src <- key(object, id)
if(is.null(src)) return(NULL)
nms <- if(is.null(name)) names(object) else nms
nms <- if(is.null(nms)) paste0(class(object)[1], 1:length(object)) else nms
value <- as.character(object[!is.na(nms) & nchar(nms) > 0])
nms <- nms[!is.na(nms) & nchar(nms) > 0]
srcs <- paste0(src, ":", nms)
idx <- vapply(srcs,
function(x) substr(base64encode(charToRaw(digest(x))),1,key.len),
"character")
lapply(1:length(idx), function(i){
list(index=idx[i], src=srcs[i], value=value[i])
})
}
index.list <- function(object, id="tangram", key.len=4, ...)
{
x <- lapply(object,
function(i) {
i <- copy_src(i, object)
index(i,id=id,key.len=key.len, ...)
})
do.call(c, x)
}
index.cell_label <- function(object, id="tangram", key.len=4, ...)
{
if("cell_value" %in% class(object))
{
cls <- class(object)
pos <- match("cell_label",cls) + 1
class(object) <- cls[pos:length(cls)]
index(object)
} else {
NULL
}
} |
context("geometry")
test_that("geometry helpers work as expected", {
xy <- rotate_xy(c(0, 1), c(0, 1), 90)
expect_equal(xy$x, c(1, 0))
expect_equal(xy$y, c(0, 1))
})
test_that("geometry patterns work as expected", {
png_file <- tempfile(fileext = ".png")
png(png_file)
expect_error(grid.pattern_crosshatch(x, y, density = 1.1))
expect_error(grid.pattern_stripe(x, y, density = 1.1))
dev.off()
unlink(png_file)
skip_if_not_installed("vdiffr")
skip_on_ci()
library("vdiffr")
expect_doppelganger("default", grid.pattern)
expect_doppelganger("none", function() grid.pattern("none"))
x <- 0.5 + 0.5 * cos(seq(2 * pi / 4, by = 2 * pi / 6, length.out = 6))
y <- 0.5 + 0.5 * sin(seq(2 * pi / 4, by = 2 * pi / 6, length.out = 6))
expect_doppelganger("circle", function()
grid.pattern_circle(x, y, color="blue", fill="yellow", size = 2, density = 0.5))
expect_doppelganger("crosshatch", function()
grid.pattern_crosshatch(x, y, color="black", fill="blue", fill2="yellow", density = 0.5))
expect_error(assert_rp_shape(1), "Unknown shape 1")
expect_null(assert_rp_shape(c("square", "convex4")))
expect_null(assert_rp_shape(c("star5", "circle", "null")))
expect_doppelganger("regular_polygon", function()
grid.pattern_regular_polygon(x, y, color = "black", fill = "blue", density = 0.5))
expect_doppelganger("hexagon", function()
grid.pattern_regular_polygon(x, y, color = "transparent", fill = c("white", "grey", "black"),
density = 1.0, shape = "convex6", grid = "hex"))
expect_doppelganger("square", function()
grid.pattern_regular_polygon(x, y, color = "black", fill = c("white", "grey"),
density = 1.0, shape = "square"))
expect_doppelganger("eight_sided_star", function()
grid.pattern_regular_polygon(x, y, colour = "black", fill = c("blue", "yellow"),
density = 1.0, spacing = 0.1, shape = "star8"))
expect_doppelganger("stripe", function()
grid.pattern_stripe(x, y, color="black", fill=c("yellow", "blue"), density = 0.5))
expect_doppelganger("stripe_gpar", function() {
x <- c(0.1, 0.6, 0.8, 0.3)
y <- c(0.2, 0.3, 0.8, 0.5)
grid.pattern("stripe", x, y, gp = gpar(col="blue", fill="red", lwd=2))
})
expect_doppelganger("wave_sine", function()
grid.pattern_wave(x, y, colour = "black", type = "sine",
fill = c("red", "blue"), density = 0.4,
spacing = 0.15, angle = 0,
amplitude = 0.05, frequency = 1 / 0.20))
expect_doppelganger("wave_triangle", function()
grid.pattern_wave(x, y, color="black", fill="yellow",
type = "triangle", density = 0.5, spacing = 0.15))
expect_doppelganger("weave", function()
grid.pattern_weave(x, y, color="black", fill="yellow", fill2="blue",
type = "twill", density = 0.5))
centroid_dot_pattern <- function(params, boundary_df, aspect_ratio, legend) {
boundary_sf <- convert_polygon_df_to_polygon_sf(boundary_df)
centroid <- sf::st_centroid(boundary_sf)
grid::pointsGrob(x = centroid[1],
y = centroid[2],
pch = params$pattern_shape,
size = unit(params$pattern_size, 'char'),
default.units = "npc",
gp = grid::gpar(col = alpha(params$pattern_fill, params$pattern_alpha))
)
}
options(ggpattern_geometry_funcs = list(centroid = centroid_dot_pattern))
x <- 0.5 + 0.5 * cos(seq(2 * pi / 4, by = 2 * pi / 6, length.out = 6))
y <- 0.5 + 0.5 * sin(seq(2 * pi / 4, by = 2 * pi / 6, length.out = 6))
expect_doppelganger("centroid", function()
grid.pattern("centroid", x, y, fill="blue", size = 5))
x <- c(0, 0, 0.5, 0.5, 0.5, 0.5, 1, 1)
y <- c(0, 0.5, 0.5, 0, 0.5, 1, 1, 0.5)
id <- rep(1:2, each = 4L)
expect_doppelganger("two_id", function()
grid.pattern(x = x, y = y, id = id))
}) |
localdar<-
function (mippp, mippp.sp=NULL, nx=NULL, ny=NULL, mimark=NULL, idar = "isar", buffer=0, bfw=NULL,
r, cross.idar = FALSE, tree = NULL, traits = NULL, namesmark=NULL, correct.trait.na=TRUE, correct.trait = "mean", correct.phylo="mean")
{
gridok <- FALSE
bufferex<-FALSE
bufferect<- FALSE
if(!is.marked(mippp)) stop ("mapIDAR requires a marked point pattern")
if (!is.null(namesmark)) mippp$marks <- factor((mippp$marks[namesmark][[1]]))
dmark<-dim(marks(mippp))
if(is.null(namesmark) & !is.null(dmark)){
if(dmark[2]==1) marks(mippp)<-mippp$marks[,1] else stop(
"you should indicate which column of the dataframe of marks
stores species names (argument 'namesmark')\n\n")
}
if(!is.null(mippp.sp)) gridok <- FALSE
if (!is.null(mimark)){
if (mimark %in% levels(mippp$marks) == FALSE) {
stop(paste(mimark, " can't be recognized as a mark\n\n\n
have you indicated in which column of thedataframe are the species\n
marks? (argument 'namesmark'\n\n"))
}
mippp.sp<- unmark(mippp[mippp$marks==mimark])
gridok<- FALSE
}
if(is.null(mippp.sp)){
if(is.null(nx)& is.null(ny)) nx<-ny<-30
if(is.null(nx)& !is.null(ny)) nx<-ny
if(is.null(nx)& !is.null(ny)) ny<-nx
gridxy <-gridcentres(mippp$window, nx, ny)
okbig<-inside.owin(gridxy, w=mippp$window)
mippp.sp <- ppp(x=gridxy$x[okbig], y=gridxy$y[okbig], window=mippp$window)
gridok<- TRUE
}
if(!is.null(bfw)){
bufferex<- TRUE
ok<- inside.owin(mippp.sp, w = bfw)
mippp.sp0 <- mippp.sp
mippp.sp <- mippp.sp[ok]
}
if(buffer!=0 & buffer !="adapt" & is.null(bfw)){
if (is.numeric(buffer) & is.null(bfw)){
if(mippp$window$type!="rectangle") stop("numeric buffer only available for rectangular windows")
bfw <- owin(mippp$window$xrange + c(buffer, -buffer),
mippp$window$yrange + c(buffer, -buffer))
bufferect<- TRUE
}
if (!gridok){
ok<- inside.owin(mippp.sp, w = bfw)
mippp.sp0 <- mippp.sp
mippp.sp <- mippp.sp[ok]
}
if (gridok){
okbig<-inside.owin(gridxy, w=bfw)
mippp.sp <- ppp(x=gridxy$x[okbig], y=gridxy$y[okbig], window=mippp$window)
}
}
if (cross.idar == TRUE & gridok ==FALSE) {
if(is.null(mimark)) stop("for crossed maps you should indicate a focal species (argument 'mimark')")
mippp<- mippp[mippp$marks!=mimark]
}
if (!is.null(tree))
tree <- checktree(tree = tree, mippp = mippp, idar = idar,
correct.phylo = correct.phylo)
if (!is.null(traits))
traits <- checktraits(traits = traits, mippp = mippp,
idar = idar, correct.trait.na = correct.trait.na,
correct.trait = correct.trait)
cosamt <- mitable(mippp.sp, mippp, r)
if (idar %in% c("iraodar.O", "icwmar.O")) {
cosamt.O <- cosamt
for (i in 2:length(cosamt.O)) cosamt.O[[i]] <- cosamt[[i]] -
cosamt[[i - 1]]
if (buffer == "adapt") {
ok<- NULL
bdp <- bdist.points(mippp.sp)
for (i in 1:length(r)){
ok<- cbind(ok, bdp >= r[i])
cosamt.O[[i]] <- cosamt.O[[i]][bdp >= r[i], ]
}
}
}
if (!idar %in% c("iraodar.O", "icwmar.O")) {
if (buffer == "adapt") {
ok<-NULL
bdp <- bdist.points(mippp.sp)
for (i in 1:length(r)){
ok<- cbind(ok, bdp >= r[i])
cosamt[[i]] <- cosamt[[i]][bdp >= r[i], ]
}
}
}
isar.r <- function(x) {
Ptj <- function(x) sum(x == 0)/length(x)
result <- sum(apply(x, 2, function(x) 1 - Ptj(x)))
return(result)
}
cwm.r <- function(x, traits) {
if (!is.null(dim(traits)))
stop("to compute icwmar, 'traits' mut be a vector with the values of juts one trait")
return(sum(x * traits, na.rm = TRUE)/sum(x))
}
if (idar == "icwmar") {
micwmar <- sapply(cosamt, function(tr) {
if (is.null(dim(tr)))
tr <- rbind(tr, tr)
cwm.ind <- apply(tr, 1, function(x) cwm.r(x, traits = traits[match( dimnames(tr)[[2]], names(traits))]))
cwm.ind[is.na(cwm.ind)] <- 0
return(cwm.ind)
})
result <- micwmar
}
if (idar == "icwmar.O") {
micwmar <- sapply(cosamt.O, function(tr) {
if (is.null(dim(tr)))
tr <- rbind(tr, tr)
cwm.ind <- apply(tr, 1, function(x) cwm.r(x, traits = traits[match( dimnames(tr)[[2]], names(traits))]))
cwm.ind[is.na(cwm.ind)] <- 0
return(cwm.ind)
})
result <- micwmar
}
if (idar == "iraodar") {
miraodar <- sapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (dim(x)[1] < 1)
return(NA)
res <- raoDmap(comm = x, phy = tree)
return(res)
})
result <- miraodar
}
if (idar == "iraodar.O") {
miraodar <- sapply(cosamt.O, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (dim(x)[1] < 1)
return(NA)
res <- raoDmap(comm = x, phy = tree)
return(res)
})
result <- miraodar
}
if (idar == "ifdar") {
mifdar <- sapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
res <- fdismap(x, traits = traits)
return(res)
})
result <- mifdar
}
if (idar == "isar") {
misar <- sapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
res<-apply(x,1,function(y) sum(y>0))
return(res)
})
result <- misar
}
if (idar == "ipsear") {
mipsear <- lapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (sum(colSums(x) > 0) > 1)
res <- pse(x, tree = tree)$PSE
if (sum(colSums(x) > 0) <= 1)
res <- rep(NA, dim(x)[1])
return(res)
})
result <- mipsear
}
if (idar == "ipsvar") {
mipsvar <- lapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (sum(colSums(x) > 0) > 1)
res <- psv(x, tree = tree, compute.var = F)$PSVs
if (sum(colSums(x) > 0) <= 1)
res <- rep(NA, dim(x)[1])
return(res)
})
result <-mipsvar
}
if (idar == "ipsrar") {
mipsrar <- lapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (sum(colSums(x) > 0) > 1)
res <- psr(x, tree = tree, compute.var = F)$PSR
if (sum(colSums(x) > 0) <= 1)
res <- rep(NA, dim(x)[1])
return(res)
})
result <-mipsrar
}
if (idar == "ipscar") {
mipscar <- lapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (sum(colSums(x) > 0) > 1)
res <- psc(x, tree = tree)$PSCs
if (sum(colSums(x) > 0) <= 1)
res <- rep(NA, dim(x)[1])
return(res)
})
result <-mipscar
}
if (idar == "imntdar") {
mimntdar <- lapply(cosamt, function(x) {
if (is.null(dim(x)))
x <- rbind(x, x)
if (sum(colSums(x) > 0) > 1)
res <- mntd(x, dis = tree, abundance.weighted = FALSE)
if (sum(colSums(x) > 0) <= 1)
res <- rep(NA, dim(x)[1])
return(res)
})
result <-mimntdar
}
if(is.matrix(result)) result<- as.data.frame(result)
if(gridok) {
result.im=list()
for (i in 1: length(cosamt)){
resultgrid=rep(NA,nx*ny)
if(buffer=="adapt") resultgrid[okbig][ok[,i]] <-result[[i]]
if(buffer!="adapt" & buffer!=0 & !bufferect) resultgrid[okbig][ok] <-result[[i]]
if(bufferect) resultgrid[okbig] <-result[[i]]
if(bufferex) resultgrid[okbig][ok] <-result[[i]]
if(buffer==0 & !bufferex) resultgrid[okbig]<-result[[i]]
result.im[[i]]<- as.im(list(x=unique(gridxy$x),y=unique(gridxy$y),z=matrix(resultgrid,nx,ny)))
}
}
if(!gridok) {
if(bufferex | bufferect) mippp.sp<- mippp.sp0
result.im=list()
for (i in 1: length(cosamt)){
marks(mippp.sp)<-NA
if(buffer=="adapt") marks(mippp.sp)[ok[,i]] <-result[[i]]
if(buffer!="adapt" & buffer!=0 ) marks(mippp.sp) [ok]<- result[[i]]
if(buffer==0 & !bufferex) marks(mippp.sp) <- result[[i]]
if(bufferex) marks(mippp.sp)[ok]<- result[[i]]
result.im[[i]] <- mippp.sp
}
}
names(result.im)<- paste(idar, "_",r* mippp$window$units$multiplier,"_", mippp$window$units$plural, sep="")
return(result.im)
}
raoDmap<-
function (comm, phy = NULL)
{
res <- list()
if (is.null(phy)) {
tij <- 1 - diag(x = rep(1, length(comm[1, ])))
}
else {
if (!inherits (phy, what= "phylo")) {
if (!is.matrix(phy) & !inherits (phy, what= "dist") )
stop("Phy must be a distance matrix")
if (is.matrix(phy))
phy <- as.dist(phy)
dat <- match.comm.dist(comm, phy)
comm <- dat$comm
phy <- dat$dist
tij <- as.matrix(phy/2)
}
if (inherits (phy, what= "phylo")) {
if (!is.ultrametric(phy))
stop("Phylogeny must be ultrametric")
dat <- match.phylo.comm(phy, comm)
comm <- dat$comm
phy <- dat$phy
tij <- cophenetic(phy)/2
}
}
x <- as.matrix(comm)
S <- length(x[1, ])
N <- length(x[, 1])
total <- apply(x, 1, sum)
samp.relabund <- total/sum(x)
x.combined <- matrix(apply(x, 2, sum), nrow = 1)/sum(x)
x <- sweep(x, 1, total, "/")
D <- vector(length = N)
names(D) <- rownames(x)
for (k in 1:N) D[k] <- sum(tij * outer(as.vector(t(x[k, ])),
as.vector(t(x[k, ]))))
res$Dkk <- D
res$alpha <- sum(res$Dkk * samp.relabund)
return(res$Dkk)
}
fdismap<-
function (comm, traits)
{
sp.a <- colSums(comm) > 0
filas <- dim(comm)[1]
if (sum(sp.a) < 1)
return(NA)
if (sum(sp.a) == 1)
return(0)
if (sum(sp.a) > 1) {
m.ok <- comm[, sp.a]
sp.trait.ok <- !is.na(match(rownames(traits), colnames(m.ok)))
if (!is.null(dim(m.ok))) {
com.G.0 <- rowSums(m.ok) > 0
cosad <- as.dist(traits[sp.trait.ok, sp.trait.ok,
drop = FALSE])
if (sum(cosad, na.rm = TRUE) == 0)
return(0)
if (sum(sp.trait.ok) >= 2) {
com.G.02 <- rowSums(m.ok[, labels(cosad)]) >
0
cosaf <- fdisp(d = cosad, a = m.ok[com.G.02,
labels(cosad), drop = FALSE], tol = 1e-07)$FDis
result<-rep(NA, filas)
result[com.G.02]<- cosaf
}
if (sum(sp.trait.ok) < 2) {
cosaf <- fdisp(d = cosad, a = t(as.matrix(m.ok[com.G.0,
labels(cosad)])), tol = 1e-07)$FDis
result<-rep(NA, filas)
result[com.G.0]<- cosaf
}
}
if (is.null(dim(m.ok)))
result <- NA
return(result)
}
} |
library(DRomics)
visualize <- FALSE
niterboot <- 25
if (visualize)
{
datafilename <- system.file("extdata", "insitu_RNAseq_sample.txt", package="DRomics")
(o <- RNAseqdata(datafilename, backgrounddose = 2e-2, transfo.method = "vst"))
(s <- itemselect(o))
(f <- drcfit(s))
(fbis <- drcfit(s, enablesfequal0inGP = FALSE,
enablesfequal0inLGP = FALSE,
preventsfitsoutofrange = FALSE))
(idnotinf <- fbis$fitres$id[!(fbis$fitres$id %in% f$fitres$id)])
plot(fbis, items = idnotinf, dose_log_transfo = TRUE)
plot(fbis, items = idnotinf, dose_log_transfo = FALSE)
(id2explore <- f$fitres$id[f$fitres$model %in% c("Gauss-probit", "log-Gauss-probit") &
f$fitres$f == 0])
f$fitres[f$fitres$id %in% id2explore, ]
plot(f, items = id2explore, dose_log_transfo = TRUE)
plot(fbis, items = id2explore, dose_log_transfo = TRUE)
plot(f, items = id2explore, dose_log_transfo = FALSE)
plot(fbis, items = id2explore, dose_log_transfo = FALSE)
(r <- bmdcalc(f))
(rbis <- bmdcalc(fbis))
b <- bmdboot(r, niter = niterboot)
bbis <- bmdboot(rbis, niter = niterboot)
plot(f , items = id2explore,
BMDoutput = b, dose_log_transfo = TRUE)
plot(fbis , items = id2explore,
BMDoutput = bbis, dose_log_transfo = TRUE)
} |
xpstQ = function (A, Tmat = diag(ncol(A)), normalize = FALSE, eps = 1e-05,
maxit = 1000, method = "quartimin", methodArgs = NULL, PhiWeight = NULL, PhiTarget = NULL, wxt2 = 1e0)
{
vgQ.pst <- function(L, W=NULL, Target=NULL){
if(is.null(W)) stop("argument W must be specified.")
if(is.null(Target)) stop("argument Target must be specified.")
Btilde <- W * Target
list(Gq= 2*(W*L-Btilde),
f = sum((W*L-Btilde)^2),
Method="Partially specified target")
}
vgQ.pstPhi <- function(Transform, PhiW=NULL, PhiTarget=NULL, wxt2 = 1e0){
if(is.null(PhiW)) stop("argument W must be specified.")
if(is.null(PhiTarget)) stop("argument Target must be specified.")
if (max(abs(PhiTarget - t(PhiTarget)))>1.0e-10) stop(" PhiTarget must be symmetric.")
if (max(abs(PhiW - t(PhiW)))>1.0e-10) stop(" PhiW must be symmetric.")
Phi = t(Transform) %*% Transform
Btilde <- PhiW * PhiTarget
Gq2phi = 2*(PhiW * Phi - Btilde)
f.Phi = sum((PhiW * Phi - Btilde)^2) / 2
Method="Partially specified target: Phi"
m = dim(Transform)[1]
dQ2T = matrix(0,m,m)
for (j in 2:m) {
for (i in 1:j) {
if (PhiW[i,j]==1) {
dQ2T[1:m,i] = dQ2T[1:m,i] + Transform[1:m,j] * Gq2phi[i,j]
dQ2T[1:m,j] = dQ2T[1:m,j] + Transform[1:m,i] * Gq2phi[i,j]
}
}
}
list(dQ2T = dQ2T * wxt2,
f.Phi = f.Phi * wxt2,
Method=Method)
}
if (1 >= ncol(A))
stop("rotation does not make sense for single factor models.")
if ((!is.logical(normalize)) || normalize) {
A2 = A * A
Com = rowSums(A2)
W = sqrt(Com) %*% matrix(1,1,ncol(A))
normalize <- TRUE
A <- A/W
}
al <- 1
L <- A %*% t(solve(Tmat))
Method <- paste("vgQ", method, sep = ".")
VgQ <- do.call(Method, append(list(L), methodArgs))
G1 <- -t(t(L) %*% VgQ$Gq %*% solve(Tmat))
f1 <- VgQ$f
VgQ.2 = vgQ.pstPhi(Tmat, PhiWeight, PhiTarget,wxt2)
f = f1 + VgQ.2$f.Phi
G = G1 + VgQ.2$dQ2T
Table <- NULL
VgQt <- do.call(Method, append(list(L), methodArgs))
VgQ.2 = vgQ.pstPhi(Tmat, PhiWeight, PhiTarget,wxt2)
for (iter in 0:maxit) {
Gp <- G - Tmat %*% diag(c(rep(1, nrow(G)) %*% (Tmat *
G)))
s <- sqrt(sum(diag(crossprod(Gp))))
Table <- rbind(Table, c(iter, f, log10(s), al))
if (s < eps)
break
al <- 2 * al
for (i in 0:10) {
X <- Tmat - al * Gp
v <- 1/sqrt(c(rep(1, nrow(X)) %*% X^2))
Tmatt <- X %*% diag(v)
L <- A %*% t(solve(Tmatt))
VgQt <- do.call(Method, append(list(L), methodArgs))
VgQ.2 = vgQ.pstPhi(Tmatt, PhiWeight, PhiTarget,wxt2)
improvement <- f - ( VgQt$f + VgQ.2$f.Phi )
if (improvement > 0.5 * s^2 * al)
break
al <- al/2
}
Tmat <- Tmatt
f1 <- VgQt$f
G1 <- -t(t(L) %*% VgQt$Gq %*% solve(Tmatt))
VgQ.2 = vgQ.pstPhi(Tmatt, PhiWeight, PhiTarget,wxt2)
f = f1 + VgQ.2$f.Phi
G = G1 + VgQ.2$dQ2T
}
convergence <- (s < eps)
if ((iter == maxit) & !convergence)
warning("convergence not obtained in GPFoblq. ", maxit,
" iterations used.")
if (normalize)
L <- L * W
dimnames(L) <- dimnames(A)
r <- list(loadings = L, Phi = t(Tmat) %*% Tmat, Th = Tmat,
Table = Table, method = VgQ$Method, orthogonal = FALSE,
convergence = convergence, Gq = VgQt$Gq)
class(r) <- "GPArotation"
r
} |
context("vis_miss")
test_that("Valid ggplot object is produced",{
skip_on_cran()
skip_on_ci()
monitors <- c("ASN00003003", "ASM00094299")
weather_df <- suppressMessages(meteo_pull_monitors(monitors))
out <- vis_miss(weather_df)
expect_is(out, "ggplot")
}) |
write.bayescan<-function(dat=dat,diploid=TRUE,fn="dat.bsc"){
nloc<-dim(dat)[2]-1
npop<-length(table(dat[,1]))
alc.dat<-allele.count(dat,diploid)
nal<-unlist(lapply(alc.dat,function(x) dim(x)[1]))
nindx<-sapply(alc.dat,function(x) apply(x,2,sum))
write(paste("[loci]=",nloc,sep=""),fn)
write("",fn,append=TRUE)
write(paste("[populations]=",npop,sep=""),fn,append=TRUE)
write("",fn,append=TRUE)
for (ip in 1:npop){
write("",fn,append=TRUE)
write(paste("[pop]=",ip,sep=""),fn,append=TRUE)
for (il in 1:nloc){
tow<-c(il,nindx[ip,il],nal[il],alc.dat[[il]][,ip])
write(tow,fn,
append=TRUE,ncolumns=length(tow))
}
}
} |
context("Checking grab")
test_that("grab gets strings",{
expect_equivalent(grab("@split_keep_delim"), "(?<=[^%s])(?=[%s])")
expect_equivalent(grab("@rm_percent"), "\\(?[0-9.]+\\)?%")
expect_equivalent(grab("rm_percent"), "\\(?[0-9.]+\\)?%")
expect_error(grab("@foo"))
}) |
test_that("silently extracts elements of length 1", {
expect_equal(vec_list_cast(list(1, 2), double()), c(1, 2))
})
test_that("elements of length 0 become NA without error", {
x <- list(1, double())
out <- vec_list_cast(x, double())
expect_equal(out, c(1, NA))
})
test_that("elements of length >1 are truncated with error", {
x <- list(1, c(2, 1), c(3, 2, 1))
expect_lossy(vec_list_cast(x, dbl()), dbl(1, 2, 3), x = list(), to = dbl())
x <- list(c(2, 1), c(3, 2, 1))
expect_lossy(vec_list_cast(x, dbl()), dbl(2, 3), x = list(), to = dbl())
}) |
library('PerformanceAnalytics')
data(managers)
data(edhec)
managers.length = dim(managers)[1]
manager.col = 1
peers.cols = c(2,3,4,5,6)
indexes.cols = c(7,8)
Rf.col = 10
trailing12.rows = ((managers.length - 11):managers.length)
trailing36.rows = ((managers.length - 35):managers.length)
trailing60.rows = ((managers.length - 59):managers.length)
frInception.rows = (length(managers[,1]) -
length(managers[,1][!is.na(managers[,1])]) + 1):length(managers[,1])
charts.PerformanceSummary(managers[,c(manager.col,indexes.cols)],
colorset=rich6equal, lwd=2, ylog=TRUE)
t(table.CalendarReturns( managers[,c(manager.col,indexes.cols)]) )
table.Stats(managers[,c(manager.col,peers.cols)])
chart.Boxplot(managers[ trailing36.rows, c(manager.col, peers.cols,
indexes.cols)], main = "Trailing 36-Month Returns")
layout(rbind(c(1,2),c(3,4)))
chart.Histogram(managers[,1,drop=F], main = "Plain", methods = NULL)
chart.Histogram(managers[,1,drop=F], main = "Density", breaks=40,
methods = c("add.density", "add.normal"))
chart.Histogram(managers[,1,drop=F], main = "Skew and Kurt", methods = c
("add.centered", "add.rug"))
chart.Histogram(managers[,1,drop=F], main = "Risk Measures", methods = c
("add.risk"))
chart.RiskReturnScatter(managers[trailing36.rows,1:8], Rf=.03/12, main =
"Trailing 36-Month Performance", colorset=c("red", rep("black",5), "orange",
"green"))
charts.RollingPerformance(managers[, c(manager.col, peers.cols,
indexes.cols)], Rf=.03/12, colorset = c("red", rep("darkgray",5), "orange",
"green"), lwd = 2)
chart.RelativePerformance(managers[ , manager.col, drop = FALSE],
managers[ , c(peers.cols, 7)], colorset = tim8equal[-1], lwd = 2, legend.loc
= "topleft")
chart.RelativePerformance(managers[ , c(manager.col, peers.cols) ],
managers[, 8, drop=F], colorset = rainbow8equal, lwd = 2, legend.loc =
"topleft")
table.CAPM(managers[trailing36.rows, c(manager.col, peers.cols)],
managers[ trailing36.rows, 8, drop=FALSE], Rf = managers[ trailing36.rows,
Rf.col, drop=F ])
charts.RollingRegression(managers[, c(manager.col, peers.cols), drop =
FALSE], managers[, 8, drop = FALSE], Rf = .03/12, colorset = redfocus, lwd =
2)
table.DownsideRisk(managers[,1:6],Rf=.03/12)
data(managers)
head(managers)
dim(managers)
managers.length = dim(managers)[1]
colnames(managers)
manager.col = 1
peers.cols = c(2,3,4,5,6)
indexes.cols = c(7,8)
Rf.col = 10
trailing12.rows = ((managers.length - 11):managers.length)
trailing12.rows
trailing36.rows = ((managers.length - 35):managers.length)
trailing60.rows = ((managers.length - 59):managers.length)
frInception.rows = (length(managers[,1]) -
length(managers[,1][!is.na(managers[,1])]) + 1):length(managers[,1])
charts.PerformanceSummary(managers[,c(manager.col,indexes.cols)],
colorset=rich6equal, lwd=2, ylog=TRUE) |
library(urca)
data(UKpppuip)
names(UKpppuip)
attach(UKpppuip)
dat1 <- cbind(p1, p2, e12, i1, i2)
dat2 <- cbind(doilp0, doilp1)
args('ca.jo')
H1 <- ca.jo(dat1, type = 'trace', K = 2, season = 4,
dumvar = dat2)
H1.trace <- summary(ca.jo(dat1, type = 'trace', K = 2,
season = 4, dumvar = dat2))
H1.eigen <- summary(ca.jo(dat1, type = 'eigen', K = 2,
season = 4, dumvar = dat2)) |
expected <- TRUE
test(id=235, code={
argv <- structure(list(x = expression(exp(-0.5 * u^2)), y = expression(
exp(-0.5 * u^2))), .Names = c("x", "y"))
do.call('identical', argv);
}, o = expected);
|
perror <- function(q, xs) {stop("perror is not exported as a standalone function. You must first run the quantForestError function to define perror. See documentation.")} |
sync.plot <- function(syncList){
stopifnot(is.list(syncList))
if (class(syncList) != "sync") {
stop("'syncList' is no a list output of function sync")
}
if(is.data.frame(syncList[1]) != FALSE) {
stop("'syncList' is no a list output of function sync")
}
if(is.data.frame(syncList[2]) != FALSE) {
stop("'syncList' is no a list output of function sync")
}
pd <- position_dodge(.2)
aza1 <- do.call(rbind, lapply(syncList[1], data.frame, stringsAsFactors = FALSE))
aza2 <- do.call(rbind, lapply(syncList[2], data.frame, stringsAsFactors = FALSE))
if(dim(aza1)[1] == 1){stop("Broad evaluation plot has not sense (mBE)")}
aexp <- expression(paste(bold("Within-group "),bolditalic(hat(a)["c"])))
mdn <- aza1[2,1]
bexp <- paste(mdn)
aa1 <- aza1[[3]]-aza1[[4]]
aa2 <- aza1[[3]]+aza1[[4]]
am2 <- max(aa2)
p1 <- ggplot(aza1, aes(x=aza1$GroupName,y=aza1$a_Group))+
geom_errorbar(aes(ymin = aa1, ymax = aa2), width = 0.2, size = 0.7, position = pd, col = 4) +
geom_point(shape = 16, size = 4, position = pd, col = 4) +
labs(x = "Grouping variable", y = aexp)+
expand_limits(y = 0)+
scale_y_continuous()+
ggtitle(bexp)+
theme_bw()+
theme(axis.title.y = element_text(vjust = 1.8),
axis.title.x = element_text(vjust = -0.5),
axis.title = element_text(face = "bold"),
plot.title = element_text(hjust = 0.5),
axis.text=element_text(size=11),
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
aexp1 <- expression(paste(bold("Between-group "),bolditalic(hat(a)["c"])))
ab1 <- aza2[[3]]-aza2[[4]]
ab2 <- aza2[[3]]+aza2[[4]]
cexp <- paste(mdn)
p2 <- ggplot(aza2, aes(x = aza2$GroupName, y = aza2$a_betw_Grp))+
geom_errorbar(aes(ymin = ab1, ymax = ab2), width = 0.2, size = 0.7, position = pd, col = "royalblue") +
geom_point(shape = 16, size = 4, position = pd, col = "royalblue") +
labs(x = "Grouping variable",y = aexp1)+
expand_limits(y = c(0, am2))+
scale_y_continuous()+
ggtitle(cexp)+
theme_bw()+
theme(axis.title.y = element_text(vjust = 1.8),
axis.title.x = element_text(vjust = -0.5),
axis.title = element_text(face = "bold"),
plot.title = element_text(hjust = 0.5),
axis.text=element_text(size=11),
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
grid.arrange(p1, p2, ncol = 2)
} |
"boa.plot.close" <- function(which = dev.cur())
{
shutdown <- NULL
current <- boa.par("dev.list")
idx <- is.element(current, which)
for(i in intersect(current[idx], dev.list())) {
shutdown <- dev.off(i)
}
boa.par(dev.list = current[!idx])
return(shutdown)
} |
NULL
getLocusAttributes = function(x, markers = NULL,
attribs = c("alleles", "afreq", "name", "chrom",
"posMb", "mutmod")) {
if(is.pedList(x))
x = x[[1]]
if(!is.ped(x))
stop2("Input must be a `ped` object or a list of such")
markers = markers %||% seq_markers(x)
attribs = match.arg(attribs, several.ok = TRUE)
mlist = getMarkers(x, markers)
lapply(mlist, function(m) {
a = attributes(m)[attribs]
a = a[!is.na(names(a))]
a
})
}
setLocusAttributes = function(x, markers = NULL, locusAttributes,
matchNames = NA, erase = FALSE) {
if(is.pedList(x)) {
y = lapply(x, setLocusAttributes, markers = markers,
locusAttributes = locusAttributes, matchNames = matchNames, erase = erase)
return(y)
}
if(!is.ped(x))
stop2("Input must be a `ped` object or a list of such")
N = nMarkers(x)
if(N == 0)
stop2("This function can only modify already attached markers.\nUse `setMarkers() to attach new markers.")
recyclingNeeded = is.list(locusAttributes) && !is.list(locusAttributes[[1]])
if(recyclingNeeded) {
if(is.null(markers))
stop2("When `locusAttributes` is a single list, then `markers` cannot be NULL")
locusAttributes = rep(list(locusAttributes), length(markers))
}
if(is.null(markers)) {
if(is.na(matchNames) || isTRUE(matchNames)) {
hasNames = all(vapply(locusAttributes, function(a) 'name' %in% names(a), FUN.VALUE = FALSE))
if(hasNames)
nms = vapply(locusAttributes, function(a) a[['name']], FUN.VALUE = "")
else
nms = names(locusAttributes)
if(dup <- anyDuplicated(nms))
stop2("Duplicated marker name in attribute list: ", nms[dup])
if(is.na(matchNames)) {
matchNames = !is.null(nms) && all(nms %in% name(x, 1:N))
}
}
if(matchNames) markers = nms
else markers = 1:N
}
if(anyDuplicated(markers))
stop2("Duplicated markers: ", markers[duplicated(markers)])
midx = whichMarkers(x, markers)
M = length(midx)
L = length(locusAttributes)
if(L != M)
stop2("List of locus attributes does not match the number of markers")
als = getAlleles(x, markers = midx)
oldAttrs = getLocusAttributes(x, markers = midx)
for(i in seq_along(midx)) {
ali = als[, c(2*i - 1, 2*i), drop = FALSE]
newattri = locusAttributes[[i]]
if(!erase) {
updatedattri = modifyList(oldAttrs[[i]], newattri)
if("alleles" %in% names(newattri) && !"afreq" %in% names(newattri))
updatedattri$afreq = NULL
newattri = updatedattri
}
arglist = c(list(x = x, allelematrix = ali), newattri)
newM = do.call(marker, arglist)
x$MARKERS[[midx[i]]] = newM
}
x
} |
tam_mml_3pl_inits_group <- function(group, ndim, G, variance.inits, groups)
{
var.indices <- NULL
if ( ! is.null(group) ){
var.indices <- rep(1,G)
for (gg in 1:G){
var.indices[gg] <- which( group==gg )[1]
}
if ( is.null( variance.inits ) ){
variance <- array( 0, dim=c(G,ndim,ndim) )
for (gg in 1:G){
variance[gg,,] <- diag(ndim)
}
}
}
res <- list(G=G, groups=groups, group=group, var.indices=var.indices)
return(res)
} |
context("PERMISSIONS")
tmp <- tempfile()
X <- FBM(10, 10, backingfile = tmp, init = NA)$save()
expect_output(print(X), "A Filebacked Big Matrix of type 'double'")
expect_identical(file.access(X$bk, 4), setNames(0L, X$bk))
expect_identical(file.access(X$bk, 2), setNames(0L, X$bk))
X <- big_attach(paste0(tmp, ".rds"))
expect_true(all(is.na(X[])))
X[] <- 1
expect_true(all(X[] == 1))
X$is_read_only <- TRUE
expect_output(print(X), "A read-only Filebacked Big Matrix of type 'double'")
expect_error(X[] <- 2, "This FBM is read-only.")
expect_true(all(X[] == 1))
Sys.chmod(paste0(tmp, ".bk"), "0444")
if (file.access(X$bk, 2) != 0) {
X <- big_attach(paste0(tmp, ".rds"))
expect_true(all(X[] == 1))
expect_error(X[] <- 3, "You don't have write permissions for this FBM.")
Sys.chmod(paste0(tmp, ".bk"), "0666")
X[] <- 4
expect_true(all(X[] == 4))
} |
pathsep <- .Platform$path.sep |
amBarplot <- function(x, y, data, xlab = "", ylab = "", ylim = NULL, groups_color = NULL,
horiz = FALSE, stack_type = c("none", "regular", "100"),
layered = FALSE, show_values = FALSE, depth = 0, dataDateFormat = NULL,
minPeriod = ifelse(!is.null(dataDateFormat), "DD", ""), ...)
{
data <- .testFormatData(data)
stack_type <- match.arg(stack_type)
.testCharacterLength1(char = xlab)
.testCharacterLength1(char = ylab)
.testLogicalLength1(logi = layered)
.testLogicalLength1(logi = horiz)
.testLogicalLength1(logi = show_values)
.testInterval(num = depth, binf = 0, bsup = 100)
if (missing(x) && !length(rownames(data))) {
stop("Argument x is not provided and the data.frame does not have row names")
} else if (missing(x) && length(rownames(data))){
x <- "xcat_"
data$xcat_ <- rownames(data)
} else if (is.character(x) && !(x %in% colnames(data))) {
stop("Argument x does not correspond to a column name")
} else if (is.numeric(x) && x > ncol(data)) {
stop("Error in argument x")
} else {}
if (is.numeric(x))
x <- colnames(data)[x]
if (is.factor(data[,x]))
data[,x] <- as.character(data[,x])
.testCharacter(char = data[,x])
y <- match.arg(arg = y, choices = colnames(data), several.ok = TRUE)
sapply(1:length(y), FUN = function(i) {
if (is.numeric(y[i])) {
if (y[i] > ncol(data))
stop("Error in argument x")
y[i] <<- colnames(data)[y[i]]
} else if(is.character(y) && !all(y %in% colnames(data))) {
stop(paste("Cannot extract column(s)", y, "from data"))
} else {}
if (!is.numeric(data[,y[i]]))
stop(paste("The column ", y[i], "of the dataframe must be numeric."))
})
if (layered && stack_type != "none")
stop("You have to choose : layered or stacked. If layered
is set to TRUE, stack_type must be equal to 'none'")
if (!is.null(stack_type)) {
.testCharacter(char = stack_type)
.testIn(vect = stack_type, control = c("regular", "100", "none"))
}
stack_type <- switch(stack_type, "100" = "100%", stack_type)
color_palette = c("
"
if (!"color" %in% colnames(data)) {
if (length(y) == 1) {
if (!is.null(groups_color)) {
data$color <- groups_color[1]
} else {
data$color <- rep(x = color_palette, length.out = nrow(data))
}
}
} else {
if (!is.null(groups_color)) {
vec_col <- rep(groups_color, nrow(data))
data$color <- vec_col[1:nrow(data)]
}
}
if ((depth3D <- depth) > 0) {
angle <- 30
} else {
angle <- 0
}
if (show_values) {
label_text <- "[[value]]"
} else {
label_text <- ""
}
if (!is.null(ylim)) {
ymin <- ylim[1]
ymax <- ylim[2]
} else {
ymin <- NULL
ymax <- NULL
}
pipeR::pipeline(
amSerialChart(dataProvider = data, categoryField = x, rotate = horiz,
depth3D = depth3D, angle = angle, dataDateFormat = dataDateFormat),
addValueAxis(title = ylab, position = 'left', stackType = stack_type,
minimum = ymin, maximum = ymax, strictMinMax = !is.null(ylim)),
setCategoryAxis(title = xlab, gridPosition = 'start', axisAlpha = 0, gridAlpha = 0,
parseDates = !is.null(dataDateFormat), minPeriod = minPeriod),
(~ chart)
)
if (length(y) == 1) {
if ("description" %in% colnames(data)) {
tooltip <- '<b>[[description]]</b>'
} else {
tooltip <- '<b>[[value]]</b>'
}
chart <- addGraph(chart, balloonText = tooltip, fillColorsField = 'color', fillAlphas = 0.85,
lineAlpha = 0.1, type = 'column', valueField = y, labelText = label_text)
} else {
if (!is.null(groups_color)) {
v_col <- rep(x = groups_color, length.out = length(y))
} else {
v_col <- rep(x = color_palette, length.out = length(y))
}
graphs_list <- lapply(X = seq(length(y)), FUN = function (i) {
if ("description" %in% colnames(data)) {
tooltip2 <- '<b>[[description]]</b>'
} else {
tooltip2 <- paste0(as.character(y[i]),": [[value]]")
}
graph_obj <- graph(chart, id = paste0("AmGraph-",i), balloonText = tooltip2, fillColors = v_col[i],
legendColor = v_col[i], fillAlphas = 0.85, lineAlpha = 0.1, type = 'column', valueField = y[i],
title = y[i], labelText = label_text)
if (layered) {
return(setProperties(graph_obj, clustered = FALSE, columnWidth = 0.9/(1.8^(i-1))))
} else {
return(graph_obj)
}
})
chart <- setGraphs(chart, graphs = graphs_list)
}
chart <- setProperties(.Object = chart, RType_ = "barplot")
amOptions(chart, ...)
} |
context("parseFilename")
test_that("multiplication works", {
expect_equal(2 * 2, 4)
}) |
tar_cue <- function(
mode = c("thorough", "always", "never"),
command = TRUE,
depend = TRUE,
format = TRUE,
iteration = TRUE,
file = TRUE
) {
tar_assert_lgl(command)
tar_assert_lgl(depend)
tar_assert_lgl(format)
tar_assert_lgl(iteration)
tar_assert_lgl(file)
tar_assert_scalar(command)
tar_assert_scalar(depend)
tar_assert_scalar(format)
tar_assert_scalar(iteration)
tar_assert_scalar(file)
cue_init(
mode = match.arg(mode),
command = command,
depend = depend,
format = format,
iteration = iteration,
file = file
)
} |
.rex <- new.env(parent = emptyenv())
.rex$env <- new.env(parent = emptyenv())
.rex$mode <- FALSE
register <- function(...) {
names <- gsub("`", "", as.character(eval(substitute(alist(...)))), fixed = TRUE)
list2env(structure(list(...), .Names = names), envir = .rex$env)
}
register_object <- function(object) {
list2env(as.list(object), envir = .rex$env)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(RandomForestsGLS)
rmvn <- function(n, mu = 0, V = matrix(1)){
p <- length(mu)
if(any(is.na(match(dim(V),p))))
stop("Dimension not right!")
D <- chol(V)
t(matrix(rnorm(n*p), ncol=p)%*%D + rep(mu,rep(n,p)))
}
set.seed(5)
n <- 200
coords <- cbind(runif(n,0,1), runif(n,0,1))
set.seed(2)
x <- as.matrix(runif(n),n,1)
sigma.sq = 10
phi = 1
tau.sq = 0.1
D <- as.matrix(dist(coords))
R <- exp(-phi*D)
w <- rmvn(1, rep(0,n), sigma.sq*R)
y <- rnorm(n, 10*sin(pi * x) + w, sqrt(tau.sq))
set.seed(1)
est_known <- RFGLS_estimate_spatial(coords, y, x, ntree = 50, cov.model = "exponential",
nthsize = 20, sigma.sq = sigma.sq, tau.sq = tau.sq,
phi = phi)
set.seed(1)
est_unknown <- RFGLS_estimate_spatial(coords, y, x, ntree = 50, cov.model = "exponential",
nthsize = 20, param_estimate = TRUE)
Xtest <- matrix(seq(0,1, by = 1/10000), 10001, 1)
RFGLS_predict_known <- RFGLS_predict(est_known, Xtest)
library(randomForest)
set.seed(1)
RF_est <- randomForest(x, y, nodesize = 20)
RF_predict <- predict(RF_est, Xtest)
mean((RF_predict - 10*sin(pi * Xtest))^2)
mean((RFGLS_predict_known$predicted - 10*sin(pi * Xtest))^2)
RFGLS_predict_unknown <- RFGLS_predict(est_unknown, Xtest)
mean((RFGLS_predict_unknown$predicted - 10*sin(pi * Xtest))^2)
rfgls_loess_10 <- loess(RFGLS_predict_known$predicted ~ c(1:length(Xtest)), span=0.1)
rfgls_smoothed10 <- predict(rfgls_loess_10)
rf_loess_10 <- loess(RF_predict ~ c(1:length(RF_predict)), span=0.1)
rf_smoothed10 <- predict(rf_loess_10)
xval <- c(10*sin(pi * Xtest), rf_smoothed10, rfgls_smoothed10)
xval_tag <- c(rep("Truth", length(10*sin(pi * Xtest))), rep("RF", length(rf_smoothed10)),
rep("RF-GLS",length(rfgls_smoothed10)))
plot_data <- as.data.frame(xval)
plot_data$Methods <- xval_tag
coval <- c(rep(seq(0,1, by = 1/10000), 3))
plot_data$Covariate <- coval
library(ggplot2)
ggplot(plot_data, aes(x=Covariate, y=xval, color=Methods)) +
geom_point() + labs( x = "x") + labs( y = "f(x)")
est_known_short <- RFGLS_estimate_spatial(coords[1:160,], y[1:160],
matrix(x[1:160,],160,1), ntree = 50, cov.model = "exponential",
nthsize = 20, param_estimate = TRUE)
RFGLS_predict_spatial <- RFGLS_predict_spatial(est_known_short, coords[161:200,],
matrix(x[161:200,],40,1))
pred_mat <- as.data.frame(cbind(RFGLS_predict_spatial$prediction, y[161:200]))
colnames(pred_mat) <- c("Predicted", "Observed")
ggplot(pred_mat, aes(x=Observed, y=Predicted)) + geom_point() +
geom_abline(intercept = 0, slope = 1, color = "blue") +
ylim(0, 16) + xlim(0, 16)
nu = 3/2
R1 <- (D*phi)^nu/(2^(nu-1)*gamma(nu))*besselK(x=D*phi, nu=nu)
diag(R1) <- 1
set.seed(2)
w <- rmvn(1, rep(0,n), sigma.sq*R1)
y <- rnorm(n, 10*sin(pi * x) + w, sqrt(tau.sq))
set.seed(3)
est_misspec <- RFGLS_estimate_spatial(coords, y, x, ntree = 50, cov.model = "exponential",
nthsize = 20, param_estimate = TRUE)
RFGLS_predict_misspec <- RFGLS_predict(est_misspec, Xtest)
set.seed(4)
RF_est <- randomForest(x, y, nodesize = 20)
RF_predict <- predict(RF_est, Xtest)
mean((RFGLS_predict_misspec$predicted - 10*sin(pi * Xtest))^2)
mean((RF_predict - 10*sin(pi * Xtest))^2)
rho <- 0.9
set.seed(1)
b <- rho
s <- sqrt(sigma.sq)
eps = arima.sim(list(order = c(1,0,0), ar = b), n = n, rand.gen = rnorm, sd = s)
y <- c(eps + 10*sin(pi * x))
set.seed(1)
est_temp_known <- RFGLS_estimate_timeseries(y, x, ntree = 50, lag_params = rho, nthsize = 20)
set.seed(1)
est_temp_unknown <- RFGLS_estimate_timeseries(y, x, ntree = 50, lag_params = rho,
nthsize = 20, param_estimate = TRUE)
Xtest <- matrix(seq(0,1, by = 1/10000), 10001, 1)
RFGLS_predict_temp_known <- RFGLS_predict(est_temp_known, Xtest)
library(randomForest)
set.seed(1)
RF_est_temp <- randomForest(x, y, nodesize = 20)
RF_predict_temp <- predict(RF_est_temp, Xtest)
mean((RF_predict_temp - 10*sin(pi * Xtest))^2)
mean((RFGLS_predict_temp_known$predicted - 10*sin(pi * Xtest))^2)
RFGLS_predict_temp_unknown <- RFGLS_predict(est_temp_unknown, Xtest)
mean((RFGLS_predict_temp_unknown$predicted - 10*sin(pi * Xtest))^2)
rho1 <- 0.7
rho2 <- 0.2
set.seed(2)
b <- c(rho1, rho2)
s <- sqrt(sigma.sq)
eps = arima.sim(list(order = c(2,0,0), ar = b), n = n, rand.gen = rnorm, sd = s)
y <- c(eps + 10*sin(pi * x))
set.seed(3)
est_misspec_temp <- RFGLS_estimate_timeseries(y, x, ntree = 50, lag_params = 0,
nthsize = 20, param_estimate = TRUE)
RFGLS_predict_misspec_temp <- RFGLS_predict(est_misspec_temp, Xtest)
set.seed(4)
RF_est_temp <- randomForest(x, y, nodesize = 20)
RF_predict_temp <- predict(RF_est_temp, Xtest)
mean((RFGLS_predict_misspec_temp$predicted - 10*sin(pi * Xtest))^2)
mean((RF_predict_temp - 10*sin(pi * Xtest))^2)
set.seed(5)
n <- 200
coords <- cbind(runif(n,0,1), runif(n,0,1))
set.seed(2)
x <- as.matrix(runif(n),n,1)
sigma.sq = 10
phi = 1
tau.sq = 0.1
nu = 0.5
D <- as.matrix(dist(coords))
R <- exp(-phi*D)
w <- rmvn(1, rep(0,n), sigma.sq*R)
y <- rnorm(n, 10*sin(pi * x) + w, sqrt(tau.sq))
set.seed(1)
est_known_pl <- RFGLS_estimate_spatial(coords, y, x, ntree = 50, cov.model = "exponential",
nthsize = 20, sigma.sq = sigma.sq, tau.sq = tau.sq,
phi = phi, h = 2)
RFGLS_predict_known_pl <- RFGLS_predict(est_known_pl, Xtest, h = 2)
mean((RFGLS_predict_known$predicted - 10*sin(pi * Xtest))^2)
mean((RFGLS_predict_known_pl$predicted - 10*sin(pi * Xtest))^2) |
context("Isotonic regression")
testthat::test_that("Pooled Adjacent Violator Algorithm", {
onerun <- function() {
n <- 10
x <- runif(n,-4,4)
y <- rbinom(n,1,lava::expit(-1+x))
ord <- order(x)
pv <- targeted::pava(y[ord])
xx <- x[ord[pv$index]]
yy <- pv$value
af <- stepfun(c(xx), c(yy,max(yy)), f=0, right=TRUE)
af2 <- as.stepfun(stats::isoreg(x,y))
plot(af); lines(af2, col=lava::Col("red",0.2),lwd=5)
testthat::expect_true(sum((af(x)-af2(x))^2)<1e-12)
}
replicate(10,onerun())
}) |
library(hamcrest)
library(methods)
setClass("AA", representation(a="numeric"))
setClass("BB", contains="AA")
setMethod("Arith", signature("AA","AA"), function(e1, e2) environment())
setMethod("^", signature("AA","AA"), function(e1, e2) environment())
setMethod("*", signature("BB","BB"), function(e1, e2) environment())
a <- new("AA")
b <- new("BB")
m = a + a
n = a ^ a
o = b + b
p = b ^ b
q = b * b
assertThat(
ls(all.names=TRUE) %in% c(".Random.seed", "a", "b", ".__C__AA", ".__C__BB", "m", "n", "o",
"p", "q", ".__T__Arith:base", ".__T__^:base", ".__T__*:base"),
identicalTo( c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) )
)
test.s4.dispatch.metadata.01b = function() {
assertThat( ls(m, all.names=TRUE) %in% c(".defined", "e1", "e2", ".Generic", ".Method", ".Methods", ".target") , identicalTo( c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) ))
}
test.s4.dispatch.metadata.01d = function() {
assertThat( ls(o, all.names=TRUE) %in% c(".defined", "e1", "e2", ".Generic", ".Method", ".Methods", ".target"), identicalTo( c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) ))
}
test.s4.dispatch.metadata.01e = function() {
assertThat( ls(p, all.names=TRUE) %in% c(".defined", "e1", "e2", ".Generic", ".Method", ".Methods", ".target") , identicalTo( c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) ))
}
test.s4.dispatch.metadata.02 = function() {
assertThat( typeof(m$e1) , identicalTo( "S4" ))
assertThat( typeof(m$.Generic) , identicalTo( "character" ))
assertThat( typeof(m$.Method) , identicalTo( "closure" ))
assertThat( typeof(m$.target) , identicalTo( "character" ))
assertThat( typeof(a) , identicalTo( "S4" ))
assertThat( typeof(`.__C__AA`) , identicalTo( "S4" ))
assertThat( typeof(m) , identicalTo( "environment" ))
assertThat( typeof(`.__T__Arith:base`) , identicalTo( "environment" ))
assertThat( typeof(m$.defined) , identicalTo( "character" ))
assertThat( typeof(attr(m$.defined, "class") ) , identicalTo( "character" ))
assertThat( typeof(attr(m$.defined, "names") ) , identicalTo( "character" ))
assertThat( typeof(attr(m$.defined, "package") ) , identicalTo( "character" ))
assertThat( typeof(attr(attr(m$.defined, "class"), "package") ) , identicalTo( "character" ))
assertThat( typeof(attr(m$.Method, "defined")) , identicalTo( "character" ))
assertThat( typeof(attr(attr(m$.Method, "defined"), "class")), identicalTo( "character"))
assertThat( typeof(attr(attr(m$.Method, "defined"), "names")) , identicalTo( "character" ))
assertThat( typeof(attr(attr(m$.Method, "defined"), "class")) , identicalTo( "character" ))
}
test.s4.dispatch.metadata.03 = function() {
assertThat( attr(m$.defined, "names") , identicalTo( c("e1", "e2") ))
assertThat( attr(m$.defined, "package") , identicalTo( c(".GlobalEnv", ".GlobalEnv") ))
assertThat( attr(attr(m$.defined, "class"), "package") , identicalTo( "methods" ))
assertThat( attr(m$.defined, "class")[1] , identicalTo( "signature" ))
assertThat( attr(attr(m$.Method, "defined"), "names") , identicalTo( c("e1", "e2") ))
assertThat( attr(attr(m$.Method, "defined"), "package") , identicalTo( c(".GlobalEnv", ".GlobalEnv") ))
assertThat( attr(attr(m$.Method, "defined"), "class")[1], identicalTo( "signature"))
}
test.extend.primitive.5 = function() {
setClass("Foo", contains="numeric")
x <- new("Foo", .Data = 42)
assertThat(typeof(x), identicalTo("double"))
assertThat(is.double(x), identicalTo(TRUE))
assertThat(x[1], identicalTo(42))
} |
test_that("entire icon list prints correctly", {
expect_equal(
object = length(find_icons()),
expected = length(rheroicons),
label = "Returned array does not match the length of the icon set"
)
})
test_that("query returns expected icons", {
expect_equal(
object = find_icons(query = "chevron_double"),
expected = c(
"chevron_double_down",
"chevron_double_left",
"chevron_double_right",
"chevron_double_up"
)
)
}) |
make_perclab <- function(x, d = 2) {
return(paste0(round((x * 100), d), "%"))
} |
.wtss_coverage_description <- function(URL, cov){
name <- cov$name
timeline <- lubridate::as_date(cov$timeline)
band_info <- cov$attributes
attr <- tibble::as_tibble(band_info)
bands <- attr$name
t <- dplyr::select(dplyr::filter(attr, name %in% bands),
name, missing_value, scale_factor, valid_range)
missing_values <- t$missing_value
names(missing_values) <- t$name
scale_factors <- t$scale_factor
names(scale_factors) <- t$name
minimum_values <- t$valid_range$min
names(minimum_values) <- t$name
maximum_values <- t$valid_range$max
names(maximum_values) <- t$name
if (all(scale_factors == 1))
scale_factors <- 1/maximum_values
xmin <- cov$spatial_extent$xmin
ymin <- cov$spatial_extent$ymin
xmax <- cov$spatial_extent$xmax
ymax <- cov$spatial_extent$ymax
xres <- cov$spatial_resolution$x
yres <- cov$spatial_resolution$y
nrows <- cov$dimension$y$max_idx - cov$dimensions$y$min_idx + 1
ncols <- cov$dimension$x$max_idx - cov$dimensions$x$min_idx + 1
crs <- cov$crs$proj4
sat_sensor <- .wtss_guess_satellite(xres)
satellite <- sat_sensor["satellite"]
sensor <- sat_sensor["sensor"]
cov.tb <- tibble::tibble(URL = URL,
satellite = satellite,
sensor = sensor,
name = name,
bands = list(bands),
scale_factors = list(scale_factors),
missing_values = list(missing_values),
minimum_values = list(minimum_values),
maximum_values = list(maximum_values),
timeline = list(timeline),
nrows = nrows,
ncols = ncols,
xmin = xmin,
xmax = xmax,
ymin = ymin,
ymax = ymax,
xres = xres,
yres = yres,
crs = crs)
class(cov.tb) <- append(class(cov.tb), c("sits_cube"), after = 0)
return(cov.tb)
}
.wtss_print_coverage <- function(cov.tb){
cat("---------------------------------------------------------------------")
cat(paste0("\nWTSS server URL = ", cov.tb$URL, "\n"))
cat(paste0("Cube (coverage) = ", cov.tb$name))
print(knitr::kable(dplyr::select(cov.tb, satellite, sensor, bands),
padding = 0))
print(knitr::kable(dplyr::select(cov.tb, scale_factors), padding = 0))
print(knitr::kable(dplyr::select(cov.tb, minimum_values), padding = 0))
print(knitr::kable(dplyr::select(cov.tb, maximum_values), padding = 0))
print(knitr::kable(dplyr::select(cov.tb, nrows, ncols, xmin, xmax, ymin,
ymax, xres, yres, crs), padding = 0))
timeline <- lubridate::as_date(cov.tb$timeline[[1]])
n_time_steps <- length(timeline)
cat(paste0("\nTimeline - ",n_time_steps," time steps\n"))
cat(paste0("start_date: ", timeline[1],
" end_date: ", timeline[n_time_steps],"\n"))
cat("-------------------------------------------------------------------\n")
}
.wtss_list_coverages <- function(URL) {
items <- NULL
ce <- 0
response <- NULL
request <- paste(URL,"/list_coverages",sep = "")
items <- .wtss_process_request(request)
if (purrr::is_null(items))
return(NULL)
else
return(items$coverages)
}
.wtss_guess_satellite <- function(xres) {
if (xres < 1.0 ) {
res_m <- geosphere::distGeo(p1 = c(0.0, 0.0), p2 = c(xres, 0.00))
}
else
res_m <- xres
if (res_m > 200.0 && res_m < 2000.0) {
sat_sensor <- c("TERRA", "MODIS")
}
else if (res_m > 60.00 && res_m < 80.0)
sat_sensor <- c("CBERS", "AWFI")
else if (res_m > 25.00 && res_m < 35.0)
sat_sensor <- c("LANDSAT", "OLI")
else if (res_m < 25.00 && res_m > 5.0)
sat_sensor <- c("SENTINEL-2", "MSI")
else
sat_sensor <- c("UNKNOWN", "UNKNOWN")
names(sat_sensor) <- c("satellite", "sensor")
return(sat_sensor)
}
.wtss_remove_trailing_dash <- function(URL) {
url_length <- stringr::str_length(URL)
url_loc_dash <- stringr::str_locate_all(URL, "/")[[1]]
nrow_ld <- nrow(url_loc_dash)
lg <- as.numeric(url_loc_dash[nrow_ld, "start"])
url_new <- URL
if (lg == url_length)
url_new <- stringr::str_sub(URL, end = (url_length - 1))
return(url_new)
} |
pBrIII <- function(x , para = c(1, 2, 0.5)) {
scale <- para[1]; shape1 <- para[2]; shape2 <- para[3]
u <- (1 + (1/shape1)*((x/scale)^(-1/shape2)))^(-shape1*shape2)
return(u)
} |
wendland <- function(crd, knots, w = NULL, ..., longlat = TRUE) {
if (!is.matrix(x = crd)) stop("crd must be a matrix")
if (ncol(x = crd) != 2L) stop("crd must be a matrix with 2 columns")
if (!is.matrix(x = knots)) stop("knots must be a matrix")
if (ncol(x = knots) != 2L) stop("knots must be a matrix with 2 columns")
if (is.null(x = w)) {
dis <- sp::spDists(x = knots, y = knots, longlat = longlat)
w <- 1.5 * min(dis[upper.tri(x = dis, diag = FALSE)])
message("basis function scale set to ", round(w,4))
}
if (w < 1e-8) stop("w must be positive")
return( .wendland(crd = crd, knots = knots, w = w, longlat = longlat) )
}
.wendland <- function(..., crd, knots, w, longlat = TRUE) {
if (longlat) {
dis <- fields::rdist.earth(x1 = crd, x2 = knots, miles = FALSE) / w
} else {
dis <- sp::spDists(x = crd, y = knots, longlat = longlat) / w
}
nzero <- dis <= 1.0
dis2 <- dis[nzero]
tt <- {1.0 - dis2}^6 * {35.0*dis2^2 + 18.0*dis2 + 3.0} / 3.0
dis[] <- 0.0
dis[nzero] <- tt
return( dis )
} |
context("Checking word_length")
test_that("word_length gives the desired output",{
wls <- with(DATA, word_length(state, person))
expect_true(class(wls) == "word_length")
m <- counts(wls)
expect_true(is.data.frame(m))
expect_true(all(dim(m) == c(5, 10)))
}) |
normal.freq <-
function (histogram,frequency=1, ...)
{
xx <- histogram$mids
if(frequency==1)yy<-histogram$counts
if(frequency==2)yy<-histogram$counts/sum(histogram$counts)
if(frequency==3)yy<-histogram$density
media <- sum(yy * xx)/sum(yy)
variancia <- sum(yy * (xx - media)^2)/sum(yy)
zz <- histogram$breaks
x1 <- xx[1] - 4 * (zz[2] - zz[1])
z <- length(zz)
x2 <- xx[z - 1] + 4 * (zz[z] - zz[z - 1])
x <- seq(x1, x2, length = 200)
y <- rep(0, 200)
area <- 0
for (k in 1:(z - 1)) area = area + yy[k] * (zz[k + 1] - zz[k])
for (i in 1:200) {
y[i] <- area * exp(-((x[i] - media)^2)/(2 * variancia))/sqrt(2 *
pi * variancia)
}
lines(x, y, ...)
abline(h = 0)
} |
check.data <- function(data,type="fit"){
if(type=="fit") {
if(!is.data.frame(data)|is.null(data$y)|is.null(data$subj)|is.null(data$argvals))
stop("'data' should be a data frame with three variables:argvals,subj and y")
if(sum(is.na(data))>0) stop("No NA values are allowed in the data")
}
if(type=="predict"){
if(!is.data.frame(data)|is.null(data$y)|is.null(data$subj)|is.null(data$argvals))
stop("'newdata' should be a data frame with three variables:argvals,subj and y")
}
return(0)
} |
transparentColorBase = function(color, alphaTrans=alphaTrans)
{
if(alphaTrans>1 || alphaTrans<0)
stop(paste('alphaTrans (',alphaTrans,') must be in [0,1]!', sep=''))
if( any(is.na(match(color, colors()))) )
stop(paste('color (',color,') must be legal R colors()!',sep=''))
ac = t(col2rgb(color))/255
return(rgb(ac[,1], ac[,2], ac[,3], alpha=alphaTrans))
} |
BP_DetectBackground <- function(bone, analysis=1, show.plot=TRUE) {
red <- bone[c(2:5, dim(bone)[1]-2:5), c(2:5, dim(bone)[2]-2:5), 1, 1]
green <- bone[c(2:5, dim(bone)[1]-2:5), c(2:5, dim(bone)[2]-2:5), 1, 2]
blue <- bone[c(2:5, dim(bone)[1]-2:5), c(2:5, dim(bone)[2]-2:5), 1, 3]
bg <- rgb(red=median(red), green=median(green), blue=median(blue))
bone <- RM_add(x=bone, RMname=analysis,
valuename = "bg", value=bg)
bone <- RM_delete(x=bone, RMname = analysis, valuename="threshold")
bone <- RM_delete(x=bone, RMname = analysis, valuename="contour")
bone <- RM_delete(x=bone, RMname = analysis, valuename="centers")
bone <- RM_delete(x=bone, RMname = analysis, valuename="compactness")
bone <- RM_delete(x=bone, RMname = analysis, valuename="array.compactness")
bone <- RM_delete(x=bone, RMname = analysis, valuename="cut.distance.center")
bone <- RM_delete(x=bone, RMname = analysis, valuename="cut.angle")
bone <- RM_delete(x=bone, RMname = analysis, valuename="compactness.synthesis")
bone <- RM_delete(x=bone, RMname = analysis, valuename="optim")
bone <- RM_delete(x=bone, RMname = analysis, valuename="used.centers")
bone <- RM_delete(x=bone, RMname = analysis, valuename="optimRadial")
if (show.plot) plot(bone)
return(bone)
} |
PSEkNUCTri_DNA<-function(seqs,selectedIdx=c("Dnase I", "Bendability (DNAse)"),lambda=3,w = 0.05,l=3,ORF=FALSE,reverseORF=TRUE,threshold=1,label=c()){
path.pack=system.file("extdata",package="ftrCOOL")
if(length(seqs)==1&&file.exists(seqs)){
seqs<-fa.read(seqs,alphabet="dna")
seqs_Lab<-alphabetCheck(seqs,alphabet = "dna",label)
seqs<-seqs_Lab[[1]]
label<-seqs_Lab[[2]]
}
else if(is.vector(seqs)){
seqs<-sapply(seqs,toupper)
seqs_Lab<-alphabetCheck(seqs,alphabet = "dna",label)
seqs<-seqs_Lab[[1]]
label<-seqs_Lab[[2]]
}
else {
stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.")
}
flag=0
if(ORF==TRUE){
if(length(label)==length(seqs)){
names(label)=names(seqs)
flag=1
}
seqs=maxORF(seqs,reverse=reverseORF)
if(flag==1)
label=label[names(seqs)]
}
numSeqs<-length(seqs)
aaIdxAD<-paste0(path.pack,"/TRI_DNA.csv")
aaIdx<-read.csv(aaIdxAD)
row.names(aaIdx)<-aaIdx[,1]
aaIdx<-aaIdx[selectedIdx,-1]
aaIdx<-as.matrix(aaIdx)
aaIdx<-type.convert(aaIdx)
if(threshold!=1){
aaIdx<-t(aaIdx)
corr<-cor(aaIdx)
corr2<-corr^2
tmp<-corr2
tmp[upper.tri(tmp)]<-0
for(i in 1:ncol(tmp)){
tmp[i,i]=0
}
aaIdx<- aaIdx[,!apply(tmp,2,function(x) any(x > threshold))]
aaIdx<- t(aaIdx)
}
minFea<-apply(aaIdx, 1, min)
maxFea<-apply(aaIdx, 1, max)
aaIdx<-(aaIdx-minFea)/(maxFea-minFea)
numFea<-nrow(aaIdx)
start<-4^l+1
end<-4^l+lambda
featureMatrix<-matrix(0,nrow = numSeqs,ncol = ((4^l)+lambda))
sum_small_th<-vector(mode = "numeric",length = numSeqs)
small_theta<-matrix(0, ncol = lambda,nrow = numSeqs)
N<-sapply(seqs,nchar)
dict<-list("A"=1,"C"=2,"G"=3,"T"=4)
for(n in 1:numSeqs){
seq<-seqs[n]
if (lambda>N[n] || lambda<=0){
stop("Error: lambda should be between [1,N]. N is the minimum of sequence lengths")
}
chars<-unlist(strsplit(seq,NULL))
temp1<-chars[1:(N[n]-2)]
temp2<-chars[2:(N[n]-1)]
temp3<-chars[3:N[n]]
Trimers<-paste0(temp1,temp2,temp3)
lenTrimer=N[n]-2
for(k in 1:lambda){
vecti=1:(lenTrimer-k)
vectj=vecti+k
tempMat<-matrix(0,nrow = numFea,ncol = (lenTrimer-k))
for(m in 1:numFea){
tempMat[m,]=(aaIdx[m,Trimers[vecti]]-aaIdx[m,Trimers[vectj]])^2
}
bigThetaVect<-apply(tempMat, 2, sum)
sumbigThetas<-sum(bigThetaVect)
small_theta[n,k]<-(1/(N[n]-k))*sumbigThetas
}
}
sum_small_th<-apply(small_theta, 1, sum)
NUCmat<-kNUComposition_DNA(seqs,rng=l,normalized = FALSE,upto = FALSE)
index=1
for(index in 1:numSeqs){
featureMatrix[index,1:(4^l)]<-NUCmat[index,]/(N[index]+(w*sum_small_th[index]))
featureMatrix[index,start:end]<- w*small_theta[index,]/(N[index]+w*(sum_small_th[index]))
}
namNUC<-nameKmer(k=l,type = "dna")
temp=1:lambda
colnam=c(namNUC,paste("lambda",temp,sep=""))
colnames(featureMatrix)=colnam
if(length(label)==numSeqs){
featureMatrix<-as.data.frame(featureMatrix)
featureMatrix<-cbind(featureMatrix,label)
}
row.names(featureMatrix)<-names(seqs)
return(featureMatrix)
} |
knit_print.dml <- function(x, ...) {
if (pandoc_version() < 2.4) {
stop("pandoc version >= 2.4 required for DrawingML output in pptx")
}
if (is.null(opts_knit$get("rmarkdown.pandoc.to")) ||
opts_knit$get("rmarkdown.pandoc.to") != "pptx") {
stop("DrawingML currently only supported for pptx output")
}
layout <- knitr::opts_current$get("layout")
master <- knitr::opts_current$get("master")
doc <- get_reference_pptx()
if(is.null( ph <- knitr::opts_current$get("ph") )){
ph <- officer::ph_location_type(type = "body")
}
if(!inherits(ph, "location_str")){
stop("ph should be a placeholder location; ",
"see officer::placeholder location for an example.",
call. = FALSE)
}
id_xfrm <- get_content_ph(ph, layout, master, doc)
dml_file <- tempfile(fileext = ".dml")
img_directory = get_img_dir()
dml_pptx(file = dml_file, width = id_xfrm$width, height = id_xfrm$height,
offx = id_xfrm$left, offy = id_xfrm$top, pointsize = x$pointsize,
last_rel_id = 1L,
editable = x$editable, standalone = FALSE, raster_prefix = img_directory)
tryCatch({
if (!is.null(x$ggobj) ) {
stopifnot(inherits(x$ggobj, "ggplot"))
print(x$ggobj)
} else {
rlang::eval_tidy(x$code)
}
}, finally = dev.off() )
dml_xml <- read_xml(dml_file)
raster_files <- list_raster_files(img_dir = img_directory )
if (length(raster_files)) {
rast_element <- xml_find_all(dml_xml, "//p:pic/p:blipFill/a:blip")
raster_files <- list_raster_files(img_dir = img_directory )
raster_id <- xml_attr(rast_element, "embed")
for (i in seq_along(raster_files)) {
xml_attr(rast_element[i], "r:embed") <- raster_files[i]
}
}
dml_str <- paste(
as.character(xml_find_first(dml_xml, "//p:grpSp")),
collapse = "\n"
)
knit_print(asis_output(
x = paste("```{=openxml}", dml_str, "```", sep = "\n")
))
}
get_ph_uncached <- function(ph, layout, master, doc) {
ls <- layout_summary(doc)
if(!master %in% ls$master){
stop("could not find master ", master, call. = FALSE)
}
slide_index <- which(ls$layout %in% layout & ls$master %in% master)
if(length(slide_index)<1){
stop("could not find layout ", layout, " and master ", master, call. = FALSE)
}
doc <- on_slide(doc, index = slide_index)
fortify_location(ph, doc)
}
get_content_ph <- memoise(get_ph_uncached)
get_img_dir <- function(){
uid <- basename(tempfile(pattern = ""))
img_directory = file.path(tempdir(), uid )
img_directory
}
list_raster_files <- function(img_dir){
path_ <- dirname(img_dir)
uid <- basename(img_dir)
list.files(path = path_, pattern = paste0("^", uid, "(.*)\\.png$"), full.names = TRUE )
} |
markov1<-new("markovchain", states=c("a","b","c"), transitionMatrix=
matrix(c(0.2,0.5,0.3,
0,1,0,
0.1,0.8,0.1),nrow=3, byrow=TRUE, dimnames=list(c("a","b","c"),
c("a","b","c"))
))
require(matlab)
mathematicaMatr <- zeros(5)
mathematicaMatr[1,] <- c(0, 1/3, 0, 2/3, 0)
mathematicaMatr[2,] <- c(1/2, 0, 0, 0, 1/2)
mathematicaMatr[3,] <- c(0, 0, 1/2, 1/2, 0)
mathematicaMatr[4,] <- c(0, 0, 1/2, 1/2, 0)
mathematicaMatr[5,] <- c(0, 0, 0, 0, 1)
statesNames <- letters[1:5]
mathematicaMc <- new("markovchain", transitionMatrix = mathematicaMatr,
name = "Mathematica MC", states = statesNames)
context("Basic DTMC proprieties")
test_that("States are those that should be", {
expect_equal(absorbingStates(markov1), "b")
expect_equal(transientStates(markov1), c("a","c"))
expect_equal(is.irreducible(mathematicaMc), FALSE)
expect_equal(transientStates(mathematicaMc), c("a","b"))
expect_equal(is.accessible(mathematicaMc, "a", "c"), TRUE)
expect_equal(.recurrentClassesRcpp(mathematicaMc), list(c("c", "d"), c("e")))
})
context("Conversion of objects")
provaMatr2Mc<-as(mathematicaMatr,"markovchain")
test_that("Conversion of objects",
{
expect_equal(class(provaMatr2Mc)=="markovchain",TRUE)
})
sequence1 <- c("a", "b", "a", "a", NA, "a", "a", NA)
sequence2 <- c(NA, "a", "b", NA, "a", "a", "a", NA, "a", "b", "a", "b", "a", "b", "a", "a", "b", "b", "b", "a", NA)
mcFit <- markovchainFit(data = sequence1, byrow = FALSE, sanitize = TRUE)
mcFit2 <- markovchainFit(c("a","b","a","b"), sanitize = TRUE)
test_that("Fit should satisfy", {
expect_equal((mcFit["logLikelihood"])[[1]], log(1/3) + 2*log(2/3))
expect_equal(markovchainFit(data = sequence2, method = "bootstrap")["confidenceInterval"]
[[1]]["confidenceLevel"][[1]], 0.95)
expect_equal(mcFit2$upperEndpointMatrix, matrix(c(0,1,1,0), nrow = 2, byrow = TRUE,
dimnames = list(c("a", "b"), c("a", "b"))))
})
bigseq <- rep(c("a", "b", "c"), 500000)
bigmcFit <- markovchainFit(bigseq)
test_that("MC Fit for large sequence 1", {
expect_equal(bigmcFit$logLikelihood, 0)
expect_equal(bigmcFit$confidenceLevel, 0.95)
expect_equal(bigmcFit$estimate@transitionMatrix, bigmcFit$upperEndpointMatrix)
})
bigmcFit <- markovchainFit(bigseq, sanitize = TRUE)
test_that("MC Fit for large sequence 2", {
expect_equal(bigmcFit$logLikelihood, 0)
expect_equal(bigmcFit$confidenceLevel, 0.95)
expect_equal(bigmcFit$estimate@transitionMatrix, bigmcFit$upperEndpointMatrix)
})
matseq <- matrix(c("a", "b", "c", NA ,"b", "c"), nrow = 2, byrow = T)
test_that("Markovchain Fit for matrix as input", {
expect_equal(markovchainFit(matseq)$estimate@transitionMatrix,
matrix(c(0, 1, 0, 0, 0, 1, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(markovchainFit(matseq, sanitize = TRUE)$estimate@transitionMatrix,
matrix(c(0, 1, 0, 0, 0, 1, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(markovchainFit(as.data.frame(matseq))$estimate@transitionMatrix,
matrix(c(0, 1, 0, 0, 0, 1, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(markovchainFit(as.data.frame(matseq), sanitize = TRUE)$estimate@transitionMatrix,
matrix(c(0, 1, 0, 0, 0, 1, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
})
mle_sequence <- c("a", "b", NA, "b", "b", "a", "a", "a", "b", "b", NA, "b", "b", "a", "a", "b", "a", "a", "b", "c")
mle_fit1 <- markovchainFit(mle_sequence)
mle_fit2 <- markovchainFit(mle_sequence, sanitize = TRUE)
test_that("MarkovchainFit MLE", {
expect_equal(mle_fit1$estimate@transitionMatrix,
matrix(c(0.5, 0.5, 0, 3/7, 3/7, 1/7, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(mle_fit2$estimate@transitionMatrix,
matrix(c(0.5, 0.5, 0, 3/7, 3/7, 1/7, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(mle_fit1$logLikelihood, mle_fit2$logLikelihood)
expect_equal(mle_fit1$confidenceInterval, mle_fit2$confidenceInterval)
expect_equal(mle_fit2$standardError, mle_fit2$standardError)
})
lap_sequence <- c("a", "b", NA, "b", "b", "a", "a", "a", "b", "b", NA, "b", "b", "a", "a", "b", "a", "a", "b", "c")
lap_fit1 <- markovchainFit(lap_sequence, "laplace")
lap_fit2 <- markovchainFit(lap_sequence, "laplace", sanitize = TRUE)
test_that("Markovchain Laplace", {
expect_equal(lap_fit1$estimate@transitionMatrix,
matrix(c(0.5, 0.5, 0, 3/7, 3/7, 1/7, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(lap_fit2$estimate@transitionMatrix,
matrix(c(0.5, 0.5, 0, 3/7, 3/7, 1/7, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(lap_fit1$logLikelihood, lap_fit2$logLikelihood)
})
mix_seq <- c("a", "b", NA, "b", "b", "a", "a", "a", "b", "b", NA, "b", "b", "a", "a", "b", "a", "a", "b", "c")
mix_fit1 <- markovchainFit(mix_seq, "mle", sanitize = TRUE, possibleStates = c("d"))
mix_fit2 <- markovchainFit(mix_seq, "laplace", sanitize = TRUE, possibleStates = c("d"))
mix_fit3 <- markovchainFit(mix_seq, "map", sanitize = TRUE, possibleStates = c("d"))
test_that("Mixture of Markovchain Fitting", {
expect_equal(mix_fit2$estimate@transitionMatrix,
matrix(c(.5, .5, 0, 0, 3/7, 3/7, 1/7, 0,
1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4), nrow = 4, byrow = TRUE,
dimnames = list(c("a", "b", "c", "d"), c("a", "b", "c", "d"))
)
)
expect_equal(mix_fit1$estimate@transitionMatrix,
matrix(c(.5, .5, 0, 0, 3/7, 3/7, 1/7, 0,
1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4), nrow = 4, byrow = TRUE,
dimnames = list(c("a", "b", "c", "d"), c("a", "b", "c", "d"))
)
)
expect_equal(mix_fit3$estimate@transitionMatrix,
matrix(c(.5, .5, 0, 0, 3/7, 3/7, 1/7, 0,
1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4, 1/4), nrow = 4, byrow = TRUE,
dimnames = list(c("a", "b", "c", "d"), c("a", "b", "c", "d"))
)
)
})
rsequence <- c("a", "b", NA, "b", "b", "a", "a", "a", "b", "b", NA, "b", "b", "a", "a", "b", "a", "a", "b", "c")
test_that("createSequenceMatrix : Permutation of parameters",{
expect_equal(createSequenceMatrix(rsequence, FALSE, FALSE),
matrix(c(4, 4, 0, 3, 3, 1, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(createSequenceMatrix(rsequence, FALSE, TRUE),
matrix(c(4, 4, 0, 3, 3, 1, 1, 1, 1), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(createSequenceMatrix(rsequence, TRUE, FALSE),
matrix(c(4/8, 4/8, 0, 3/7, 3/7, 1/7, 0, 0, 0), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_equal(createSequenceMatrix(rsequence, TRUE, TRUE),
matrix(c(4/8, 4/8, 0, 3/7, 3/7, 1/7, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
})
data <- matrix(c("a", "a", "b", "a", "b", "a", "b", "a", NA, "a", "a", "a", "a", "b", NA, "b"), ncol = 2,
byrow = TRUE)
test_that("createSequenceMatrix : input as matrix",{
expect_equal(createSequenceMatrix(data),
matrix(c(2, 1, 3, 0), nrow = 2, byrow = TRUE,
dimnames = list(c("a", "b"), c("a", "b"))))
expect_equal(createSequenceMatrix(data, toRowProbs = TRUE),
matrix(c(2/3, 1/3, 3/3, 0), nrow = 2, byrow = TRUE,
dimnames = list(c("a", "b"), c("a", "b"))))
expect_equal(createSequenceMatrix(data, toRowProbs = TRUE, possibleStates = "d",
sanitize = TRUE),
matrix(c(2/3, 1/3, 0, 1, 0, 0, 1/3, 1/3, 1/3), nrow = 3,
byrow = TRUE, dimnames = list(c("a", "b", "d"), c("a", "b", "d"))))
})
statesNames <- c("a", "b", "c")
mcB <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1),
nrow = 3, byrow = TRUE, dimnames = list(statesNames, statesNames)))
s1 <- markovchainSequence(10, mcB)
s2 <- markovchainSequence(10, mcB, include.t0 = TRUE)
s3 <- markovchainSequence(10, mcB, t0 = "b", include.t0 = TRUE)
s4 <- markovchainSequence(10, mcB, useRCpp = FALSE)
s5 <- markovchainSequence(10, mcB, include.t0 = TRUE, useRCpp = FALSE)
s6 <- markovchainSequence(10, mcB, t0 = "b", include.t0 = TRUE, useRCpp = FALSE)
test_that("Output format of markovchainSequence", {
expect_equal(length(s1), 10)
expect_equal(length(s2), 11)
expect_equal(length(s3), 11)
expect_equal(s3[1], "b")
expect_equal(length(s4), 10)
expect_equal(length(s5), 11)
expect_equal(length(s6), 11)
expect_equal(s6[1], "b")
})
statesNames <- c("a", "b", "c")
mcA <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
mcB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
mcC <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
mclist <- new("markovchainList", markovchains = list(mcA, mcB, mcC))
o1 <- rmarkovchain(15, mclist, "list")
o2 <- rmarkovchain(15, mclist, "matrix")
o3 <- rmarkovchain(15, mclist, "data.frame")
o4 <- rmarkovchain(15, mclist, "list", t0 = "a", include.t0 = TRUE)
o5 <- rmarkovchain(15, mclist, "matrix", t0 = "a", include.t0 = TRUE)
o6 <- rmarkovchain(15, mclist, "data.frame", t0 = "a", include.t0 = TRUE)
test_that("Output format of rmarkovchain", {
expect_equal(length(o1), 15)
expect_equal(length(o1[[1]]), 3)
expect_equal(all(dim(o2) == c(15, 3)), TRUE)
expect_equal(all(dim(o3) == c(45, 2)), TRUE)
expect_equal(length(o4), 15)
expect_equal(length(o4[[1]]), 4)
expect_equal(o4[[1]][1], "a")
expect_equal(all(dim(o5) == c(15, 4)), TRUE)
expect_equal(all(o5[, 1] == "a"), TRUE)
expect_equal(all(dim(o6) == c(60, 2)), TRUE)
})
data1 <- c("a", "b", "a", "c", "a", "b", "a", "b", "c", "b", "b", "a", "b")
data2 <- c("c", "a", "b")
test_that("MAP fits must satisfy", {
expect_identical(markovchainFit(data1, method = "map")$estimate@transitionMatrix,
markovchainFit(data1, method = "mle")$estimate@transitionMatrix)
expect_identical(markovchainFit(data1, method = "map")$estimate@transitionMatrix,
matrix(c(0.0, 0.6, 0.5,
0.8, 0.2, 0.5,
0.2, 0.2, 0.0), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_identical(markovchainFit(data1, method = "map", hyperparam =
matrix(c(2, 1, 3,
4, 5, 2,
2, 2, 1), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))$estimate@transitionMatrix,
matrix(c(1/10, 3/10, 3/5,
7/10, 5/10, 2/5,
2/10, 2/10, 0), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
})
test_that("predictiveDistribution must satisfy", {
expect_equal(predictiveDistribution(data1, character()), 0)
expect_equal(predictiveDistribution(data1, data2, hyperparam =
matrix(c(2, 1, 3,
4, 5, 2,
2, 2, 1), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c")))),
log(4 / 13))
})
test_that("inferHyperparam must satisfy", {
expect_identical(inferHyperparam(data = data1)$dataInference,
matrix(c(1, 4, 2,
5, 2, 2,
2, 2, 1), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
expect_identical(inferHyperparam(transMatr =
matrix(c(0.0, 0.6, 0.5,
0.8, 0.2, 0.5,
0.2, 0.2, 0.0), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))),
scale = c(10, 10, 10))$scaledInference,
matrix(c(0, 6, 5,
8, 2, 5,
2, 2, 0), nrow = 3,
dimnames = list(c("a", "b", "c"), c("a", "b", "c"))))
})
pDRes <- c(log(3/2), log(3/2))
names(pDRes) <- c("a", "b")
test_that("priorDistribution must sastisfy", {
expect_equal(priorDistribution(matrix(c(0.5, 0.5, 0.5, 0.5),
nrow = 2,
dimnames = list(c("a", "b"), c("a", "b"))),
matrix(c(2, 2, 2, 2),
nrow = 2,
dimnames = list(c("a", "b"), c("a", "b")))),
pDRes)
})
energyStates <- c("sigma", "sigma_star")
byRow <- TRUE
gen <- matrix(data = c(-3, 3,
1, -1), nrow = 2,
byrow = byRow, dimnames = list(energyStates, energyStates))
molecularCTMC <- new("ctmc", states = energyStates,
byrow = byRow, generator = gen,
name = "Molecular Transition Model")
test_that("steadyStates must satisfy", {
expect_identical(steadyStates(molecularCTMC),
matrix(c(1/4, 3/4), nrow = 1, dimnames = list(c(), energyStates)))
})
transMatr<-matrix(c(0.99,0.01,0.01,0.99),nrow=2,byrow=TRUE)
simpleMc<-new("markovchain", states=c("a","b"),
transitionMatrix=transMatr)
test_that("expectedRewards must satisfy", {
expect_equal(expectedRewards(simpleMc,1,c(0,1)),c(0.01,1.99))
expect_equal(expectedRewards(simpleMc,2,c(0,1)),c(0.0298,2.9702))
})
transMatr <- matrix(c(0,0,0,1,0.5,
0.5,0,0,0,0,
0.5,0,0,0,0,
0,0.2,0.4,0,0,
0,0.8,0.6,0,0.5),nrow = 5)
object <- new("markovchain", states=c("a","b","c","d","e"),transitionMatrix=transMatr, name="simpleMc")
answer <- c(0.444,0.889,0.000,0.444,1.000)
names <- c("a","b","c","d","e")
names(answer) <- names
test_that("committorAB must satisfy", {
expect_equal(round(committorAB(object,c(5),c(3)),3),answer)
})
statesNames <- c("a", "b", "c")
testmarkov <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3,
0.5, 0.1, 0.4,
0.1, 0.8, 0.1), nrow = 3, byrow = TRUE,
dimnames = list(statesNames, statesNames)
))
answer <- matrix(c(.8000,
0.6000,
0.2540
),nrow = 3,dimnames = list(c("1","2","3"),"set"))
test_that("firstPassageMultiple function satisfies", {
expect_equal(firstPassageMultiple(testmarkov,"a",c("b","c"),3),answer)
})
M <- matrix(0,nrow=10,ncol=10,byrow=TRUE)
M[1,2]<- 0.7
M[1,3]<- 0.3
M[2,3]<- 1
M[3,4]<- 1
M[4,1]<- 1
M[5,6]<- 1
M[6,7]<- 1
M[7,8]<- 1
M[8,9]<- 1
M[9,10]<- 1
M[10,1]<- 1
markovChain <- new("markovchain",transitionMatrix=M)
context("Checking is.accesible")
test_that("is accesible is equivalent to reachability matrix", {
for (mc in subsetAllMCs) {
expect_true(.testthatIsAccesibleRcpp(mc$object))
}
}) |
forecast.tbats <- function(object, h, level = c(80, 95), fan = FALSE, biasadj = NULL, ...) {
if (identical(class(object), "bats")) {
return(forecast.bats(object, h, level, fan, biasadj, ...))
}
if (any(class(object$y) == "ts")) {
ts.frequency <- frequency(object$y)
} else {
ts.frequency <- ifelse(!is.null(object$seasonal.periods), max(object$seasonal.periods), 1)
}
if (missing(h)) {
if (is.null(object$seasonal.periods)) {
h <- ifelse(ts.frequency == 1, 10, 2 * ts.frequency)
} else {
h <- 2 * max(object$seasonal.periods)
}
}
else if (h <= 0) {
stop("Forecast horizon out of bounds")
}
if (fan) {
level <- seq(51, 99, by = 3)
} else {
if (min(level) > 0 && max(level) < 1) {
level <- 100 * level
} else if (min(level) < 0 || max(level) > 99.99) {
stop("Confidence limit out of range")
}
}
if (!is.null(object$k.vector)) {
tau <- 2 * sum(object$k.vector)
} else {
tau <- 0
}
x <- matrix(0, nrow = nrow(object$x), ncol = h)
y.forecast <- numeric(h)
if (!is.null(object$beta)) {
adj.beta <- 1
} else {
adj.beta <- 0
}
w <- .Call("makeTBATSWMatrix", smallPhi_s = object$damping.parameter, kVector_s = as.integer(object$k.vector), arCoefs_s = object$ar.coefficients, maCoefs_s = object$ma.coefficients, tau_s = as.integer(tau), PACKAGE = "forecast")
if (!is.null(object$seasonal.periods)) {
gamma.bold <- matrix(0, nrow = 1, ncol = tau)
.Call("updateTBATSGammaBold", gammaBold_s = gamma.bold, kVector_s = as.integer(object$k.vector), gammaOne_s = object$gamma.one.values, gammaTwo_s = object$gamma.two.values, PACKAGE = "forecast")
} else {
gamma.bold <- NULL
}
g <- matrix(0, nrow = (tau + 1 + adj.beta + object$p + object$q), ncol = 1)
if (object$p != 0) {
g[(1 + adj.beta + tau + 1), 1] <- 1
}
if (object$q != 0) {
g[(1 + adj.beta + tau + object$p + 1), 1] <- 1
}
.Call("updateTBATSGMatrix", g_s = g, gammaBold_s = gamma.bold, alpha_s = object$alpha, beta_s = object$beta.v, PACKAGE = "forecast")
F <- makeTBATSFMatrix(alpha = object$alpha, beta = object$beta, small.phi = object$damping.parameter, seasonal.periods = object$seasonal.periods, k.vector = as.integer(object$k.vector), gamma.bold.matrix = gamma.bold, ar.coefs = object$ar.coefficients, ma.coefs = object$ma.coefficients)
y.forecast[1] <- w$w.transpose %*% object$x[, ncol(object$x)]
x[, 1] <- F %*% object$x[, ncol(object$x)]
if (h > 1) {
for (t in 2:h) {
x[, t] <- F %*% x[, (t - 1)]
y.forecast[t] <- w$w.transpose %*% x[, (t - 1)]
}
}
lower.bounds <- upper.bounds <- matrix(NA, ncol = length(level), nrow = h)
variance.multiplier <- numeric(h)
variance.multiplier[1] <- 1
if (h > 1) {
for (j in 1:(h - 1)) {
if (j == 1) {
f.running <- diag(ncol(F))
} else {
f.running <- f.running %*% F
}
c.j <- w$w.transpose %*% f.running %*% g
variance.multiplier[(j + 1)] <- variance.multiplier[j] + c.j^2
}
}
variance <- object$variance * variance.multiplier
st.dev <- sqrt(variance)
for (i in 1:length(level)) {
marg.error <- st.dev * abs(qnorm((100 - level[i]) / 200))
lower.bounds[, i] <- y.forecast - marg.error
upper.bounds[, i] <- y.forecast + marg.error
}
if (!is.null(object$lambda)) {
y.forecast <- InvBoxCox(y.forecast, object$lambda, biasadj, list(level = level, upper = upper.bounds, lower = lower.bounds))
lower.bounds <- InvBoxCox(lower.bounds, object$lambda)
if (object$lambda < 1) {
lower.bounds <- pmax(lower.bounds, 0)
}
upper.bounds <- InvBoxCox(upper.bounds, object$lambda)
}
colnames(upper.bounds) <- colnames(lower.bounds) <- paste0(level, "%")
forecast.object <- list(
model = object, mean = future_msts(object$y, y.forecast),
level = level, x = object$y, series = object$series,
upper = future_msts(object$y, upper.bounds),
lower = future_msts(object$y, lower.bounds),
fitted = copy_msts(object$y, object$fitted.values),
method = as.character(object),
residuals = copy_msts(object$y, object$errors)
)
if (is.null(object$series)) {
forecast.object$series <- deparse(object$call$y)
}
class(forecast.object) <- "forecast"
return(forecast.object)
}
as.character.tbats <- function(x, ...) {
name <- "TBATS("
if (!is.null(x$lambda)) {
name <- paste(name, round(x$lambda, digits = 3), sep = "")
} else {
name <- paste(name, "1", sep = "")
}
name <- paste(name, ", {", sep = "")
if (!is.null(x$ar.coefficients)) {
name <- paste(name, length(x$ar.coefficients), sep = "")
} else {
name <- paste(name, "0", sep = "")
}
name <- paste(name, ",", sep = "")
if (!is.null(x$ma.coefficients)) {
name <- paste(name, length(x$ma.coefficients), sep = "")
} else {
name <- paste(name, "0", sep = "")
}
name <- paste(name, "}, ", sep = "")
if (!is.null(x$damping.parameter)) {
name <- paste(name, round(x$damping.parameter, digits = 3), ",", sep = "")
} else {
name <- paste(name, "-,", sep = "")
}
if (!is.null(x$seasonal.periods)) {
name <- paste(name, " {", sep = "")
M <- length(x$seasonal.periods)
for (i in 1:M) {
name <- paste(name, "<", round(x$seasonal.periods[i], 2), ",", x$k.vector[i], ">", sep = "")
if (i < M) {
name <- paste(name, ", ", sep = "")
} else {
name <- paste(name, "})", sep = "")
}
}
} else {
name <- paste(name, "{-})", sep = "")
}
return(name)
} |
warp.sample <- function(samp, w, mode) {
if (mode == "backward") {
apply(samp, 1, function(x)
approx(x, NULL, w)$y)
} else {
apply(samp, 1, function(x) {
approx(w, x, xout = 1:length(x))$y
})
}
} |
require(atom4R, quietly = TRUE)
require(testthat)
require(XML)
context("DCElement")
test_that("encoding/decoding DCEntry",{
testthat::skip_on_cran()
dcentry <- DCEntry$new()
dcentry$setId("my-dc-entry")
dcentry$addDCDate(Sys.time())
dcentry$addDCTitle("atom4R - Tools to read/write and publish metadata as Atom XML format")
dcentry$addDCType("Software")
creator <- DCCreator$new(value = "Blondel, Emmanuel")
creator$attrs[["affiliation"]] <- "Independent"
dcentry$addDCCreator(creator)
dcentry$addDCSubject("R")
dcentry$addDCSubject("FAIR")
dcentry$addDCSubject("Interoperability")
dcentry$addDCSubject("Open Science")
dcentry$addDCDescription("Atom4R offers tools to read/write and publish metadata as Atom XML syndication format, including Dublin Core entries. Publication can be done using the Sword API which implements AtomPub API specifications")
dcentry$addDCPublisher("GitHub")
funder <- DCContributor$new(value = "CNRS")
funder$attrs[["type"]] <- "Funder"
dcentry$addDCContributor(funder)
dcentry$addDCRelation("Github repository: https://github.com/eblondel/atom4R")
dcentry$addDCSource("Atom Syndication format - https://www.ietf.org/rfc/rfc4287")
dcentry$addDCSource("AtomPub, The Atom publishing protocol - https://tools.ietf.org/html/rfc5023")
dcentry$addDCSource("Sword API - http://swordapp.org/")
dcentry$addDCSource("Dublin Core Metadata Initiative - https://www.dublincore.org/")
dcentry$addDCSource("Guidelines for implementing Dublin Core in XML - https://www.dublincore.org/specifications/dublin-core/dc-xml-guidelines/")
dcentry$addDCLicense("NONE")
dcentry$addDCRights("MIT License")
xml <- dcentry$encode()
expect_is(dcentry, "DCEntry")
dcentry2 <- DCEntry$new(xml = xml)
xml2 <- dcentry2$encode()
expect_true(AtomAbstractObject$compare(dcentry, dcentry2))
}) |
selftest.ttest.tck <- function(){
options(guiToolkit="tcltk")
w <- gwindow(title = "t-tests")
size(w) <- c(700, 900)
g <- ggroup(container=w, horizontal=FALSE, use.scrollwindow = TRUE)
gp1 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp1.1 <- ggroup(container = gp1, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("1) ", container = gp1.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from a normal distribution with unknown mean, \u03bc, and known variance, \u03c3\u00b2. \nWe want to conduct a null hypothesis test concerning the value of \u03bc. We would use a...", container = gp1.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans1 <- c("(a) pooled variance t-test.",
"(b) Welch t-test.",
"(c) paired t-test.",
"(d) one sample z-test.",
"(e) one sample t-test."
)
f1 <- function(h,....){
if(tail(svalue(r1),1) == ans1[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r1),1)== ans1[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r1),1)== ans1[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r1),1)== ans1[4]){
gmessage(msg="Correct")
}
if(tail(svalue(r1),1)== ans1[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r1) <- character(0)
}
r1 <- gcheckboxgroup(ans1, container = gp1, checked = FALSE, where = "beginning", handler = f1)
gp2 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp2.1 <- ggroup(container = gp2, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("2) ", container = gp2.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from a normal distribution with unknown mean, \u03bc, and unknown variance, \u03c3\u00b2. \nWe want to conduct a null hypothesis test concerning the value of \u03bc. We would use a...", container = gp2.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans2 <- c("(a) pooled variance t-test.",
"(b) Welch t-test.",
"(c) paired t-test.",
"(d) one sample z-test.",
"(e) one sample t-test."
)
f2 <- function(h,....){
if(tail(svalue(r2),1) == ans2[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[5]){
gmessage(msg="Correct")
}
svalue(r2) <- character(0)
}
r2 <- gcheckboxgroup(ans2, container = gp2, checked = FALSE, where = "beginning", handler = f2)
gp3 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp3.1 <- ggroup(container = gp3, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("3) ", container = gp3.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from two normal distributions with unknown means, \u03bc\u2081, \u03bc\u2082, and common variance, \u03c3\u00b2 \n(i.e., we assume \u03c3\u00b2\u2081 = \u03c3\u00b2\u2082 = \u03c3\u00b2). We want to conduct a null hypothesis test concerning \nthe value of \u03bc\u2081 - \u03bc\u2082. We would use a...", container = gp3.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans3 <- c("(a) pooled variance t-test.",
"(b) Welch t-test.",
"(c) paired t-test.",
"(d) one sample z-test.",
"(e) one sample t-test."
)
f3 <- function(h,....){
if(tail(svalue(r3),1) == ans3[1]){
gmessage(msg="Correct")
}
if(tail(svalue(r3),1)== ans3[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r3),1)== ans3[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r3),1)== ans3[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r3),1)== ans3[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r3) <- character(0)
}
r3 <- gcheckboxgroup(ans3, container = gp3, checked = FALSE, where = "beginning", handler = f3)
gp4 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp4.1 <- ggroup(container = gp4, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("4) ", container = gp4.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We have a blocked experimental design and in each block we have two treatments. \nWe measure the differences of treatments in blocks and assume that these differences come from \na normal distribution with an unknown mean and an unknown variance. We want to conduct a null \nhypothesis test concerning the value of the unknown true mean of differences. We would use a...", container = gp4.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans4 <- c("(a) pooled variance t-test.",
"(b) Welch t-test.",
"(c) paired t-test.",
"(d) one sample z-test.",
"(e) one sample t-test."
)
f4 <- function(h,....){
if(tail(svalue(r4),1) == ans4[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r4),1)== ans4[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r4),1) == ans4[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r4),1)== ans4[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r4),1)== ans4[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r4) <- character(0)
}
r4 <- gcheckboxgroup(ans4, container = gp4, checked = FALSE, where = "beginning", handler = f4)
gp5 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp5.1 <- ggroup(container = gp5, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("5) ", container = gp5.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from two normal distributions with unknown means, \u03bc\u2081, \u03bc\u2082, and unknown variances, \u03c3\u00b2\u2081 \nand \u03c3\u00b2\u2082. We want to conduct a null hypothesis test concerning the value of \u03bc\u2081 - \u03bc\u2082. We would use a...", container = gp5.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans5 <- c("(a) pooled variance t-test.",
"(b) Welch t-test.",
"(c) paired t-test.",
"(d) one sample z-test.",
"(e) one sample t-test."
)
f5 <- function(h,....){
if(tail(svalue(r5),1) == ans5[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r5),1)== ans5[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r5),1) == ans5[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r5),1)== ans5[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r5),1)== ans5[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r5) <- character(0)
}
r5 <- gcheckboxgroup(ans5, container = gp5, checked = FALSE, where = "beginning", handler = f5)
gp6 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp6.1 <- ggroup(container = gp6, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("6) ", container = gp6.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("To calculate the pooled variance t-test test statistic we must calculate...", container = gp6.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans6 <- c("(a) MSE.",
"(b) the Satterthwaite degrees of freedom.",
"(c) the standard deviation of differences within blocks.",
"(d) the mean of differences within blocks.",
"(e) (c) and (d)."
)
f6 <- function(h,....){
if(tail(svalue(r6),1)== ans6[1]){
gmessage(msg="Correct")
}
if(tail(svalue(r6),1)== ans6[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r6),1) == ans6[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r6),1)== ans6[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r6),1)== ans6[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r6) <- character(0)
}
r6 <- gcheckboxgroup(ans6, container = gp6, checked = FALSE, where = "beginning", handler = f6)
gp7 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp7.1 <- ggroup(container = gp7, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("7) ", container = gp7.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("To calculate the paired t-test test statistic we must calculate...", container = gp7.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans7 <- c("(a) MSE.",
"(b) the Satterthwaite degrees of freedom.",
"(c) the standard deviation of differences within blocks.",
"(d) the mean of differences within blocks.",
"(e) (c) and (d)."
)
f7 <- function(h,....){
if(tail(svalue(r7),1) == ans7[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r7),1)== ans7[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r7),1) == ans7[3]){
gmessage(msg="Partially correct", icon = "error")
}
if(tail(svalue(r7),1)== ans7[4]){
gmessage(msg="Partially correct", icon = "error")
}
if(tail(svalue(r7),1) == ans7[5]){
gmessage(msg="Correct")
}
svalue(r7) <- character(0)
}
r7 <- gcheckboxgroup(ans7, container = gp7, checked = FALSE, where = "beginning", handler = f7)
gp8 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp8.1 <- ggroup(container = gp8, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("8) ", container = gp8.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("To calculate the Welch t-test p-value we must calculate...", container = gp8.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans8 <- c("(a) MSE.",
"(b) the Satterthwaite degrees of freedom.",
"(c) the standard deviation of differences within blocks.",
"(d) the mean of differences within blocks.",
"(e) (c) and (d)."
)
f8 <- function(h,....){
if(tail(svalue(r8),1) == ans8[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r8),1)== ans8[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r8),1) == ans8[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r8),1)== ans8[4]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r8),1) == ans8[5]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r8) <- character(0)
}
r8 <- gcheckboxgroup(ans8, container = gp8, checked = FALSE, where = "beginning", handler = f8)
gp9 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp9.1 <- ggroup(container = gp9, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("9) ", container = gp9.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null distribution for a one sample z-test is...", container = gp9.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans9 <- c("(a) t(n-1).",
"(b) t(n\u2081 + n\u2082 - 2).",
"(c) t(\u03bd), where \u03bd = the Satterthwaite degrees of freedom.",
"(d) N(0,1).")
f9 <- function(h,....){
if(tail(svalue(r9),1) == ans9[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r9),1)== ans9[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r9),1) == ans9[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r9),1)== ans9[4]){
gmessage(msg="Correct")
}
svalue(r9) <- character(0)
}
r9 <- gcheckboxgroup(ans9, container = gp9, checked = FALSE, where = "beginning", handler = f9)
gp10 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp10.1 <- ggroup(container = gp10, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("10) ", container = gp10.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null distribution for a pooled variance t-test is...", container = gp10.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans10 <- c("(a) t(n-1).",
"(b) t(n\u2081 + n\u2082 - 2).",
"(c) t(\u03bd), where \u03bd = the Satterthwaite degrees of freedom.",
"(d) N(0,1).")
f10 <- function(h,....){
if(tail(svalue(r10),1) == ans10[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r10),1)== ans10[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r10),1) == ans10[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r10),1)== ans10[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r10) <- character(0)
}
r10 <- gcheckboxgroup(ans10, container = gp10, checked = FALSE, where = "beginning", handler = f10)
gp11 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp11.1 <- ggroup(container = gp11, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("11) ", container = gp11.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null distribution for a paired t-test is...", container = gp11.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans11 <- c("(a) t(n-1).",
"(b) t(n\u2081 + n\u2082 - 2).",
"(c) t(\u03bd), where \u03bd = the Satterthwaite degrees of freedom.",
"(d) N(0,1).")
f11 <- function(h,....){
if(tail(svalue(r11),1) == ans11[1]){
gmessage(msg="Correct")
}
if(tail(svalue(r11),1)== ans11[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r11),1) == ans11[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r11),1)== ans11[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r11) <- character(0)
}
r11 <- gcheckboxgroup(ans11, container = gp11, checked = FALSE, where = "beginning", handler = f11)
gp12 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp12.1 <- ggroup(container = gp12, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("12) ", container = gp12.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null distribution for a Welch t-test is...", container = gp12.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans12 <- c("(a) t(n-1).",
"(b) t(n\u2081 + n\u2082 - 2)",
"(c) t(\u03bd), where \u03bd = the Satterthwaite degrees of freedom",
"(d) N(0,1).")
f12 <- function(h,....){
if(tail(svalue(r12),1) == ans12[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r12),1)== ans12[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r12),1) == ans12[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r12),1)== ans12[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r12) <- character(0)
}
r12 <- gcheckboxgroup(ans12, container = gp12, checked = FALSE, where = "beginning", handler = f12)
gp13 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp13.1 <- ggroup(container = gp13, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("13) ", container = gp13.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null hypothesis for the Fligner-Killeen test is...", container = gp13.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans13 <- c("(a) H\u2080: \u03bc = \u03bc\u2080.",
"(b) H\u2080: \u03bc\u2081 = \u03bc\u2082.",
"(c) H\u2080: The underlying population is normal.",
"(d) H\u2080: \u03c3\u00b2\u2081 = \u03c3\u00b2\u2082.")
f13 <- function(h,....){
if(tail(svalue(r13),1) == ans13[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r13),1)== ans13[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r13),1) == ans13[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r13),1)== ans13[4]){
gmessage(msg="Correct")
}
svalue(r13) <- character(0)
}
r13 <- gcheckboxgroup(ans13, container = gp13, checked = FALSE, where = "beginning", handler = f13)
gp14 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp14.1 <- ggroup(container = gp14, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("14) ", container = gp14.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The null hypothesis for the Shapiro-Wilk test is...", container = gp14.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans14 <- c("(a) H\u2080: \u03bc = \u03bc\u2080.",
"(b) H\u2080: \u03bc\u2081 = \u03bc\u2082.",
"(c) H\u2080: The underlying population is normal.",
"(d) H\u2080: \u03c3\u00b2\u2081 = \u03c3\u00b2\u2082.")
f14 <- function(h,....){
if(tail(svalue(r14),1) == ans14[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r14),1)== ans14[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r14),1) == ans14[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r14),1)== ans14[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r14) <- character(0)
}
r14 <- gcheckboxgroup(ans14, container = gp14, checked = FALSE, where = "beginning")
gp15 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp15.1 <- ggroup(container = gp15, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("15) ", container = gp15.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The plot below is a...", container = gp15.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
x <- rnorm(20)
gp15.1a <- getWidget(gp15)
img <- tkrplot::tkrplot(gp15.1a, function(){
par(bg = "white", mar = c(4.5,4.1,1,1))
qqnorm(x, cex.lab =.9, main = "")
qqline(x, col = 2, lty = 2)
}
)
add(gp15, img)
ans15 <- c("(a) regression plot.",
"(b) heteroscedasticy plot.",
"(c) normal probability plot.",
"(d) homoscedasticity plot.")
f15 <- function(h,....){
if(tail(svalue(r15),1) == ans15[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r15),1)== ans15[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r15),1)== ans15[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r15),1)== ans15[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r15) <- character(0)
}
r15 <- gcheckboxgroup(ans15, container = gp15, checked = FALSE, where = "beginning", handler = f15)
gp16 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp16.1 <- ggroup(container = gp16, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("16) ", container = gp16.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("The plot from the previous question is generally used to...", container = gp16.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans16 <- c("(a) Check for the validity of the equal variances assumption.",
"(b) Check for the validity of the assumption of normality.",
"(c) Check for the validity of the assumption of independence.",
"(d) Check for outliers.")
f16 <- function(h,....){
if(tail(svalue(r16),1) == ans16[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r16),1)== ans16[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r16),1) == ans16[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r16),1)== ans16[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r16) <- character(0)
}
r16 <- gcheckboxgroup(ans16, container = gp16, checked = FALSE, where = "beginning", handler = f16)
} |
gpdpwmb <- function(data, threshold, a=0.35, b=0, hybrid = FALSE){
if ( length(unique(threshold)) != 1){
warning("Threshold must be a single numeric value for est = 'pwmb'. Taking only the first value !!!")
threshold <- threshold[1]
}
exceed <- data[data>threshold]
nat <- length( exceed )
pat <- nat / length( data )
if ( nat == 0 )
stop("None observation above the specified threshold !!!")
exceed <- sort(exceed)
loc <- threshold
excess <- exceed - loc
m <- mean(excess)
n <- length(excess)
p <- (1:n - a) / (n + b)
t <- sum((1-p)*excess)/n
shape <- - m / (m- 2*t ) + 2
scale <- 2 * m * t / (m - 2*t )
est <- 'PWMB'
if (hybrid)
if ( (max(excess) >= (-scale / shape)) & (shape < 0) ){
shape <- -scale / max(excess)
est <- 'PWMB Hybrid'
}
estim <- c(scale = scale, shape = shape)
param <- c(scale = scale, shape = shape)
convergence <- NA
counts <- NA
a11 <- scale^2 * (7-18*shape+11*shape^2-2*shape^3)
a12 <- - scale * (2-shape) * (2-6*shape+7*shape^2-2*shape^3)
a21 <- a12
a22 <- (1-shape) * (2 -shape)^2 * (1-shape+2*shape^2)
var.cov <- 1 / ( (1-2*shape) * (3-2*shape)*nat ) *
matrix(c(a11,a21,a12,a22),2)
colnames(var.cov) <- c('scale','shape')
rownames(var.cov) <- c('scale','shape')
std.err <- sqrt( diag(var.cov) )
.mat <- diag(1/std.err, nrow = length(std.err))
corr <- structure(.mat %*% var.cov %*% .mat)
diag(corr) <- rep(1, length(std.err))
colnames(corr) <- c('scale','shape')
rownames(corr) <- c('scale','shape')
if ( shape > 0.5 )
message <- "Assymptotic theory assumptions for standard error may not be fullfilled !"
else message <- NULL
var.thresh <- FALSE
return(list(fitted.values = estim, std.err = std.err, var.cov = var.cov,
param = param, message = message, threshold = threshold,
corr = corr, convergence = convergence, counts = counts,
nat = nat, pat = pat, exceed = exceed,
scale=scale, var.thresh = var.thresh, est = est))
} |
"stationary.taper.cov" <- function(x1, x2=NULL, Covariance = "Exponential",
Taper = "Wendland", Dist.args = NULL, Taper.args = NULL,
aRange = 1, V = NULL, C = NA, marginal = FALSE, spam.format = TRUE,
verbose = FALSE, theta=NULL, ...) {
if( !is.null( theta)){
aRange<- theta
}
Cov.args <- list(...)
if (is.data.frame(x1))
x1 <- as.matrix(x1)
if (!is.matrix(x1))
x1 <- matrix(c(x1), ncol = 1)
if (is.null(x2))
x2 <- x1
if (is.data.frame(x2))
x2 <- as.matrix(x1)
if (!is.matrix(x2))
x2 <- matrix(c(x2), ncol = 1)
d <- ncol(x1)
n1 <- nrow(x1)
n2 <- nrow(x2)
if (Taper == "Wendland") {
if (is.null(Taper.args)) {
Taper.args <- list(aRange = 1, k = 2, dimension = ncol(x1))
}
if (is.null(Taper.args$dimension)) {
Taper.args$dimension <- ncol(x1)
}
}
if (is.null(Taper.args)) {
Taper.args <- list(aRange = 1)
}
great.circle <- ifelse(is.null(Dist.args$method), FALSE,
Dist.args$method == "greatcircle")
if (length(aRange) > 1) {
stop("aRange as a matrix has been depreciated, use the V argument")
}
if (!is.null(V)) {
if (aRange != 1) {
stop("can't specify both aRange and V!")
}
if (great.circle) {
stop("Can not mix great circle distance\nwith general scaling (V argument or vecotr of aRange's)")
}
x1 <- x1 %*% t(solve(V))
x2 <- x2 %*% t(solve(V))
}
if (great.circle) {
miles <- ifelse(is.null(Dist.args$miles), TRUE, Dist.args$miles)
delta <- (180/pi) * Taper.args$aRange/ifelse(miles, 3963.34,
6378.388)
}
else {
delta <- Taper.args$aRange
}
if (length(delta) > 1) {
stop("taper range must be a scalar")
}
if (!marginal) {
sM <- do.call("nearest.dist", c(list(x1, x2, delta = delta,
upper = NULL), Dist.args))
sM@entries <- do.call(Covariance, c(list(d = sM@entries/aRange),
Cov.args)) * do.call(Taper, c(list(d = sM@entries),
Taper.args))
if (verbose) {
print(sM@entries/aRange)
print(do.call(Covariance, c(list(d = sM@entries/aRange),
Cov.args)))
print(do.call(Taper, c(list(d = sM@entries), Taper.args)))
}
if (is.na(C[1])) {
if (spam.format) {
return(sM)
}
else {
return(as.matrix(sM))
}
}
else {
return(sM %*% C)
}
}
else {
tau2 <- do.call(Covariance, c(list(d = 0), Cov.args)) *
do.call(Taper, c(list(d = 0), Taper.args))
return(rep(tau2, nrow(x1)))
}
} |
check.lik.proc.data.coefs = function(lik=NULL,proc=NULL,data=NULL,times=NULL,coefs=NULL)
{
if(!is.null(data)){
if(!is.null(times)){
if( length(times)!= dim(data)[1]){
stop('Vector of observation times does not matich dimension of data')
}
}
else{ times = 1:dim(data[1]) }
}
if(!is.null(lik) & !is.null(times)){
if(dim(lik$bvals)[1] != length(times)){
stop('Size of lik$bvals does not match number of observations')
}
if(ncol(lik$bvals) != nrow(coefs) ){
stop('Number of basis functions does not match number of coefficients.')
}
}
if(!is.null(proc)){
if(is.list(proc$bvals)){
if( !all( dim(proc$bvals$bvals) == dim(proc$vals$dbvals)) ){
stop('proc bvals and dbvals dimensions do not match.')
}
if( !is.null(proc$more$qpts) ){
if( nrow(proc$bvals$bvals) != length(proc$more$qpts)){
stop('proc bvals object dimensions do not correspond to number of quadrature points')
}
}
} else{
if( nrow(proc$bvals) != length(proc$more$qpts)+1){
stop('proc bvals object dimensions do not correspond to number of quadrature points')
}
}
if(!is.null(coefs)){
if(is.list(proc$bvals)){
if( ncol(proc$bvals$bvals) != nrow(coefs) ){
stop('Number of basis functions does not match number of coefficients.')
}
} else{
if( ncol(proc$bvals) != nrow(coefs) ){
stop('Number of basis functions does not match number of coefficients.')
}
}
if(!is.null(proc$more$names)){
if( length(proc$more$names) != ncol(coefs) ){
stop('dimension of coefficients does not match length of state variable names')
}
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.