code
stringlengths 1
13.8M
|
---|
context("Test if values in examples in functions stay the same")
library("TOSTER")
test_that("Test that one-sample t-test output is same as previous version", {
res <- TOSTone(m=0.54,mu=0.5,sd=1.2,n=100,low_eqbound_d=-0.3, high_eqbound_d=0.3, alpha=0.05, plot = FALSE)
expect_equal(res$diff, 0.04, tolerance = .0001)
expect_equal(res$TOST_t1, 3.333333, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0006040021, tolerance = .0001)
expect_equal(res$TOST_t2, -2.666667, tolerance = .0001)
expect_equal(res$TOST_p2, 0.004474619, tolerance = .0001)
expect_equal(res$TOST_df, 99, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.36, tolerance = .0001)
expect_equal(res$high_eqbound, 0.36, tolerance = .0001)
expect_equal(res$low_eqbound_d, -0.3, tolerance = .0001)
expect_equal(res$high_eqbound_d, 0.3, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1592469, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2392469, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.198106, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.278106, tolerance = .0001)
})
test_that("Test that raw one-sample t-test output is same as previous version", {
res <- TOSTone.raw(m=0.52,mu=0.5,sd=0.5,n=300,low_eqbound=-0.1, high_eqbound=0.1, alpha=0.05, plot = FALSE)
expect_equal(res$diff, 0.02, tolerance = .0001)
expect_equal(res$TOST_t1, 4.156922, tolerance = .0001)
expect_equal(res$TOST_p1, 0.00002108451, tolerance = .0001)
expect_equal(res$TOST_t2, -2.771281, tolerance = .0001)
expect_equal(res$TOST_p2, 0.002966762, tolerance = .0001)
expect_equal(res$TOST_df, 299, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.1, tolerance = .0001)
expect_equal(res$high_eqbound, 0.1, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.02763041, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.06763041, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.03680924, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.07680924, tolerance = .0001)
})
test_that("Test that two-sample t-test output is same as previous version", {
res <- TOSTtwo(m1=5.25,m2=5.22,sd1=0.95,sd2=0.83,n1=95,n2=89,low_eqbound_d=-0.43,high_eqbound_d=0.43, plot = FALSE)
expect_equal(res$diff, 0.03, tolerance = .0001)
expect_equal(res$TOST_t1, 3.14973, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0009560083, tolerance = .0001)
expect_equal(res$TOST_t2, -2.692771, tolerance = .0001)
expect_equal(res$TOST_p2, 0.003875522, tolerance = .0001)
expect_equal(res$TOST_df, 181.1344, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.3835687, tolerance = .0001)
expect_equal(res$high_eqbound, 0.3835687, tolerance = .0001)
expect_equal(res$low_eqbound_d, -0.43, tolerance = .0001)
expect_equal(res$high_eqbound_d, 0.43, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1870843, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2470843, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.2290799, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.2890799, tolerance = .0001)
})
test_that("Test that raw two-sample t-test output is same as previous version", {
res <- TOSTtwo.raw(m1=5.25,m2=5.22,sd1=0.95,sd2=0.83,n1=95,n2=89,low_eqbound=-0.384,high_eqbound=0.384, plot = FALSE)
expect_equal(res$diff, 0.03, tolerance = .0001)
expect_equal(res$TOST_t1, 3.153015, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0009458745, tolerance = .0001)
expect_equal(res$TOST_t2, -2.696056, tolerance = .0001)
expect_equal(res$TOST_p2, 0.003838994, tolerance = .0001)
expect_equal(res$TOST_df, 181.1344, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.384, tolerance = .0001)
expect_equal(res$high_eqbound, 0.384, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1870843, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2470843, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.2290799, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.2890799, tolerance = .0001)
})
test_that("Test that paired two-sample t-test output is same as previous version", {
res <- TOSTpaired(n=65,m1=5.83,m2=5.75,sd1=1.17,sd2=1.29,r12=0.75,low_eqbound_dz=-0.4,high_eqbound_dz=0.4, plot = FALSE)
expect_equal(res$diff, 0.08, tolerance = .0001)
expect_equal(res$TOST_t1, 3.960381, tolerance = .0001)
expect_equal(res$TOST_p1, 0.00009531728, tolerance = .0001)
expect_equal(res$TOST_t2, -2.489426, tolerance = .0001)
expect_equal(res$TOST_p2, 0.00770235, tolerance = .0001)
expect_equal(res$TOST_df, 64, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.350782, tolerance = .0001)
expect_equal(res$high_eqbound, 0.350782, tolerance = .0001)
expect_equal(res$low_eqbound_dz, -0.4, tolerance = .0001)
expect_equal(res$high_eqbound_dz, 0.4, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1015433, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2615433, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.1372988, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.2972988, tolerance = .0001)
})
test_that("Test that raw paired two-sample t-test output is same as previous version", {
res <- TOSTpaired.raw(n=65,m1=5.83,m2=5.75,sd1=1.17,sd2=1.30,r12=0.745,low_eqbound=-0.34,high_eqbound=0.34, plot = FALSE)
expect_equal(res$diff, 0.08, tolerance = .0001)
expect_equal(res$TOST_t1, 3.803437, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0001606103, tolerance = .0001)
expect_equal(res$TOST_t2, -2.354508, tolerance = .0001)
expect_equal(res$TOST_p2, 0.01081349, tolerance = .0001)
expect_equal(res$TOST_df, 64, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.34, tolerance = .0001)
expect_equal(res$high_eqbound, 0.34, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1043032, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2643032, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.1406022, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.3006022, tolerance = .0001)
})
test_that("Test that correlation test output is same as previous version", {
res <- TOSTr(n=100, r = 0.02, low_eqbound_r=-0.3, high_eqbound_r=0.3, alpha=0.05, plot = FALSE)
expect_equal(res$r, 0.02, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0005863917, tolerance = .0001)
expect_equal(res$TOST_p2, 0.002176282, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound_r, -0.3, tolerance = .0001)
expect_equal(res$high_eqbound_r, 0.3, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.145957, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.1848622, tolerance = .0001)
expect_equal(res$LL_CI_TTEST, -0.1771139, tolerance = .0001)
expect_equal(res$UL_CI_TTEST, 0.2155713, tolerance = .0001)
})
test_that("Test that meta test output is same as previous version", {
res <- TOSTmeta(ES=0.12, se=0.09, low_eqbound_d=-0.2, high_eqbound_d=0.2, alpha=0.05, plot = FALSE)
expect_equal(res$ES, 0.12, tolerance = .0001)
expect_equal(res$TOST_Z1, 3.555556, tolerance = .0001)
expect_equal(res$TOST_p1, 0.0001885906, tolerance = .0001)
expect_equal(res$TOST_Z2, -0.8888889, tolerance = .0001)
expect_equal(res$TOST_p2, 0.1870314, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound_d, -0.2, tolerance = .0001)
expect_equal(res$high_eqbound_d, 0.2, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.02803683, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.2680368, tolerance = .0001)
expect_equal(res$LL_CI_ZTEST, -0.05639676, tolerance = .0001)
expect_equal(res$UL_CI_ZTEST, 0.2963968, tolerance = .0001)
})
test_that("Test that two proportions test output is same as previous version", {
res <- TOSTtwo.prop(prop1 = .65, prop2 = .70, n1 = 100, n2 = 100, low_eqbound = -0.1, high_eqbound = 0.1, alpha = .05, plot = FALSE)
expect_equal(res$dif, -0.05, tolerance = .0001)
expect_equal(res$TOST_z1, 0.7559289, tolerance = .0001)
expect_equal(res$TOST_p1, 0.2248459, tolerance = .0001)
expect_equal(res$TOST_z2, -2.267787, tolerance = .0001)
expect_equal(res$TOST_p2, 0.0116711, tolerance = .0001)
expect_equal(res$alpha, 0.05, tolerance = .0001)
expect_equal(res$low_eqbound, -0.1, tolerance = .0001)
expect_equal(res$high_eqbound, 0.1, tolerance = .0001)
expect_equal(res$LL_CI_TOST, -0.1587968, tolerance = .0001)
expect_equal(res$UL_CI_TOST, 0.05879684, tolerance = .0001)
expect_equal(res$LL_CI_ZTEST, -0.1796394, tolerance = .0001)
expect_equal(res$UL_CI_ZTEST, 0.07963943, tolerance = .0001)
expect_equal(res$NHST_z, -0.7559289, tolerance = .0001)
expect_equal(res$NHST_p, 0.4496918, tolerance = .0001)
}) |
scatterdens <- function(x, y, dens.frac = 1/5, ...) {
zones <- matrix(c(2,0,1,3), ncol = 2, byrow = TRUE)
layout(zones, widths = c(1 - dens.frac, dens.frac), heights = c(dens.frac, 1 - dens.frac))
x.dens <- density(x)
y.dens <- density(y)
top <- max(x.dens$y, y.dens$y)
op <- par(mar = c(3, 3, 1, 1))
plot(x, y, main = "", ...)
par(mar = c(0, 3, 1, 1))
plot(x.dens, axes = FALSE, ylim = c(0, top), main = "")
par(mar = c(3, 0, 1, 1))
plot(y.dens$y, y.dens$x, type = "l", axes = FALSE, xlim = c(0, top))
par(op)
}
scatterhist <- function(x, y, xlab = "", ylab = "", dens.frac = 1/5, ...) {
zones <- matrix(c(2,0,1,3), ncol = 2, byrow = TRUE)
layout(zones, widths = c(1 - dens.frac, dens.frac), heights = c(dens.frac, 1 - dens.frac))
xhist <- hist(x, plot = FALSE)
yhist <- hist(y, plot = FALSE)
top <- max(c(xhist$counts, yhist$counts))
op <- par(mar = c(3, 3, 1, 1))
plot(x, y, main = "", ...)
par(mar = c(0, 3, 1, 1))
barplot(xhist$counts, axes = FALSE, ylim = c(0, top), space = 0)
par(mar = c(3, 0, 1, 1))
barplot(yhist$counts, axes = FALSE, xlim = c(0, top), space = 0, horiz = TRUE)
par(op)
} |
BestSlope = function(x, y, adm="Extravascular", TOL=1e-4)
{
Result = c(R2 = NA,
R2ADJ = NA,
LAMZNPT = 0,
LAMZ = NA,
b0 = NA,
CORRXY = NA,
LAMZLL = NA,
LAMZUL = NA,
CLSTP = NA)
n = length(x)
if (n != length(y) | !is.numeric(x) | !is.numeric(y) | length(y[y < 0]) > 0) {
Result["LAMZNPT"] = 0
return(Result)
}
if (length(unique(y)) == 1) {
Result["LAMZNPT"] = 0
Result["b0"] = unique(y)
return(Result)
}
if (UT(adm) == "BOLUS") {
locStart = which.max(y)
} else {
locStart = which.max(y) + 1
}
locLast = max(which(y > 0))
if (locLast - locStart < 2) {
Result["LAMZNPT"] = 0
return(Result)
}
tmpMat = matrix(nrow=(locLast - locStart - 1), ncol=length(Result))
colnames(tmpMat) = names(Result)
for (i in locStart:(locLast - 2)) {
tmpMat[i - locStart + 1,] = Slope(x[i:locLast], log(y[i:locLast]))
}
tmpMat = tmpMat[tmpMat[,"LAMZNPT"] > 2,,drop=FALSE]
if (is.matrix(tmpMat) & nrow(tmpMat) > 0) {
maxAdjRsq = max(tmpMat[,"R2ADJ"])
OKs = ifelse(abs(maxAdjRsq - tmpMat[,"R2ADJ"]) < TOL, TRUE, FALSE)
nMax = max(tmpMat[OKs,"LAMZNPT"])
Result = tmpMat[OKs & tmpMat[,"LAMZNPT"]==nMax,]
} else {
Result["LAMZNPT"] = 0
}
return(Result)
} |
RS.estimates = function(x,thin = 100, burns, CI = c(0.05,0.95), corrmat = FALSE, acf.plot =TRUE , palette = 'mono')
{
if(class(x)=='RS.impute')
{
if(missing(burns)){burns =min(round(dim(x$par.matrix)[1]/2),25000)}
windw = seq(burns,dim(x$par.matrix)[1],thin)
est = apply(x$par.matrix[windw,], 2, mean)
CI=t(apply(x$par.matrix[windw,], 2, quantile,probs = CI))
form = function(x,mm = 2){format(round(x, mm), nsmall = mm)}
dat=(cbind(form(cbind(est,CI),3)))
dat = matrix(as.numeric(as.matrix(dat)),dim(dat)[1])
rownames(dat)=paste0('theta[',1:dim(x$par.matrix)[2],']')
colnames(dat) = c('Estimate','Lower_CI','Upper_CI')
dat2=(form(cor(x$par.matrix[windw,])))
dat2 = matrix(as.numeric(as.matrix(dat2)),dim(dat2)[1])
rownames(dat2)=paste0('theta[',1:dim(x$par.matrix)[2],']')
colnames(dat2)=paste0('theta[',1:dim(x$par.matrix)[2],']')
if(acf.plot)
{
nper=dim(x$par.matrix)[2]
if(nper==1){par(mfrow=c(1,2))}
if(nper==2){par(mfrow=c(2,2))}
if(nper==3){par(mfrow=c(2,2))}
if(nper>3)
{
d1=1:((nper)+1)
d2=d1
O=outer(d1,d2)
test=O-((nper)+1)
test[test<0]=100
test=test[1:4,1:4]
test
wh=which(test==min(test))
d1=d1[col(test)[wh[1]]]
d2=d2[row(test)[wh[1]]]
par(mfrow=c(d1,d2))
}
if(palette=='mono')
{
cols =rep('
}else{
cols=rainbow_hcl(nper, start = 10, end = 275,c=100,l=70)
}
for(i in 1:dim(x$par.matrix)[2])
{
acf(x$par.matrix[windw,i],main=paste0('ACF: theta[',i,']\nThin=',thin,', Burns=',burns,', N=',length(windw)),col = cols[i],lwd=2)
}
}
if(corrmat){return(list(estimates = dat, corrmat = dat2))}
return(dat)
}
} |
mod_acercade_ui <- function(id){
ns <- NS(id)
tagList(
img(src = "img/Logo.png",
style = paste0("padding-bottom:20px;margin-left: auto;",
"margin-right: auto;display: block;width: 50%;")),
infoBoxPROMiDAT(
labelInput("copyright"), "PROMiDAT S.A.", icono = icon("copyright")
),
infoBoxPROMiDAT(
labelInput("info"), tags$a(
href = "https://www.promidat.com/", style = "color:white;",
target = "_blank", "https://www.promidat.com"), icono = icon("info")
),
infoBoxPROMiDAT(
labelInput("version"), "2.0.5", icono = icon("file-code"))
)
}
mod_acercade_server <- function(input, output, session){
ns <- session$ns
}
|
plot_specs <- function(df = NULL,
plot_a = NULL,
plot_b = NULL,
choices = c("x", "y", "model", "controls", "subsets"),
labels = c("A", "B"),
rel_heights = c(2, 3),
desc = FALSE,
null = 0,
ci = TRUE,
ribbon = FALSE,
sample_perc = 1,
...) {
if (!is.null(df)) {
if (sample_perc > 1 | sample_perc < 0) {
stop("`sample_n` must be greater than 0 and less than 1!")
}
df <- dplyr::sample_n(df, size = sample_perc*nrow(df))
plot_a <- plot_curve(df, ci = ci, ribbon = ribbon, desc = desc, null = null)
plot_b <- plot_choices(df, choices = choices, desc = desc, null = null)
}
cowplot::plot_grid(plot_a,
plot_b,
labels = labels,
align = "v",
axis = "rbl",
rel_heights = rel_heights,
ncol = 1,
...)
} |
f7Messages <- function(id, title = NULL, autoLayout = TRUE, newMessagesFirst = FALSE,
scrollMessages = TRUE, scrollMessagesOnEdge = TRUE) {
config <- dropNulls(
list(
autoLayout = autoLayout,
newMessagesFirst = newMessagesFirst,
scrollMessages = scrollMessages,
scrollMessagesOnEdge = scrollMessagesOnEdge
)
)
shiny::tags$div(
id = id,
shiny::tags$script(
type = "application/json",
`data-for` = id,
jsonlite::toJSON(
x = config,
auto_unbox = TRUE,
json_verbatim = TRUE
)
),
class = "messages",
if (!is.null(title)) {
shiny::tags$div(class = "messages-title", title)
}
)
}
f7MessageBar <- function(inputId, placeholder = "Message") {
ns <- shiny::NS(inputId)
shiny::tags$div(
id = inputId,
class = "toolbar messagebar",
shiny::tags$div(
class = "toolbar-inner",
shiny::tags$div(
class = "messagebar-area",
shiny::tags$textarea(
class = "resizable",
placeholder = placeholder
)
),
shiny::tags$a(
id = ns("send"),
href = "
class = "link icon-only demo-send-message-link f7-action-button",
f7Icon("arrow_up_circle_fill")
)
)
)
}
updateF7MessageBar <- function(inputId, value = NULL, placeholder = NULL,
session = shiny::getDefaultReactiveDomain()) {
message <- dropNulls(
list(
value = value,
placeholder = placeholder
)
)
session$sendInputMessage(inputId, message)
}
f7Message <- function(text, name, type = c("sent", "received"),
header = NULL, footer = NULL, avatar = NULL,
textHeader = NULL, textFooter = NULL, image = NULL,
imageSrc = NULL, cssClass = NULL) {
type <- match.arg(type)
dropNulls(
list(
text = text,
header = header,
footer = footer,
name = name,
avatar = avatar,
type = type,
textHeader = textHeader,
textFooter = textFooter,
image = image,
imageSrc = imageSrc
)
)
}
updateF7Messages <- function(id, messages, showTyping = FALSE,
session = shiny::getDefaultReactiveDomain()) {
message <- list(
value = jsonlite::toJSON(
messages,
auto_unbox = TRUE,
pretty = TRUE,
json_verbatim = TRUE
),
showTyping = showTyping
)
session$sendInputMessage(id, message)
}
f7AddMessages <- function(id, messages, showTyping = FALSE,
session = shiny::getDefaultReactiveDomain()) {
.Deprecated(
"updateF7Messages",
package = "shinyMobile",
"f7AddMessages will be removed in future release. Please use
updateF7Messages instead.",
old = as.character(sys.call(sys.parent()))[1L]
)
updateF7Messages(id, messages, showTyping, session)
} |
interpTs <-
function(x, type = c("linear", "series.median", "series.mean", "cycle.median",
"cycle.mean"), gap = NULL) {
gap.max <- nrow(as.matrix(x)) - 2
if (is.null(gap))
gap <- gap.max
if (is.na(as.numeric(gap)) || gap < 1 || gap > gap.max)
stop("gap must be a number between 1 and the length - 2")
type <- match.arg(type)
if (!is.ts(x) && type %in% c("cycle.median", "cycle.mean"))
stop("x must be a time series for these types")
tspx <- tsp(x)
replaceNA <- function (x, stat) {
x <- ts(x, start = tspx[1], frequency = tspx[3])
x1 <- window(x, start = start(x)[1], end = c(end(x)[1], 12), extend = TRUE)
x2 <- matrix(x1, byrow = TRUE, ncol = 12)
stats <- apply(x2, 2, stat, na.rm = TRUE)
indx <- (seq_len(length(x1)))[is.na(x1)]
x3 <- replace(x1, indx, stats[cycle(x1)[indx]])
window(x3, start = tspx[1], end = tspx[2])
}
f1 <- function(x, gap, type) {
if (sum(!is.na(x)) < 2) {
x1 <- x
} else {
x1 <- switch(type,
linear = na.approx(x, na.rm = FALSE),
series.median = ifelse(is.na(x), median(x, na.rm = TRUE), x),
series.mean = ifelse(is.na(x), mean(x, na.rm = TRUE), x),
cycle.median = replaceNA(x, median),
cycle.mean = replaceNA(x, mean)
)
for (i in seq_len(length(x) - gap)) {
seq1 <- i:(i + gap)
if (all(is.na(x[seq1])))
x1[seq1] <- x[seq1]
}
}
x1
}
if (is.matrix(x)) {
ans <- apply(x, 2, f1, gap, type)
} else {
ans <- f1(x, gap, type)
}
if (is.ts(x)) {
ans <- ts(ans, start = start(x), frequency = frequency(x))
}
ans
} |
deconvolute_and_contextualize <- function(count_file,signature_matrix, DEG_list, case_grep, control_grep, max_proportion_change = -9, print_plots=T, plot_names="scMappR",theSpecies = "human", FC_coef = T, sig_matrix_size = 3000, drop_unknown_celltype = TRUE, toSave = FALSE, path = NULL, deconMethod = "DeconRNASeq") {
count_class <- class(count_file)[1] %in% c("character", "data.frame", "matrix")
if((count_class[1] == FALSE )[1]) {
stop("count_file must be of class character, data.frame, or matrix.")
}
signature_class <- class(signature_matrix)[1] %in% c("character", "data.frame", "matrix")
if((signature_class[1] == FALSE)[1]) {
stop("count_file must be of class character, data.frame, or matrix.")
}
DEG_list_class <- class(DEG_list)[1] %in% c("character", "data.frame", "matrix")
if((DEG_list_class[1] == FALSE)[1]) {
stop("DEG_list must be of class character, data.frame, or matrix.")
}
case_grep_class <- class(case_grep)[1] %in% c("character", "numeric", "integer")
if((case_grep_class[1] == FALSE)[1]) {
stop("case_grep must be of class character (as a single character designating cases in column names) or of class numeric (integer matrix giving indeces of cases).")
}
control_grep_class <- class(control_grep)[1] %in% c("character", "numeric", "integer")
if((control_grep_class == FALSE)[1]) {
stop("control_grep must be of class character (as a single character designating controls in column names) or of class numeric (integer matrix giving indeces of controls).")
}
if((all(is.numeric(max_proportion_change), is.numeric(sig_matrix_size))[1] == FALSE)[1]) {
stop(" max_proportion_change, and sig_matrix_size must all be of class numeric" )
}
if((all(is.logical(print_plots), is.logical(FC_coef), is.logical(drop_unknown_celltype), is.logical(toSave))[1] == FALSE)[1]) {
stop("print_plots, FC_coef, drop_unknown_celltype, toSave must all be of class logical." )
}
if(is.character(plot_names)[1] == FALSE) {
stop("plot_names must be of class character.")
}
if((!(theSpecies %in% c("human", "mouse")))[1]) {
if((theSpecies != -9)) {
warning("species_name is not 'human' 'mouse' or '-9' (case sensitive). If you are also completing pathway enrichment, please use a species name compatible with the gProfileR and gprofiler2 packages.")
}
}
if(toSave == TRUE) {
if(is.null(path)) {
stop("scMappR is given write permission by setting toSave = TRUE but no directory has been selected (path = NULL). Pick a directory or set path to './' for current working directory")
}
if(!dir.exists(path)) {
stop("The selected directory does not seem to exist, please check set path.")
}
}
rowVars <- function(x) return(apply(x, 1, stats::var))
colMedians <- function(x) return(apply(x, 2, stats::median))
colVars <- function(x) return(apply(x, 2 , stats::var))
if(is.character(count_file)) {
warning("reading count file table, assuming first column is the gene symbols -- not reccomended.")
norm_counts_i <- utils::read.table(count_file, header = T, as.is = T, sep = "\t")
rownames(norm_counts_i) <- norm_counts_i[,1]
norm_counts_i <- norm_counts_i[,-1]
} else {
norm_counts_i <- count_file
}
if(is.character(signature_matrix)) {
warning("loading in signature matrix from Rdata file -- not reccomeneded.")
load(signature_matrix)
} else {
wilcoxon_rank_mat_or <- signature_matrix
}
if(is.character(DEG_list)) {
DEGs <- utils::read.table(DEG_list, header = FALSE, as.is = T, sep = "\t")
} else {
DEGs <- as.data.frame(DEG_list)
}
colnames(DEGs) <- c("gene_name", "padj", "log2fc")
sm <- wilcoxon_rank_mat_or
if(theSpecies == -9) {
gsym <- get_gene_symbol(sm)
RN_2 <- gsym$rowname
theSpecies <- gsym$species
} else {
RN_2 <- rownames(sm)
}
toInter <- intersect(RN_2, rownames(norm_counts_i))
if(length(toInter)==0) {
message("Rownames of signature matrix")
message(utils::head(RN_2))
message("Rownames of count matrix")
message(utils::head(norm_counts_i))
stop("There is no overlap between the signature and count matrix. Please make sure that gene symbols are row names and they are gene symbols of te same species.")
}
rownames(wilcoxon_rank_mat_or) <- RN_2
unknown <- grep("unknown",colnames(wilcoxon_rank_mat_or))
if((length(unknown) > 0 & drop_unknown_celltype == TRUE)[1]) {
message("Removing unknown cell-types")
wilcox_or <- wilcoxon_rank_mat_or[,-unknown]
} else {
wilcox_or <- wilcoxon_rank_mat_or
}
wilcox_var <- wilcox_or
wilcox_or <- as.data.frame(wilcox_or)
wilcox_or[wilcox_or < 0 ] <- 0
if((nrow(wilcox_or) > sig_matrix_size)[1]) {
message(paste0("For deconvolution, we're using the top ", sig_matrix_size," most vairable signatures"))
RVar <- rowVars(wilcox_var)
wilcox_or_var <- wilcox_or[order(RVar, decreasing = T), ]
wilcox_or_signature <- wilcox_or_var[1:sig_matrix_size,]
} else {
wilcox_or_signature <- wilcox_or
}
if((length(unique(colnames(wilcox_or_signature))) < length(colnames(wilcox_or_signature)))[1]) {
warning("cell-type naming is not unique, appending unique identifier (1:ncol(signature))")
colnames(wilcox_or_signature) <- paste0(colnames(wilcox_or_signature), "_", 1:ncol(wilcox_or_signature))
}
if(is.matrix(norm_counts_i)) norm_counts_i <- as.data.frame(norm_counts_i)
cVar_wilcox <- colVars(wilcox_or_signature)
wilcox_or_signature <- wilcox_or_signature[,cVar_wilcox > 0]
if(deconMethod == "DCQ") {
all_genes_in <- t(ADAPTS::estCellPercent(wilcox_or_signature,norm_counts_i, method = "DCQ") / 100)
all_genes_in <- all_genes_in[,colnames(all_genes_in) != "others"]
}
if(deconMethod == "DeconRNASeq") {
all_genes_in <- DeconRNAseq_CRAN(as.data.frame(norm_counts_i),as.data.frame(wilcox_or_signature))$out.all
}
if(deconMethod == "WGCNA") {
all_genes_in <- t(ADAPTS::estCellPercent(wilcox_or_signature,norm_counts_i, method = "proportionsInAdmixture") / 100)
all_genes_in <- all_genes_in[,colnames(all_genes_in) != "others"]
}
proportions <- all_genes_in
rownames(proportions) <- colnames(norm_counts_i)
propmeans <- colMeans(proportions)
proportions <- proportions[,colMeans(proportions) > 0.001]
message("your bulk data contains the following cell types")
message(paste(colnames(proportions), " "))
wilcox_or <- wilcox_or[,colnames(proportions)]
wilcox_or_df <- as.data.frame(wilcox_or)
wilcox_or_signature <- as.data.frame(wilcox_or_signature[,colnames(proportions)])
bulk_in <- norm_counts_i
DEGs <- DEGs[stats::complete.cases(DEGs),]
genesIn <- DEGs$gene_name[DEGs$gene_name %in% rownames(bulk_in)]
message(length(genesIn))
if(length(genesIn) == 0) {
stop("None of your DEGs overlap with genes in your count matrix")
}
if(!is.data.frame(bulk_in)) bulk_in <- as.data.frame(bulk_in)
if(!is.data.frame(wilcox_or)) wilcox_or <- as.data.frame(wilcox_or)
max_bulk <- max(bulk_in)
if(max_bulk < 50) {
warning("You most highly expressed gene is < 50 suggesting your counts are log2 normalized. Removing log2 transformation")
message("You most highly expressed gene is < 50 suggesting your counts are log2 normalized. Removing log2 transformation. We suggest you input non-log transformed count data.")
bulk_in <- 2^bulk_in
}
deconvolute_gene_removed <- function(x, bulk = bulk_in, signature = wilcox_or_signature) {
if(x %in% rownames(bulk)) {
bulk_rem <- bulk[-which(rownames(bulk) == x),]
} else {
warning(paste0(x, " is not in your bulk matrix, remove gene and rerun or check gene symbol matching in general."))
bulk_rem <- bulk
}
if(x %in% rownames(signature)) {
signature_rem <- signature[-which(rownames(signature) == x),]
signature_var <- apply(signature_rem, 2, stats::var)
if(any(signature_var == 0)[1]) {
signature_rem <- signature
bulk_rem <- bulk
}
} else {
signature_rem <- signature
}
if(deconMethod == "DCQ") {
proportions <- t(ADAPTS::estCellPercent(signature_rem,bulk_rem, method = "DCQ") / 100)
proportions <- proportions[,colnames(proportions) != "others"]
}
if(deconMethod == "DeconRNASeq") {
proportions <- DeconRNAseq_CRAN(bulk_rem,signature_rem)$out.all
}
if(deconMethod == "WGCNA") {
proportions <- t(ADAPTS::estCellPercent(signature_rem,bulk_rem, method = "proportionsInAdmixture") / 100)
proportions <- proportions[,colnames(proportions) != "others"]
}
return(proportions)
}
iterated <- pbapply::pblapply(genesIn, deconvolute_gene_removed)
names(iterated) <- genesIn
proportion_pull <- function(tester) {
rownames(tester) <- colnames(bulk_in)
cases <- grep(case_grep, rownames(tester))
control <- grep(control_grep, rownames(tester))
if((any(length(cases) < 2, length(control) < 2))[1]) {
stop("There is fewer than two cases or controls, please check 'case_grep' or 'control_grep'.")
}
cases_Med <- colMedians(tester[cases,])
control_Med <- colMedians(tester[control,])
M <- min(c(min(cases_Med[cases_Med != 0]), min(control_Med[control_Med != 0])))
cases_Med[cases_Med == 0] <- M
control_Med[control_Med == 0] <- M
FC <- cases_Med/control_Med
Mean_CC <- (cases_Med + control_Med) / 2
l <- list(cases = cases_Med, control = control_Med, FC = FC, Mean = Mean_CC)
return(l)
}
message("Leave one out cell proporitons: ")
iterated_pull <- pbapply::pblapply(iterated, proportion_pull)
pull_means <- function(x) return(x$Mean)
pull_fc <- function(x) return(x$FC)
means <- do.call("rbind",lapply(iterated_pull, pull_means))
fold_changes <- do.call("rbind",lapply(iterated_pull, pull_fc))
if( max_proportion_change != -9) {
message("converting maximum CT proportion change to have a maximum odds-ratio of")
message(max_proportion_change)
fold_changes[fold_changes > max_proportion_change] <- max_proportion_change
fold_changes[fold_changes < (1/max_proportion_change)] <- (1/max_proportion_change)
}
cmeaned <- lapply(iterated, colMeans)
cmeaned_stacked <- do.call("rbind", cmeaned)
n <- colnames(cmeaned_stacked)
message("Done")
cmeaned_no0 <- as.data.frame(cmeaned_stacked[,colSums(cmeaned_stacked) > 0 ])
if((length(colnames(cmeaned_stacked)) != length(unique(colnames(cmeaned_stacked))))[1]) {
message("adding code for non-unique cell-types")
colnames(fold_changes) <- colnames(wilcox_or) <- colnames(means) <- colnames(cmeaned_stacked) <- paste0(n,"_",1:ncol(cmeaned_stacked))
} else {
colnames(fold_changes) <- colnames(wilcox_or) <- colnames(means) <- colnames(cmeaned_stacked) <- n
}
scaled_odds_ratio <- wilcox_or
dup_gene_names <- which(duplicated(DEGs$gene_name))
if((length(dup_gene_names) > 0)[1]) {
dup_gene_names <- DEGs$gene_name[dup_gene_names]
warning("Duplicated gene names:")
message(paste(dup_gene_names, " "))
warning("Some gene names are duplicated -- keeping the first duplicate in the list. Check if there should be duplicate gene symbols in your dataset.")
}
DEGs <- DEGs[!duplicated(DEGs$gene_name),]
rownames(DEGs) <- DEGs$gene_name
intered <- genesIn
toInter_InGene<- DEGs[intered,]
fc_co <- FC_coef
values_with_preferences <- function(gene, FC_coef = fc_co) {
if(gene %in% rownames(scaled_odds_ratio)) {
scaled_pref <- scaled_odds_ratio[gene,]
} else {
scaled_pref <- rep(1, ncol(scaled_odds_ratio))
}
gene_DE <- DEGs[gene,]
prop <- means[gene,]
prop_fc <- fold_changes[gene, ]
up <- gene_DE$log2fc > 0
sign <- -1
if((up == T)[1]) {
prop_fc <- 1/prop_fc
sign <- 1
}
if(FC_coef == TRUE) {
val <- scaled_pref * prop * prop_fc * sign*2^abs(gene_DE$log2fc)
} else {
warning("using P-FDR instead of fold-change -- Not reccomended")
val <- scaled_pref * prop * prop_fc * sign*-1*log10(gene_DE$padj)
}
return(val)
}
message("Adjusting Coefficients:")
vals_out <- pbapply::pblapply(toInter_InGene$gene_name, values_with_preferences)
message("Done")
vals_out_mat <- do.call("rbind", vals_out)
rownames(vals_out_mat) <- toInter_InGene$gene_name
colnames(vals_out_mat) <- colnames(wilcox_or)
all_reordered <- vals_out_mat
comp <- plot_names
printing <- print_plots == TRUE & toSave == TRUE
if(printing[1] == TRUE) {
boxplot_values <- function(cmeaned_stacked, names) {
all_stack <- c()
for(i in 1:ncol(cmeaned_stacked)) {
cm_stack <- cmeaned_stacked[,i]
top3 <- head(sort(cm_stack), 3)
bottom3 <- utils::tail(sort(cm_stack), 3)
empty <- rep("", length(cm_stack))
names(empty) <- names(cm_stack)
empty[names(top3)] <- names(top3)
empty[names(bottom3)] <- names(bottom3)
y <- cbind(names(cm_stack), unname(cm_stack), colnames(cmeaned_stacked)[i], unname(empty))
all_stack <- rbind(all_stack, y)
}
all_stack <- as.data.frame(all_stack)
colnames(all_stack) <- c("gene", "proportion", "cell_type", "label")
all_stack$gene <- tochr(all_stack$gene)
all_stack$proportion <- toNum(all_stack$proportion)
all_stack$cell_type <- tochr(all_stack$cell_type)
all_stack$label <- tochr(all_stack$label)
cell_type <- all_stack$cell_type
proportion<- all_stack$proportion
label <- all_stack$label
grDevices::pdf(paste0(path,"/","deconvolute_generemove_quantseq_",names,".pdf"))
g <- ggplot2::ggplot(all_stack, ggplot2::aes(factor(cell_type), proportion)) + ggplot2::geom_boxplot() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 1, size = 8))
print(g)
grDevices::dev.off()
for(i in unique(all_stack$cell_type)) {
cm_one <- all_stack[all_stack$cell_type == i,]
cell_type <- cm_one$cell_type
proportion <- cm_one$proportion
label <- cm_one$label
g <- ggplot2::ggplot(cm_one, ggplot2::aes(factor(cell_type), proportion)) + ggplot2::geom_boxplot() + ggplot2::geom_text(ggplot2::aes(label=label),hjust=-0.2) + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 0, hjust = 1, size = 12))
grDevices::pdf(paste0(path,"/","deconvolute_generemov_quantseq_", i,"_",names,".pdf"))
print(g)
grDevices::dev.off()
message(i)
}
return("Done!")
}
}
l <- list(cellWeighted_Foldchange = all_reordered,
cellType_Proportions = proportions,
leave_one_out_proportions = cmeaned_stacked,
processed_signature_matrix = scaled_odds_ratio)
return(l)
} |
expected <- c("x", "CC", "f")
test(id=5, code={
argv <- structure(list(x = structure(list(x = 1:6, CC = 11:16, f = structure(c(1L,
1L, 2L, 2L, 3L, 3L), .Label = c("1", "2", "3"), class = "factor")), .Names = c("x",
"CC", "f"), row.names = c(NA, -6L), class = "data.frame")), .Names = "x")
do.call('colnames', argv);
}, o = expected);
|
context("Checking Outputs")
test_that("checking value",{
expect_identical(round(pMultiBin(2,4,0.5,0.4),4),
0.5288)
})
test_that("checking class",{
expect_that(pMultiBin(2,4,0.5,0.1),
is_a("numeric"))
})
test_that("checking length of output",{
expect_equal(length(pMultiBin(1:2,4,0.5,1)),2)
}) |
create_scatter <- function(data,
metric_x,
metric_y,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
required_variables <- c(hrvar,
metric_x,
metric_y,
"PersonId")
data %>%
check_inputs(requirements = required_variables)
violate_thres_chr <-
data %>%
group_by(!!sym(hrvar)) %>%
summarise(n = n_distinct(PersonId)) %>%
filter(n < mingroup) %>%
pull(!!sym(hrvar))
clean_x <- us_to_space(metric_x)
clean_y <- us_to_space(metric_y)
myTable <-
data %>%
filter(!(!!sym(hrvar) %in% violate_thres_chr)) %>%
group_by(PersonId, !!sym(hrvar)) %>%
summarise_at(vars(!!sym(metric_x),
!!sym(metric_y)),
~mean(.)) %>%
ungroup()
plot_object <-
myTable %>%
ggplot(aes(x = !!sym(metric_x),
y = !!sym(metric_y),
colour = !!sym(hrvar))) +
geom_point(alpha = 0.5) +
labs(title = paste0(clean_x, " and ", clean_y),
subtitle = paste("Distribution of employees by", tolower(camel_clean(hrvar))),
caption = extract_date_range(data, return = "text")) +
xlab(clean_x) +
ylab(clean_y) +
theme_wpa_basic()
myTable_return <-
myTable %>%
group_by(!!sym(hrvar)) %>%
summarise_at(vars(!!sym(metric_x),
!!sym(metric_y)),
~mean(.))
if(return == "table"){
return(myTable_return)
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
} |
statamode <- function(x, method = c("last", "stata", "sample")){
if(is.null(x)){
return(NA)
}
if (missing(method)){
method <- "stata"
} else {
method <- match.arg(method)
}
xClass <- class(x)
x <- as.character(x)
if (method == 'stata'){
z <- table(as.vector(x))
m <- names(z)[z == max(z)]
if (length(m) == 1){
if(xClass == "factor"){
m <- factor(m)
} else{
class(m) <- xClass
}
return(m)
}
return(".")
}
else if (method == 'sample'){
z <- table(as.vector(x))
m<-names(z)[z == max(z)]
if (length(m)==1){
if(xClass == "factor"){
m <- factor(m)
} else{
class(m) <- xClass
}
return(m)
}
else if (length(m) > 1){
if(xClass == "factor"){
m <- factor(m)
} else{
class(m) <- xClass
}
return(sample(m, 1))
}
else if (length(m) < 1){
if(xClass == "character"){
return(NA_character_)
} else if(xClass == "numeric"){
return(NA_real_)
} else if(xClass == "integer"){
return(NA_integer_)
} else if(xClass == "factor"){
return(NA_character_)
}
}
}
else if (method=='last'){
x_vec <- as.vector(x)
z <- table(x_vec)
m <- names(z[which(z == max(z))])
m <- x[which(x %in% m)]
m <- m[length(m)]
if(length(m) > 0){
if(xClass == "factor"){
m <- factor(m)
return(m)
} else {
class(m) <- xClass
return(m)
}
}
else if(length(m) < 1){
if(xClass == "character"){
return(NA_character_)
} else if(xClass == "numeric"){
return(NA_real_)
} else if(xClass == "integer"){
return(NA_integer_)
} else if(xClass == "factor"){
return(NA_character_)
}
}
}
} |
summaryFull.formula <-
function (object, data = NULL, subset, na.action = na.pass, ...)
{
if (missing(object) || (length(object) != 3L))
stop("formula missing or incorrect")
m <- match.call(expand.dots = FALSE)
if (is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m$... <- NULL
m$formula <- m$object
m$object <- NULL
m$na.action <- na.action
requireNamespace("stats", quietly = TRUE)
m[[1L]] <- as.name("model.frame")
mf <- eval(m, parent.frame())
response <- attr(attr(mf, "terms"), "response")
arg.list <- list(object = mf[, response])
dot.list <- list(...)
match.vec <- pmatch(names(dot.list), "data.name")
if (length(match.vec) == 0 || all(is.na(match.vec)))
arg.list <- c(arg.list, list(data.name = names(mf)[response]))
if (ncol(mf) == 1)
arg.list <- c(arg.list, dot.list)
else arg.list <- c(arg.list, list(group = mf[, -response]),
dot.list)
do.call(summaryFull.default, arg.list)
} |
RNA <- c("NM_00001","NM_00001","NM_00002")
Cpos <- as.integer(c(1,5,1))
Cpos2 <- as.integer(c(1,100000005,1))
ncratio <- c(0.1,0.5,0.3)
pv.adj <- c(0.001,0.1,0.3)
BSdata <- data.frame(RNA, Cpos, ncratio, pv.adj, stringsAsFactors = FALSE)
BSdata2 <- as.matrix(BSdata)
BSdata3 <- data.frame(RNA, Cpos, ncratio, stringsAsFactors = FALSE)
BSdata4 <- data.frame(Cpos, RNA, ncratio, pv.adj, stringsAsFactors = FALSE)
BSdata5 <- data.frame(RNA, ncratio, Cpos, pv.adj, stringsAsFactors = FALSE)
BSdata6 <- data.frame(RNA, Cpos, Cpos, pv.adj, stringsAsFactors = FALSE)
BSdata7 <- data.frame(RNA, Cpos, ncratio, Cpos, stringsAsFactors = FALSE)
BSdata8 <- data.frame(RNA, Cpos2, ncratio, pv.adj, stringsAsFactors = FALSE)
bsXP <- class.BisXP(BSdata)
testthat::test_that("Does class.BisXP yield BisXP object or throw an error?", {
testthat::expect_equal(class(bsXP), "BisXP")
testthat::expect_error(class.BisXP(BSdata2),"class.BisXP requires a data frame as input")
testthat::expect_error(class.BisXP(BSdata3),"class.BisXP's input should have 4 columns: RNA, C.position, non-conversion ratio, adjusted p-value")
testthat::expect_error(class.BisXP(BSdata4),"Column 1 should contain RNA names, as character or as factor")
testthat::expect_error(class.BisXP(BSdata5),"Column 2 should contain cytosine position - starts at 1, integer")
testthat::expect_error(class.BisXP(BSdata6),"Column 3 should contain non-conversion ratio - numeric >=0 and <=1")
testthat::expect_error(class.BisXP(BSdata7),"Column 4 should contain adjusted p-values - numeric >=0 and <=1")
testthat::expect_error(class.BisXP(BSdata8),"C position > 100,000,000, please increase this limit, in class.BisXP.R")
}
)
fichier <- system.file("testdata","BSdata.tabular", package = "BisRNA")
BSdata9 <- read.BisXP(fichier)
testthat::test_that("Does read.BisXP correctly read BisXP object?", {
testthat::expect_equal(class(BSdata9), "BisXP")
}
)
x <- c(1e-3,1e-3,1e-3,1)
px <- fisher.method(x)
testthat::test_that("Does fisher.method works correctly?", {
testthat::expect_equal(px,1.719731e-06)
}
)
BSinter <- intersectMatrix(as.data.frame(BSdata,
row.names=c("NM_00001_1","NM_00001_5","NM_00002_1")),
as.data.frame(BSdata8,
row.names=c("NM_00001_1","NM_00001_10005","NM_00002_1")) )
testthat::test_that("Does intersectMatrix work?", {
testthat::expect_equal(nrow(BSinter),2)
}
)
RNA <- c("NM1")
Cpos <- 1:1000
coverage <- c(4:1003)
set.seed(1)
ncratio <- rpois(n = 1000,lambda = c(4:1003)*0.1) / 4:1003
BSrna <- data.frame(RNA, Cpos, coverage, ncratio, stringsAsFactors = FALSE)
lambdaetc <- RNAmeth.poisson.par(BSrna)
testthat::test_that("Does RNAmeth.poisson.par produce the actual rate?", {
testthat::expect_lt(lambdaetc$bootbca95[1],0.1)
testthat::expect_gt(lambdaetc$bootbca95[2],0.1)
}
)
data(Bisdata,package="BisRNA")
lambda1 <- RNAmeth.poisson.par(Bisdata1)$estimate
BisXP1 <- RNAmeth.poisson.test(Bisdata1,lambda1,method="BH")
testthat::test_that("Does RNAmeth.poisson.test produce the correct output?", {
testthat::expect_equal(class(BisXP1),"BisXP")
}
)
data(Bisdata,package="BisRNA")
lambda1 <- RNAmeth.poisson.par(Bisdata1)$estimate
BisXP1 <- RNAmeth.poisson.test(Bisdata1,lambda1,method="BH")
lambda2 <- RNAmeth.poisson.par(Bisdata2)$estimate
BisXP2 <- RNAmeth.poisson.test(Bisdata2,lambda2,method="BH")
lambda3 <- RNAmeth.poisson.par(Bisdata3)$estimate
BisXP3 <- RNAmeth.poisson.test(Bisdata3,lambda3,method="BH")
BisXP.combined <- samples.combine(BisXP1,BisXP2,BisXP3)
testthat::test_that("Does samples.combine produce the expected output?", {
testthat::expect_equal(class(BisXP.combined),"data.frame")
testthat::expect_equal(ncol(BisXP.combined),3)
testthat::expect_lte(nrow(BisXP.combined),length(BisXP1$RNA.pos))
}
) |
"%||%" <- function(a, b) if (!is.null(a)) a else b
all_identical <- function(xs) {
if (length(xs) <= 1) return(TRUE)
for (i in seq(2, length(xs))) {
if (!identical(xs[[1]], xs[[i]])) return(FALSE)
}
TRUE
}
normalize_melt_arguments <- function(data, measure.ind, factorsAsStrings) {
measure.attributes <- lapply(measure.ind, function(i) {
attributes(data[[i]])
})
measure.attrs.equal <- all_identical(measure.attributes)
if (measure.attrs.equal) {
measure.attributes <- measure.attributes[[1]]
} else {
warning("attributes are not identical across measure variables; ",
"they will be dropped", call. = FALSE)
measure.attributes <- NULL
}
if (!factorsAsStrings && !measure.attrs.equal) {
warning("cannot avoid coercion of factors when measure attributes not identical",
call. = FALSE)
factorsAsStrings <- TRUE
}
any.factors <- any( sapply( measure.ind, function(i) {
is.factor( data[[i]] )
}))
if (factorsAsStrings && any.factors) {
measure.attributes <- NULL
}
list(
measure.attributes = measure.attributes,
factorsAsStrings = factorsAsStrings
)
}
is.string <- function(x) {
is.character(x) && length(x) == 1
} |
IntegralCorrelation <-
function(HRVData, Data, m, tau, r) {
.Deprecated("CalculateSampleEntropy")
DataExp = BuildTakensVector(HRVData,Data,m=m,tau=tau)
numelem = nrow(DataExp)
VerboseMessage(HRVData$Verbose, "Calculating Integral Correlation")
mutualDistance = as.matrix(dist(DataExp,method="maximum"))
Cmr = array(1:numelem)
for (i in 1:numelem) {
iDistance = mutualDistance[i, 1:numelem]
Cmr[i] = length(iDistance[iDistance <= r]) / numelem
}
VerboseMessage(HRVData$Verbose, paste("Integral Correlation:", rhrvFormat(sum(Cmr))))
return(Cmr)
} |
standard_error <- function(model, ...) {
UseMethod("standard_error")
}
standard_error.default <- function(model, method = NULL, verbose = TRUE, ...) {
if (!is.null(method)) {
method <- tolower(method)
} else {
method <- "wald"
}
if (method == "robust") {
standard_error_robust(model, ...)
} else {
se <- tryCatch(
{
if (grepl("^Zelig-", class(model)[1])) {
unlist(model$get_se())
} else {
.get_se_from_summary(model)
}
},
error = function(e) {
NULL
}
)
if (is.null(se)) {
se <- tryCatch(
{
varcov <- insight::get_varcov(model)
se_from_varcov <- sqrt(diag(varcov))
names(se_from_varcov) <- colnames(varcov)
se_from_varcov
},
error = function(e) {
NULL
}
)
}
if (is.null(se)) {
if (isTRUE(verbose)) {
insight::print_color("\nCould not extract standard errors from model object.\n", "red")
}
} else {
.data_frame(
Parameter = names(se),
SE = as.vector(se)
)
}
}
}
.get_se_from_summary <- function(model, component = NULL) {
cs <- stats::coef(summary(model))
se <- NULL
if (is.list(cs) && !is.null(component)) cs <- cs[[component]]
if (!is.null(cs)) {
se_col <- which(colnames(cs) == "Std. Error")
if (length(se_col) == 0) se_col <- 2
se <- as.vector(cs[, se_col])
if (is.null(names(se))) {
coef_names <- rownames(cs)
if (length(coef_names) == length(se)) names(se) <- coef_names
}
}
names(se) <- .remove_backticks_from_string(names(se))
se
} |
is_connected <- function(fw){
DFS <- function(m, i, visited, env = envf) {
for (n in which(m[i,] > 0)){
if (!env$visited[n]){
env$visited[n] = TRUE
DFS(m, n, env$visited)
}
}
return()
}
fw.s <- fw
fw.s[lower.tri(fw.s)] <- t(fw.s)[lower.tri(fw.s)]
visited <- rep(FALSE, nrow(fw.s))
visited[1] <- TRUE
envf <- environment()
visited <- DFS(fw.s, 1, visited, envf)
return(all(visited))
} |
searchrules <- function(d,
lhs=2:ncol(d),
rhs=1,
tnorm=c("goedel", "goguen", "lukasiewicz"),
n=100,
best=c("confidence"),
minSupport=0.02,
minConfidence=0.75,
maxConfidence=1,
maxLength=4,
numThreads=1,
trie=(maxConfidence < 1)) {
.mustBe(is.fsets(d), "'d' must be an instance of class 'fsets'")
.mustBe(ncol(d) >= 2, "'d' must have at least 2 columns")
.mustBe(nrow(d) >= 1, "'d' must not be empty")
.mustBeNumericVector(lhs)
.mustBe(min(lhs) >= 1 && max(lhs) <= ncol(d), "'lhs' must contain valid indexes of the columns of 'd'")
.mustBeNumericVector(rhs)
.mustBe(min(rhs) >= 1 && max(rhs) <= ncol(d), "'rhs' must contain valid indexes of the columns of 'd'")
.mustBeNumericScalar(n)
.mustBe(n >= 0, "'n' must be a non-negative number (zero means unlimited number of rules)")
.mustBeNumericScalar(minSupport)
.mustBeInInterval(minSupport, 0, 1)
.mustBeNumericScalar(minConfidence)
.mustBeInInterval(minConfidence, 0, 1)
.mustBeNumericScalar(maxConfidence)
.mustBeInInterval(maxConfidence, 0, 1)
.mustBe(maxConfidence >= minConfidence, "'maxConfidence' must be greater or equal to 'minConfidence'")
if (maxLength < 0) {
maxLength <- -1
}
.mustBeNumericScalar(numThreads)
.mustBe(numThreads >= 1, "'numThreads' must be positive integer number")
tnorm <- match.arg(tnorm)
if (tnorm == 'goedel') {
tnorm <- 'minimum'
} else if (tnorm == 'goguen') {
tnorm <- 'product'
}
best = match.arg(best)
config <- list(vars=as.numeric(as.factor(vars(d))),
minSupport=minSupport,
minConfidence=minConfidence,
maxConfidence=maxConfidence,
maxLength=maxLength,
lhs=lhs - 1,
rhs=rhs - 1,
tnorm=tnorm,
n=n,
best=best,
numThreads=numThreads,
trie=trie)
result <- .Call("_lfl_search", d, config, PACKAGE="lfl")
map <- colnames(d)
names(map) <- 1:ncol(d)
rules <- lapply(result$rules, function(x) {
x <- x + 1
x[] <- map[unlist(x)]
return(x)
})
if (is.null(result$statistics) || length(result$statistics) <= 0) {
stats <- matrix(0, nrow=0, ncol=0)
} else {
stats <-matrix(unlist(result$statistics),
byrow=TRUE,
nrow=length(result$statistics))
colnames(stats) <- c('support', 'lhsSupport', 'rhsSupport', 'confidence', 'lift', 'loLift', 'hiLift')
stats <- stats[, c('support', 'lhsSupport', 'rhsSupport', 'confidence'), drop=FALSE]
if (tnorm == 'product') {
stats <- cbind(stats,
lift=stats[, 'confidence'] / stats[, 'rhsSupport'],
conviction=(1 - stats[, 'rhsSupport']) / (1 - stats[, 'confidence']))
}
}
res <- farules(rules=rules,
statistics=stats)
return(res)
} |
obj_tracker <- new.env()
make_id_char <- function(id) {
if(is.na(id)) {
return(NA)
}
else {
id_char <- format(as.integer64(id), width=25, scientific = FALSE)
return(id_char)
}
}
new_id_obj <- function(id) {
return(environment())
}
is_open <- function(id) {
id_char <- make_id_char(id)
return(exists(id_char, envir=obj_tracker))
}
get_obj <- function(id) {
id_char <- make_id_char(id)
if(exists(id_char, envir=obj_tracker)) {
return(get(id_char, envir=obj_tracker)$obj)
}
else {
return(NULL)
}
}
incr_count <- function(id) {
id_char <- make_id_char(id)
if(exists(id_char, envir=obj_tracker)) {
item <- get(id_char, envir=obj_tracker)
item$count <- item$count + 1
assign(x=id_char, value=item, envir=obj_tracker)
return(item)
}
else {
item <- list(count=1, obj=new_id_obj(id))
assign(x=id_char, value=item, envir=obj_tracker)
return(item)
}
}
rm_obj <- function(id) {
id_char <- make_id_char(id)
item <- try(get(id_char, envir=obj_tracker), silent=TRUE)
if(!inherits(item, "try-error")) {
item$obj$id <- NA
rm(list=id_char, envir=obj_tracker)
}
else {
print(paste("Couldn't delete", id_char))
}
return(invisible(NULL))
}
decr_count <- function(id) {
id_char <- make_id_char(id)
if(exists(id_char, envir=obj_tracker)) {
item <- get(id_char, envir=obj_tracker)
if(item$count == 1) {
rm_obj(id)
return(invisible(NULL))
}
else {
item$count <- item$count - 1
assign(x=id_char, value=item, envir=obj_tracker)
return(item)
}
}
else {
stop(paste("Can't decrease count of obj", id_char," - already 0"))
}
}
obj_info <- function(id) {
if(!is.character(id)) {
id_char <- make_id_char(id)
}
else {
id_char <- id
}
item <- get(id_char, envir=obj_tracker)
id_internal <- item$obj$id
return(data.frame(id=id, count=item$count, id_internal=id_internal))
}
list_tracked_obj <- function() {
gc()
all_obj <- as.list(ls(envir=obj_tracker))
res <- do.call("rbind", lapply(all_obj, obj_info))
rownames(res) <- NULL
return(res)
} |
BIC.MeanNormal <-
function(a, N, L){
-2 * a + {N + 2} * log(L)
} |
"psdata" |
snake_case_fact <- function(ft) {
UseMethod("snake_case_fact")
}
snake_case_fact.fact_table <- function(ft) {
sep = "_"
attr(ft, "name") <-
snakecase::to_snake_case(attr(ft, "name"), sep_out = sep)
attr(ft, "foreign_keys") <-
snakecase::to_snake_case(attr(ft, "foreign_keys"), sep_out = sep)
attr(ft, "measures") <-
snakecase::to_snake_case(attr(ft, "measures"), sep_out = sep)
attr(ft, "nrow_agg") <-
snakecase::to_snake_case(attr(ft, "nrow_agg"), sep_out = sep)
names(ft) <- snakecase::to_snake_case(names(ft), sep_out = sep)
ft
} |
subsetOffsets <- function(offsets, objects, image_type = c("img", "msk")) {
if(missing(offsets)) stop("'offsets' can't be missing")
if(missing(objects)) stop("'objects' can't be missing")
assert(offsets, cla = "IFC_offset")
assert(image_type, alw = c("img", "msk"))
XIF_test = ifelse(length(attr(offsets, "test")) == 0, testXIF(attr(offsets, "fileName_image")), attr(offsets, "test"))
type = as.integer(XIF_test == 1) + 1L
objects = as.integer(objects); objects = objects[(objects >= 0) & (objects < attr(offsets, "obj_count")) & (is.finite(objects))]
if(length(objects) == 0) {
warning("subsetOffsets: No objects to subset, check the objects you provided.", immediate. = TRUE, call. = FALSE)
foo = integer()
} else {
if(all(c("img", "msk") %in% image_type)) {
if(type == 1) {
in_offsets = objects + 1L
warning("subsetOffsets: There may be no mask to subset.", immediate. = TRUE, call. = FALSE)
} else {
in_offsets = unlist(lapply(objects, FUN=function(x) c(2*x+1,2*(x+1))))
}
} else {
if("img" %in% image_type) {
if(type == 1) {
in_offsets = objects + 1L
} else {
in_offsets = 2 * objects + 1
}
} else {
if(type == 1) {
in_offsets = NULL
warning("subsetOffsets: There may be no mask to subset.", immediate. = TRUE, call. = FALSE)
} else {
in_offsets = 2 * (objects + 1)
}
}
}
foo = attr(offsets, "all")[in_offsets]
}
attr(foo, "all") = attr(offsets, "all")
attr(foo, "first") = attr(offsets, "first")
attr(foo, "fileName_image") = attr(offsets, "fileName_image")
attr(foo, "checksum") = attr(offsets, "checksum")
attr(foo, "obj_count") = attr(offsets, "obj_count")
attr(foo, "test") = XIF_test
class(foo) = c("IFC_offset")
return(foo)
} |
gcat.test = function(counts, distmatrix=NULL, C0=NULL, method="C-uMST", Nperm=0){
if (length(method)==0){
cat("Specify an appropriate method to use.\n")
return(0)
}
methodid = match(method, c("aMST","C-uMST", "uMST", "C-uNNB", "RC0", "TC0"))
NAids = which(is.na(methodid))
if (length(NAids)>0){
cat(method[NAids], "is/are not in the method list and so removed.\n")
methodid = methodid[-NAids]
}
if (length(methodid)==0){
cat("Specify an appropriate method to use.\n")
return(0)
}
if ((!is.na(match(1,methodid))) && Nperm==0){
cat("Specify the number of permutations for calculating p-value for R_aMST\n")
return(0)
}
if (( (!is.na(match(1,methodid))) || (!is.na(match(2,methodid))) || (!is.na(match(3,methodid))) || (!is.na(match(4,methodid)))) && is.null(distmatrix)){
cat("You need to specify the distance matrix on the categories for calculating R_aMST, R_C-uMST, R_uMST, or R_C-uNNB.\n")
return(0)
}
if (((!is.na(match(5,methodid))) || (!is.na(match(6,methodid)))) && is.null(C0)){
cat("You need to specify the edge information for calcuating RC0 or TC0.\n")
return(0)
}
K = dim(counts)[1]
B = Nperm
permmat = matrix(0,K,2*(B+1))
permmat[,1:2] = counts
v1 = counts[,1]
v2 = counts[,2]
if (B>0){
for (j in 1:B){
temp = perm(v1,v2)
permmat[,2*j+(1:2)] = t(temp)
}
}
result = list()
if (!is.na(match(1,methodid))){
rawresult0 = .C("RG", as.double(rep(0,(B+1))), as.integer(0), as.double(rep(0,K*(K-1))), as.integer(0), as.integer(0), as.integer(K), as.integer(B+1), as.integer(permmat), as.double(distmatrix), PACKAGE="gCat")
result0 = rawresult0[[1]]
r = matrix(c(result0[1], myp_left(result0[2:(B+1)], result0[1])),1)
colnames(r) = c("R_aMST", "pval.perm")
result = c(result, list(aMST=r))
}
if (!is.na(match(2,methodid)) || (!is.na(match(3,methodid)))){
rawresult1 = .C("RG", as.double(rep(0,(B+1))), as.integer(0), as.double(rep(0,K*(K-1))), as.integer(1), as.integer(0), as.integer(K), as.integer(B+1), as.integer(permmat), as.double(distmatrix), PACKAGE="gCat")
edge = t(matrix(rawresult1[[3]],2)[,1:rawresult1[[2]]]) + 1
if (!is.na(match(2,methodid))){
result1 = rawresult1[[1]]
tmp = getMV(v1, v2, edge)
if (B<=0){
r = matrix(c(result1[1], pnorm(result1[1], tmp$Mean, tmp$Sd)),1)
colnames(r) = c("R_C-uMST", "pval.appr")
}else{
r = matrix(c(result1[1], pnorm(result1[1], tmp$Mean, tmp$Sd), myp_left(result1[2:(B+1)], result1[1])),1)
colnames(r) = c("R_C-uMST", "pval.appr", "pval.perm")
}
result = c(result, list(CuMST=r))
}
if (!is.na(match(3,methodid))){
rawresult4 = .C("RG", as.double(rep(0,(B+1))), as.integer(0), as.double(rep(0,K*(K-1))), as.integer(4), as.integer(0), as.integer(K), as.integer(B+1), as.integer(permmat), as.double(distmatrix), PACKAGE="gCat")
result4 = rawresult4[[1]]
tmp = getMV_uMST(v1, v2, edge)
if (B<=0){
r = matrix(c(result4[1], pnorm(result4[1], tmp$Mean, tmp$Sd)),1)
colnames(r) = c("R_uMST", "pval.appr")
}else{
r = matrix(c(result4[1], pnorm(result4[1], tmp$Mean, tmp$Sd), myp_left(result4[2:(B+1)], result4[1])),1)
colnames(r) = c("R_uMST", "pval.appr", "pval.perm")
}
result = c(result, list(uMST=r))
}
}
if (!is.na(match(4,methodid))){
rawresult3 = .C("RG", as.double(rep(0,(B+1))), as.integer(0), as.double(rep(0,K*(K-1))), as.integer(3), as.integer(0), as.integer(K), as.integer(B+1), as.integer(permmat), as.double(distmatrix), PACKAGE="gCat")
result3 = rawresult3[[1]]
edge3 = t(matrix(rawresult3[[3]],2)[,1:rawresult3[[2]]]) + 1
tmp3 = getMV(v1, v2, edge3)
if (B<=0){
r = matrix(c(result3[1], pnorm(result3[1], tmp3$Mean, tmp3$Sd)),1)
colnames(r) = c("R_C-uNNB", "pval.appr")
}else{
r = matrix(c(result3[1], pnorm(result3[1], tmp3$Mean, tmp3$Sd), myp_left(result3[2:(B+1)], result3[1])),1)
colnames(r) = c("R_C-uNNB", "pval.appr", "pval.perm")
}
result = c(result, list(CuNNB=r))
}
if (!is.na(match(5,methodid))){
R = RC(counts, C0)
tmp = getMV(v1,v2,C0)
if (B<=0){
r = matrix(c(R, pnorm(R,tmp$Mean, tmp$Sd)), 1)
colnames(r) = c("RC0", "pval.appr")
}else{
Rv = rep(0,B)
for (j in 1:B){
Rv[j] = RC(permmat[,(2*j)+(1:2)], C0)
}
r = matrix(c(R, pnorm(R,tmp$Mean, tmp$Sd), myp_left(Rv,R)), 1)
colnames(r) = c("RC0", "pval.appr", "pval.perm")
}
result = c(result, list(RC0=r))
}
if (!is.na(match(6,methodid))){
R = TC(counts, C0)
tmp = getMV_uMST(v1,v2,C0)
if (B<=0){
r = matrix(c(R, pnorm(R,tmp$Mean, tmp$Sd)), 1)
colnames(r) = c("RC0", "pval.appr")
}else{
Rv = rep(0,B)
for (j in 1:B){
Rv[j] = TC(permmat[,(2*j)+(1:2)], C0)
}
r = matrix(c(R, pnorm(R,tmp$Mean, tmp$Sd), myp_left(Rv,R)), 1)
colnames(r) = c("TC0", "pval.appr", "pval.perm")
}
result = c(result, list(TC0=r))
}
return(result)
}
RC = function(counts, edge){
v1 = counts[,1]
v2 = counts[,2]
v = v1+v2
R = sum(2*v1*v2/v)
for (i in 1:(dim(edge)[1])){
k1 = edge[i,1]
k2 = edge[i,2]
R = R + (v1[k1]*v2[k2] + v1[k2]*v2[k1])/v[k1]/v[k2]
}
R
}
TC = function(counts, edge){
v1 = counts[,1]
v2 = counts[,2]
v = v1+v2
R = sum(v1*v2)
for (i in 1:(dim(edge)[1])){
k1 = edge[i,1]
k2 = edge[i,2]
R = R + (v1[k1]*v2[k2] + v1[k2]*v2[k1])
}
R
} |
oxcalCalibrate <- function(bp, std, names = 1:length(bp)) {
oxcal_script <- R_Date(names, bp, std)
result_file <- executeOxcalScript(oxcal_script)
result <- readOxcalOutput(result_file)
RVA <- parseOxcalOutput(result)
RVA
} |
context("Function .fillClusterDesc")
sapply(studyPathS, function(studyPath){
opts <- setSimulationPath(studyPath)
clusterDesc <- readClusterDesc()
describe(".fillClusterDesc", {
it("fill missing values with provided defaults", {
.fillClusterDesc(clusterDesc, marginal.cost = 0, min.stable.power = 0)
expect_false(any(is.na(clusterDesc$marginal.cost)))
expect_false(any(is.na(clusterDesc$min.stable.power)))
})
it("creates columns if they are not present", {
.fillClusterDesc(clusterDesc, fictiveCol = "ok !")
expect_false(is.null(clusterDesc$fictiveCol))
expect_true(all(clusterDesc$fictiveCol == "ok !"))
})
})
}) |
verbose=TRUE
Sys.setlocale("LC_ALL", "C")
Sys.getlocale()
require(haplo.stats)
if(verbose)
cat("prepare two datasets, one with char alleles, the other 3 loci from hla data\n")
geno.char <- matrix(c('F','f','g','G','h1','h1',
'F','F','g','G','H','h1',
'F','f','g','G','h2','h2',
'f','f','g','G','h2','h1',
'F','F','g','G','H','h2',
'f','f','G','G','h1','h2',
'F','f','G','g','h2','h2',
'F','F','g','G','h1','z',
'F','f','z','z','h1','h1',
'F','f','G','g','h1','h2',
'F','f','G','G','h1','h2',
'F','F','g','G','h1','z',
'F','f','z','z','h1','h1',
'f','f','G','g','h1','h2'), nrow=14,byrow=T)
y.response <- c(2.0,4.5,1.8,2.1,5.2,1.3,3.4,2.5,2.2,1.9,2.1,1.2,3.0,1.9)
y.pheno <- c(0,1,0,0,1,0,0,1,0,0,0,1,1,0)
char.label <- c("F","G","H")
data(hla.demo)
hla.sub <- hla.demo[,c(1,2,3,4,17,18,21:24)]
geno.hla <- hla.sub[,-c(1:4)]
hla.resp <- hla.sub[,1]
hla.respcat <- hla.sub[,2]
hla.sex <- hla.sub[,3]
hla.label=c("DQB","DRB","HLA.B")
seed <- c(33, 10, 39, 6, 16, 0, 40, 24, 12, 60, 7, 1)
set.seed(seed)
runif(10)
if(verbose) cat("character alleles, binary trait, additive and dominant\n")
set.seed(seed)
score.char.pheno.add <- haplo.score(y.pheno, geno.char, trait.type="binomial",
locus.label=char.label, miss.val='z',
offset = NA, x.adj = NA, min.count=4, simulate=FALSE,
haplo.effect="additive",
sim.control = score.sim.control(),
em.control = haplo.em.control())
print(score.char.pheno.add)
set.seed(seed)
runif(10)
set.seed(seed)
score.char.pheno.dom <- haplo.score(y.pheno, geno.char, trait.type="binomial",
locus.label=char.label, miss.val='z',
offset = NA, x.adj=NA, min.count=4, simulate=FALSE,
haplo.effect="dom",
sim.control = score.sim.control(),
em.control = haplo.em.control())
print(score.char.pheno.dom)
if(verbose) cat("character alleles, gaussian trait\n")
set.seed(seed)
score.char.gaus <- haplo.score(y.response, geno.char, trait.type="gaussian",
skip.haplo=.1,
locus.label=char.label, miss.val="z",simulate=TRUE,
sim.control=score.sim.control(min.sim=50, p.threshold=.25,
max.sim=1000,verbose=FALSE),
em.control = haplo.em.control())
print(score.char.gaus)
if(verbose) cat("hla data, gaussian trait and x.adj\n")
set.seed(seed)
score.hla.resp.adj <- haplo.score(hla.resp,geno.hla,trait.type="gaussian",
locus.label=hla.label, miss.val=0, x.adj=hla.sex,
simulate=FALSE, min.count=5)
print(score.hla.resp.adj)
if(verbose) cat("hla data ordinal trait\n")
set.seed(seed)
score.hla.respcat <- haplo.score(hla.respcat, geno.hla, trait.type="ordinal",
locus.label=hla.label, miss.val=0,
simulate=FALSE, min.count=5,
offset=NA, x.adj=NA)
print(score.hla.respcat)
set.seed(seed)
score.hla.respcat.adj <- haplo.score(hla.respcat, geno.hla, trait.type="ordinal",
locus.label=hla.label, miss.val=0,
simulate=FALSE, min.count=5,
offset=NA, x.adj=hla.sex)
print(score.hla.respcat)
if(verbose) cat("snap SNP data with binary trait to test dominance,recessive\n")
snapDF <- read.table("snapData.csv",header=TRUE, sep=",")
y.bin <- snapDF[,1]-1
geno <- setupGeno(geno=snapDF[,-1])
set.seed(seed)
y.ord <- sample(c("low", "med", "hi"), size=nrow(snapDF), prob=c(.3,.4,.3), replace=TRUE)
geno.rec <- setupGeno(snapDF[,-c(1:9)])
set.seed(seed)
hcount=5
bin.snap.add <- haplo.score(y=y.bin, geno=geno.rec, trait.type="binomial",
min.count=hcount,
simulate=TRUE, haplo.effect="add",
sim.control=score.sim.control(min.sim=200,max.sim=500))
print(bin.snap.add)
set.seed(seed)
bin.snap.dom <- haplo.score(y=y.bin, geno=geno.rec, trait.type="binomial",
min.count=hcount, simulate=TRUE, haplo.effect="dom",
sim.control=score.sim.control(min.sim=200,max.sim=500))
print(bin.snap.dom)
set.seed(seed)
bin.snap.rec <- haplo.score(y=y.bin, geno=geno.rec, trait.type="binomial",
min.count=hcount, simulate=TRUE,
haplo.effect="rec",
sim.control=score.sim.control(min.sim=200,max.sim=500))
print(bin.snap.rec)
set.seed(seed)
ord.snap.add <- haplo.score(y=y.ord, geno=geno.rec, trait.type="ordinal",
min.count=hcount, simulate=TRUE, haplo.effect="add",
sim.control=score.sim.control(min.sim=200,max.sim=500))
print(ord.snap.add)
set.seed(seed)
ord.snap.add.adj <- haplo.score(y=y.ord, geno=geno.rec, trait.type="ordinal",
min.count=hcount, simulate=TRUE, haplo.effect="add", x.adj=hla.sex,
sim.control=score.sim.control(min.sim=200,max.sim=500))
print(ord.snap.add.adj) |
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "rpart1SE"
set.seed(2)
training <- twoClassSim(50, linearVars = 2)
testing <- twoClassSim(500, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all")
cctrl2 <- trainControl(method = "LOOCV")
cctrl3 <- trainControl(method = "none",
classProbs = TRUE, summaryFunction = twoClassSummary)
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = cctrl1,
preProc = c("center", "scale"))
set.seed(849)
test_class_cv_form <- train(Class ~ ., data = training,
method = "rpart1SE",
trControl = cctrl1,
preProc = c("center", "scale"))
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = cctrl2,
preProc = c("center", "scale"))
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = cctrl3,
tuneGrid = test_class_cv_model$bestTune,
metric = "ROC",
preProc = c("center", "scale"))
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_rec <- train(x = rec_cls,
data = training,
method = "rpart1SE",
trControl = cctrl1)
if(
!isTRUE(
all.equal(test_class_cv_model$results,
test_class_rec$results))
)
stop("CV weights not giving the same results")
test_class_imp_rec <- varImp(test_class_rec)
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
library(caret)
library(plyr)
library(recipes)
library(dplyr)
set.seed(1)
training <- SLC14_1(30)
testing <- SLC14_1(100)
trainX <- training[, -ncol(training)]
trainY <- training$y
rec_reg <- recipe(y ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
testX <- trainX[, -ncol(training)]
testY <- trainX$y
rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all")
rctrl2 <- trainControl(method = "LOOCV")
rctrl3 <- trainControl(method = "none")
set.seed(849)
test_reg_cv_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = rctrl1,
preProc = c("center", "scale"))
test_reg_pred <- predict(test_reg_cv_model, testX)
set.seed(849)
test_reg_cv_form <- train(y ~ ., data = training,
method = "rpart1SE",
trControl = rctrl1,
preProc = c("center", "scale"))
test_reg_pred_form <- predict(test_reg_cv_form, testX)
set.seed(849)
test_reg_loo_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = rctrl2,
preProc = c("center", "scale"))
set.seed(849)
test_reg_none_model <- train(trainX, trainY,
method = "rpart1SE",
trControl = rctrl3,
tuneGrid = test_reg_cv_model$bestTune,
preProc = c("center", "scale"))
test_reg_none_pred <- predict(test_reg_none_model, testX)
set.seed(849)
test_reg_rec <- train(x = rec_reg,
data = training,
method = "rpart1SE",
trControl = rctrl1)
if(
!isTRUE(
all.equal(test_reg_cv_model$results,
test_reg_rec$results))
)
stop("CV weights not giving the same results")
test_reg_imp_rec <- varImp(test_reg_rec)
test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)])
test_class_predictors1 <- predictors(test_class_cv_model)
test_reg_predictors1 <- predictors(test_reg_cv_model)
test_class_imp <- varImp(test_class_cv_model)
test_reg_imp <- varImp(test_reg_cv_model)
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
if(!interactive())
q("no") |
library(tidymodels)
library(nycflights13)
library(doMC)
library(rlang)
library(xgboost)
library(vctrs)
num_resamples <- 5
num_grid <- 10
num_cores <- 3
preproc <- "no preprocessing"
par_method <- "resamples"
set.seed(123)
flight_data <-
flights %>%
mutate(
arr_delay = ifelse(arr_delay >= 30, "late", "on_time"),
arr_delay = factor(arr_delay),
date = as.Date(time_hour)
) %>%
inner_join(weather, by = c("origin", "time_hour")) %>%
select(dep_time, flight, origin, dest, air_time, distance,
carrier, date, arr_delay, time_hour) %>%
na.omit() %>%
mutate_if(is.character, as.factor) %>%
sample_n(4000)
flights_rec <-
recipe(arr_delay ~ ., data = flight_data) %>%
update_role(flight, time_hour, new_role = "ID") %>%
step_date(date, features = c("dow", "month")) %>%
step_holiday(date, holidays = timeDate::listHolidays("US")) %>%
step_rm(date) %>%
step_dummy(all_nominal_predictors()) %>%
step_zv(all_predictors())
preproc_data <-
flights_rec %>%
prep() %>%
juice(all_predictors(), all_outcomes())
xgboost_spec <-
boost_tree(trees = tune(), min_n = tune(), tree_depth = tune(), learn_rate = tune(),
loss_reduction = tune(), sample_size = tune()) %>%
set_mode("classification") %>%
set_engine("xgboost")
if (preproc != "no preprocessing") {
xgboost_workflow <-
workflow() %>%
add_recipe(flights_rec) %>%
add_model(xgboost_spec)
set.seed(33)
bt <- bootstraps(flight_data, times = num_resamples)
} else {
xgboost_workflow <-
workflow() %>%
add_variables(arr_delay, predictors = c(everything())) %>%
add_model(xgboost_spec)
set.seed(33)
bt <- bootstraps(preproc_data, times = num_resamples)
}
set.seed(22)
xgboost_grid <-
xgboost_workflow %>%
parameters() %>%
update(trees = trees(c(100, 2000))) %>%
grid_max_entropy(size = num_grid)
if (num_cores > 1) {
registerDoMC(cores=num_cores)
}
roc_res <- metric_set(roc_auc)
ctrl <- control_grid(parallel_over = par_method)
grid_time <- system.time({
set.seed(99)
xgboost_workflow %>%
tune_grid(bt, grid = xgboost_grid, metrics = roc_res, control = ctrl)
})
times <- tibble::tibble(
elapsed = grid_time[3],
num_resamples = num_resamples,
num_grid = num_grid,
num_cores = num_cores,
preproc = preproc,
par_method = par_method
)
save(times, file = paste0("xgb_", num_cores, format(Sys.time(), "_%Y_%m_%d_%H_%M_%S.RData")))
sessioninfo::session_info()
if (!interactive()) {
q("no")
} |
skip_on_cran()
test_that("gn_version", {
expect_is(gn_version(), "list")
expect_named(gn_version(), c("version", "build"))
expect_is(gn_version()$version, "character")
expect_is(gn_version()$build, "character")
}) |
ct_shiny <- function() {
shiny::runApp(system.file('ct_shiny', package='competitiontoolbox'))
}
trade_shiny <- function() {
ct_shiny()
}
antitrust_shiny <- function() {
ct_shiny()
} |
predict.sscox <- function (object,newdata,se.fit=FALSE,
include=c(object$terms$labels,object$lab.p),...)
{
if (class(object)!="sscox") stop("gss error in predict.sscox: not a sscox object")
nnew <- nrow(newdata)
nbasis <- length(object$id.basis)
nnull <- length(object$d)
nz <- length(object$b)
nn <- nbasis + nnull + nz
labels.p <- object$lab.p
if (!is.null(object$d)) s <- matrix(0,nnew,nnull)
r <- matrix(0,nnew,nbasis)
for (label in include) {
if (label%in%labels.p) next
xx <- object$mf[object$id.basis,object$terms[[label]]$vlist]
xnew <- newdata[,object$terms[[label]]$vlist]
nphi <- object$terms[[label]]$nphi
nrk <- object$terms[[label]]$nrk
if (nphi) {
iphi <- object$terms[[label]]$iphi
phi <- object$terms[[label]]$phi
for (i in 1:nphi) {
s[,iphi+(i-1)] <- phi$fun(xnew,nu=i,env=phi$env)
}
}
if (nrk) {
irk <- object$terms[[label]]$irk
rk <- object$terms[[label]]$rk
for (i in 1:nrk) {
r <- r + 10^object$theta[irk+(i-1)]*
rk$fun(xnew,xx,nu=i,env=rk$env,out=TRUE)
}
}
}
if (!is.null(object$partial)) {
vars.p <- as.character(attr(object$partial$mt,"variables"))[-1]
facs.p <- attr(object$partial$mt,"factors")
vlist <- vars.p[as.logical(apply(facs.p,1,sum))]
for (lab in labels.p) {
if (lab%in%include) {
vlist.wk <- vars.p[as.logical(facs.p[,lab])]
vlist <- vlist[!(vlist%in%vlist.wk)]
}
}
if (length(vlist)) {
for (lab in vlist) newdata[[lab]] <- 0
}
matx.p <- model.matrix(object$partial$mt,newdata)[,-1,drop=FALSE]
matx.p <- sweep(matx.p,2,object$partial$center)
matx.p <- sweep(matx.p,2,object$partial$scale,"/")
nu <- nnull-dim(matx.p)[2]
for (label in labels.p) {
nu <- nu+1
if (label%in%include) s[,nu] <- matx.p[,label]
}
}
if (nz) {
if (is.null(newdata$random)) z.wk <- matrix(0,nnew,nz)
else z.wk <- newdata$random
rs <- cbind(r,z.wk,s)
}
else rs <- cbind(r,s)
if (!se.fit) as.vector(exp(rs%*%c(object$c,object$b,object$d)))
else {
fit <- as.vector(exp(rs%*%c(object$c,object$b,object$d)))
se.fit <- .Fortran("hzdaux2",
as.double(object$se.aux$v), as.integer(dim(rs)[2]),
as.integer(object$se.aux$jpvt),
as.double(t(rs)), as.integer(dim(rs)[1]),
se=double(dim(rs)[1]), PACKAGE="gss")[["se"]]
list(fit=fit,se.fit=se.fit)
}
} |
isNumberScalarOrNull <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = 1, zeroAllowed = TRUE, negativeAllowed = TRUE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = FALSE, nanAllowed = FALSE, infAllowed = FALSE, message = message, argumentName = argumentName)
} |
vcgUniformRemesh <- function(x,voxelSize=NULL,offset=0, discretize=FALSE, multiSample=FALSE,absDist=FALSE, mergeClost=FALSE,silent=FALSE) {
if (is.null(voxelSize))
voxelSize <- bbox(x)$dia/50
vb <- x$vb
it <- x$it-1
out <- .Call("RuniformResampling",vb,it,voxelSize,offset,discretize,multiSample, absDist,mergeClost,silent)
out$vb <- rbind(out$vb,1)
out$normals <- rbind(out$normals,1)
class(out) <- "mesh3d"
return(out)
}
bbox <- function(x) {
bbox <- apply(t(x$vb[1:3,]), 2, range)
bbox <- expand.grid(bbox[, 1], bbox[, 2], bbox[, 3])
dia <- max(dist(bbox))
return(list(bbox=bbox,diag=dia))
}
|
spca <- function (...) UseMethod("spca")
spca.default <- function(x, ...) {
stop(sprintf("No spca method for object of class %s",
paste(class(x), collapse = " ")))
}
spca.matrix <- function(x, xy = NULL, cn = NULL, matWeight = NULL,
center = TRUE, scale = FALSE, scannf = TRUE,
nfposi = 1, nfnega = 1,
type = NULL, ask = TRUE,
plot.nb = TRUE, edit.nb = FALSE,
truenames = TRUE,
d1 = NULL, d2 = NULL, k = NULL,
a = NULL, dmin = NULL, ...) {
if (!requireNamespace("spdep", quietly=TRUE)) {
install <- paste0('install.packages(', shQuote("spdep"), ")")
msg <- c("The spdep package is required. Please use `", install, "` to install it")
stop(paste(msg, collapse = ""))
}
if (!requireNamespace("adespatial", quietly=TRUE)) {
install <- paste0('install.packages(', shQuote("adespatial"), ")")
msg <- c("The adespatial package is required. Please use `", install, "` to install it")
stop(paste(msg, collapse = ""))
}
if (!is.numeric(x)) {
stop("Only matrices of numeric values are accepted.")
}
if(is.null(xy) & (inherits(cn,"nb") & !inherits(cn,"listw")) ){
xy <- attr(cn,"xy")
}
if(is.null(xy)) {
stop("xy coordinates are not provided")
}
if(is.data.frame(xy)) {
xy <- as.matrix(xy)
}
if(!is.matrix(xy)) {
stop("provided 'xy' cannot be converted to matrix")
}
if(ncol(xy) != 2) {
stop("xy does not have two columns.")
}
if(nrow(xy) != nrow(x)) {
stop("x and xy must have the same row numbers.")
}
resCN <- NULL
if (!is.null(matWeight)) {
if (!is.matrix(matWeight)) {
stop("matWeight is not a matrix")
}
if (!is.numeric(matWeight)) {
stop("matWeight is not numeric")
}
if (nrow(matWeight) != ncol(matWeight)) {
stop("matWeight is not square")
}
if (nrow(matWeight) != nrow(x)) {
stop("dimension of datWeight does not match data")
}
diag(matWeight) <- 0
matWeight <- prop.table(matWeight, 1)
resCN <- spdep::mat2listw(matWeight)
resCN$style <- "W"
}
if(is.null(resCN) & !is.null(cn)) {
if(inherits(cn,"nb")) {
if(!inherits(cn,"listw")){
cn <- spdep::nb2listw(cn, style="W", zero.policy=TRUE)
}
resCN <- cn
} else {
stop("cn does not have a recognized class")
}
}
if(is.null(resCN)) {
resCN <- chooseCN(xy=xy, ask=ask, type=type, plot.nb=plot.nb, edit.nb=edit.nb,
result.type="listw", d1=d1, d2=d2, k=k, a=a, dmin=dmin)
}
x_pca <- ade4::dudi.pca(x, center = center, scale = scale, scannf = FALSE)
out <- adespatial::multispati(dudi = x_pca, listw = resCN, scannf = scannf,
nfposi = nfposi, nfnega = nfnega)
nfposi <- out$nfposi
nfnega <- out$nfnega
out$tab <- x_pca$tab
out$xy <- xy
rownames(out$xy) <- rownames(out$li)
colnames(out$xy) <- c("x","y")
out$lw <- resCN
dots <- list(...)
if (!is.null(dots$call)) {
out$call <- dots$call
} else {
out$call <- match.call()
}
posaxes <- if (nfposi > 0) {1:nfposi} else NULL
negaxes <- if (nfnega > 0) {(length(out$eig)-nfnega+1):length(out$eig)} else NULL
keptaxes <- c(posaxes, negaxes)
colnames(out$c1) <- paste("Axis",keptaxes)
colnames(out$li) <- paste("Axis",keptaxes)
colnames(out$ls) <- paste("Axis",keptaxes)
row.names(out$c1) <- colnames(x)
colnames(out$as) <- colnames(out$c1)
temp <- row.names(out$as)
row.names(out$as) <- paste("PCA", temp)
class(out) <- "spca"
return(out)
}
spca.data.frame <- function(x, xy = NULL, cn = NULL, matWeight = NULL,
center = TRUE, scale = FALSE, scannf = TRUE,
nfposi = 1, nfnega = 1,
type = NULL, ask = TRUE,
plot.nb = TRUE, edit.nb = FALSE,
truenames = TRUE,
d1 = NULL, d2 = NULL, k = NULL,
a = NULL, dmin = NULL, ...) {
call <- match.call()
spca(as.matrix(x), xy = xy, cn = cn, matWeight = matWeight, center = center,
cale = scale, scannf = scannf, nfposi = nfposi, nfnega = nfnega,
type = type, ask = ask, plot.nb = plot.nb, edit.nb = edit.nb,
truenames = truenames, d1 = d1, d2 = d2, k = k, a = a, dmin = dmin,
call = call, ...)
}
spca.genind <- function(obj, xy = NULL, cn = NULL, matWeight = NULL,
scale = FALSE, scannf = TRUE,
nfposi = 1, nfnega = 1,
type = NULL, ask = TRUE,
plot.nb = TRUE, edit.nb = FALSE,
truenames = TRUE,
d1 = NULL, d2 = NULL, k = NULL,
a = NULL, dmin = NULL, ...){
invisible(validObject(obj))
if(is.null(xy) & !is.null(obj$other$xy)) {
xy <- obj$other$xy
}
if(any(is.na(obj@tab))){
warning("NAs in data are automatically replaced (to mean allele frequency)")
}
X <- tab(obj, freq = TRUE, NA.method = "mean")
call <- match.call()
spca(X, xy = xy, cn = cn, matWeight = matWeight,
center = TRUE, scale = scale, scannf = scannf,
nfposi = nfposi, nfnega = nfnega,
type = type, ask = ask,
plot.nb = plot.nb, edit.nb = edit.nb,
truenames = truenames,
d1 = d1, d2 = d2, k = k,
a = a, dmin = dmin,
call = call, ...)
}
spca.genpop <- function(obj, xy = NULL, cn = NULL, matWeight = NULL,
scale = FALSE, scannf = TRUE,
nfposi = 1, nfnega = 1,
type = NULL, ask = TRUE,
plot.nb = TRUE, edit.nb = FALSE,
truenames = TRUE,
d1 = NULL, d2 = NULL, k = NULL,
a = NULL, dmin = NULL, ...){
invisible(validObject(obj))
if(is.null(xy) & !is.null(obj$other$xy)) {
xy <- obj$other$xy
}
if(any(is.na(obj@tab))){
warning("NAs in data are automatically replaced (to mean allele frequency)")
}
X <- tab(obj, freq = TRUE, NA.method = "mean")
call <- match.call()
spca(X, xy = xy, cn = cn, matWeight = matWeight,
center = TRUE, scale = scale, scannf = scannf,
nfposi = nfposi, nfnega = nfnega,
type = type, ask = ask,
plot.nb = plot.nb, edit.nb = edit.nb,
truenames = truenames,
d1 = d1, d2 = d2, k = k,
a = a, dmin = dmin,
call = call, ...)
}
print.spca <- function(x, ...){
cat("\t
cat("\t
cat("\t
cat("class: ")
cat(class(x))
cat("\n$call: ")
print(x$call)
cat("\n$nfposi:", x$nfposi, "axis-components saved")
cat("\n$nfnega:", x$nfnega, "axis-components saved")
cat("\nPositive eigenvalues: ")
l0 <- sum(x$eig >= 0)
cat(signif(x$eig, 4)[1:(min(5, l0))])
if (l0 > 5)
cat(" ...\n")
else cat("\n")
cat("Negative eigenvalues: ")
l0 <- sum(x$eig <= 0)
cat(sort(signif(x$eig, 4))[1:(min(5, l0))])
if (l0 > 5)
cat(" ...\n")
else cat("\n")
cat('\n')
sumry <- array("", c(1, 4), list(1, c("vector", "length",
"mode", "content")))
sumry[1, ] <- c('$eig', length(x$eig), mode(x$eig), 'eigenvalues')
class(sumry) <- "table"
print(sumry)
cat("\n")
sumry <- array("", c(5, 4),
list(1:5, c("data.frame", "nrow", "ncol", "content")))
sumry[1, ] <- c("$tab", nrow(x$tab), ncol(x$tab),
"transformed data: optionally centred / scaled")
sumry[2, ] <- c("$c1", nrow(x$c1), ncol(x$c1),
"principal axes: scaled vectors of alleles loadings")
sumry[3, ] <- c("$li", nrow(x$li), ncol(x$li),
"principal components: coordinates of entities ('scores')")
sumry[4, ] <- c("$ls", nrow(x$ls), ncol(x$ls),
"lag vector of principal components")
sumry[5, ] <- c("$as", nrow(x$as), ncol(x$as),
"pca axes onto spca axes")
class(sumry) <- "table"
print(sumry)
cat("\n$xy: matrix of spatial coordinates")
cat("\n$lw: a list of spatial weights (class 'listw')")
cat("\n\nother elements: ")
if (length(names(x)) > 10)
cat(names(x)[11:(length(names(x)))], "\n")
else cat("NULL\n")
}
summary.spca <- function (object, ..., printres=TRUE) {
if (!inherits(object, "spca"))stop("to be used with 'spca' object")
norm.w <- function(X, w) {
f2 <- function(v) sum(v * v * w)/sum(w)
norm <- apply(X, 2, f2)
return(norm)
}
resfin <- list()
if(printres) {
cat("\nSpatial principal component analysis\n")
cat("\nCall: ")
print(object$call)
}
appel <- as.list(object$call)
obj <- eval(appel$obj)
if(is.null(appel$truenames)) appel$truenames <- FALSE
f1 <- function(vec){
m <- mean(vec,na.rm=TRUE)
vec[is.na(vec)] <- m
return(vec)
}
if(is.genind(obj)) { X <- obj@tab }
if(is.genpop(obj)) { X <- makefreq(obj, quiet=TRUE) }
X <- apply(X,2,f1)
nfposi <- object$nfposi
nfnega <- object$nfnega
dudi <- dudi.pca(X, center=TRUE, scale=FALSE, scannf=FALSE, nf=nfposi+nfnega)
lw <- object$lw
n <- nrow(X)
I0 <- -1/(n-1)
L <- spdep::listw2mat(lw)
eigL <- suppressWarnings(as.numeric(eigen(0.5*(L+t(L)))$values))
Imin <- min(eigL)
Imax <- max(eigL)
Ival <- data.frame(I0=I0,Imin=Imin,Imax=Imax)
row.names(Ival) <- ""
if(printres) {
cat("\nConnection network statistics:\n")
print(Ival)
}
Istat <- c(I0,Imin,Imax)
names(Istat) <- c("I0","Imin","Imax")
resfin$Istat <- Istat
nf <- dudi$nf
eig <- dudi$eig[1:nf]
cum <- cumsum(dudi$eig)[1:nf]
ratio <- cum/sum(dudi$eig)
w <- apply(dudi$l1,2,spdep::lag.listw,x=lw)
moran <- apply(w*as.matrix(dudi$l1)*dudi$lw,2,sum)
res <- data.frame(var=eig,cum=cum,ratio=ratio, moran=moran)
row.names(res) <- paste("Axis",1:nf)
if(printres) {
cat("\nScores from the centred PCA\n")
print(res)
}
resfin$pca <- res
eig <- object$eig
nfposimax <- sum(eig > 0)
nfnegamax <- sum(eig < 0)
ms <- adespatial::multispati(dudi=dudi, listw=lw, scannf=FALSE,
nfposi=nfposimax, nfnega=nfnegamax)
ndim <- dudi$rank
nf <- nfposi + nfnega
agarder <- c(1:nfposi,if (nfnega>0) (ndim-nfnega+1):ndim)
varspa <- norm.w(ms$li,dudi$lw)
moran <- apply(as.matrix(ms$li)*as.matrix(ms$ls)*dudi$lw,2,sum)
res <- data.frame(eig=eig,var=varspa,moran=moran/varspa)
row.names(res) <- paste("Axis",1:length(eig))
if(printres) {
cat("\nsPCA eigenvalues decomposition:\n")
print(res[agarder,])
}
resfin$spca <- res
return(invisible(resfin))
}
plot.spca <- function (x, axis = 1, useLag=FALSE, ...){
if (!inherits(x, "spca")) stop("Use only with 'spca' objects.")
if(axis>ncol(x$li)) stop("wrong axis required.")
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(mar = rep(.1,4), mfrow=c(3,2))
n <- nrow(x$li)
xy <- x$xy
if(useLag){
z <- x$ls[,axis]
} else {
z <- x$li[,axis]
}
nfposi <- x$nfposi
nfnega <- x$nfnega
nLinks <- sum(spdep::card(x$lw$neighbours))
if(nLinks < 500) {
neig <- nb2neig(x$lw$neighbours)
} else {
neig <- NULL
}
sub <- paste("Score",axis)
csub <- 2
if(n<30) clab <- 1 else clab <- 0
s.label(xy, clabel=clab, include.origin=FALSE, addaxes=FALSE, neig=neig,
cneig=1, sub="Connection network", csub=2)
s.image(xy,z, include.origin=FALSE, grid=TRUE, kgrid=10, cgrid=1,
sub=sub, csub=csub, possub="bottomleft")
box()
if(n<30) {neig <- nb2neig(x$lw$neighbours)} else {neig <- NULL}
s.value(xy,z, include.origin=FALSE, addaxes=FALSE, clegend=0, csize=.6,
neig=neig, sub=sub, csub=csub, possub="bottomleft")
s.value(xy,z, include.origin=FALSE, addaxes=FALSE, clegend=0, csize=.6,
method="greylevel", neig=neig, sub=sub, csub=csub, possub="bottomleft")
omar <- par("mar")
par(mar = c(0.8, 2.8, 0.8, 0.8))
m <- length(x$eig)
col.w <- rep("white", m)
col.w[1:nfposi] <- "grey"
if (nfnega>0) {col.w[m:(m-nfnega+1)] <- "grey"}
j <- axis
if (j>nfposi) {j <- j-nfposi +m -nfnega}
col.w[j] <- "black"
barplot(x$eig, col = col.w)
scatterutil.sub(cha ="Eigenvalues", csub = 2.5, possub = "topright")
par(mar=rep(.1,4))
box()
par(mar=omar)
par(mar=c(4,4,2,1))
screeplot(x,main="Eigenvalues decomposition")
par(mar=rep(.1,4))
box()
return(invisible(match.call()))
}
screeplot.spca <- function(x,...,main=NULL){
opar <- par("las")
on.exit(par(las=opar))
sumry <- summary(x,printres=FALSE)
labels <- lapply(1:length(x$eig),function(i) bquote(lambda[.(i)]))
par(las=1)
xmax <- sumry$pca[1,1]*1.1
I0 <- sumry$Istat[1]
Imin <- sumry$Istat[2]
Imax <- sumry$Istat[3]
plot(x=sumry$spca[,2],y=sumry$spca[,3],type='n',xlab='Variance',ylab="Spatial autocorrelation (I)",xlim=c(0,xmax),ylim=c(Imin*1.1,Imax*1.1),yaxt='n',...)
text(x=sumry$spca[,2],y=sumry$spca[,3],do.call(expression,labels))
ytick <- c(I0,round(seq(Imin,Imax,le=5),1))
ytlab <- as.character(round(seq(Imin,Imax,le=5),1))
ytlab <- c(as.character(round(I0,1)),as.character(round(Imin,1)),ytlab[2:4],as.character(round(Imax,1)))
axis(side=2,at=ytick,labels=ytlab)
rect(0,Imin,xmax,Imax,lty=2)
segments(0,I0,xmax,I0,lty=2)
abline(v=0)
if(is.null(main)) main <- ("Spatial and variance components of the eigenvalues")
title(main)
return(invisible(match.call()))
}
colorplot.spca <- function(x, axes=1:ncol(x$li), useLag=FALSE, ...){
if(!any(inherits(x,"spca"))) stop("x in not a spca object.")
xy <- x$xy
if(useLag) {
X <- as.matrix(x$ls)
} else {
X <- as.matrix(x$li)
}
colorplot(xy, X, axes, ...)
} |
source("ESEUR_config.r")
library("plyr")
runtime=read.csv(paste0(ESEUR_dir, "benchmark/runtime-powerperf.csv.xz"), as.is=TRUE)
C1T=subset(runtime, CMPxSMT == "2C1T")
SPEC_ind=grepl("^X4", names(C1T))
Core_2D_45=subset(C1T, Processor == "Core 2D (45)")
arith_geo_mean=function(freq)
{
F_1603=subset(Core_2D_45, Frequency == freq)
SPEC_perf=t(F_1603[, -(1:4)])
return(c(mean(SPEC_perf), exp(mean(log(SPEC_perf)))))
}
perf_base=arith_geo_mean(1603)
perf_24=arith_geo_mean(2403)
perf_30=arith_geo_mean(3066)
perf_base/perf_24
perf_base/perf_30
base_ratio=function(freq)
{
F_1603=subset(Core_2D_45, Frequency == 1603)
F_freq=subset(Core_2D_45, Frequency == freq)
SPEC_F=t(F_1603[, -(1:4)])
SPEC_freq=t(F_freq[, -(1:4)])
return(mean(SPEC_F/SPEC_freq))
}
ratio_24=base_ratio(2403)
ratio_30=base_ratio(3066)
ratio_24
ratio_30 |
strwrap_ctl <- function(
x, width = 0.9 * getOption("width"), indent = 0,
exdent = 0, prefix = "", simplify = TRUE, initial = prefix,
warn=getOption('fansi.warn', TRUE),
term.cap=getOption('fansi.term.cap', dflt_term_cap()),
ctl='all', normalize=getOption('fansi.normalize', FALSE),
carry=getOption('fansi.carry', FALSE),
terminate=getOption('fansi.terminate', TRUE)
) {
strwrap2_ctl(
x=x, width=width, indent=indent,
exdent=exdent, prefix=prefix, simplify=simplify, initial=initial,
warn=warn, term.cap=term.cap, ctl=ctl, normalize=normalize,
carry=carry, terminate=terminate
)
}
strwrap2_ctl <- function(
x, width = 0.9 * getOption("width"), indent = 0,
exdent = 0, prefix = "", simplify = TRUE, initial = prefix,
wrap.always=FALSE, pad.end="",
strip.spaces=!tabs.as.spaces,
tabs.as.spaces=getOption('fansi.tabs.as.spaces', FALSE),
tab.stops=getOption('fansi.tab.stops', 8L),
warn=getOption('fansi.warn', TRUE),
term.cap=getOption('fansi.term.cap', dflt_term_cap()),
ctl='all', normalize=getOption('fansi.normalize', FALSE),
carry=getOption('fansi.carry', FALSE),
terminate=getOption('fansi.terminate', TRUE)
) {
if(!is.logical(wrap.always)) wrap.always <- as.logical(wrap.always)
if(length(wrap.always) != 1L || is.na(wrap.always))
stop("Argument `wrap.always` must be TRUE or FALSE.")
if(!is.logical(tabs.as.spaces)) tabs.as.spaces <- as.logical(tabs.as.spaces)
if(wrap.always && width < 2L)
stop("Width must be at least 2 in `wrap.always` mode.")
VAL_IN_ENV (
x=x, warn=warn, term.cap=term.cap, ctl=ctl, normalize=normalize,
carry=carry, terminate=terminate, tab.stops=tab.stops,
tabs.as.spaces=tabs.as.spaces, strip.spaces=strip.spaces
)
if(tabs.as.spaces && strip.spaces)
stop("`tabs.as.spaces` and `strip.spaces` should not both be TRUE.")
VAL_WRAP_IN_ENV(width, indent, exdent, prefix, initial, pad.end)
res <- .Call(
FANSI_strwrap_csi,
x, width,
indent, exdent,
prefix, initial,
wrap.always, pad.end,
strip.spaces,
tabs.as.spaces, tab.stops,
WARN.INT, TERM.CAP.INT,
FALSE,
CTL.INT, normalize,
carry, terminate
)
if(simplify) {
if(normalize) normalize_state(unlist(res), warn=FALSE, term.cap)
else unlist(res)
} else {
if(normalize) normalize_state_list(res, 0L, TERM.CAP.INT, carry=carry)
else res
}
}
strwrap_sgr <- function(
x, width = 0.9 * getOption("width"), indent = 0,
exdent = 0, prefix = "", simplify = TRUE, initial = prefix,
warn=getOption('fansi.warn', TRUE),
term.cap=getOption('fansi.term.cap', dflt_term_cap()),
normalize=getOption('fansi.normalize', FALSE),
carry=getOption('fansi.carry', FALSE),
terminate=getOption('fansi.terminate', TRUE)
)
strwrap_ctl(
x=x, width=width, indent=indent,
exdent=exdent, prefix=prefix, simplify=simplify, initial=initial,
warn=warn, term.cap=term.cap, ctl='sgr', normalize=normalize,
carry=carry, terminate=terminate
)
strwrap2_sgr <- function(
x, width = 0.9 * getOption("width"), indent = 0,
exdent = 0, prefix = "", simplify = TRUE, initial = prefix,
wrap.always=FALSE, pad.end="",
strip.spaces=!tabs.as.spaces,
tabs.as.spaces=getOption('fansi.tabs.as.spaces', FALSE),
tab.stops=getOption('fansi.tab.stops', 8L),
warn=getOption('fansi.warn', TRUE),
term.cap=getOption('fansi.term.cap', dflt_term_cap()),
normalize=getOption('fansi.normalize', FALSE),
carry=getOption('fansi.carry', FALSE),
terminate=getOption('fansi.terminate', TRUE)
)
strwrap2_ctl(
x=x, width=width, indent=indent,
exdent=exdent, prefix=prefix, simplify=simplify, initial=initial,
wrap.always=wrap.always, pad.end=pad.end,
strip.spaces=strip.spaces,
tabs.as.spaces=tabs.as.spaces,
tab.stops=tab.stops,
warn=warn, term.cap=term.cap, ctl='sgr', normalize=normalize,
carry=carry, terminate=terminate
)
VAL_WRAP_IN_ENV <- function(
width, indent, exdent, prefix, initial, pad.end
) {
call <- sys.call(-1)
env <- parent.frame()
stop2 <- function(x) stop(simpleError(x, call))
is_scl_int_pos <- function(x, name, strict=FALSE) {
x <- as.integer(x)
if(
!is.numeric(x) || length(x) != 1L || is.na(x) ||
if(strict) x <= 0 else x < 0
)
stop2(
sprintf(
"Argument `%s` %s.", name,
"must be a positive scalar numeric representable as integer"
) )
x
}
exdent <- is_scl_int_pos(exdent, 'exdent', strict=FALSE)
indent <- is_scl_int_pos(indent, 'indent', strict=FALSE)
if(is.numeric(width))
width <- as.integer(min(c(max(c(min(width), 2L)), .Machine$integer.max)))
else stop2("Argument `width` must be numeric.")
width <- is_scl_int_pos(width, 'width', strict=TRUE)
width <- width - 1L
if(!is.character(prefix)) prefix <- as.character(prefix)
if(length(prefix) != 1L)
stop2("Argument `prefix` must be a scalar character.")
prefix <- enc_to_utf8(prefix)
if(Encoding(prefix) == "bytes")
stop2("Argument `prefix` cannot be \"bytes\" encoded.")
if(!is.character(initial)) initial <- as.character(initial)
if(length(initial) != 1L)
stop2("Argument `initial` must be a scalar character.")
initial <- enc_to_utf8(initial)
if(Encoding(initial) == "bytes")
stop2("Argument `initial` cannot be \"bytes\" encoded.")
if(!is.character(pad.end)) pad.end <- as.character(pad.end)
if(length(pad.end) != 1L)
stop2("Argument `pad.end` must be a scalar character.")
pad.end <- enc_to_utf8(pad.end)
if(Encoding(pad.end) == "bytes")
stop2("Argument `pad.end` cannot be \"bytes\" encoded.")
if(nchar(pad.end, type='bytes') > 1L)
stop2("Argument `pad.end` must be at most one byte long.")
list2env(
list(
width=width, indent=indent, exdent=exdent, prefix=prefix, initial=initial,
pad.end=pad.end
),
env
)
} |
identifyCoeffs <-
function(fixed, data, random,
XmaxIter=1000,
XmsMaxIter=1000,
Xtolerance=.01,
XniterEM=1000,
XmsMaxEval=400,
XmsTol=.00001,
Xopt='optim',
diagnose=FALSE, verbose=TRUE)
{
MC <- match.call()
if(verbose) {
print("", quote = FALSE)
print("Running identifyCoeffs", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
print("Call:", quote = FALSE)
print(MC)
print("", quote = FALSE)
}
newcontrol <- nlme::lmeControl(maxIter=XmaxIter, msMaxIter=XmsMaxIter, tolerance=Xtolerance,
niterEM=XniterEM, msMaxEval=XmsMaxEval, msTol=XmsTol, opt=Xopt)
newcontrol <<- newcontrol
zzzz <- data
zzzz <<- zzzz
on.exit(rm(zzzz, pos=1))
on.exit(rm(newcontrol, pos=1))
lmerun <- nlme::lme(fixed,data,random, control=newcontrol)
coeffs <- lmerun$coefficients
fixd <- coeffs[[1]]
rndm <- coeffs[[2]]
print("Typical fixed coefficient estimates from a run of lme( ) on fixdat", quote=FALSE)
print(fixd)
print("", quote = FALSE)
print("", quote = FALSE)
print("Typical random coefficient estimates from a run of lme( ) on fixdat", quote=FALSE)
print(rndm)
print("", quote = FALSE)
dimsN <- lmerun$dims$N
dimsQ <- lmerun$dims$Q
IDs <- NULL
for(jjj in 1:dimsQ){
IDs1 <- dimnames(rndm[[jjj]])[[1]]
IDs2 <- dimnames(rndm[[jjj]])[[2]]
IDs <- c(IDs, paste(rep(IDs1,times=length(IDs2)), rep(IDs2,each =length(IDs1)),sep="--"))
IDs <- c(IDs)
}
vectfixd <- 1:length(fixd)
names(vectfixd) <- names(fixd)
uu <- unlist(rndm)
vectrandm <- (length(fixd) + 1):(length(fixd)+length(uu))
names(vectrandm) <- IDs
vectrandm <- as.matrix(vectrandm, col=1)
print("When only a few coefficients can be graphed, specify them using the following codes:", quote=FALSE)
print("", quote = FALSE)
print("Fixed coefficient estimates", quote=FALSE)
print(vectfixd, quote = FALSE)
print("", quote = FALSE)
print("", quote = FALSE)
print("Random coefficient estimates", quote=FALSE)
print(vectrandm)
print("", quote = FALSE)
if(verbose) {
print("", quote = FALSE)
print("Finished running identifyCoeffs", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
}
list("Fixed coefficients"=fixd, "Complete random coefficients"=rndm, "Use these random codes"=vectrandm)
} |
order_neighborhood <- function(bigZ, B, V, Vt, constraint)
{
assertthat::assert_that(
nrow(bigZ) == ncol(B) + 1,
ncol(bigZ) == nrow(B))
if (is.null(V))
{
sel.indx <- t(apply(bigZ,
MARGIN = 2,
FUN = function (X) {
unlist(as.matrix(sort.int(X,
index.return = TRUE))[2])}))
}
else
{
bigV <- t(cbind(matrix(V$v[B],
dim(B)),
Vt$v))
opname <- paste0("constraint_", constraint$name)
ord.args <- constraint
ord.args$name <- NULL
ord.args$B <- B
ord.args$bigZ <- bigZ
ord.args$bigV <- bigV
ord.args$V <- V$v
ord.args$Vt <- Vt$v
sel.indx <- do.call(opname,
args = ord.args)
}
return(sel.indx)
} |
context("detect and convert crs") |
exp1st <- function(alpha,tol,itmax,n,eps) {
ny <- 2*n
err1 <- -alpha
c1 <- 1.0
while (err1 < 0)
{ c1 <- c1 -0.05
h <- alpha + pchisq(ny*c1/(1+eps),ny)
c2 <- qchisq(h,ny) * (1+eps)/ny
err1 <- pchisq(ny*(1+eps)*c2,ny) - pchisq(ny*(1+eps)*c1,ny) - alpha
}
c1L <- c1
c1R <- c1 + 0.05
it <- 0
while (abs(err1) >= tol && it <= itmax)
{ it <- it + 1
c1 <- (c1L+c1R) / 2
h <- alpha + pchisq(ny*c1/(1+eps),ny)
c2 <- qchisq(h,ny) * (1+eps)/ny
err1 <- pchisq(ny*(1+eps)*c2,ny) - pchisq(ny*(1+eps)*c1,ny) - alpha
if (err1 <= 0)
c1R <- c1 else
c1L <- c1
}
pow0 <- pchisq(ny*c2,ny) - pchisq(ny*c1,ny)
c1 <- n*c1
c2 <- n*c2
cat(" ALPHA =",alpha," TOL =",tol," ITMAX =",itmax," N =",n," EPS =",eps,
" IT =",it,"\n","C1 =",c1," C2 =",c2," ERR1 =",err1," POW0 =",pow0)
} |
boundaryweight_fct_2p3p<- function(formula, model.object, data_select_from, boundary_weights){
formula_plus_boundary.weight <- as.formula(paste(paste(all.vars(formula)[1],"~"), paste(c(attr(terms(model.object),"term.labels"), boundary_weights), collapse= "+")))
design_matrix<- design_matrix.s1_return(formula=formula_plus_boundary.weight, data=data_select_from)
Z1_bar_weighted<- apply(design_matrix, 2, weighted.mean, w=design_matrix[,boundary_weights])
Z1_bar_weighted[- which(names(Z1_bar_weighted) %in% boundary_weights)]
} |
test.ezsim <-
function(x,return_name=TRUE,print_result=FALSE,...){
parameter_list <- generate(x$parameter_def)
create_cluster_flag <- FALSE
if (x$use_core > 1 & is.null(x$cluster) ){
x$cluster <- makeCluster(x$use_core)
if (!is.null(x$cluster_packages)){
for (i in 1:length(x$cluster_packages))
eval(substitute(
clusterEvalQ(x$cluster , require(w, character.only=TRUE) ) ,
list( w=x$cluster_packages[i] )
))
}
clusterSetRNGStream(x$cluster,x$use_seed)
create_cluster_flag<-TRUE
}
if (x$use_core == 1)
set.seed(x$use_seed)
i=NULL
tryCatch({
cat("Testing for estimator...")
compute_estimates <- function(i,ezsim_object) {
ezsim_object$estimator(Jmisc::evalFunctionOnList(ezsim_object$dgp,i))
}
test_estimates<-
if (!is.null(x$cluster)){
parLapply(x$cluster,parameter_list,fun=compute_estimates,ezsim_object=x)
} else{
lapply(parameter_list,FUN=compute_estimates,ezsim_object=x)
}
cat("Passed\n")
cat("Testing for estimator parser...")
test_estimates_parsed<-
foreach( i = test_estimates ) %do%{
x$estimator_parser(i)
}
if (any(!sapply(test_estimates_parsed,is.vector)))
stop("estimator parser do not return a vector")
length_estimates<-sapply(test_estimates_parsed,length)
if (!all(length_estimates==length_estimates[[1]]))
stop("length of estimates are not the same")
cat("Passed\n")
cat("Testing for true value...")
if (is.function(x$true_value)){
compute_true_value <- function(i,ezsim_object) {
Jmisc::evalFunctionOnList(ezsim_object$true_value,i)
}
test_true_value<-
if (!is.null(x$cluster)){
parLapply(x$cluster,parameter_list,fun=compute_true_value,ezsim_object=x)
} else{
lapply(parameter_list,FUN=compute_true_value,ezsim_object=x)
}
length_true_value<-sapply(test_true_value,length)
if (!all(length_true_value==length_true_value[[1]]))
stop("length of true value are not the same")
if (length_true_value[[1]]!=length_estimates[[1]])
stop("length of true value and estimates are not the same")
}
cat("Passed\n")
}, finally = {
if (create_cluster_flag){
tryCatch({
stopCluster(x$cluster)
}, finally = {
x$cluster<-NULL
})
}
})
} |
context("Kantorovich distance")
test_that("Main example - numeric mode", {
mu <- c(1/7, 2/7, 4/7)
nu <- c(1/4, 1/4, 1/2)
x <- kantorovich(mu, nu)
expect_equal(x, 0.107142857142857)
mu <- setNames(mu, c("a","b","c"))
nu <- setNames(nu, c("a","b","c"))
x <- kantorovich(mu, nu)
expect_equal(x, 0.107142857142857)
mu <- setNames(mu, c("a","b","c"))
nu <- c(c=1/2, a=1/4, b=1/4)
x <- kantorovich(mu, nu)
expect_equal(x, 0.107142857142857)
mu <- setNames(c(1/7, 2/7, 4/7), c("a","b","c"))
nu <- setNames(c(1/4, 1/4, 1/2), c("a","b","c"))
M <- matrix(1, nrow=3, ncol=3) - diag(3)
expect_error(kantorovich(mu, nu, dist=M))
rownames(M) <- colnames(M) <- c("a","b","c")
x <- kantorovich(mu, nu, dist=M)
expect_equal(x, 0.107142857142857)
mu <- c(1/7, 2/7, 4/7)
nu <- c(1/4, 1/4, 1/2)
x <- kantorovich(mu, nu, details=TRUE)
bestj <- attr(x, "joinings")
expect_equal(length(bestj), 1)
expect_equal(bestj[[1]], structure(c(0.142857142857143, 0.0357142857142857, 0.0714285714285714,
0, 0.25, 0, 0, 0, 0.5), .Dim = c(3L, 3L), .Dimnames = list(c("1",
"2", "3"), c("1", "2", "3")))
)
})
test_that("Main example - bigq mode", {
mu <- as.bigq(c(1,2,4), 7)
nu <- as.bigq(c(1,1,1), c(4,4,2))
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
mu <- setNames(as.bigq(c(1,2,4), 7), c("a","b","c"))
nu <- setNames(as.bigq(c(1,1,1), c(4,4,2)), c("a","b","c"))
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
mu <- setNames(as.bigq(c(1,2,4), 7), c("a","b","c"))
nu <- setNames(as.bigq(c(1,1,1), c(2,4,4)), c("c","a","b"))
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
x <- kantorovich(mu, nu, details=TRUE)
bestj <- attr(x, "joinings")
expect_equal(length(bestj), 1)
expect_equal(bestj[[1]], structure(c("1/7", "1/28", "1/14", "0", "1/4", "0", "0", "0", "1/2"),
.Dim = c(3L, 3L),
.Dimnames = list(c("a", "b", "c"), c("a", "b", "c")))
)
bestj_num <- attr(kantorovich(as.numeric(mu), as.numeric(nu)[c(2,3,1)], details=TRUE), "joinings")[[1]]
expect_equal(as.numeric(as.bigq(bestj[[1]])), as.vector(bestj_num))
})
test_that("Main example - character mode", {
mu <- c("1/7", "2/7", "4/7")
nu <- c("1/4", "1/4", "1/2")
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
mu <- setNames(c("1/7", "2/7", "4/7"), c("a","b","c"))
nu <- setNames(c("1/4", "1/4", "1/2"), c("a","b","c"))
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
mu <- setNames(c("1/7", "2/7", "4/7"), c("a","b","c"))
nu <- setNames(c("1/2", "1/4", "1/4"), c("c","a","b"))
x <- kantorovich(mu, nu)
expect_true(x==as.bigq(3,28))
x <- kantorovich(mu, nu, details=TRUE)
bestj <- attr(x, "joinings")
expect_equal(length(bestj), 1)
expect_equal(bestj[[1]], structure(c("1/7", "1/28", "1/14", "0", "1/4", "0", "0", "0", "1/2"),
.Dim = c(3L, 3L),
.Dimnames = list(c("a", "b", "c"), c("a", "b", "c")))
)
bestj_bigq <- attr(kantorovich(as.bigq(mu), as.bigq(nu)[c(2,3,1)], details=TRUE), "joinings")[[1]]
expect_equal(as.numeric(as.bigq(bestj[[1]])), as.numeric(as.bigq(bestj_bigq)))
expect_equal(rownames(bestj[[1]]), names(mu))
expect_false(all(colnames(bestj[[1]])==names(nu)))
})
test_that("Non-square example - numeric mode", {
mu <- c(2/5,3/5)
nu <- c(1/4,1/4,1/4,1/4)
x <- kantorovich(mu, nu)
expect_equal(x, 0.5)
mu <- setNames(mu, c("a","b"))
nu <- setNames(nu, c("a","b","c","d"))
x <- kantorovich(mu, nu)
expect_equal(x, 0.5)
mu <- setNames(mu, c("b","a"))
x <- kantorovich(mu, nu)
expect_equal(x, 0.5)
mu <- setNames(c(2/5,3/5), c("a","b"))
nu <- setNames(c(1/4,1/4,1/4,1/4), c("a","b","c","d"))
M <- matrix(1, nrow=4, ncol=4) - diag(4)
rownames(M) <- c("a","b","c","d"); colnames(M) <- names(nu)
x <- kantorovich(mu, nu)
expect_equal(x, 0.5)
})
test_that("Non-square example - bigq mode", {
mu <- as.bigq(c(2/5,3/5))
nu <- as.bigq(c(1/4,1/4,1/4,1/4))
x <- kantorovich(mu, nu)
expect_identical(x, as.bigq(0.5))
mu <- setNames(mu, c("a","b"))
nu <- setNames(nu, c("a","b","c","d"))
x <- kantorovich(mu, nu)
expect_identical(x, as.bigq(0.5))
mu <- setNames(mu, c("b","a"))
x <- kantorovich(mu, nu)
expect_identical(x, as.bigq(0.5))
}) |
nlists <- function(...) {
args <- list(...)
if (length(args)) {
return(as_nlists(args))
}
structure(list(), class = "nlists")
} |
module_convert_to_table <- function(MEGENA.output,mod.pval = 0.05,hub.pval = 0.05,min.size = 10,max.size)
{
summary.output <- MEGENA.ModuleSummary(MEGENA.output,mod.pvalue = mod.pval,hub.pvalue = hub.pval,
min.size = min.size,max.size = max.size,annot.table = NULL,symbol.col = NULL,id.col = NULL,
output.sig = TRUE)
modules <- summary.output$modules
is.annted <- any(sapply(modules,function(x) length(grep("\\|",x)) > 0))
df <- mapply(FUN = function(x,y) data.frame(id = x,module = rep(y,length(x))),x = modules,y = as.list(names(modules)),SIMPLIFY = FALSE)
df <- do.call('rbind.data.frame',df)
if (is.annted)
{
df <- data.frame(id = df[[1]],gene.symbol = gsub("\\|(.*)","",as.character(df[[1]])),gene.symbol2 = gsub("^(.*)\\|","",as.character(df[[1]])),
module = df[[2]])
}
if (!is.null(summary.output$module.table))
{
modtbl <- summary.output$module.table
df <- cbind.data.frame(df[,-ncol(df)],module.parent = modtbl$module.parent[match(df$module,modtbl$module.id)],module = df[[ncol(df)]])
rm(modtbl)
colnames(df)[1] <- "id"
}
if (!is.null(MEGENA.output$node.summary))
{
colnames(df)[1] <- "id"
hubs <- lapply(MEGENA.output$hub.output$module.degreeStat,function(x,hp) as.character(x[[1]])[which(x$pvalue < hp)],hp = hub.pval)
hvec <- rep(NA,nrow(df))
for (j in 1:length(hubs)) hvec[which(df[[1]] %in% hubs[[j]] & df$module == names(hubs)[j])] <- "hub"
df <- cbind.data.frame(df[,-ncol(df)],node.degree = MEGENA.output$node.summary$node.degree[match(df$id,MEGENA.output$node.summary$id)],
node.strength = MEGENA.output$node.summary$node.strength[match(df$id,MEGENA.output$node.summary$id)],is.hub = hvec,
module = df[[ncol(df)]]);
rm(MEGENA.output,summary.output)
}
rownames(df) <- NULL
return(df)
}
module_rank=function(X){
X=as.matrix(X)
G=apply(X,2,function(y) {z=rank(y);M=max(z);(M+1-z)/M} )
apply(G,1,function(x) sum(log(x)))
}
flatten.table <- function(master.table,factor.col,out.cols)
{
if (length(factor.col) == 1)
{
factor.vec <- factor(master.table[[factor.col]])
}else{
factor.vec <- factor(apply(do.call(cbind,lapply(master.table[factor.col],as.character)),1,function(x) paste(x,collapse = "~")))
}
split.table <- lapply(split(1:nrow(master.table),factor.vec),function(ii,m) m[ii,],m = master.table)
common.id <- Reduce("union",lapply(split.table,function(x) as.character(x[[1]])))
big.table <- list()
for (out.col in out.cols)
{
aligned.table <- do.call(cbind,lapply(split.table,function(tbl,id,out.col) {
vec <- rep(NA,length(id));names(vec) <- id;
if (is.numeric(tbl[[out.col]])) vec[as.character(tbl[[1]])] <- as.numeric(tbl[[out.col]])
if (is.factor(tbl[[out.col]])) vec[as.character(tbl[[1]])] <- as.character(tbl[[out.col]])
return(vec)
},id = common.id,out.col = out.col))
colnames(aligned.table) <- paste(names(master.table)[out.col],colnames(aligned.table),sep = "__")
big.table <- c(big.table,list(aligned.table))
}
big.table <- data.frame(module = common.id,do.call(cbind.data.frame,big.table))
return(big.table)
}
combine.table <- function(abl,bbl)
{
common.id <- union(as.character(abl[[1]]),as.character(bbl[[1]]))
abl.align <- do.call(cbind,lapply(abl[2:ncol(abl)],function(x,y,z) {
names(x) <- z;
vec <- rep(NA,length(y));names(vec) <- y;
if (is.numeric(x)) {vec[match(names(x),names(vec))] <- x;}else{
vec[match(names(x),names(vec))] <- as.character(x);}
return(vec)
},y = common.id,z = as.character(abl[[1]])))
bbl.align <- do.call(cbind,lapply(bbl[2:ncol(bbl)],function(x,y,z) {
names(x) <- z;
vec <- rep(NA,length(y));names(vec) <- y;
if (is.numeric(x)) {vec[match(names(x),names(vec))] <- x;}else{
vec[match(names(x),names(vec))] <- as.character(x);}
return(vec)
},y = common.id,z = as.character(bbl[[1]])))
out <- cbind.data.frame(data.frame(id = common.id),abl.align,bbl.align)
return(out)
}
coerce.manyTables <- function(table.lst)
{
if (length(table.lst) > 1)
{
out.table <- table.lst[[1]]
for (i in 2:length(table.lst))
{
out.table <- combine.table(out.table,table.lst[[i]])
}
}else{
out.table <- table.lst[[1]];
}
return(out.table)
} |
rrf.opt.1 <- function(X.train, Y.train, X.test=NULL, Y.test=NULL, pwr, weight, iter=1,total=10, cutoff=0.5) {
surrogate <- min(weight[which(weight>0)])*0.1;
weight[which(weight==0)] <- surrogate;
coefReg <- weight^pwr;
coefReg <- coefReg/max(coefReg);
feature.rrf <- select.stable(X.train, Y.train, coefReg, total, cutoff)
n <- length(Y.train);
m <- length(feature.rrf);
aic <- c();
auc <- c();
auc.test <- c();
if(length(feature.rrf) >= 1) {
for(i in 1:iter) {
model.rrf_rf <- randomForest(X.train[, feature.rrf], Y.train)
if(class(Y.train) == 'factor') {
p1 <- model.rrf_rf$votes[,2]
pred <- data.frame(response=Y.train, pred=p1);
roc <- roc.curve(pred[which(pred$response==1), 'pred'], pred[which(pred$response==0), 'pred'])
auc <- c(auc, roc$auc);
p1 <- sapply(p1, function(x) ifelse(x==0, 1/(2*n), ifelse(x==1, 1-1/(2*n), x)))
y <- data.frame(p1=p1, class=as.numeric(as.character(Y.train)));
lh <- sum(y$class*log(y$p1) + (1-y$class)*log(1-y$p1), na.rm=F);
aic <- c(aic, 2*m - 2*lh);
if(!is.null(X.test)){
pred.test <- predict(model.rrf_rf, X.test[, feature.rrf], type='prob')
pred.test <- data.frame(response=Y.test, pred=pred.test[, 2]);
roc.test <- roc.curve(pred.test[which(pred.test$response==1), 'pred'], pred.test[which(pred.test$response==0), 'pred'])
auc.test <- c(auc.test, roc.test$auc);
}
} else {
mse <- mean((model.rrf_rf$predicted - Y.train)^2);
aic <- c(aic, 2*m + n*log(mse));
auc <- NA
auc.test <- NA
}
}
cat('par ', pwr, ' ... number of features ', m, ' ... aic ', mean(aic), ' ... auc ', mean(auc), ' ... auc.test ', mean(auc.test), '...\n');flush.console();
return(list(AIC=aic, AUC=auc, Test.AUC=auc.test, feaSet=feature.rrf));
} else {
return("No feature is selected");
}
} |
.simd <- function(dat,mod,...,.p,.dry) {
if(!inherits(mod, "packmod")) loadso(mod)
if(.dry) {
return(dat)
} else {
return(.p(mrgsim_d(mod,dat,...,output="df"),mod))
}
}
future_mrgsim_d <- function(mod, data, nchunk = 4, ..., .as_list = FALSE,
.p = NULL, .dry = FALSE, .seed = TRUE,
.parallel = TRUE) {
if(!inherits(data,"list")) data <- chunk_by_id(data,nchunk)
pa <- "mrgsolve"
if(!is.function(.p)) .p <- .nothing
if((length(data)==1)) {
return(.simd(data[[1]],mod,...,.p=.p,.dry=.dry))
}
if(isTRUE(.parallel)) {
ans <- future_lapply(
X = data,
future.packages = pa,
future.globals = character(0),
future.seed = .seed,
mod = mod,
.p = .p,
.dry = .dry,
FUN = .simd,
...
)
} else {
ans <- lapply(X = data, mod = mod, .p = .p, .dry = .dry, FUN = .simd,...)
}
if(.as_list) return(ans)
return(bind_rows(ans))
}
mc_mrgsim_d <- function(mod, data, nchunk = 4, ..., .as_list = FALSE,
.p = NULL, .dry = FALSE, .seed = NULL,
.parallel = TRUE) {
if(!inherits(data,"list")) data <- chunk_by_id(data,nchunk)
if(!is.function(.p)) .p <- .nothing
if((length(data)==1)) {
return(.simd(data[[1]],mod,...,.p=.p,.dry=.dry))
}
if(mc_able() & isTRUE(.parallel)) {
ans <- mclapply(X = data, mod = mod, .p = .p, .dry = .dry, FUN = .simd, ...)
} else {
ans <- lapply(X = data, mod = mod, .p = .p, .dry = .dry, FUN = .simd,...)
}
if(.as_list) return(ans)
return(bind_rows(ans))
}
fu_mrgsim_d <- future_mrgsim_d
fu_mrgsim_d0 <- function(...,.dry=TRUE) fu_mrgsim_d(...,.dry=TRUE) |
make_Sample <- function(
book,
depth,
geometry = "cuboid",
radius,
height,
width,
length,
slice = TRUE,
force = FALSE,
n_cores = max(1,parallel::detectCores() - 2)
) {
if (!all(c("sandbox", "book") %in% attributes(book)[c("package", "medium")]))
stop("[make_Sample()] 'book' is not an object created by sandbox!", call. = FALSE)
if (geometry == "cuboid") {
depth_range <- c(
depth[1] - height[1] / 2,
depth[1] + height[1] / 2)
V_sample <- height[1] * width[1] * length[1]
} else if (geometry == "cylinder") {
depth_range <- c(
depth[1] - radius[1],
depth[1] + radius[1])
V_sample <- pi * radius[1]^2 * length[1]
}
n_estimate <- 1000
z_estimate <- runif(
n = n_estimate,
min = depth_range[1],
max = depth_range[2])
v_estimate <- lapply(
X = z_estimate,
FUN = function(z, book) {
p_z <- vapply(
X = book$population[-1],
FUN = function(x, z) {
x$value(x = z)},
FUN.VALUE = numeric(1), z = z)
p_z[p_z < 0] <- 0
p_z <- p_z / sum(p_z)
p_z <- base::sample(
x = 1:length(p_z),
size = 1,
prob = p_z)
if (book$grainsize[[p_z + 1]]$type == "exact") {
d_z <- book$grainsize[[p_z + 1]][[2]](z)
} else if (book$grainsize[[p_z + 1]]$type == "normal") {
d_z <- stats::rnorm(
n = 1,
mean = book$grainsize[[p_z + 1]]$mean(z),
sd = book$grainsize[[p_z + 1]]$sd(z))
} else if (book$grainsize[[p_z + 1]]$type == "uniform") {
d_z <- stats::runif(
n = 1,
min = book$grainsize[[p_z + 1]]$min(z),
max = book$grainsize[[p_z + 1]]$max(z))
} else if (book$grainsize[[p_z + 1]]$type == "gamma") {
d_z <- stats::rgamma(
n = 1,
shape = book$grainsize[[p_z + 1]]$shape(z),
scale = book$grainsize[[p_z + 1]]$scale(z)) +
book$grainsize[[p_z + 1]]$offset(z)
}
if (book$packing[[p_z + 1]]$type == "exact") {
w_z <- book$packing[[p_z + 1]][[2]](z)
} else if (book$packing[[p_z + 1]]$type == "normal") {
w_z <- stats::rnorm(
n = 1,
mean = book$packing[[p_z + 1]]$mean(z),
sd = book$packing[[p_z + 1]]$sd(z))
} else if (book$packing[[p_z + 1]]$type == "uniform") {
w_z <- stats::runif(
n = 1,
min = book$packing[[p_z + 1]]$min(z),
max = book$packing[[p_z + 1]]$max(z))
} else if (book$packing[[p_z + 1]]$type == "gamma") {
w_z <- stats::rgamma(
n = 1,
shape = book$packing[[p_z + 1]]$shape(z),
scale = book$packing[[p_z + 1]]$scale(z)) +
book$packing[[p_z + 1]]$offset(z)
}
r_z <- convert_units(phi = d_z) / 2000000
v_z <- 4 / 3 * pi * r_z^3 * 1/w_z
if (v_z > 0) return(v_z)
}, book = book)
n_grains <- round(V_sample * n_estimate / sum(unlist(v_estimate)) * 1.1)
if (n_grains < 1)
stop("[make_Sample()] Sample volume is smaller than grain diameter!", call. = FALSE)
if (geometry == "cuboid") {
d_sample <- runif(
n = n_grains,
min = depth_range[1],
max = depth_range[2])
} else if (geometry == "cylinder") {
depth_i <- runif(
n = n_grains,
min = depth_range[1],
max = depth_range[2]) - depth
depth_circle <- sqrt(radius^2 - depth_i^2)
depth_weight <- depth_circle/max(depth_circle)
d_sample <- sample(
x = depth_i,
size = n_grains,
replace = TRUE,
prob = depth_weight) + depth
}
if (n_grains > 10 ^ 7 & force == FALSE) {
stop(paste0(
"More than 10^7 grains (",
n_grains,
") to model. Enable with force = TRUE."
), call. = FALSE)
}
cl <- parallel::makeCluster(getOption("mc.cores", n_cores[1]))
on.exit(parallel::stopCluster(cl))
if (slice[1]) {
i_slice <- c(
seq(from = 1,
to = length(d_sample),
by = 1e+06),
length(d_sample) + 1)
d_sample_slice <- vector(
mode = "list", length = length(i_slice) - 1)
for (i in 1:length(d_sample_slice))
d_sample_slice[[i]] <- d_sample[(i_slice[i]):(i_slice[i + 1] - 1)]
} else {
d_sample_slice <- list(d_sample)
}
population <- vector(mode = "list", length = length(d_sample_slice))
for (i in 1:length(population)) {
population[[i]] <- parallel::parLapply(
cl = cl,
X = d_sample_slice[[i]],
fun = function(d_sample, book) {
p_z <- lapply(
X = book$population[-1],
FUN = function(x, d_sample) {x$value(x = d_sample)}, d_sample)
p_z <- do.call(c, p_z)
p_z[p_z < 0] <- 0
p_z <- p_z / sum(p_z)
base::sample(
x = 1:length(p_z),
size = 1,
prob = p_z)
}, book = book)
population[[i]] <- do.call(c, population[[i]])
}
population <- do.call(c, population)
parameters <- matrix(nrow = n_grains, ncol = length(book) - 1)
colnames(parameters) <- names(book)[-1]
grains <- 1:n_grains
grains <- as.data.frame(
cbind(grains,d_sample, population, parameters))
for (i in 2:length(book)) {
if (book[[i]]$group == "general") {
if (book[[i]][[2]]$type == "exact") {
x_out <- try({
book[[i]][[2]][[2]](x = grains$d_sample)
}, silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "normal") {
sd_pre <- try({
book[[i]][[2]]$sd(x = grains$d_sample)
}, silent = TRUE)
try(sd_pre[sd_pre < 0] <- 0, silent = TRUE)
x_out <- try(
stats::rnorm(n = nrow(grains),
mean = book[[i]][[2]]$mean(
x = grains$d_sample),
sd = sd_pre),
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "uniform") {
min_pre <- try({
book[[i]][[2]]$min(x = grains$d_sample)
}, silent = TRUE)
max_pre <- try({
book[[i]][[2]]$max(x = grains$d_sample)
}, silent = TRUE)
x_out <- try({
stats::runif(
n = nrow(grains),
min = min_pre,
max = max_pre)},
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "gamma") {
shape_pre <- try(book[[i]][[2]]$shape(x = grains$d_sample),
silent = TRUE)
scale_pre <- try(book[[i]][[2]]$scale(x = grains$d_sample),
silent = TRUE)
offset_pre <- try(book[[i]][[2]]$offset(x = grains$d_sample),
silent = TRUE)
x_out <- try({
stats::rgamma(
n = nrow(grains),
shape = shape_pre,
scale = scale_pre) + offset_pre
}, silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[,i + 2] <- x_out
}
} else {
for (j in 1:(length(book$population) - 1)) {
ID_population_j <- (1:nrow(grains))[grains$population == j]
if (book[[i]][[2]]$type == "exact") {
x_out <- try(book[[i]][[j + 1]]$value(
x = grains$d_sample[ID_population_j]),
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[ID_population_j,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "normal") {
x_out <- try(
stats::rnorm(
n = length(ID_population_j),
mean = book[[i]][[j + 1]]$mean(x = grains$d_sample),
sd = abs(book[[i]][[j + 1]]$sd(x = grains$d_sample))),
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[ID_population_j,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "uniform") {
x_out <- try(
stats::runif(
n = length(ID_population_j),
min = book[[i]][[j + 1]]$min(x = grains$d_sample),
max = book[[i]][[j + 1]]$max(x = grains$d_sample)),
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[ID_population_j,i + 2] <- x_out
} else if (book[[i]][[2]]$type == "gamma") {
x_out <- try(
stats::rgamma(
n = length(ID_population_j),
shape = book[[i]][[j + 1]]$shape(x = grains$d_sample),
scale = book[[i]][[j + 1]]$scale(x = grains$d_sample)) +
book[[i]][[j + 1]]$offset(x = grains$d_sample),
silent = TRUE)
if (class(x_out[1]) == "try-error")
x_out <- rep(NA, nrow(grains))
grains[ID_population_j,i + 2] <- x_out
}
}
}
}
r_grains <- (convert_units(phi = grains$grainsize) / (2 * 1e+06))
V_grains <- cumsum(4 / 3 * pi * r_grains^3 * 1/grains$packing)
grains <- grains[V_sample >= V_grains,]
attributes(grains) <- c(
attributes(grains),
list(package = "sandbox"))
return(grains)
} |
filter_evaluator <- filterEvaluator('determinationCoefficient')
LV_search <- LasVegas()
res <- LV_search(iris, 'Species', filter_evaluator)
print(res) |
pc.skel <- function(dataset, method = "pearson", alpha = 0.01, R = 1, stat = NULL, ini.pvalue = NULL) {
is.init.vals <- c(!is.null(stat), !is.null(ini.pvalue))
if (is.null(stat)) stat <- matrix();
if (is.null(ini.pvalue)) ini.pvalue <- matrix();
.Call(Rfast_pc_skel,dataset, method, alpha, R, stat, ini.pvalue, is.init.vals)
} |
read.neuron.hxskel<-function(file, ...){
ndata=read.amiramesh(file)
required_fields=c("Coordinates", "NeighbourCount", "Radii", "NeighbourList")
missing_fields=setdiff(required_fields,names(ndata))
if(length(missing_fields))
stop("Neuron: ",file," is missing fields: ",paste(missing_fields,collapse=" "))
d=data.frame(ndata$Coordinates)
colnames(d)=c("X","Y","Z")
d$W=ndata$Radii*2
nVertices=nrow(d)
d$PointNo=seq(nVertices)
d[,1:4]=zapsmall(d[,1:4])
Neighbours=data.frame(Neighbour=ndata$NeighbourList+1,
CurPoint=rep(seq(nVertices),ndata$NeighbourCount))
Origin=ndata$Origins
if(!is.null(Origin)) Origin=Origin+1
if(length(ndata$vertexTypeList)){
SegmentProps=data.frame(
PointNo=rep(seq(nVertices),ndata$vertexTypeCounter),
Id=ndata$vertexTypeList)
if(length(attr(ndata,'Materials'))){
attr(SegmentProps,'Materials')=attr(ndata,'Materials')
}
FirstSegmentProps=SegmentProps[!duplicated(SegmentProps$PointNo),]
d$Label=0L
d[FirstSegmentProps$PointNo,"Label"]=FirstSegmentProps$Id
}
el=data.matrix(Neighbours)
doubleg=ngraph(el, d$PointNo, directed=TRUE)
ug=as.undirected(doubleg, mode='collapse')
if(!inherits(ug,'ngraph')) class(ug)=c("ngraph",class(ug))
n=as.neuron(ug, vertexData=d, origin=Origin, InputFileName=file, ... )
n
}
is.hxskel<-is.amiratype('SkeletonGraph')
read.neuron.hxlineset<-function(file, defaultDiameter=NA_real_, ...){
amdata=read.amiramesh(file)
if(!all(c("Coordinates","LineIdx")%in%names(amdata)))
stop("Cannot find required data sections")
coords=as.data.frame(amdata$Coordinates)
colnames(coords)=c("X","Y","Z")
radiusData=amdata[!names(amdata)%in%c("Coordinates","LineIdx")]
lad=length(radiusData)
if(lad==0){
warning("No width data for neuron:",file)
coords[,"W"]=defaultDiameter
} else if (lad==1) {
coords[,"W"]=radiusData[[1]]*2
} else if (lad>1) {
warning("Assuming that Data section ",lad," (",names(radiusData)[lad],") specifies radius")
coords[,"W"]=radiusData[[lad]]*2
}
coords=cbind(PointNo=seq(1:nrow(coords)), zapsmall(coords))
lpts = amdata$LineIdx+1
lpts[lpts==0]=NA
el=cbind(start=lpts[-length(lpts)], end=lpts[-1])
el=el[!is.na(rowSums(el)),]
vertices_in_edges=na.omit(unique(lpts))
missing_vertices=setdiff(vertices_in_edges, coords$PointNo)
if(length(missing_vertices)) {
stop(
"Invalid amiramesh file - adjacency list mentions ",
length(missing_vertices),
" vertices that are undefined!"
)
}
ng=ngraph(el, vertexlabels=coords$PointNo, xyz = coords[,c("X","Y","Z"), drop=FALSE], diam=coords[,"W"])
as.neuron(ng, InputFileName=file, ...)
}
is.hxlineset<-is.amiratype('HxLineSet')
write.neuron.hxskel<-function(x, file, WriteAllSubTrees=TRUE,
ScaleSubTreeNumsTo1=TRUE, sep=NULL){
if(WriteAllSubTrees && isTRUE(x$nTrees>1)){
WriteAllSubTrees=TRUE
SegList=unlist(x$SubTrees,recursive=FALSE)
} else {
WriteAllSubTrees=FALSE
SegList=x$SegList
}
chosenVertices=sort(unique(unlist(SegList)))
nVertices=length(chosenVertices)
nEdgeList=sum(sapply(SegList,length)-1)*2
makeEdges=function(seg){
lSeg=length(seg)
if(lSeg<2) return()
elFwd=cbind(seg[-lSeg],seg[-1])
elRev=cbind(seg[-1],seg[-lSeg])
df=data.frame(rbind(elFwd,elRev))
names(df)=c("CurPoint","Neighbour")
df[order(df$CurPoint,df$Neighbour),]
}
EdgeList=do.call('rbind',lapply(SegList,makeEdges))
EdgeList=EdgeList[order(EdgeList$CurPoint,EdgeList$Neighbour),]
cat("
fc=file(file,open="at")
cat("
cat("nVertices", nVertices,"\nnEdges",nEdgeList,"\n",file=fc)
vertexTypeList=ifelse(WriteAllSubTrees,nVertices,0)
cat("define Origins 1\ndefine vertexTypeList",vertexTypeList,"\n\n",file=fc)
cat("Parameters {\n",file=fc)
cat(" ContentType \"SkeletonGraph\"\n",file=fc)
cat("}\n\n",file=fc)
cat("Vertices { float[3] Coordinates } @1\n",file=fc)
cat("Vertices { int NeighbourCount } @2\n",file=fc)
cat("Vertices { float Radii } @3\n",file=fc)
cat("EdgeData { int NeighbourList } @4\n",file=fc)
cat("Origins { int Origins } @5\n",file=fc)
cat("Vertices { int vertexTypeCounter } @6\n",file=fc)
cat("vertexTypeList { int vertexTypeList } @7\n\n",file=fc)
cat("@1
if(is.null(sep)){
Coords=as.matrix(x$d[,c("X","Y","Z")])
rownames(Coords)<-colnames(Coords)<-NULL
write.table(format(Coords,trim=FALSE,scientific=FALSE),
quote=F,row.names=FALSE,col.names=FALSE,file=fc)
} else {
write.table(x$d[chosenVertices,c("X","Y","Z")],col.names=F,row.names=F,file=fc,sep=sep)
}
cat("\n@2
numNeighbours=integer(nVertices)
numNeighbours[sort(unique(EdgeList$CurPoint))]=table(EdgeList$CurPoint)
write.table(numNeighbours,col.names=F,row.names=F,file=fc)
cat("\n@3
write.table(x$d$W[chosenVertices]/2,col.names=F,row.names=F,file=fc)
cat("\n@4
write.table(EdgeList$Neighbour-1,col.names=F,row.names=F,file=fc)
cat("\n@5
cat(x$StartPoint-1,"\n",file=fc)
cat("\n@6
cat(paste(rep(0,nVertices),"\n"),sep="",file=fc)
if(WriteAllSubTrees) {
cat("\n@7
if(ScaleSubTreeNumsTo1) x$d$SubTree=x$d$SubTree/max(x$d$SubTree)
write.table(x$d$SubTree,col.names=F,row.names=F,file=fc)
}
cat("\n",file=fc)
close(fc)
}
write.neuron.hxlineset<-function(x, file=NULL, WriteAllSubTrees=TRUE,
ScaleSubTreeNumsTo1=TRUE, WriteRadius=TRUE){
SegList=as.seglist(x, all=WriteAllSubTrees, flatten=TRUE)
WriteAllSubTrees=WriteAllSubTrees && isTRUE(x$nTrees>1)
chosenVertices=sort(unique(unlist(SegList)))
nVertices=length(chosenVertices)
nLinePoints=length(unlist(SegList))+length(SegList)
cat("
fc=file(file,open="at")
cat("
cat("define Lines",nLinePoints,"\n",file=fc)
cat("define Vertices", nVertices,"\n\n",file=fc)
cat("Parameters {\n",file=fc)
cat(" ContentType \"HxLineSet\"\n",file=fc)
cat("}\n\n",file=fc)
sectionNumbers=c(Coordinates=1,LineIdx=2)
cat("Vertices { float[3] Coordinates } = @1\n",file=fc)
if(WriteRadius){
if(any(is.na(x$d$W))) {
warning("Width has NAs. Omitting invalid width data from file:", file)
WriteRadius=FALSE
} else {
cat("Vertices { float Data } = @2\n",file=fc)
sectionNumbers=c(Coordinates=1,Data=2,LineIdx=3)
}
}
cat("Lines { int LineIdx } = @",sectionNumbers['LineIdx'],"\n",sep="",file=fc)
if(WriteAllSubTrees) {
sectionNumbers=c(sectionNumbers,Data2=max(sectionNumbers)+1)
cat("Vertices { float Data2 } =@",sectionNumbers['Data2'],"\n",sep="",file=fc)
}
cat("\n",file=fc)
cat("@1
write.table(x$d[chosenVertices,c("X","Y","Z")],col.names=F,row.names=F,file=fc)
if(WriteRadius){
cat("\n@",sectionNumbers['Data'],"
write.table(x$d$W[chosenVertices]/2,col.names=F,row.names=F,file=fc,na='NaN')
}
cat("\n@",sectionNumbers['LineIdx'],"
lapply(SegList,function(x) cat(x-1,"-1 \n",file=fc))
if(WriteAllSubTrees) {
cat("\n@",sectionNumbers['Data2'],"
if(ScaleSubTreeNumsTo1) x$d$SubTree=x$d$SubTree/max(x$d$SubTree)
write.table(x$d$SubTree,col.names=F,row.names=F,file=fc)
}
close(fc)
} |
add_r_depend <- function() {
r_version <- get_minimal_r_version()
if (!is.null(r_version)) {
r_version <- paste0("R (>= ", r_version, ")")
descr <- read_descr()
if (is.null(descr$"Depends")) {
descr$"Depends" <- r_version
} else {
depends <- unlist(strsplit(descr$"Depends", "\n\\s+|,|,\\s+"))
is_r <- grep("R \\(.*\\)", depends)
if (length(is_r)) {
depends[is_r] <- r_version
} else {
depends <- c(r_version, depends)
}
descr$"Depends" <- paste0(depends, collapse = ", ")
}
write_descr(descr)
ui_done(paste0("Adding the following line to {ui_value('DESCRIPTION')}: ",
"{ui_code(paste('Depends:', r_version))}"))
} else {
ui_done(paste0("No minimal R version detected"))
}
invisible(NULL)
} |
list_transform <- function(x) {
df <- as.data.frame(t(as.data.frame(x, stringsAsFactors = FALSE)),
row.names = FALSE,
stringsAsFactors = FALSE)
return(df)
} |
today_pin <- substr(paste(paste(unlist(strsplit(as.character(Sys.Date()),split = "-")), collapse = ""),"0000",sep=""), 3, 12)
tomorrow_pin <- paste(paste(unlist(strsplit(as.character(Sys.Date()+1),split = "-")), collapse = ""),"0000",sep="")
context("as.pin")
test_that(desc="class: pin",{
expect_is(as.pin("196408233234"), class = "pin")
})
test_that(desc="numeric: YYYYMMDDNNNC",{
expect_equal(as.character(suppressMessages(as.pin(196408233234))), expected = "196408233234")
expect_equal(as.character(suppressMessages(as.pin(200108230000))), expected = "200108230000")
expect_is(as.character(suppressMessages(as.pin(200108230000))), "character")
expect_is(as.character(suppressMessages(as.pin(pin = c(NA,198501169885)))), "character")
expect_is(as.character(suppressMessages(as.pin(pin = as.numeric(NA)))), "character")
})
test_that(desc="numeric: YYMMDDNNNC",{
expect_equal(as.character(suppressMessages(as.pin(6408233234))), expected = "196408233234")
expect_equal(as.character(suppressMessages(as.pin(108230000))), expected = "200108230000")
expect_equal(as.character(suppressMessages(as.pin(pin = c(8230000,108230000)))), expected = c("200008230000", "200108230000"))
expect_is(as.character(suppressMessages(as.pin(c(NA,8501169885)))), "character")
})
test_that(desc="character: 'YYMMDDNNNC'",{
expect_equal(as.character(suppressMessages(as.pin("6408233234"))), expected = "196408233234")
expect_equal(as.character(suppressMessages(as.pin("0008230000"))), expected = "200008230000")
expect_equal(as.character(suppressMessages(as.pin(today_pin))), expected = paste("20",today_pin, sep=""))
expect_is(as.character(suppressMessages(as.pin(c(NA,"8501169885")))), "character")
})
test_that(desc="factor: 'YYMMDDNNNC'",{
expect_equal(as.character(suppressMessages(as.pin(as.factor("6408233234")))), expected = "196408233234")
expect_equal(as.character(suppressMessages(as.pin(as.factor("0008230000")))), expected = "200008230000")
})
test_that(desc="character: 'YYYYMMDDNNNC'",{
expect_equal(as.character(suppressMessages(as.pin("196408233234"))), expected = "196408233234")
expect_is(as.character(suppressMessages(as.pin(c(NA,"198501169885")))), "character")
})
test_that(desc="different formats",{
expect_equal(as.character(suppressMessages(as.pin(c("196408233234", "640823-3234", "19640823-3234", "6408233234")))),
expected = rep("196408233234", 4))
expect_equal(as.character(suppressMessages(as.pin(c(196408233234, 6408233234)))),
expected = rep("196408233234", 2))
})
test_that(desc="character: 'YYMMDD-NNNC'",{
expect_equal(as.character(as.pin("640823-3234")), expected = "196408233234")
expect_equal(as.character(as.pin("000823-0000")), expected = "200008230000")
expect_equal(as.character(as.pin("000823+0000")), expected = "190008230000")
})
test_that(desc="error expected",{
suppressWarnings(expect_equal(as.character(as.pin(tomorrow_pin)), as.character(NA)))
suppressWarnings(expect_equal(as.character(as.pin(pin = "AA6408233234")), as.character(NA)))
suppressWarnings(expect_equal(as.character(as.pin("196418233234")), as.character(NA)))
suppressWarnings(expect_equal(as.character(as.pin("196408333234")), as.character(NA)))
expect_warning(as.pin(tomorrow_pin))
expect_warning(as.pin("AA6408233234"))
expect_warning(as.pin("196418233234"))
expect_warning(as.pin("196408333234"))
test_pin <- c("196408233234", tomorrow_pin, "AA6408323234", "19640823323", "1964083332349", "196408333234", "19640823-334", "19640823")
test_pin_res <- c(TRUE, rep(FALSE, 7))
suppressWarnings(expect_equal(!is.na(as.pin(test_pin)), test_pin_res))
non_relevant_class <- lm(1:10~rep(1:5,2))
expect_error(as.pin(non_relevant_class))
expect_error(as.pin(c(TRUE,FALSE)))
})
test_that("as.pin.pin", {
suppressWarnings(expect_equal(as.pin(as.pin("test_pin")), as.pin("test_pin")))
})
test_that("as.pin.logical", {
expect_is(as.pin(NA), "pin")
expect_error(as.pin(TRUE))
})
test_pins <- c("18920822-2298", "18920822-2299", "19920419-1923")
test_that("Recycling rules", {
expect_is(data.frame(as.pin(test_pins), 1:9), "data.frame")
expect_equal(nrow(data.frame(as.pin(test_pins), 1:9)), 9)
expect_equal(data.frame(as.pin(test_pins), 1:9)[1:3, 1], data.frame(as.pin(test_pins), 1:9)[4:6, 1])
expect_equal(data.frame(as.pin(test_pins), 1:9)[1:3, 1], data.frame(as.pin(test_pins), 1:9)[7:9, 1])
})
semi_pins <- c("550504333A", "19280118123X", "850504111T", "850504111 ", "19280118123 ")
test_that("deceased 1947 - 1967", {
suppressWarnings(expect_is(as.pin(semi_pins), "pin"))
expect_warning(as.pin(semi_pins[3]), "Erroneous pin")
expect_warning(as.pin(semi_pins[4]), "Erroneous pin")
expect_message(as.pin(semi_pins[1]), "less than 100 years old and people with birth year")
expect_message(as.pin(semi_pins[2]), "Assumption: People with birth year before 1967 and character")
expect_message(as.pin(semi_pins[5]), "Assumption: People with birth year before 1967 and character")
})
test_that("Expect message only when YYMMDDNNNC format is used", {
num_to_check <- c("202100-6255","121212-1212","19121212-1212","121212+1212", 121212121212, NA, Inf, TRUE, F, "foo", 123, 456L)
expect_silent(suppressWarnings(as.pin(num_to_check)))
}) |
context("ImportData")
test_csv <- "test.csv"
test_that("ImportData input", {
expect_error(ImportData(), "Please provide file path of data to import.")
expect_error(ImportData("xxx.rds"), "Please provide the social media type of data to import.")
supported_types <- c("csv", "rds")
not_supp_msg <- paste0("File format not supported. please choose from: ",
paste0(supported_types, collapse = ", "), ".")
expect_error(ImportData("xxx", "twitter"), not_supp_msg)
expect_error(ImportData("xxx.graphml", "twitter"), not_supp_msg)
expect_error(suppressWarnings(ImportData("xxx.rds", "twitter")))
if (file.exists(test_csv)) {
expect_error(ImportData(test_csv, "twitter", "rds"))
expect_error(capture.output(ImportData(test_csv, "xxx", "csv")),
"Unknown social media type provided as datasource.")
}
})
test_that("ImportData output", {
skip_if_not(file.exists(test_csv), message = "csv file exists")
capture.output({ data <- ImportData(test_csv, "twitter", "csv") })
expect_s3_class(data, "data.frame")
expect_s3_class(data, "datasource")
expect_s3_class(data, "twitter")
}) |
test_that("evaluate methods with random values", {
skip_on_cran()
status_pu <- sample(0:3, 10, replace = TRUE)
status_pu <- ifelse(status_pu == 1, 0, status_pu)
status_action <- sample(0:3, 10, replace = TRUE)
status_action <- ifelse(status_action == 1, 0, status_action)
bound <- expand.grid(seq_len(10), seq_len(10))
colnames(bound) <- c("id1", "id2")
pu_sim <- data.frame(
id = seq_len(10),
monitoring_cost = c(0.1, sample(1:10, 9, replace = TRUE)),
status = ifelse(status_pu == 1, 0 , status_pu))
features_sim <- data.frame(
id = seq_len(2),
target_recovery = sample(1:10, 2, replace = TRUE),
name = letters[seq_len(2)])
dist_features_sim <- data.frame(
pu = rep(seq_len(10), 2),
feature = c(rep(1, 10), rep(2, 10)),
amount = sample(1:10, 20, replace = TRUE))
threats_sim <- data.frame(
id = seq_len(1),
blm_actions = sample(1:10, 1, replace = TRUE),
name = letters[seq_len(1)])
dist_threats_sim <- data.frame(
pu = seq_len(10),
threat = rep(1, 10),
amount = rep(1, 10),
action_cost = sample(1:10, 10, replace = TRUE),
status = ifelse(status_action == 1, 0 , status_action))
boundary_sim <- data.frame(
bound,
boundary = sample(1:10, nrow(bound), replace = TRUE))
blm_values = sample(0:10, 3, replace = FALSE)
port <- suppressWarnings(evalBlm(pu = pu_sim,
features = features_sim,
dist_features = dist_features_sim,
threats = threats_sim,
dist_threats = dist_threats_sim,
boundary = boundary_sim,
values = blm_values,
output_file = FALSE))
expect_s3_class(port, "Portfolio")
expect_equal(length(port$data), 3)
for (i in seq_along(port$data))
expect_s3_class(port$data[[i]], "Solution")
expect_type(port$getBlms(), "double")
expect_equal(port$getBlms(), blm_values)
expect_equal(port$getNames(), paste0("Blm", blm_values))
})
test_that("evaluate solutions values", {
skip_on_cran()
bound <- expand.grid(seq_len(10), seq_len(10))
colnames(bound) <- c("id1", "id2")
pu_sim <- data.frame(
id = seq_len(10),
monitoring_cost = c(0.1, 1, 2, 3, 2, 1, 2, 3, 2, 1),
status = c(0, 0, 3, 2, 0, 3, 3, 0, 2, 2))
features_sim <- data.frame(
id = seq_len(2),
target_recovery = c(0.2, 0.5),
name = letters[seq_len(2)])
dist_features_sim <- data.frame(
pu = rep(seq_len(10), 2),
feature = c(rep(1, 10), rep(2, 10)),
amount = 1)
threats_sim <- data.frame(
id = seq_len(1),
blm_actions = 0.5,
name = letters[seq_len(1)])
dist_threats_sim <- data.frame(
pu = seq_len(10),
threat = rep(1, 10),
amount = rep(1, 10),
action_cost = c(1.5, 2.5, 2.5, 1.5, 2.5, 2.5, 1.5, 2.5, 1.5, 2.5),
status = c(0, 0, 3, 0, 0, 3, 3, 2, 2, 2))
boundary_sim <- data.frame(
bound,
boundary = 0.5)
w <- capture_warnings(port <- evalBlm(pu = pu_sim,
features = features_sim,
dist_features = dist_features_sim,
threats = threats_sim,
dist_threats = dist_threats_sim,
boundary = boundary_sim,
values = c(0, 4),
output_file = FALSE))
s1 <- port$data[[1]]$data
s2 <- port$data[[2]]$data
expect_equal(s1$sol[1:20], c(0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1))
expect_equal(s2$sol[1:20], c(1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1))
expect_gt(s2$objval, s1$objval)
expect_match(w, "The blm argument was set to 0", all = FALSE)
}) |
context("convertToShortString")
test_that("convertToShortString", {
expect_equal(convertToShortString(1L), "1")
expect_equal(convertToShortString(1.0), "1")
expect_equal(convertToShortString(1.23), "1.23")
expect_equal(convertToShortString(numeric(0)), "numeric(0)")
expect_equal(convertToShortString(factor(c())), "factor(0)")
expect_equal(convertToShortString(iris), "<data.frame>")
expect_equal(convertToShortString(NULL), "<NULL>")
expect_equal(convertToShortString(c(a=1, b=2)), "1,2")
expect_equal(convertToShortString(expression(a + b + 3)), "a + b + 3")
expect_equal(convertToShortString(list(a=1, 45)), "a=1, <unnamed>=45")
expect_equal(convertToShortString(list(a=1, b=list(x=3))), "a=1, b=<list>")
expect_equal(convertToShortString(list(a=1, b=iris)), "a=1, b=<data.frame>")
expect_equal(convertToShortString(list()), "")
expect_equal(convertToShortString(list(a=1)), "a=1")
expect_equal(convertToShortString(list(a=1:2)), "a=1,2")
expect_equal(convertToShortString(list(a=1:20)), "a=1,2,3,4,5,6,...")
expect_equal(convertToShortString(list(a=1, 2, b=3)), "a=1, <unnamed>=2, b=3")
expect_equal(convertToShortString(list(a=1, 2, b=data.frame())), "a=1, <unnamed>=2, b=<data.frame>")
expect_equal(convertToShortString(list(a=identity, b=new.env(), c = NULL, d = expression(a + b + 3))), "a=<function>, b=<environment>, c=<NULL>, d=a + b + 3")
expect_equal(convertToShortString(list(a=1, b=3.2)), "a=1, b=3.2")
expect_equal(convertToShortString(list(a=1, b=3.223), num.format="%.2f"), "a=1.00, b=3.22")
expect_equal(convertToShortString(list(a=1L, b=3.223), num.format="%.2f"), "a=1, b=3.22")
}) |
backtransform.par.rLNLN <-
function(this.par,m,fix.mu,fixed.mu) {
if (!fix.mu) {
TY <- (length(this.par)+1)/(m+2)
}
else {
TY <- (length(this.par)+1)/2
}
if (TY>1) {
this.w <- this.par[1:(TY-1)]
p.sums <- rep(NA,TY-1)
p.sums[length(p.sums)] <- stochprof.expit(this.w[length(this.w)])
if (TY>2) {
for (i in (length(p.sums)-1):1) {
p.sums[i] <- stochprof.expit(this.w[i]) * p.sums[i+1]
}
}
if (TY>2) {
p.sums.shifted <- c(0,p.sums[1:(length(p.sums)-1)])
this.p <- p.sums - p.sums.shifted
}
else {
this.p <- p.sums
}
}
else {
this.p <- NULL
}
if (!fix.mu) {
this.mu <- this.par[TY:((m+1)*TY-1)]
}
else {
this.mu <- fixed.mu
}
this.sigma <- exp(this.par[length(this.par)-(TY-1):0])
this.theta <- c(this.p,this.mu,this.sigma)
return(this.theta)
} |
print.toufit <- function(x, ...) {
fm <- x
if(fm$method == 'ml'){
cat(' Maximum Likelihood', '\n')
cat("$fit", '\n')
print(fm$fit)
cat("AIC = ", fm$aic, " ", "BIC = ", fm$bic, "\n")
cat('\n', 'Null: delta = 0 (Poisson)', '\n')
printCoefmat(fm$test, P.values=TRUE, has.Pvalue=TRUE)
}
if( fm$method %in% c('mm','gmm') ){
r <- ifelse( fm$method == 'mm', 2, 3 )
cat(' Method of Moments', ' ( r = ', r, ')', '\n')
cat("$fit", '\n')
print(fm$fit)
cat('\n', 'Null: delta = 0 (Poisson)', '\n')
printCoefmat(fm$test, P.values=TRUE, has.Pvalue=TRUE)
}
} |
chicane <- function(
bam = NULL,
baits = NULL,
fragments = NULL,
interactions = NULL,
replicate.merging.method = 'sum',
distribution = 'negative-binomial',
include.zeros = 'none',
bait.filters = c(0, 1),
target.filters = c(0, 1),
distance.bins = NULL,
multiple.testing.correction = c('bait-level', 'global'),
adjustment.terms = NULL,
remove.adjacent = FALSE,
temp.directory = NULL,
keep.files = FALSE,
maxit = 100,
epsilon = 1e-8,
cores = 1,
trace = FALSE,
verbose = FALSE,
interim.data.dir = NULL
) {
if( is.null(interactions) && (is.null(bam) || is.null(baits) || is.null(fragments)) ) {
stop('Must provide either interactions or bam/baits/fragments.');
}
if( !is.null(interactions) && !(is.null(bam) || is.null(baits) || is.null(fragments)) ) {
stop('Cannot deal with both interactions and bam/baits/fragments. Please provide one or the other.');
}
if( !is.null(interactions) && !is.character(interactions) && !is.data.table(interactions) ) {
stop('interactions should be either a data.table object or the path to a text file generated by prepare.data');
}
if( is.null(interactions) ) {
input.files <- list(bam, baits, fragments);
object.is.character <- vapply(
input.files,
FUN = function(x) all( is.character(x) ),
FUN.VALUE = FALSE
);
if( !all(object.is.character) ) {
stop('bam, baits, and fragments should be character strings');
}
if( !all( 1 == vapply(input.files[-1], length, FUN.VALUE = 0) ) ) {
stop('bam, baits, and fragments should have length 1');
}
for( input.file in unlist(input.files) ) {
if( !file.exists(input.file) ) {
error.message <- paste('File', input.file, 'does not exist');
stop(error.message);
}
}
}
if( !is.null(interactions) && 'none' != include.zeros ) {
stop('Zeros are added in the prepare.data step. Please provide bam/baits/fragments');
}
replicate.merging.method <- match.arg(replicate.merging.method);
multiple.testing.correction <- match.arg(multiple.testing.correction);
if( is.null(interactions) ) {
if( verbose ) {
cat('PREPARING DATA\n');
}
interaction.data <- prepare.data(
bam,
baits,
fragments,
replicate.merging.method = replicate.merging.method,
include.zeros = include.zeros,
remove.adjacent = remove.adjacent,
temp.directory = temp.directory,
keep.files = keep.files,
verbose = verbose
);
} else if( is.character(interactions) ) {
if( !file.exists(interactions) ) {
error.message <- paste('File', interactions, 'does not exist');
stop(error.message);
}
if( verbose ) {
cat('READING DATA FROM FILE\n');
}
interaction.data <- data.table::fread(interactions);
} else if( is.data.table(interactions) ) {
interaction.data <- interactions;
rm(interactions);
}
if( verbose ) {
cat('FITTING MODEL\n');
}
chicane.results <- fit.model(
interaction.data,
distance.bins = distance.bins,
distribution = distribution,
bait.filters = bait.filters,
target.filters = target.filters,
adjustment.terms = adjustment.terms,
verbose = verbose,
cores = cores,
maxit = maxit,
epsilon = epsilon,
trace = trace,
interim.data.dir = interim.data.dir
);
chicane.results <- multiple.testing.correct(
chicane.results,
bait.level = 'bait-level' == multiple.testing.correction
);
chicane.results <- chicane.results[ order(q.value, p.value) ];
return(chicane.results);
} |
confint.fe.prov <- function(object, parm = "all", level = 0.95, data, Y.char, Z.char, prov.char,...) {
prov.all <- unique(data[data$included==1,prov.char])
if(is.null(parm) | identical(parm,"all")) {
data <- data[data$included==1, ]
} else {
presence.parm <- parm %in% prov.all
if (max(presence.parm)==0) {
stop("All provider ID(s) misspecified!", call.=F)
} else if (length(parm[!presence.parm])==0) {
data <- data[data[,prov.char] %in% parm[presence.parm], ]
} else {
warning("Provider ID(s) '",paste(parm[!presence.parm], collapse="', '"),
"' misspecified with no confidence intervals!", call.=F, immediate.=T)
data <- data[data[,prov.char] %in% parm[presence.parm], ]
}
}
fe.ls <- object
alpha <- 1 - level
data <- data[data$included==1, ]
df.prov <- fe.ls$df.prov
gamma <- df.prov$gamma; names(gamma) <- rownames(df.prov)
beta <- fe.ls$beta
max.gamma <- norm(as.matrix(gamma[is.finite(gamma)]),"I")
CL.finite <- function(df) {
UL.gamma <- function(Gamma)
ppoibin(Obs-1,plogis(Gamma+Z.beta))+0.5*dpoibin(Obs,plogis(Gamma+Z.beta))-alpha/2
LL.gamma <- function(Gamma)
1-ppoibin(Obs,plogis(Gamma+Z.beta))+0.5*dpoibin(Obs,plogis(Gamma+Z.beta))-alpha/2
prov <- ifelse(length(unique(df[,prov.char]))==1, unique(df[,prov.char]),
stop("Number of providers involved NOT equal to one!"))
Z.beta <- as.matrix(df[,Z.char])%*%beta
Obs <- df.prov[prov, "Obs"]; Exp <- df.prov[prov, "Exp"]
gamma.lower <- uniroot(LL.gamma, gamma[prov]+c(-5,0))$root
gamma.upper <- uniroot(UL.gamma, gamma[prov]+c(0,5))$root
SRR.lower <- sum(plogis(gamma.lower+Z.beta)) / Exp
SRR.upper <- sum(plogis(gamma.upper+Z.beta)) / Exp
return(c(gamma.lower, gamma.upper, SRR.lower, SRR.upper))
}
CL.no.readm <- function(df) {
prov <- ifelse(length(unique(df[,prov.char]))==1, unique(df[,prov.char]),
stop("Number of providers involved NOT equal to one!"))
Z.beta <- as.matrix(df[,Z.char])%*%beta
max.Z.beta <- norm(Z.beta, "I")
gamma.upper <- uniroot(function(x) prod(plogis(-x-Z.beta))/2-alpha,
(10+max.Z.beta)*c(-1,1))$root
SRR.upper <- sum(plogis(gamma.upper+Z.beta)) / df.prov[prov, "Exp"]
return(c(-Inf, gamma.upper, 0, SRR.upper))
}
CL.all.readm <- function(df) {
prov <- ifelse(length(unique(df[,prov.char]))==1, unique(df[,prov.char]),
stop("Number of providers involved NOT equal to one!"))
Z.beta <- as.matrix(df[,Z.char])%*%beta
max.Z.beta <- norm(Z.beta, "I")
Exp <- df.prov[prov, "Exp"]; SRR <- df.prov[prov, "SRR"]
gamma.lower <- uniroot(function(x) prod(plogis(x+Z.beta))/2-alpha,
(10+max.Z.beta)*c(-1,1))$root
SRR.lower <- sum(plogis(gamma.lower+Z.beta)) / Exp
return(c(gamma.lower, Inf, SRR.lower, SRR))
}
confint.finite <- sapply(by(data[(data$no.readm==0) & (data$all.readm==0),], data[(data$no.readm==0) & (data$all.readm==0),prov.char],identity),
FUN=function(df) CL.finite(df))
confint.no.readm <- sapply(by(data[data$no.readm==1,], data[data$no.readm==1,prov.char],identity),
FUN=function(df) CL.no.readm(df))
confint.all.readm <- sapply(by(data[data$all.readm==1,], data[data$all.readm==1,prov.char],identity),
FUN=function(df) CL.all.readm(df))
confint.df <- as.data.frame(t(cbind(confint.finite, confint.no.readm, confint.all.readm)))
names(confint.df) <- c("gamma.lower", "gamma.upper", "SRR.lower", "SRR.upper")
return(confint.df[order(rownames(confint.df)),])
} |
NULL
.gtimer.guiWidgetsToolkittcltk <- function(toolkit, ms, FUN, data=NULL, one.shot=FALSE, start=TRUE)
GTimer$new(toolkit, ms, FUN, data=data, one.shot=one.shot, start=start)
GTimer <- setRefClass("GTimer",
fields=list(
"again"="logical",
interval="integer",
data="ANY",
FUN="ANY",
FUN_wrapper="ANY",
ID = "ANY"
),
methods=list(
initialize=function(toolkit=guiToolkit(), ms, FUN=function(...) {},
data=NULL,
one.shot=FALSE, start=TRUE) {
f <- function() {
FUN(data)
if(again) {
start_timer()
} else {
stop_timer()
}
}
initFields(interval=as.integer(ms),
again=!one.shot,
data=data,
FUN=FUN,
FUN_wrapper=f
)
ID <<- ""
if(start)
start_timer()
callSuper()
},
set_interval=function(ms) {
"Set the interval. Need to stop and start active timer to implement."
interval <<- as.integer(ms)
},
start_timer = function() {
"Start the timer"
again <<- TRUE
ID <<- tcl("after", interval, FUN_wrapper)
},
stop_timer = function() {
"stop the timer"
again <<- FALSE
tcl("after", "cancel", ID)
}
)) |
getSubstrate <-
function(substrate){
substratelist<-list()
substratelist[[1]]<-xmlGetAttr(substrate,"id","unknow")
substratelist[[2]]<-xmlGetAttr(substrate,"name","unknow")
names(substratelist)<-c("id","name")
return(substratelist)
} |
test_that("credentials are provided", {
creds <- list(
access_key_id = "foo",
secret_access_key = "bar"
)
expect_true(is_credentials_provided(creds))
})
test_that("credentials not provided", {
creds <- NULL
expect_false(is_credentials_provided(creds))
creds <- Creds(
access_key_id = "",
secret_access_key = "bar"
)
expect_false(is_credentials_provided(creds))
creds <- Creds(
access_key_id = "foo",
secret_access_key = ""
)
expect_false(is_credentials_provided(creds))
creds <- Creds(
access_key_id = "",
secret_access_key = ""
)
expect_false(is_credentials_provided(creds))
})
test_that("credentials expired", {
creds <- Creds(
access_key_id = "foo",
secret_access_key = "bar",
expiration = 0
)
expect_false(is_credentials_provided(creds))
creds <- Creds(
access_key_id = "foo",
secret_access_key = "bar",
expiration = Inf
)
expect_true(is_credentials_provided(creds))
creds <- Creds(
access_key_id = "foo",
secret_access_key = "bar",
expiration = NA
)
expect_true(is_credentials_provided(creds))
})
f_get_credentials <- function() {
cfg <- get_config()
if (!is_credentials_provided(cfg$credentials$creds, window = 0)) {
get_credentials(cfg$credentials)
}
return(cfg)
}
g_dont_get_credentials <- function() {
cfg <- get_config()
return(cfg)
}
credential_provider <- function() {
list(
access_key_id = "AKID",
secret_access_key = "SECRET",
session_token = "SESSION",
expiration = Sys.time() + 5,
provider_name = "StaticProvider"
)
}
service <- function(config = list()) {
svc <- list(
get_credentials = f_get_credentials,
dont_get_credentials = g_dont_get_credentials
)
svc <- set_config(svc, config)
svc$.internal$config$credentials$provider <- list(credential_provider)
return(svc)
}
test_that("credentials are cached", {
creds <- list(access_key_id = "foo", secret_access_key = "bar")
svc <- service(config = list(credentials = list(creds = creds)))
actual <- svc$get_credentials()
expect_equivalent(actual$credentials$creds$access_key_id, creds$access_key_id)
expect_equivalent(actual$credentials$creds$secret_access_key, creds$secret_access_key)
svc <- service()
foo <- svc$get_credentials()
actual <- svc$dont_get_credentials()
expect_equivalent(actual$credentials$creds$access_key_id, "AKID")
expect_equivalent(actual$credentials$creds$secret_access_key, "SECRET")
})
test_that("credentials refresh when expired", {
svc <- service()
f1 <- svc$get_credentials()
expiration1 <- f1$credentials$creds$expiration
Sys.sleep(1)
f2 <- svc$get_credentials()
expiration2 <- f2$credentials$creds$expiration
expect_equal(expiration1, expiration2)
Sys.sleep(5)
f3 <- svc$get_credentials()
expiration3 <- f3$credentials$creds$expiration
expect_true(expiration1 != expiration3)
}) |
drawUniMMHPIntensity <- function(mmhp, simulation,
int_title = "Intensity of MMHP",
leg_location = "topright",
color = 1,
add = FALSE) {
events <- simulation$events
event_state <- simulation$zt
state <- simulation$z
state_time <- simulation$x
lambda0 <- mmhp$lambda0
lambda1 <- mmhp$lambda1
alpha <- mmhp$alpha
beta <- mmhp$beta
n <- length(events)
m <- length(state)
ylim <- c()
for (i in 1:(m - 1)) {
if (state[i] == 1) {
hawkes_time <- events[events >= state_time[i] &
events < state_time[i + 1]]
if (i == 1) hawkes_time <- hawkes_time[-1]
history <- events[events < state_time[i]]
hawkes_obj <- list(
lambda0 = lambda1,
alpha = alpha,
beta = beta
)
if (length(hawkes_time) > 1) {
ylim <- append(ylim, hawkes_max_intensity(hawkes_obj, hawkes_time))
}
}
}
if (!is.null(ylim)) {
yupper <- max(ylim)
} else {
message("No events in Hawkes state.")
yupper <- lambda0 + 1
}
if (add == FALSE) {
plot(0, 0,
xlim = c(0, state_time[m]), ylim = c(0, yupper * 2), type = "n",
xlab = "Time", ylab = "Intensity",
main = int_title
)
points(events[-1], rep(lambda0 / 2, n - 1),
cex = 0.6,
pch = ifelse(event_state[-1] == 1, 16, 1), col = "blue"
)
points(state_time, rep(lambda0, m), cex = 0.6, pch = 4, col = "red")
}
for (i in 1:(m - 1)) {
if (state[i] == 1) {
hawkes_time <- events[events >= state_time[i] &
events < state_time[i + 1]]
if (i == 1) {
hawkes_time <- hawkes_time[-1]
}
history <- events[events < state_time[i]]
hawkes_obj <- list(
lambda0 = lambda1,
alpha = alpha,
beta = beta
)
drawHPIntensity(
hp = hawkes_obj,
start = state_time[i],
end = state_time[i + 1],
history = history[-1],
events = hawkes_time,
color = color, i, add = TRUE
)
segments(x0 = state_time[i], y0 = lambda0, y1 = lambda1)
} else {
segments(
x0 = state_time[i], x1 = state_time[i + 1], y0 = lambda0,
lty = 2, col = color
)
}
}
if (add == FALSE) {
legend(leg_location, c(
"Hawkes event", "Poisson event",
"state change point"
),
col = c("blue", "blue", "red"),
pch = c(16, 1, 4), cex = 0.6
)
} else {
legend(leg_location, c("True", "Estimation"),
col = c("black", color),
lty = c(1, 1), cex = 0.6
)
}
} |
single2abr <- function(x){
stopifnot(is.integer(x))
x5 <- x - x %% 5
x5[x %in% c(1:4)] <- 1
x5
} |
spans <-
function(startandend, start, end){
return(startandend[1] <= start & startandend[2] >= end)
} |
get_minimum_wage <- function() {
params <- list(subject="minwage")
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('%,\\)]", "")
cols <- stringi::stri_replace_all_fixed(cols, "&", "_and_")
cols <- stringi::stri_replace_all_fixed(cols, "/", "_")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
cols <- stringi::stri_replace_first_regex(cols, "([[:digit:]])", "x_$1")
cols <- stringi::stri_replace_all_regex(cols, "_+", "_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
} |
dyplot.PrepGR <- function(x, ...) {
if (!inherits(x, "PrepGR")) {
stop("Non convenient data for x argument. Must be of class \"PrepGR\"")
}
dyplot.default(x, ...)
} |
test_that("Tests that terminal nodes are correct", {
x <- iris[, -1]
y <- iris[, 1]
context('Terminal nodes')
set.seed(24750371)
forest <- forestry(
ntree = 1,
x,
y,
replace = TRUE,
nthread = 2,
maxDepth = 5,
seed = 2323
)
skip_if_not_mac()
full_predictions <- predict(forest, x[c(5, 100, 104),], aggregation = 'terminalNodes')$terminalNodes
expect_equal(full_predictions, matrix(c(1,5,9,12), ncol = 1))
}) |
x <- rnorm(1e6)
y <- sample(0:1, size = length(x), replace = TRUE)
system.time(AUCBoot(x, y, nboot = 1e3))
y2 <- as.logical(y)
y3 <- as.factor(y)
x2 <- sample(seq_along(x))
x3 <- as.factor(x2)
microbenchmark::microbenchmark(
order(x),
order(x2),
order(x3),
xtfrm(x),
order(x, y),
order(x, y, method = "shell"),
order(x, y, method = "radix"),
order(x, y2),
order(x, y2, method = "shell"),
order(x, y2, method = "radix"),
order(x, y3),
order(x, y3, method = "shell"),
order(x, y3, method = "radix")
)
z <- runif(8)
z
(ind <- order(z))
ind2 <- sample(length(z), replace = TRUE)
ind2
microbenchmark::microbenchmark(
ind <- sample(1e6, replace = TRUE),
ind2 <- runif(1e6, min = 1, max = 1e6 + 1)
)
microbenchmark::microbenchmark(
ind2 <- sort(ind)
)
tabulate(sample(n, replace = TRUE), n)
n <- 1e6
Rcpp::sourceCpp('tmp-tests/fast-sort-sample.cpp')
library(dqrng)
microbenchmark::microbenchmark(
sort(sample(n, replace = TRUE)),
tabulate(sample(n, replace = TRUE), n),
sort(dqsample.int(n, replace = TRUE)),
tabulate(dqsample.int(n, replace = TRUE)),
sort_sample(n)
)
AUCBoot <- function(pred, target, nboot = 1e4, seed = NA, digits = NULL) {
y <- as.logical(target)
ord <- order(pred, y)
pred <- pred[ord]
y <- y[ord]
if (!is.na(seed)) {
old <- .Random.seed
on.exit( { .Random.seed <<- old } )
set.seed(seed)
}
repl <- boot_auc_sorted_tab(pred, y, nboot)
if (nbNA <- sum(is.na(repl)))
warning2("%d/%d bootstrap replicates were mono-class.", nbNA, nboot)
res <- c("Mean" = mean(repl, na.rm = TRUE),
stats::quantile(repl, c(0.025, 0.975), na.rm = TRUE),
"Sd" = stats::sd(repl, na.rm = TRUE))
round2(res, digits)
}
system.time(print(AUCBoot(x, y, nboot = 1e3))) |
setGeneric("bns.test",
function(yuima,r=rep(1,4),type="standard",adj=TRUE)
standardGeneric("bns.test"))
setMethod("bns.test",signature(yuima="yuima"),
function(yuima,r=rep(1,4),type="standard",adj=TRUE)
bns.test(yuima@data,r,type,adj))
setMethod("bns.test",signature(yuima="yuima.data"),
function(yuima,r=rep(1,4),type="standard",adj=TRUE){
bns.stat_standard <- function(yuima,r=rep(1,4)){
JV <- mpv(yuima,r=2)-mpv(yuima,r=c(1,1))
IQ <- mpv(yuima,r)
return(JV/sqrt((pi^2/4+pi-5)*IQ))
}
bns.stat_ratio <- function(yuima,r=rep(1,4),adj=TRUE){
bpv <- mpv(yuima,r=c(1,1))
RJ <- 1-bpv/mpv(yuima,r=2)
avar <- mpv(yuima,r)/bpv^2
if(adj){
avar[avar<1] <- 1
}
return(RJ/sqrt((pi^2/4+pi-5)*avar))
}
bns.stat_log <- function(yuima,r=rep(1,4),adj=TRUE){
bpv <- mpv(yuima,r=c(1,1))
RJ <- log(mpv(yuima,r=2)/bpv)
avar <- mpv(yuima,r)/bpv^2
if(adj){
avar[avar<1] <- 1
}
return(RJ/sqrt((pi^2/4+pi-5)*avar))
}
data <- get.zoo.data(yuima)
d.size <- length(data)
n <- integer(d.size)
for(d in 1:d.size){
n[d] <- sum(!is.na(as.numeric(data[[d]])))
if(n[d]<2) {
stop("length of data (w/o NA) must be more than 1")
}
}
switch(type,
"standard"="<-"(bns,bns.stat_standard(yuima,r)),
"ratio"="<-"(bns,bns.stat_ratio(yuima,r,adj)),
"log"="<-"(bns,bns.stat_log(yuima,r,adj)))
bns <- sqrt(n)*bns
result <- vector(d.size,mode="list")
for(d in 1:d.size){
p <- pnorm(bns[d],lower.tail=FALSE)
result[[d]] <- list(statistic=c(BNS=bns[d]),p.value=p,
method="Barndorff-Nielsen and Shephard jump test",
data.names=paste("x",d,sep=""))
class(result[[d]]) <- "htest"
}
return(result)
}) |
bivnormMH<-function(rho, rho1 = 0.9, sigma = c(1.2, 1.2), steps = 1000, type = 'ind'){
if(rho < -1 | rho > 1){
stop("rho must be between -1 and 1")
}
if(steps < 100)
warning("You should really do more than 100 steps")
target = candidate = matrix(0, ncol = 2, nrow = steps)
if(length(grep('^[Rr]',type))>0){
type = 'rw'
}else if(length(grep('^[Ii]',type)) > 0){
type = 'ind'
}else if(length(grep('^[Bb]',type)) > 0){
type = 'block'
}else if(length(grep('^[Gg]',type)) > 0){
type = 'gibbs'
}else{
stop("Type must be one of rw, ind, block or gibbs")
}
x0 = c(0,0)
x1 = c(0,0)
mu = c(0,0)
if(type == 'rw'){
startValue = c(2,2)
sigma1 = 0.5
var1 = sigma1^2
sigma2 = 1
var2 = sigma2^2
k = 2*pi/1000
u = runif(steps)
z1 = rnorm(steps,0,sigma1)
z2 = rnorm(steps,0,sigma1)
w = 1-rho^2
target[1,] = startValue
x1 = target[1,]
mu = target[1,]
x0 = c(mu[1]+z1[1], mu[2]+z2[1])
candidate[2,] = x0
for(n in 2:steps){
n1 = n-1
x1 = target[n1,]
x0 = candidate[n,]
canDens = exp(-1/(2*var2*w)*(x0[1]^2-2*rho*x0[1]*x0[2] +x0[2]^2))
curDens = exp(-1/(2*var2*w)*(x1[1]^2-2*rho*x1[1]*x1[2] +x1[2]^2))
if(u[n] < canDens/curDens){
target[n,] = x0
}else{
target[n,] = target[n1,]
}
mu = target[n,]
x0 = c(mu[1]+z1[n], mu[2]+z2[n])
if(n<steps)
candidate[n+1,] = x0
}
}else if(type == 'ind'){
if(rho1 < -1 | rho > 1)
stop("rho1 must be between -1 and 1")
if(any(sigma<= 0))
stop("The elements of sigma must be strictly positive non-zero")
u = runif(steps)
startValue = c(2.0, 1.5)
x1 = startValue
x0 = matrix(rnorm(2*steps, rep(0,2*steps), rep(sigma,steps)),ncol = 2)
x0[,2] = rho1*x0[,1]+sqrt(1-rho1^2)*x0[,2]
gDensInd = function(x, rho){
y = x[2]
x = x[1]
return(exp(-0.5/(1-rho^2)*(x^2 - 2*rho*x*y + y^2)))
}
qDens = function(x, rho, rho1, sigma){
zy = x[2]/sigma[2]
zx = x[1]/sigma[1]
return(exp(-0.5/(1-rho1^2)*(zx^2 - 2*rho*zx*zy + zy^2)))
}
for(n in 1:steps){
target[n,] = x1
candidate[n,] = x0[n,]
cand = gDensInd(x0[n,], rho)
cur = gDensInd(x1, rho)
qcand = qDens(x0[n,], rho, rho1, sigma)
qcur = qDens(x1, rho, rho1, sigma)
ratio = (cand/cur)*(qcur/qcand)
if(u[n] < ratio)
x1 = x0[n,]
}
}else if(type=='block'){
twosteps = 2*steps
target = candidate = matrix(0, ncol = 2, nrow = twosteps)
u = runif(twosteps)
startValue = c(2, 1.5)
x1 = startValue
sx = sqrt(1-rho^2)
vx = sx^2
sigma1 = 0.75
var1 = sigma1^2
gDensBlock = function(x, mx, vx){
return(exp(-0.5*(x-mx)^2/vx))
}
for(n in 1:steps){
mx = rho*x1[2]
x0 = c(rnorm(1,mx,sigma1), x1[2])
n1 = 2*n-1
target[n1,] = x1
candidate[n1,] = x0
cand = gDensBlock(x0[1], mx, vx)
cur = gDensBlock(x1[1], mx, vx)
qcand = gDensBlock(x0[1], mx, var1)
qcur = gDensBlock(x1[1], mx, var1)
ratio = (cand/cur)*(qcur/qcand)
if(u[n1] < ratio)
x1 = x0
my = rho*x1[1]
x0 = c(x1[1], rnorm(1, my, sigma1))
n2 = 2*n
target[n2,] = x1
candidate[n2,] = x0
cand = gDensBlock(x0[2], my, vx)
cur = gDensBlock(x1[2], my, vx)
qcand = gDensBlock(x0[2], my, var1)
qcur = gDensBlock(x1[2], my, var1)
ratio = (cand/cur)*(qcur/qcand)
if(u[n2] < ratio)
x1 = x0
}
}else if(type == 'gibbs'){
twosteps = 2*steps
target = candidate = matrix(0, ncol = 2, nrow = twosteps)
u = runif(twosteps)
startValue = c(2, 1.5)
x1 = startValue
sx = sqrt(1-rho^2)
mx = rho*x1[1]
vx = sx^2
sigma1 = sx
var1 = sigma1^2
gDensGibbs = function(x, mx, vx){
return(exp(-0.5*(x-mx)^2/vx))
}
for(n in 1:steps){
mx = rho*x1[1]
x0 = c(rnorm(1, mx, sigma1), x1[2])
n1 = 2*n-1
target[n1, ] = x1
candidate[n1,] = x0
cand = gDensGibbs(x0[1], mx, vx)
cur = gDensGibbs(x1[1], mx ,vx)
qcand = gDensGibbs(x0[1], mx, var1)
qcur = gDensGibbs(x1[1], mx ,var1)
ratio = (cand/cur)*(qcur/qcand)
if(u[n1] < ratio)
x1 = x0
mx = rho * x1[1]
x0 = c(x1[1], rnorm(1, mx, sigma1))
n2 = 2*n
target[n2,] = x1
candidate[n2,] = x0
cand = gDensGibbs(x0[2], mx, vx)
cur = gDensGibbs(x1[2], mx, vx)
qcand = gDensGibbs(x0[2], mx, var1)
qcur = gDensGibbs(x1[2], mx, var1)
ratio = (cand/cur)*(qcur/qcand)
if(u[n2] < ratio)
x1 = x0
}
}
target = data.frame(x = target[,1], y = target[,2])
plot(y~x,data = target,type = "l")
invisible(list(targetSample = target))
} |
test_that("Individual types are supported", {
result <- validate_wkt(c("GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))",
"POINT (30 10)",
"LINESTRING (30 10, 10 30, 40 40)",
"POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))",
"POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))",
"MULTIPOINT ((10 40), (40 30), (20 20), (30 10))",
"MULTIPOINT (10 40, 40 30, 20 20, 30 10)",
"MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))",
"MULTIPOLYGON (((30 20, 45 40, 10 40, 30 20)), ((15 5, 40 10, 10 20, 5 10, 15 5)))"
))
expect_length(result, 2)
expect_type(result, "list")
expect_true(is.data.frame(result))
expect_equal(sum(result$is_valid), 6)
}) |
for (i in 3) 3 |
get_all_channel_video_stats <- function(channel_id = NULL, mine = FALSE, ...) {
if (!is.character(channel_id) & !identical(tolower(mine), "true")) {
stop("Must specify a channel ID or specify mine = 'true'.")
}
a <- list_channel_resources(filter = c(channel_id = channel_id), part = "contentDetails")
playlist_id <- a$items[[1]]$contentDetails$relatedPlaylists$uploads
vids <- get_playlist_items(filter = c(playlist_id = playlist_id), max_results = 100)
vid_ids <- as.vector(vids$contentDetails.videoId)
res <- lapply(vid_ids, function(x) get_stats(x))
details <- lapply(vid_ids, get_video_details)
res_df <- do.call(what = bind_rows, lapply(res, data.frame))
details_tot <- data.frame(id = NA, title = NA,
publication_date = NA, description = NA,
channel_id = NA, channel_title = NA)
for (p in 1:length(details)) {
id <- details[[p]]$items[[1]]$id
title <- details[[p]]$items[[1]]$snippet$title
publication_date <- details[[p]]$items[[1]]$snippet$publishedAt
description <- details[[p]]$items[[1]]$snippet$description
channel_id <- details[[p]]$items[[1]]$snippet$channelId
channel_title <- details[[p]]$items[[1]]$snippet$channelTitle
detail <- data.frame(id = id, title = title,
publication_date = publication_date, description = description,
channel_id = channel_id, channel_title = channel_title)
details_tot <- rbind(detail, details_tot)
}
res_df$url <- paste0("https://www.youtube.com/watch?v=", res_df$id)
res_df <- merge(details_tot, res_df, by = "id")
res_df
} |
"nCm"<-
function(n, m, tol = 9.9999999999999984e-009)
{
len <- max(length(n), length(m))
out <- numeric(len)
n <- rep(n, length = len)
m <- rep(m, length = len)
mint <- (trunc(m) == m)
out[!mint] <- NA
out[m == 0] <- 1
whichm <- (mint & m > 0)
whichn <- (n < 0)
which <- (whichm & whichn)
if(any(which)) {
nnow <- n[which]
mnow <- m[which]
out[which] <- ((-1)^mnow) * Recall(mnow - nnow - 1, mnow)
}
whichn <- (n > 0)
nint <- (trunc(n) == n)
which <- (whichm & whichn & !nint & n < m)
if(any(which)) {
nnow <- n[which]
mnow <- m[which]
foo <- function(j, nn, mm)
{
n <- nn[j]
m <- mm[j]
iseq <- seq(n - m + 1, n)
negs <- sum(iseq < 0)
((-1)^negs) * exp(sum(log(abs(iseq))) - lgamma(m + 1))
}
out[which] <- unlist(lapply(seq(along = nnow), foo, nn = nnow,
mm = mnow))
}
which <- (whichm & whichn & n >= m)
nnow <- n[which]
mnow <- m[which]
out[which] <- exp(lgamma(nnow + 1) - lgamma(mnow + 1) - lgamma(nnow -
mnow + 1))
nna <- !is.na(out)
outnow <- out[nna]
rout <- round(outnow)
smalldif <- abs(rout - outnow) < tol
outnow[smalldif] <- rout[smalldif]
out[nna] <- outnow
out
} |
IyenGreenMLE <- function(t, q, N, type = 1, alpha = 0.05){
para0 <- c(1, 1)
res1 <- optim(par = para0, fn = IyenGreenLoglikT, method = "BFGS", control = list(trace = TRUE, REPORT = 1, fnscale = -1), t = t, q = q, N = N, type = type)
theta <- res1$par[1]
beta <- res1$par[2]
p0 <- 2 * pnorm(-abs(t))
res <- list("theta" = theta, "beta" = beta, "p" = p0)
return(res)
} |
"xf2" |
maxstat.setupSNP<-function(x, y, colSNPs=attr(x,"colSNPs"), ...)
{
if(missing(y))
stop("a case-control variable must be indicated in the second argument")
y<-deparse(substitute(y))
if (!exists(y)) y<-x[,y] else y<-get(y)
if(length(table(y))>2)
stop("case-control variable must have only 2 levels")
ans<-sapply(x[,colSNPs, drop=FALSE], function(o) maxstat(y, o, ...))
class(ans)<-"maxstat"
ans
} |
data("cdnow")
l.illegal.start.params.model <- list(c(alpha=0, beta=1, r=1, s=1),
c(alpha=-1, beta=1, r=1, s=1),
c(alpha=1, beta=1, r=0, s=1))
fct.testthat.inputchecks.clvfittedtransactions.nocov(name.method = "PNBD", method=pnbd,
start.params.model=c(r=1.234, alpha=0.678, s=2.345, beta=0.1111),
l.illegal.start.params.model = l.illegal.start.params.model,
has.cor = TRUE,
data.cdnow = cdnow) |
ynegbinompower<-function(nsize=200,r0=1.0,r1=0.5,shape0=1,shape1=shape0,pi1=0.5,alpha=0.05,twosided=1,fixedfu=1,type=1,u=c(0.5,0.5,1),ut=c(0.5,1.0,1.5),tfix=ut[length(ut)]+0.5,maxfu=10.0,tchange=c(0,0.5,1),ratec1=c(0.15,0.15,0.15),ratec0=ratec1,eps=1.0e-03){
pi0<-1-pi1
eff2<-(log(r1/r0))^2
alpha1<-alpha
if (twosided==1)alpha1<-alpha/2
qalpha<--qnorm(alpha1)
tilder0<-tilder1<-rep(0,3)
tilder0[1]<-tilder1[1]<-r0
tilder0[2]<-r0;tilder1[2]<-r1
tilder0[3]<-tilder1[3]<-pi0*r0+pi1*r1
exposure<-SDexp<-rep(0,3)
tildeXPWR<-XPWR<-tildemineffsize<-mineffsize<-rep(0,3)
if (type==1){
exposure<-fixedfu
SDexp<-0
if (shape0==0){a<-pi0*r0*exposure[1]}
else {a<-shape0*r0*exposure[1];a<-a/(1+a);a<-pi0/shape0*a}
if (shape1==0){b<-pi1*r1*exposure[2]}
else {b<-shape1*r1*exposure[2];b<-b/(1+b);b<-pi1/shape1*b}
mta<-a
mtb<-b
V1<-1/a+1/b
tildeV1<-1/mta+1/mtb
for (j in 1:3){
if (shape0==0){anull<-pi0*tilder0[j]*exposure[1]}
else {anull<-shape0*tilder0[j]*exposure[1];anull<-anull/(1+anull);anull<-pi0/shape0*anull}
if (shape1==0){bnull<-pi1*tilder1[j]*exposure[2]}
else {bnull<-shape1*tilder1[j]*exposure[2];bnull<-bnull/(1+bnull);bnull<-pi1/shape1*bnull}
mtanull=anull
mtbnull=bnull
V0<-1/anull+1/bnull
tildeV0<-1/mtanull+1/mtbnull
tildeXPWR[j]<-pnorm(-qalpha*sqrt(tildeV0/tildeV1)+sqrt(nsize)*sqrt(eff2/tildeV1))
XPWR[j]<-pnorm(-qalpha*sqrt(V0/V1)+sqrt(nsize)*sqrt(eff2/V1))
tildemineffsize[j]<-1-exp(-qalpha*sqrt(tildeV0/nsize))
mineffsize[j]<-1-exp(-qalpha*sqrt(V0/nsize))
}
}
else {
abc0=negint2(ux=r0*shape0,fixedfu=fixedfu,type=type,u=u,ut=ut,tfix=tfix,maxfu=maxfu,tchange=tchange,ratec=ratec0,eps=eps)
abc1=negint2(ux=r1*shape1,fixedfu=fixedfu,type=type,u=u,ut=ut,tfix=tfix,maxfu=maxfu,tchange=tchange,ratec=ratec1,eps=eps)
exposure[1]=abc0$tt;SDexp[1]=sqrt(abc0$vt)
exposure[2]=abc1$tt;SDexp[2]=sqrt(abc1$vt)
exposure[3]=pi0*exposure[1]+pi1*exposure[2]
SDexp[3]=pi0*SDexp[1]+pi1*SDexp[2]
if (shape0==0) {a<-pi0*r0*exposure[1];mta=a}
else {a<-shape0*r0*exposure[1];a<-a/(1+a);a<-pi0/shape0*a;mta<-pi0/shape0*abc0$mt}
if (shape1==0) {b<-pi1*r1*exposure[2];mtb=b}
else {b<-shape1*r1*exposure[2];b<-b/(1+b);b<-pi1/shape1*b;mtb<-pi1/shape1*abc1$mt}
V1<-1/a+1/b
tildeV1<-1/mta+1/mtb
for (j in 1:3){
def0=negint2(ux=tilder0[j]*shape0,fixedfu=fixedfu,type=type,u=u,ut=ut,tfix=tfix,maxfu=maxfu,tchange=tchange,ratec=ratec0,eps=eps)
def1=negint2(ux=tilder1[j]*shape1,fixedfu=fixedfu,type=type,u=u,ut=ut,tfix=tfix,maxfu=maxfu,tchange=tchange,ratec=ratec1,eps=eps)
if (shape0==0){anull<-pi0*tilder0[j]*exposure[1];mtanull=anull}
else {anull<-shape0*tilder0[j]*exposure[1];anull<-anull/(1+anull);anull<-pi0/shape0*anull;mtanull<-pi0/shape0*def0$mt}
if (shape1==0){bnull<-pi1*tilder1[j]*exposure[2];mtbnull=bnull}
else {bnull<-shape1*tilder1[j]*exposure[2];bnull<-bnull/(1+bnull);bnull<-pi1/shape1*bnull;mtbnull<-pi1/shape1*def1$mt}
V0<-1/anull+1/bnull
tildeV0<-1/mtanull+1/mtbnull
tildeXPWR[j]<-pnorm(-qalpha*sqrt(tildeV0/tildeV1)+sqrt(nsize)*sqrt(eff2/tildeV1))
XPWR[j]<-pnorm(-qalpha*sqrt(V0/V1)+sqrt(nsize)*sqrt(eff2/V1))
tildemineffsize[j]<-1-exp(-qalpha*sqrt(tildeV0/nsize))
mineffsize[j]<-1-exp(-qalpha*sqrt(V0/nsize))
}
}
list(tildeXPWR=tildeXPWR*100,XPWR=XPWR*100,tildemineffsize=tildemineffsize,mineffsize=mineffsize,Exposure=exposure,SDexp=SDexp)
} |
context("Checking select_documents")
test_that("select_documents ...",{
}) |
MeanWilliamsDesign.Equality <-
function(alpha,beta,sigma,k,margin){
n<-(qnorm(1-alpha/2)+qnorm(1-beta))^2*sigma^2/(k*margin^2)
n
} |
write.Structure <- function(object, ploidy, file = "",
samples = Samples(object), loci = Loci(object),
writepopinfo = TRUE, extracols = NULL,
missingout = -9){
if(!all(!is.na(Ploidies(object, samples = samples, loci = loci))))
stop("Ploidies needed.")
if(missing(ploidy))
stop("Ploidy of file must be specified seperately from ploidies of dataset.")
structdata <- data.frame(rowlabel=c("missing",rep(samples, each = ploidy)))
thiscol <- 1
if(writepopinfo){
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed, or set writepopinfo to FALSE")
thiscol <- thiscol+1
structdata[[thiscol]] <- c(0,rep(PopInfo(object)[samples], each = ploidy))
names(structdata)[thiscol] <- "PopInfo"
}
for(excol in dimnames(extracols)[[2]]){
thiscol <- thiscol+1
structdata[[thiscol]] <- c(0,rep(extracols[samples, excol], each = ploidy))
names(structdata)[thiscol] <- excol
}
for(L in loci){
thiscol <- thiscol + 1
alleles <- missingout
for(s in samples){
if(isMissing(object,s,L)){
thesealleles <- rep(missingout, ploidy)
} else {
if(Ploidies(object, s, L) < ploidy){
if(length(Genotype(object,s,L)) == Ploidies(object, s, L)){
thesealleles <- c(Genotype(object, s, L),
rep(missingout,
times = ploidy - Ploidies(object, s, L)))
} else {
if(length(Genotype(object, s, L)) < Ploidies(object, s, L)){
thesealleles <- c(Genotype(object, s, L),
rep(Genotype(object, s, L)[1],
times = Ploidies(object, s, L) -
length(Genotype(object, s, L))),
rep(missingout,
times = ploidy - Ploidies(object, s, L)))
} else {
thesealleles <- c(sample(Genotype(object, s, L),
Ploidies(object, s, L),replace = FALSE),
rep(missingout,
times = ploidy - Ploidies(object, s, L)))
cat(paste("Randomly removed alleles:", s, L), sep = "\n")
}
}
} else {
if(length(Genotype(object, s, L)) == ploidy){
thesealleles <- Genotype(object, s, L)
} else {
if(length(Genotype(object, s, L)) < ploidy){
thesealleles <- c(Genotype(object, s, L),
rep(Genotype(object, s, L)[1],
times = ploidy -
length(Genotype(object, s, L))))
} else {
thesealleles <- sample(Genotype(object, s, L), ploidy,
replace = FALSE)
cat(paste("Randomly removed alleles:", s, L), sep = "\n")
}
}
}
}
alleles <- c(alleles, thesealleles)
}
structdata[[thiscol]] <- alleles
names(structdata)[thiscol] <- L
}
if(writepopinfo){
colstoskip <- 2
} else {
colstoskip <- 1
}
if(!is.null(extracols)){
colstoskip <- colstoskip + dim(extracols)[2]
}
cat(c(paste(c(rep("", colstoskip), names(structdata)[-(1:colstoskip)]),
collapse = "\t"),
paste(c(rep("", colstoskip),
rep(as.character(missingout), ncol(structdata) - colstoskip)),
collapse = "\t")),
sep = "\n", file = file)
write.table(structdata[-1,], file = file, sep = "\t", row.names = FALSE,
quote = FALSE, col.names = FALSE, append = TRUE)
}
write.GenoDive<-function(object,
digits = 2, file = "", samples = Samples(object),
loci = Loci(object)){
if(!all(!is.na(Ploidies(object, samples = samples, loci = loci))))
stop("Ploidies needed.
Use estimatePloidy to get max number of alleles.")
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed.")
if(!all(!is.na(Usatnts(object)[loci])))
stop("Usatnts needed.")
numsam <- length(samples)
numloc <- length(loci)
numpop <- length(unique(PopInfo(object)[samples]))
maxploidy <- max(Ploidies(object, samples, loci))
lines <- c(Description(object),
paste(numsam, numpop, numloc, maxploidy, digits, sep = "\t"))
lines[3:(numpop+2)] <-
PopNames(object)[sort(unique(PopInfo(object)[samples]))]
lines[numpop+3]<-paste("Population\tIndividual",
paste(loci, sep = "", collapse = "\t"), sep = "\t")
for(s in 1:numsam){
lines[numpop+3+s] <- paste(PopInfo(object)[samples[s]],
samples[s], sep = "\t")
}
for(L in loci){
repmiss<-function(value){
if(value[1] == Missing(object)){ 0 } else {value}
}
convertedalleles <- mapply(repmiss, Genotypes(object, samples, L),
SIMPLIFY = FALSE)
divallele <- function(value) floor(value/Usatnts(object)[L])
convertedalleles <- mapply(divallele, convertedalleles, SIMPLIFY = FALSE)
suballele <- function(value){
if(value[1] != 0){
value-(10^(digits-1))
} else{
0
}
}
while(max(mapply(max, convertedalleles)) >= 10 ^ digits){
convertedalleles <- mapply(suballele, convertedalleles,
SIMPLIFY = FALSE)
}
for(s in 1:numsam){
charalleles <- as.character(convertedalleles[[s]])
allelestring <- ""
for(ca in charalleles){
allele <- ca
while(nchar(allele) < digits){
allele <- paste("0", allele, sep = "")
}
allelestring <- paste(allelestring, allele, sep="")
}
lines[numpop+3+s] <- paste(lines[numpop+3+s], allelestring, sep = "\t")
}
}
cat(lines, file = file, sep = "\n")
}
write.SPAGeDi<-function(object, samples = Samples(object),
loci = Loci(object),
allelesep = "/", digits = 2, file = "",
spatcoord = data.frame(X = rep(1, length(samples)),
Y = rep(1, length(samples)),
row.names = samples)){
if(!all(!is.na(Ploidies(object, samples, loci))))
stop("Ploidies needed.")
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed.")
if(!all(!is.na(Usatnts(object)[loci])))
stop("Usatnts needed.")
if(identical(row.names(spatcoord), as.character(1:dim(spatcoord)[1])))
row.names(spatcoord) < -samples
gentable <- data.frame(Ind = samples,
Cat = PopNames(object)[PopInfo(object)[samples]],
spatcoord[samples,])
for(L in loci){
genotypesL <- Genotypes(object, samples, L)
genotypesL[isMissing(object, samples, L)] <- 0
divallele <- function(value) floor(value/Usatnts(object)[L])
genotypesL <- mapply(divallele, genotypesL, SIMPLIFY = FALSE)
suballele <- function(value){
if(value[1] != 0){
value - (10 ^ (digits - 1))
} else {
0
}
}
while(max(mapply(max, genotypesL)) >= 10 ^ digits){
genotypesL <- mapply(suballele, genotypesL, SIMPLIFY = FALSE)
}
names(genotypesL) <- samples
zerostoadd <- Ploidies(object, samples, L) - mapply(length, genotypesL)
names(zerostoadd) <- samples
for(s in samples){
if(length(genotypesL[[s]]) == 1){
genotypesL[[s]] <- rep(genotypesL[[s]], Ploidies(object, s, L))
} else {
if(zerostoadd[s] < 0){
genotypesL[[s]] <- sample(genotypesL[[s]],
Ploidies(object, s, L),
replace=FALSE)
cat("Alleles randomly removed to get to ploidy:", L, s, "\n")
} else {
genotypesL[[s]] <- c(genotypesL[[s]], rep(0, zerostoadd[s]))
}
}
if(allelesep == ""){
genotypesL[[s]] <- as.character(genotypesL[[s]])
for(a in 1:length(genotypesL[[s]])){
while(nchar(genotypesL[[s]][a]) < digits){
genotypesL[[s]][a] <- paste(0, genotypesL[[s]][a],
sep = "")
}
}
}
}
genvect <- mapply(paste, genotypesL, collapse = allelesep)
gentable <- data.frame(gentable, genvect)
names(gentable)[dim(gentable)[2]] <- L
}
SpagTemp <- tempfile()
write.table(gentable, file = SpagTemp, sep = "\t", row.names = FALSE,
col.names = TRUE, quote = FALSE)
cat(paste(length(samples), length(unique(PopInfo(object)[samples])),
dim(spatcoord)[2],
length(loci), digits, max(Ploidies(object,samples,loci)),
sep="\t"),
"0",
readLines(SpagTemp), "END", sep = "\n", file = file)
}
write.GeneMapper <- function(object, file = "", samples = Samples(object),
loci = Loci(object)){
if(!all(!is.na(Ploidies(object, samples, loci))))
stop("Ploidies needed to determine number of columns.")
numallelecol <- max(Ploidies(object, samples, loci))
numrows <- length(samples) * length(loci)
gentable <- data.frame(Sample.Name = rep(samples, times = length(loci)),
Marker = rep(loci, each = length(samples)))
alcollabels <- paste("Allele.", 1:numallelecol, sep = "")
for(ac in 1:numallelecol){
gentable[[ac + 2]] <- rep("", times = numrows)
names(gentable)[ac + 2] <- alcollabels[ac]
}
currentrow <- 1
for(L in loci){
for(s in samples){
thesealleles <- as.character(Genotype(object, s, L))
while((length(thesealleles) + 2) > dim(gentable)[2])
gentable <- data.frame(gentable, rep("", numrows),
stringsAsFactors = FALSE)
gentable[currentrow, 3:(length(thesealleles) + 2)] <- thesealleles
currentrow <- currentrow + 1
}
}
write.table(gentable, file = file, sep = "\t", quote = FALSE,
row.names = FALSE, col.names = TRUE)
}
write.Tetrasat <- function(object, samples = Samples(object), loci = Loci(object),
file = ""){
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed.")
if(!all(!is.na(Usatnts(object)[loci])))
stop("Usatnts needed.")
if(!all(Ploidies(object, samples, loci) == 4))
stop("Ploidy must be 4.")
allpops <- unique(PopInfo(object)[samples])
lines <- c(Description(object)[1], loci)
datastart <- length(lines) + 1
sampleindex <- integer(0)
currentline <- datastart
for(pop in allpops){
lines[currentline] <- "Pop"
currentline <- currentline + 1
thesesamples <- samples[PopInfo(object)[samples] == pop]
indextoadd <- currentline:(currentline + length(thesesamples) - 1)
names(indextoadd) <- thesesamples
sampleindex <- c(sampleindex, indextoadd)
for(s in thesesamples){
samname <- s
while(nchar(samname) < 20){
samname <- paste(samname, " ", sep = "")
}
lines[currentline] <- samname
currentline <- currentline + 1
}
}
for(L in loci){
divallele <- function(value){
if(value[1] == Missing(object)){
value
} else {
floor(value/Usatnts(object)[L])
}
}
convertedalleles <- mapply(divallele, Genotypes(object, samples, L),
SIMPLIFY = FALSE)
names(convertedalleles) <- samples
suballele <- function(value){
if(value[1] == Missing(object)){
value
} else {
value - 10
}
}
while(max(mapply(max,convertedalleles)) >= 100){
convertedalleles <- mapply(suballele, convertedalleles,
SIMPLIFY = FALSE)
}
for(s in samples){
if(convertedalleles[[s]][1] == Missing(object)){
charalleles <- " "
} else {
charalleles <- as.character(convertedalleles[[s]])
if(length(charalleles) == 1){
charalleles <- rep(charalleles, 4)
}
if(length(charalleles) > 4){
charalleles <- sample(charalleles, 4, replace = FALSE)
cat(c("Alleles randomly removed:", s, L, "\n"), sep = " ")
}
}
allelestring <- ""
for(ca in charalleles){
allele <- ca
while(nchar(allele) < 2){
allele <- paste("0", allele, sep="")
}
allelestring <- paste(allelestring, allele, sep = "")
}
while(nchar(allelestring) < 9){
allelestring <- paste(allelestring, " ", sep = "")
}
lines[sampleindex[s]] <- paste(lines[sampleindex[s]], allelestring,
sep = "")
}
}
cat(lines, sep = "\n", file = file)
}
write.ATetra<-function(object, samples = Samples(object), loci = Loci(object),
file = ""){
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed.")
if(!all(Ploidies(object, samples, loci) == 4))
stop("Ploidy must be 4.")
lines <- paste("TIT", Description(object)[1], sep = ",")
currentline <- 2
locnums <- 1:length(loci)
names(locnums) <- loci
samnums <- 1:length(samples)
names(samnums) <- samples
popnames <- PopNames(object)[sort(unique(PopInfo(object)[samples]))]
popnums <- sort(unique(PopInfo(object)[samples]))
names(popnums) <- popnames
for(L in loci){
lines[currentline] <- paste("LOC", locnums[L], L, sep = ",")
currentline <- currentline + 1
for(p in popnames){
lines[currentline] <- paste("POP", locnums[L], popnums[p], p, sep = ",")
currentline <- currentline + 1
thesesamples <- Samples(object, populations = p)
thesesamples <- thesesamples[thesesamples %in% samples]
for(s in thesesamples){
lines[currentline] <- paste("IND", locnums[L], popnums[p],
samnums[s], s, sep = ",")
thesealleles<-Genotype(object, s, L)
if(isMissing(object, s, L)){
thesealleles <- ""
cat("Missing data:", s, L, "\n", sep = " ")
}
if(length(thesealleles) > 4){
thesealleles <- sample(thesealleles, 4, replace = FALSE)
cat("More than 4 alleles:", s, L, "\n", sep = " ")
}
for(a in 1:4){
if(length(thesealleles) >= a){
lines[currentline] <- paste(lines[currentline],
thesealleles[a], sep = ",")
} else {
lines[currentline] <- paste(lines[currentline], "", sep = ",")
}
}
currentline <- currentline + 1
}
}
}
lines[currentline] <- "END"
cat(lines, sep = "\n", file = file)
}
write.POPDIST <- function(object, samples = Samples(object),
loci = Loci(object), file = ""){
if(!all(!is.na(PopInfo(object)[samples])))
stop("PopInfo needed")
if(!all(!is.na(Ploidies(object,samples,loci))))
stop("Ploidies needed")
Lines <- c(Description(object)[1], loci)
samindex <- integer(0)
for(p in unique(PopInfo(object)[samples])){
Lines <- c(Lines, "Pop")
for(s in samples[samples %in% Samples(object, populations=p)]){
Lines <- c(Lines, paste(PopNames(object)[p], "\t,", sep = ""))
samindex <- c(samindex, length(Lines))
names(samindex)[length(samindex)] <- s
}
if(length(unique(
Ploidies(object,samples[samples %in% Samples(object,
populations = p)],
loci))) > 1)
warning(paste("Mixed ploidy in population", p,
"; POPDIST may reject file."))
}
for(L in loci){
thesegen <- Genotypes(object, samples, L)
if(max(mapply(max, thesegen)) > 99){
if(!is.na(Usatnts(object)[L]) && Usatnts(object)[L] > 1){
thesegen <- array(mapply(function(value){
if(value[1] == Missing(object)){
value
} else {
floor(value/Usatnts(object)[L])
}
},
thesegen, SIMPLIFY = FALSE),
dim = c(length(samples), 1),
dimnames=list(samples, L))
}
while(max(mapply(max, thesegen)) > 99){
thesegen <- array(mapply(function(value){
if(value[1] == Missing(object)){
value
} else {
value - 10
}
},
thesegen, SIMPLIFY = FALSE),
dim = c(length(samples), 1),
dimnames = list(samples, L))
}
}
for(s in samples){
if(thesegen[[s,L]][1] == Missing(object)){
alleles <- "00"
} else {
alleles <- as.character(thesegen[[s, L]])
}
if(length(alleles) > Ploidies(object, s, L)){
alleles <- sample(alleles, Ploidies(object, s, L))
warning(paste("Alleles randomly removed:", s, L))
}
Lines[samindex[s]] <- paste(Lines[samindex[s]], " ", sep="")
for(a in 1:Ploidies(object, s, L)){
if(a > length(alleles)){
Lines[samindex[s]] <- paste(Lines[samindex[s]], "00", sep = "")
} else {
if(nchar(alleles[a]) == 1)
alleles[a] <- paste("0", alleles[a], sep="")
Lines[samindex[s]] <- paste(Lines[samindex[s]],
alleles[a], sep = "")
}
}
}
}
cat(Lines, file = file, sep = "\n")
}
gendata.to.genind <- function(object, samples = Samples(object),
loci = Loci(object)){
if(!is(object, "gendata")) stop("genambig or genbinary object needed.")
object <- object[samples, loci]
if(!"ploidysample" %in% class(object@Ploidies)){
object <- reformatPloidies(object, output = "sample")
}
ploidy <- Ploidies(object)
if(any(is.na(ploidy))) stop("Please specify ploidy.")
if(is(object, "genambig"))
object <- genambig.to.genbinary(object)
tab <- Genotypes(object)
tab[tab == Missing(object)] <- NA
dimnames(tab)[[2]] <- gsub(".", "-", dimnames(tab)[[2]], fixed = TRUE)
x <- adegenet::genind(tab, pop = PopNames(object)[PopInfo(object)[samples]],
ploidy = ploidy, type = "PA")
return(x)
} |
publish.subgroupAnalysis <- function(object,...){
publish(summary(object,...),...)
} |
library(ComplexHeatmap)
gb = annotation_axis_grob(at = 1:5, labels = month.name[1:5], labels_rot = 0,
side = "left", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "left", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:5, labels = month.name[1:5], labels_rot = 0,
side = "left", facing = "inside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "left", facing = "inside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:5, labels = month.name[1:5], labels_rot = 0,
side = "right", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "right", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:5, labels = month.name[1:5], labels_rot = 0,
side = "right", facing = "inside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "right", facing = "inside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 0,
side = "top", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "top", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 90,
side = "top", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "top", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 45,
side = "top", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "top", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 0,
side = "top", facing = "inside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "top", facing = "inside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 0,
side = "bottom", facing = "outside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "bottom", facing = "outside"')
grid.draw(gb)
popViewport()
gb = annotation_axis_grob(at = 1:3, labels = month.name[1:3], labels_rot = 0,
side = "bottom", facing = "inside")
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
grid.rect()
grid.text('side = "bottom", facing = "inside"')
grid.draw(gb)
popViewport()
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
gb = annotation_axis_grob(labels_rot = 0, side = "left", facing = "outside")
grid.rect()
grid.text('side = "left", facing = "outside"')
grid.draw(gb)
popViewport()
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
gb = annotation_axis_grob(side = "left", direction = "reverse")
grid.rect()
grid.text('side = "left", direction = "reverse')
grid.draw(gb)
popViewport()
grid.newpage()
pushViewport(viewport(xscale = c(0, 4), yscale = c(0, 6), width = 0.6, height = 0.6))
gb = annotation_axis_grob(side = "bottom", direction = "reverse")
grid.rect()
grid.text('side = "bottom", direction = "reverse"')
grid.draw(gb)
popViewport() |
step_model<-function(HourTemp,
df=data.frame(
lower=c(-1000,1.4,2.4,9.1,12.4,15.9,18),
upper=c(1.4,2.4,9.1,12.4,15.9,18,1000),
weight=c(0,0.5,1,0.5,0,-0.5,-1)),summ=TRUE)
{lower<-df$lower;upper<-df$upper;weight<-df$weight
if (summ==TRUE) return(cumsum(sapply(HourTemp,function(x) weight[which(x>lower&x<=upper)]))) else
return(sapply(HourTemp,function(x) weight[which(x>lower&x<=upper)]))
}
Utah_Model<-function(HourTemp,summ=TRUE)
return(step_model(HourTemp,df=data.frame(lower=c(-1000,1.4,2.4,9.1,12.4,15.9,18),upper=c(1.4,2.4,9.1,12.4,15.9,18,1000),weight=c(0,0.5,1,0.5,0,-0.5,-1)),summ=summ))
Chilling_Hours<-function(HourTemp,summ=TRUE)
{
CH_range<-which(HourTemp<=7.2&HourTemp>=0)
CH_weights<-rep(0,length(HourTemp))
CH_weights[CH_range]<-1
if(summ==TRUE) return(cumsum(CH_weights)) else
return(CH_weights)
}
Dynamic_Model <- function(HourTemp,
summ = TRUE,
E0 = 4153.5,
E1 = 12888.8,
A0 = 139500,
A1 = 2567000000000000000,
slope = 1.6,
Tf = 277)
{
if(missing(HourTemp)) {
stop("HourTemp must be present! Aborting.")
}
TK <- HourTemp + 273
aa <- A0/A1
ee <- E1-E0
sr <- exp(slope*Tf*(TK-Tf)/TK)
xi <- sr/(1+sr)
xs <- aa*exp(ee/TK)
eak1 <- exp(-A1*exp(-E1/TK))
x=0
for (l in c(2:length(HourTemp))) {
S <- x[l-1]
if(x[l-1] >= 1) {
S <- S*(1-xi[l-2])
}
x[l] <- xs[l-1]-(xs[l-1]-S)*eak1[l-1]
}
delta <- rep(0,length(HourTemp))
ii <- which(x >= 1)
delta[ii] <- x[ii]*xi[ii-1]
if (summ) return(cumsum(delta))
return(delta)
}
xsfct <- function(A0, A1, E0, E1, temp) {
return ( A0/A1 * exp(-(E0 - E1)/temp) )
}
k1fct <- function(A1, E1, temp) {
return( A1*exp(-E1/temp) )
}
DynModel_driver <- function(temp,
times,
A0 = 139500,
A1 = 2567000000000000000,
E0 = 4153.5,
E1 = 12888.8,
slope = 1.6,
Tf = 4,
deg_celsius=TRUE) {
if(missing(times)) {
times <- c(1:length(temp))
}
stopifnot(length(temp) == length(times))
if(deg_celsius) {
temp <- temp + 273
Tf <- Tf + 273
}
xs <- A0/A1 * exp(-(E0 - E1)/temp)
ek1 <- exp(-A1*exp(-E1/temp)*c(diff(x=times, lag=1), 0))
x <- 0.
y <- 0.
for(i in c(1:(length(times)-1))) {
x[i+1] <- xs[i] - (xs[i] - x[i])*ek1[i]
y[i+1] <- 0
if(x[i+1] >= 1) {
xtmp <- slope*Tf*(temp[i]-Tf)/temp[i]
delta <- x[i+1]
if(xtmp < 17) {
sr <- exp(xtmp)
delta <- delta*sr/(1+sr)
}
y[i+1] <- delta
x[i+1] <- x[i+1] - delta
}
}
return(invisible(list(x=x, y=cumsum(y), delta=y, xs=xs)))
}
GDH<-function(HourTemp,summ=TRUE)
{Stress<-1
Tb<-4
Tu<-25
Tc<-36
GDH_weight<-rep(0,length(HourTemp))
GDH_weight[which(HourTemp>=Tb&HourTemp<=Tu)]<-Stress*(Tu-Tb)/2*
(1+cos(pi+pi*(HourTemp[which(HourTemp>=Tb&HourTemp<=Tu)]-Tb)/(Tu-Tb)))
GDH_weight[which(HourTemp>Tu&HourTemp<=Tc)]<-Stress*(Tu-Tb)*
(1+cos(pi/2+pi/2*(HourTemp[which(HourTemp>Tu&HourTemp<=Tc)]-Tu)/(Tc-Tu)))
if (summ) return(cumsum(GDH_weight)) else
return(GDH_weight)
}
GDH_model<-function(HourTemp,summ=TRUE)
{Stress<-1
Tb<-4
Tu<-25
Tc<-36
GDH_weight<-rep(0,length(HourTemp))
GDH_weight[which(HourTemp>=Tb&HourTemp<=Tu)]<-Stress*(Tu-Tb)/2*
(1+cos(pi+pi*(HourTemp[which(HourTemp>=Tb&HourTemp<=Tu)]-Tb)/(Tu-Tb)))
GDH_weight[which(HourTemp>Tu&HourTemp<=Tc)]<-Stress*(Tu-Tb)*
(1+cos(pi/2+pi/2*(HourTemp[which(HourTemp>Tu&HourTemp<=Tc)]-Tu)/(Tc-Tu)))
if (summ) return(cumsum(GDH_weight)) else
return(GDH_weight)
}
GDD<-function(HourTemp,summ=TRUE,Tbase=5)
{
Tlow<-10
Tup<-30
GDD_weight<-rep(0,length(HourTemp))
GDD_weight[which(HourTemp>=Tlow&HourTemp<=Tup)]<-(HourTemp[which(HourTemp>=Tlow&HourTemp<=Tup)]-Tbase)/24
GDD_weight[which(HourTemp<Tlow)]<-(Tlow-Tbase)/24
GDD_weight[which(HourTemp>Tup)]<-(Tup-Tbase)/24
if (summ) return(cumsum(GDD_weight)) else
return(GDD_weight)
} |
test_utility_calc_1 <- function() {
d <- data.frame(
predicted_probability = c(0, 0.5, 0.5, 0.5),
made_purchase = c(FALSE, TRUE, FALSE, FALSE),
false_positive_value = -5,
true_positive_value = 95,
true_negative_value = 0.001,
false_negative_value = -0.01
)
values <- model_utility(d, 'predicted_probability', 'made_purchase')
expect_true(is.null(check_utility_calc(values, constant_utilities = TRUE,
orig_score = d$predicted_probability,
orig_outcome = d$made_purchase)))
expect <- wrapr::build_frame(
"model" , "threshold", "count_taken", "fraction_taken", "true_positive_value", "false_positive_value", "true_negative_value", "false_negative_value", "total_value", "true_negative_count", "false_negative_count", "true_positive_count", "false_positive_count" |
"predicted_probability", 0 , 4 , 1 , 95 , -15 , 0 , 0 , 80 , 0 , 0 , 1 , 3 |
"predicted_probability", 0.25 , 3 , 0.75 , 95 , -10 , 0.001 , 0 , 85 , 1 , 0 , 1 , 2 |
"predicted_probability", NA_real_ , 0 , 0 , 0 , 0 , 0.003 , -0.01 , -0.007 , 3 , 1 , 0 , 0 )
wrapr::check_equiv_frames(values, expect, tolerance = 1.e-3)
invisible(NULL)
}
test_utility_calc_1()
test_utility_calc_1b <- function() {
d <- data.frame(
predicted_probability = c(0, 0, 0, 0.5),
made_purchase = c(FALSE, TRUE, FALSE, FALSE),
false_positive_value = -5,
true_positive_value = 95,
true_negative_value = 0.001,
false_negative_value = -0.01
)
values <- model_utility(d, 'predicted_probability', 'made_purchase')
expect_true(is.null(check_utility_calc(values, constant_utilities = TRUE,
orig_score = d$predicted_probability,
orig_outcome = d$made_purchase)))
expect <- wrapr::build_frame(
"model" , "threshold", "count_taken", "fraction_taken", "true_positive_value", "false_positive_value", "true_negative_value", "false_negative_value", "total_value", "true_negative_count", "false_negative_count", "true_positive_count", "false_positive_count" |
"predicted_probability", 0 , 4 , 1 , 95 , -15 , 0 , 0 , 80 , 0 , 0 , 1 , 3 |
"predicted_probability", 0.25 , 1 , 0.25 , 0 , -5 , 0.002 , -0.01 , -5.008 , 2 , 1 , 0 , 1 |
"predicted_probability", NA_real_ , 0 , 0 , 0 , 0 , 0.003 , -0.01 , -0.007 , 3 , 1 , 0 , 0 )
wrapr::check_equiv_frames(values, expect, tolerance = 1.e-3)
invisible(NULL)
}
test_utility_calc_1b()
test_utility_calc_2 <- function() {
d <- data.frame(
predicted_probability = c(0, 0.25, 0.5, 0.5, 0.5, 0.75, 0.8, 1.0),
made_purchase = c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE),
false_positive_value = -5,
true_positive_value = 95,
true_negative_value = 0.001,
false_negative_value = -0.01
)
values <- model_utility(d, 'predicted_probability', 'made_purchase')
expect_true(is.null(check_utility_calc(values, constant_utilities = TRUE,
orig_score = d$predicted_probability,
orig_outcome = d$made_purchase)))
expect <- wrapr::build_frame(
"model" , "threshold", "count_taken", "fraction_taken", "true_positive_value", "false_positive_value", "true_negative_value", "false_negative_value", "total_value", "true_negative_count", "false_negative_count", "true_positive_count", "false_positive_count" |
"predicted_probability", 0 , 8 , 1 , 380 , -20 , 0 , 0 , 360 , 0 , 0 , 4 , 4 |
"predicted_probability", 0.125 , 7 , 0.875 , 380 , -15 , 0.001 , 0 , 365 , 1 , 0 , 4 , 3 |
"predicted_probability", 0.375 , 6 , 0.75 , 285 , -15 , 0.001 , -0.01 , 270 , 1 , 1 , 3 , 3 |
"predicted_probability", 0.625 , 3 , 0.375 , 190 , -5 , 0.003 , -0.02 , 185 , 3 , 2 , 2 , 1 |
"predicted_probability", 0.775 , 2 , 0.25 , 95 , -5 , 0.003 , -0.03 , 89.97 , 3 , 3 , 1 , 1 |
"predicted_probability", 0.9 , 1 , 0.125 , 95 , 0 , 0.004 , -0.03 , 94.97 , 4 , 3 , 1 , 0 |
"predicted_probability", NA_real_ , 0 , 0 , 0 , 0 , 0.004 , -0.04 , -0.036 , 4 , 4 , 0 , 0 )
wrapr::check_equiv_frames(values, expect, tolerance = 1.e-3)
invisible(NULL)
}
test_utility_calc_2()
test_utility_calc_3 <- function() {
d <- data.frame(
predicted_probability = runif(100),
made_purchase = sample(c(FALSE, TRUE), replace = TRUE, size = 100),
false_positive_value = -5,
true_positive_value = 95,
true_negative_value = 0.001,
false_negative_value = -0.01
)
values <- model_utility(d, 'predicted_probability', 'made_purchase')
expect_true(is.null(check_utility_calc(values, constant_utilities = TRUE,
orig_score = d$predicted_probability,
orig_outcome = d$made_purchase)))
invisible(NULL)
}
test_utility_calc_3() |
getTypeMeasureName <- function(type.measure, family) {
if ("family" %in% class(family)) family <- "GLM"
if (type.measure == "deviance") {
typename <- switch(family,
gaussian = "Mean-squared Error",
binomial = "Binomial Deviance",
poisson = "Poisson Deviance",
cox = "Partial Likelihood Deviance",
multinomial = "Multinomial Deviance",
mgaussian = "Mean-squared Error",
GLM = "GLM Deviance"
)
} else {
typename <- switch(type.measure,
mse = "Mean-Squared Error",
mae = "Mean Absolute Error",
auc = "AUC",
class = "Misclassification Error",
C = "C-index"
)
}
names(typename) <- type.measure
return(typename)
} |
plot_imp_distr <- function(data, imp = 'Imputation_', id = '.id',
rownr = '.rownr',
ncol = NULL, nrow = NULL, labeller = NULL) {
pkgs <- installed.packages()[, "Package"]
if (!"ggplot2" %in% pkgs)
msg("This function requires the package ggplot2 to be installed.")
if (!"ggpubr" %in% pkgs)
msg("This function requires the package ggpubr to be installed.")
if (any(!c("ggpubr", "ggplot2") %in% pkgs)) {
return(NULL)
}
subDF <- data[, (colSums(is.na(data[data[, imp] == 0, ])) > 0 &
colSums(is.na(data[data[, imp] != 0, ])) == 0) |
names(data) %in% c(imp, id, rownr)]
DForig <- subDF[subDF[, imp] == 0, ]
w <- as.data.frame(is.na(DForig))
w[, c(imp, id, rownr)] <- DForig[, c(imp, id, rownr)]
type <- sapply(subDF, is.factor)
DFlong <- melt_data.frame(subDF, id.vars = c(imp, id, rownr))
wlong <- melt_data.frame(w, id.vars = c(imp, id, rownr), valname = 'mis')
wlong <- unique(wlong)
DFlong <- merge(DFlong, wlong, by = c(id, 'variable', rownr),
suffixes = c("",".y"))
DFlong$type <- ifelse(type[as.character(DFlong$variable)], 'factor',
'numeric')
plotDF <- DFlong[(DFlong[, imp] == 0 & !DFlong$mis) |
(DFlong[, imp] != 0 & DFlong$mis), ]
p <- lapply(split(plotDF, plotDF$variable), function(dat) {
if (unique(dat$type) == 'factor') {
dat$value <- factor(dat$value)
prop <- sapply(split(dat, dat[, imp]),
function(x) prop.table(table(x$value)))
plong <- melt_matrix(prop, valname = 'proportion',
varnames = c('value', imp))
dat <- merge(dat, plong, all = TRUE)
dat$variable <- unique(na.omit(dat$variable))
}
pl <- ggplot2::ggplot(dat) +
ggplot2::facet_wrap("variable",
scales = "free",
labeller = if (!is.null(labeller))
labeller else "label_value"
) +
ggplot2::scale_color_manual(name = '',
limits = c(FALSE, TRUE),
values = c('dodgerblue3', 'midnightblue'),
labels = c('imputed', 'observed')) +
ggplot2::scale_fill_manual(name = '', limits = c(FALSE, TRUE),
values = c('dodgerblue3', 'midnightblue'),
labels = c('imputed', 'observed')) +
ggplot2::scale_size_manual(name = '',
limits = c(FALSE, TRUE),
values = c(0.5, 1.3),
labels = c('imputed', 'observed')) +
ggplot2::xlab('')
if (unique(na.omit(dat$type) == 'numeric')) {
if (min(table(dat[, imp])) == 1) {
pl + ggplot2::stat_density(ggplot2::aes(x = as.numeric(.data$value),
color = get(imp) == 0,
size = get(imp) == 0),
geom = 'line',
position = 'identity', na.rm = TRUE) +
ggplot2::geom_point(data = subset(dat, get(imp) > 0),
ggplot2::aes(x = as.numeric(.data$value),
y = 0, color = get(imp) == 0,
shape = get(imp) == 0),
alpha = 0.5, show.legend = FALSE)
} else {
pl + ggplot2::stat_density(ggplot2::aes(x = as.numeric(.data$value),
size = get(imp) == 0,
color = get(imp) == 0,
group = get(imp)), geom = 'line',
position = 'identity', na.rm = TRUE)
}
} else {
pl + ggplot2::geom_bar(ggplot2::aes(x = .data$value,
y = .data$proportion,
group = get(imp), fill = get(imp) == 0),
position = "dodge", stat = 'identity',
color = 'midnightblue') +
ggplot2::ylab('proportion')
}
})
if (is.null(nrow) & is.null(ncol)) {
dims <- if (length(p) > 25) {
grDevices::n2mfrow(25)
} else {
grDevices::n2mfrow(length(p))
}
} else if (is.null(nrow) & !is.null(ncol)) {
dims <- c(ceiling(length(p)/ncol), ncol)
} else if (is.null(ncol) & !is.null(nrow)) {
dims <- c(nrow, ceiling(length(p)/nrow))
} else {
dims <- c(nrow, ncol)
}
ggpubr::ggarrange(plotlist = p, ncol = dims[2], nrow = dims[1],
common.legend = TRUE, legend = "bottom")
} |
`BackcastResidualsAR` <-
function(y,phi,Q=100,demean=TRUE){
if (demean)
z <- y-mean(y)
else
z <- y
p <- length(phi)
if (p==0)
a<-z
else {
n<-length(z)
p<-length(phi)
nQ<-n+Q
a<-e<-zF<-zR<-numeric(nQ)
r<-p+1
zR[1:n]<-rev(z)
zF[Q+(1:n)]<-z
for (i in r:n)
e[i]<-zR[i]-crossprod(phi,zR[i-(1:p)])
for (i in 1:Q)
zR[n+i]<-crossprod(phi,zR[(n+i)-(1:p)])
zF[1:Q]<-rev(zR[n+(1:Q)])
for (i in r:nQ)
a[i]<-zF[i]-crossprod(phi,zF[i-(1:p)])
zF[Q+(1:n)]<-z
a<-a[Q+(1:n)]
}
a
} |
library(phylopath)
models <- define_model_set(
A = c(C~M+D),
B = c(C~D),
C = c(C~D, P~M),
D = c(C~D, M~P, G~P),
E = c(C~D, P~M, G~P),
F = c(C~D, P~M+G),
G = c(C~D, M~P, P~G),
H = c(C~D, M~P),
I = c(C~D, M~M, G~P),
J = c(M~P, G~D),
K = c(P~M, G~D),
L = c(C~M+D, P~M+G),
.common = c(C~P+G)
)
plot_model_set(models, algorithm = 'kk')
(cichlids_results <- phylo_path(models, cichlids, cichlids_tree))
(s <- summary(cichlids_results))
plot(s)
best_cichlids <- best(cichlids_results)
best_cichlids
coef_plot(best_cichlids, error_bar = "se", reverse_order = TRUE) + ggplot2::coord_flip()
plot(best_cichlids) |
(m1 = matrix(1:20, nrow=4))
mean(m1[1,]); mean(m1[2,]); mean(m1[3,]); mean(m1[4,])
for (i in 1:nrow(m1)) {
print(mean(m1[i,]))
}
apply(m1,1,mean)
apply(m1, MARGIN = 2, mean)
apply(m1, 2, mean)
addmargins(m1,1,mean)
addmargins(m1,2,mean)
addmargins(m1,c(1,2),mean)
addmargins(m1)
for( i in 1:4) {
print(mean(m1[i,]))
}
nrow(m1)
ncol(m1)
for( i in 1:nrow(m1)) {
print(paste0('Mean of row', i , ' is ', mean(m1[i,])))
}
for( i in 1:ncol(m1)) {
print(paste0('Mean of Col', i , ' is ', mean(m1[,i])))
}
apply(m1, 1, mean)
apply(m1, 2, mean) |
knitr::opts_chunk$set(collapse = TRUE, comment = "
options(knitr.table.format = "html", rmarkdown.html_vignette.check_title = FALSE)
library(eRTG3D)
set.seed(123)
cerw <- reproduce.track.3d(niclas, DEM = dem)
tests <- test.verification.3d(niclas, cerw, test = "ks", plot = FALSE)
tests <- test.verification.3d(niclas, cerw, test = "ttest", plot = FALSE) |
students3 %>%
gather( , , : , = TRUE) %>%
print |
blav_model_fit <- function(lavpartable = NULL,
lavmodel = NULL,
lavjags = NULL,
x = NULL,
VCOV = NULL,
TEST = NULL) {
stopifnot(is.list(lavpartable), inherits(lavmodel, c("Model",
"lavModel")))
if(class(lavjags) != "NULL"){
lavmcmc <- make_mcmc(lavjags)
} else {
lavmcmc <- NULL
}
iterations <- attr(x, "iterations")
converged <- attr(x, "converged")
fx <- attr(x, "fx")
fx.group <- as.numeric(NA)
logl.group <- as.numeric(NA)
logl <- as.numeric(NA)
control <- attr(x, "control")
attributes(fx) <- NULL
x.copy <- x
attributes(x.copy) <- NULL
est <- lav_model_get_parameters(lavmodel = lavmodel, type = "user")
blaboot <- rearr_params(lavmcmc, lavpartable)
se <- lav_model_vcov_se(lavmodel = lavmodel, lavpartable = lavpartable,
VCOV = VCOV, BOOT = blaboot)
if(is.null(TEST)) {
test <- list()
} else {
test <- TEST
}
implied <- lav_model_implied(lavmodel, delta = (lavmodel@parameterization == "delta"))
if([email protected]) {
names(implied) <- c("cov", "mean", "slopes", "th", "group.w")
}
if(!is.null(attr(x, "partrace"))) {
PARTRACE <- attr(x, "partrace")
} else {
PARTRACE <- matrix(0, 0L, 0L)
}
new("Fit",
npar = as.integer(max(lavpartable$free)),
x = x.copy,
partrace = PARTRACE,
start = lavpartable$start,
est = est,
se = se,
fx = fx,
fx.group = fx.group,
logl = logl,
logl.group = logl.group,
iterations = as.integer(iterations),
converged = converged,
control = control,
Sigma.hat = implied$cov,
Mu.hat = implied$mean,
TH = implied$th,
test = test
)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.