code
stringlengths 1
13.8M
|
---|
context("Loading tests")
string1 <- "data/0005/00/00050060.dpa"
string2 <- "00050060.dpa"
dp <- dpload(dp.file = system.file("extdata", "00010001.dpa", package = "densitr"))
dpl <- dpload(dp.directory = system.file("extdata", package = "densitr"))
dpl2 <- dpload(dp.directory = system.file("extdata", package = "densitr"), recursive = FALSE)
test_that("Extract dpa regex", {
expect_match(extract_dpa_name(string1), "00050060")
expect_match(extract_dpa_name(string2), "00050060")
})
test_that("Loading file vs folder", {
expect_equal(length(dpl), 15)
expect_equal(length(dpl2), 5)
expect_is(dp, "dp")
expect_is(dpl[[1]], "dp")
})
test_that("Combining dpas should always return df", {
expect_true(is.data.frame(combine_footers(dpl2)))
expect_true(is.data.frame(combine_data(dpl2)))
}) |
library(shiny)
library(shinyMobile)
shinyApp(
ui = f7Page(
title = "My app",
options = list(pullToRefresh = TRUE),
f7SingleLayout(
navbar = f7Navbar(
title = "Single Layout",
hairline = FALSE,
shadow = TRUE
),
toolbar = f7Toolbar(
position = "bottom",
f7Link(label = "Link 1", href = "https://www.google.com"),
f7Link(label = "Link 2", href = "https://www.google.com")
),
uiOutput("growingList")
)
),
server = function(input, output, session) {
observe({
print(input$ptr)
print(counter())
})
counter <- reactiveVal(value = 1)
observeEvent(input$ptr, {
ptrStatus <- if (input$ptr) "on"
f7Dialog(
text = paste('ptr is', ptrStatus),
type = "alert"
)
newValue <- counter() + 1
counter(newValue)
})
output$growingList <- renderUI({
f7List(
lapply(seq_len(counter()), function(j) {
f7ListItem(
letters[j],
media = f7Icon("alarm_fill"),
right = "Right Text",
header = "Header",
footer = "Footer"
)
})
)
})
}
) |
library(ergm)
context("clustering coefficient function")
nNodes = sample(5:100, 1)
test_that("A complete graph of random size has a clustering coefficient of 1",
expect_equal(gwdegree:::clusteringCoef(network(nNodes, density = 1, directed = FALSE)), 1))
test_that("A graph with a single two-path has a clustering coefficient of 0",
expect_equal(gwdegree:::clusteringCoef(network(3, numedges = 2, directed = FALSE)), 0))
test_that("Clustering coefficient can't be calculated for an empty graph of random size",
expect_true(is.nan(gwdegree:::clusteringCoef(network(nNodes, density = 0, directed = FALSE))))) |
saveDetrendJPG = function (rwl, detrend, folderName = "Detrend", work.dir=NULL, detrend.method="", select.series =1:(ncol(rwl)) ){
if (is.null(work.dir)) work.dir = getwd()
dir.create(folderName, showWarnings = FALSE)
setwd(folderName)
for (i in select.series){
seriesnames=colnames(rwl)
yr.vec = as.numeric(rownames(rwl))
jpeg(paste(seriesnames[i], ".jpg", sep=""),width = 1200, height = 600, quality=100)
plot(yr.vec, rwl[,i], type="l", xlab = "Years",ylab = "", main = seriesnames[i], las = 1, col="blue")
mtext(paste(detrend.method, sep=""), line=0.5, side =3, adj =1, cex=0.90, col="blue",font=1)
mtext("Detrender", line=0.5, side =3, adj =0, cex=0.90, col="blue",font=1)
lines(yr.vec, detrend[,i], col=2)
dev.off()
}
setwd(work.dir)
} |
variance_adjust <-
function (fit, ctl.idx = NULL, ebayes = TRUE, pooled = TRUE,
evar = TRUE, rsvar = TRUE, bin = 10, rescaleconst = NULL)
{
n = ncol(fit$betahat)
p = nrow(fit$betahat)
if (is.null(ctl.idx)) {
if (is.list(fit$ctl))
rsvar = FALSE
else ctl.idx = fit$ctl
}
if (length(fit$multiplier) == p)
fit$multiplier = matrix(fit$multiplier, p, n)
if (length(fit$df) == 1)
fit$df = rep(fit$df, n)
if (TRUE) {
varbetahat = p.BH = matrix(NA, p, n)
for (l in 1:p) {
varbetahat[l, ] = fit$sigma2 * fit$multiplier[l,
]
p.BH[l, ] = p.adjust(fit$p[l, ], method = "BH")
}
fit$p.BH = p.BH
fit$varbetahat = varbetahat
fit$Fpvals.BH = p.adjust(fit$Fpvals, method = "BH")
}
if (rsvar) {
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
multiplier = mean(fit$betahat[l, ctl.idx]^2/fit$sigma2[ctl.idx])
varbetahat[l, ] = fit$sigma2 * multiplier
tvals[l, ] = fit$betahat[l, ]/sqrt(varbetahat[l,
])
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.rsvar = pvals
fit$p.rsvar.BH = p.BH
fit$varbetahat.rsvar = varbetahat
}
if (evar) {
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
varbetahat[l, ] = get_empirical_variances(fit$sigma2,
fit$betahat[l, ], bin = bin, rescaleconst = rescaleconst)
tvals[l, ] = fit$betahat[l, ]/sqrt(varbetahat[l,
])
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), Inf)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.evar = pvals
fit$p.evar.BH = p.BH
fit$varbetahat.evar = varbetahat
}
if (ebayes) {
temp = sigmashrink(fit$sigma2, fit$df)
fit$sigma2.ebayes = temp$sigma2
fit$df.ebayes = temp$df
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
varbetahat[l, ] = fit$sigma2.ebayes * fit$multiplier[l,
]
tvals[l, ] = fit$betahat[l, ]/sqrt(varbetahat[l,
])
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df.ebayes)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.ebayes = pvals
fit$p.ebayes.BH = p.BH
fit$varbetahat.ebayes = varbetahat
fit$Fpvals.ebayes = pf(fit$Fstats * (fit$sigma2/fit$sigma2.ebayes),
p, fit$df.ebayes, lower.tail = FALSE)
fit$Fpvals.ebayes.BH = p.adjust(fit$Fpvals.ebayes, method = "BH")
}
if (rsvar & ebayes) {
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
multiplier = mean(fit$betahat[l, ctl.idx]^2/fit$sigma2.ebayes[ctl.idx])
varbetahat[l, ] = fit$sigma2.ebayes * multiplier
tvals[l, ] = fit$betahat[l, ]/sqrt(fit$sigma2.ebayes *
multiplier)
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df.ebayes)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.rsvar.ebayes = pvals
fit$p.rsvar.ebayes.BH = p.BH
fit$varbetahat.rsvar.ebayes = varbetahat
}
if (pooled) {
fit$sigma2.pooled = rep(mean(fit$sigma2, na.rm = TRUE),
n)
fit$df.pooled = rep(sum(fit$df, na.rm = TRUE), n)
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
varbetahat[l, ] = fit$sigma2.pooled * fit$multiplier[l,
]
tvals[l, ] = fit$betahat[l, ]/sqrt(varbetahat[l,
])
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df.pooled)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.pooled = pvals
fit$p.pooled.BH = p.BH
fit$varbetahat.pooled = varbetahat
fit$Fpvals.pooled = pf(fit$Fstats * (fit$sigma2/fit$sigma2.pooled),
p, fit$df.pooled, lower.tail = FALSE)
fit$Fpvals.pooled.BH = p.adjust(fit$Fpvals.pooled, method = "BH")
}
if (rsvar & pooled) {
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
multiplier = mean(fit$betahat[l, ctl.idx]^2/fit$sigma2.pooled[ctl.idx])
varbetahat[l, ] = fit$sigma2.pooled * multiplier
tvals[l, ] = fit$betahat[l, ]/sqrt(fit$sigma2.pooled *
multiplier)
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df.pooled)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.rsvar.pooled = pvals
fit$p.rsvar.pooled.BH = p.BH
fit$varbetahat.rsvar.pooled = varbetahat
}
if (evar & pooled) {
varbetahat = pvals = p.BH = tvals = matrix(0, p, n)
for (l in 1:p) {
multiplier = mean(fit$betahat[l, ]^2/fit$sigma2.pooled)
varbetahat[l, ] = fit$sigma2.pooled * multiplier
tvals[l, ] = fit$betahat[l, ]/sqrt(fit$sigma2.pooled *
multiplier)
pvals[l, ] = 2 * pt(-abs(tvals[l, ]), fit$df.pooled)
p.BH[l, ] = p.adjust(pvals[l, ], method = "BH")
}
fit$p.evar.pooled = pvals
fit$p.evar.pooled.BH = p.BH
fit$varbetahat.evar.pooled = varbetahat
}
return(fit)
} |
tTMTI_CDF <- function (x, m, tau) {
if (m == 1) {
x
}
P <- function(x, a) {
m <- length(a)
sum(1 / factorial(m:1) * x^(m:1) * a)
}
xs <- numeric(m)
xs <- stats::qbeta(x, 1:m, m + 1 - 1:m)
PP <- list()
PP[[1]] <- xs[1]
for (i in 2:m) {
PP[[i]] <- P(xs[i], c(1, -do.call("c", PP[1:(i - 1)])))
}
hh_terms <- c (
1 - (1 - PP[[1]] / tau) * (xs[1] <= tau),
sapply (
2:m,
function (K) {
Ptau <- P(tau, c(1, -do.call("c", PP[1:(K - 1)])))
1 - (factorial(K) / tau**K) * (
Ptau -
PP[[K]]
) * (xs[K] <= tau)
}
)
)
tau_terms <- sapply (
1:m,
function (i) {
choose(m, i) * tau^i * (1 - tau)^(m - i)
}
)
pbeta_tau <- stats::pbeta(tau, 1, m)
(1 - tau)**m * (x - pbeta_tau) / (1 - pbeta_tau) * (xs[1] > tau) + sum(hh_terms * tau_terms)
} |
extract.prob <- function(train, gs, gstable, thre = 0.95, type = c("quantile", "fixed", "empirical")[1], isNumeric = FALSE, impute=TRUE){
if(isNumeric){
yes <- 1
no <- 0
miss <- -1
}else{
yes <- "Y"
no <- c("", "N")
miss <- c(".", "-")
}
countyes <- function(x){length(which(toupper(x) %in% yes))}
countno <- function(x){length(which(x %in% no))}
countmiss <- function(x){length(which(x %in% miss))}
countna <- function(x){length(which(is.na(x)))}
toLevel <- function(cond.prob, levels, cutoffs){
cond.prob.vec <- as.vector(cond.prob)
new <- rep(NA, length(cond.prob.vec))
cdf <- ecdf(cond.prob.vec)
table <- table.median <- rep(0, length(cutoffs))
for(i in length(cutoffs) : 1){
table[i] <- quantile(cdf, cutoffs[i])
if(i > 1){
table.median[i] <- quantile(cdf, (cutoffs[i] + cutoffs[i-1])/2)
}else{
table.median[i] <- quantile(cdf, (cutoffs[i])/2)
}
}
for(i in length(cutoffs) : 1){
new[which(cond.prob.vec <= table[i])] <- levels[i]
}
new <- matrix(new, dim(cond.prob)[1], dim(cond.prob)[2])
colnames(new) <- colnames(cond.prob)
rownames(new) <- rownames(cond.prob)
return(list(cond.prob = new, table.cut = table, table.median = table.median))
}
train.id <- as.character(train[, 1])
train <- train[, -1]
train.gs <- as.character(train[, gs])
if(is.null(gstable)){
gstable <- unique(train.gs)
}
train <- train[, -which(colnames(train) == gs)]
miss.train <- apply(train, 2, countmiss) / dim(train)[1]
miss.too.many <- which(miss.train > thre)
if(length(miss.too.many) > 0){
train <- train[, -miss.too.many]
warning(paste(length(miss.too.many), "symptoms deleted for missing rate over the pre-specified threshold", thre),
immediate. = TRUE)
}
gs.missing <- which(gstable %in% unique(train.gs) == FALSE)
if(length(gs.missing) > 0){
warning(paste("Causes not found in training data and deleted:",
paste(gstable[gs.missing], collapse = ", ")),
immediate. = TRUE)
gstable <- gstable[-gs.missing]
}
cond.prob <- NULL
for(i in 1:length(gstable)){
cause <- gstable[i]
list <- which(train.gs == cause)
cases <- train[list, ]
if(length(list) == 1){
cond <- rep(0, length(cases))
cond[which(toupper(cases) == yes)] <- 1
cond[which(cases == miss)] <-- NA
}else{
count <- apply(cases, 2, countyes)
denom <- (length(list) - apply(cases, 2, countmiss))
denom[denom < length(list)*(1-thre)] <- NA
cond <- count / denom
}
cond.prob <- cbind(cond.prob, cond)
}
colnames(cond.prob) <- gstable
rownames(cond.prob) <- colnames(train)
S <- dim(cond.prob)[1]
C <- dim(cond.prob)[2]
bysymps <- apply(cond.prob, 1, countna)
if(impute){
if(length(which(bysymps > 0)) > 0){
message(paste("\n", length(which(bysymps > 0)), "missing symptom-cause combinations in training data, imputed using average symptom prevalence\n"))
overall <- apply(train, 2, countyes) / dim(train)[1]
for(i in 1:S){
cond.prob[i, which(is.na(cond.prob[i,]))] <- overall[i]
}
}
}
zeroes <- which(cond.prob == 0)
ones <- which(cond.prob == 1)
if(impute) cond.prob[zeroes] <- runif(length(zeroes), min = 1e-6, max = 2e-6)
if(impute) cond.prob[ones] <- 1 - runif(length(ones), min = 1e-6, max = 2e-6)
conditionals <- as.vector(cond.prob)
data("probbase", envir = environment())
probbase <- get("probbase", envir = environment())
intertable <- probbase[2:246, 17:76]
intertable[which(intertable == "B -")] <- "B-"
intertable[which(intertable == "")] <- "N"
levels <- c("I", "A+", "A", "A-", "B+", "B" , "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "N")
counts <- rep(0, length(levels))
for(i in 1:length(levels)){
counts[i] <- length(which(as.vector(intertable) == levels[i]))
}
freqs <- cumsum(counts / sum(counts))
if(type == "quantile"){
level.tmp <- toLevel(cond.prob, rev(levels), freqs)
cond.prob.alpha <- level.tmp$cond.prob
table.num <- rev(level.tmp$table.median)
}else if(type == "fixed"){
table.num <- c(1, 0.8, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001, 0.0005, 0.0001, 0.00001, 0)
inter.cut <- c(1, table.num[-length(table.num)] + diff(table.num)/2 )
cond.prob.alpha <- matrix("N", dim(cond.prob)[1], dim(cond.prob)[2])
for(i in 1:length(inter.cut)){
cond.prob.alpha[which(cond.prob <= inter.cut[i])] <- levels[i]
}
colnames(cond.prob.alpha) <- colnames(cond.prob)
rownames(cond.prob.alpha) <- rownames(cond.prob)
}else if(type == "empirical"){
cond.prob.alpha <- NULL
levels <- NULL
table.num <- NULL
}
if(sum(is.na(cond.prob)) > 0){
cond.prob.alpha[is.na(cond.prob)] <- NA
}
return(list(cond.prob = cond.prob,
cond.prob.alpha = cond.prob.alpha,
table.alpha = levels,
table.num = table.num,
symps.train = train))
} |
renderPieChart <- function(div_id,
data, theme = "default",
radius = "50%",
center_x = "50%", center_y = "50%",
show.label = TRUE,
show.legend = TRUE, show.tools = TRUE,
font.size.legend = 12,
animation = TRUE,
hyperlinks = NULL,
running_in_shiny = TRUE){
data <- isolate(data)
theme_placeholder <- .theme_placeholder(theme)
.check_logical(c('show.label', 'show.tools', 'show.legend', 'animation', 'running_in_shiny'))
if(is.vector(data) & (is.null(hyperlinks) == FALSE)){
stop("'hyperlinks' feature doesn't support vector data for now. Only data.frame data is supported.")
}
if(is.vector(data)){
data <- data.frame(table(data))
names(data) <- c("name", "value")
} else {
if((dim(data)[2] != 2) | ("name" %in% names(data) == FALSE) | ("value" %in% names(data) == FALSE)){
stop("The data must be made up of two columns, 'name' and 'value'")
}
if(class(data$value) != 'numeric' & class(data$value) != 'integer'){
stop("The 'value' column must be numeric or integer.")
}
}
if(is.null(hyperlinks) == FALSE){
item_names <- data$name
if((length(hyperlinks) != length(item_names)) & (is.null(hyperlinks) == FALSE)){
stop("The length of 'hyperlinks' should be the same as the number of unique items in the pie chart.")
}
}
legend_data <- paste(sapply(sort(unique(data$name)), function(x){paste0("'", x, "'")}), collapse=", ")
legend_data <- paste0("[", legend_data, "]")
data <- as.character(jsonlite::toJSON(data))
data <- gsub("\"", "\'", data)
js_statement <- paste0("var " ,
div_id,
" = echarts.init(document.getElementById('",
div_id,
"')",
theme_placeholder,
");",
"option_", div_id, " = {tooltip : {trigger: 'item',formatter: '{b} : {c} ({d}%)'}, ",
ifelse(show.tools,
"toolbox:{feature:{saveAsImage:{}}}, ",
""),
ifelse(is.null(hyperlinks),
"",
"tooltip : {textStyle: {fontStyle:'italic', color:'skyblue'}},"),
ifelse(show.legend,
paste0("legend:{orient: 'vertical', left: 'left', data:",
legend_data,
", textStyle:{fontSize:", font.size.legend, "}",
"},"),
""),
"series : [{type: 'pie', radius:'", radius, "', center :['", center_x, "','", center_y, "'],",
ifelse(show.label,
"label:{normal:{show: true}},",
"label:{normal:{show: false}},"),
ifelse(animation,
"animation:true,",
"animation:false,"),
"data:",
data,
", itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)'}}}]};",
div_id,
".setOption(option_",
div_id,
");",
"window.addEventListener('resize', function(){",
div_id, ".resize()",
"});",
ifelse(is.null(hyperlinks),
"",
paste0(div_id,
".on('click', function (param){
var name=param.name;",
paste(sapply(1:length(hyperlinks),
function(i){
paste0("if(name=='", item_names[i], "'){",
"window.location.href='", hyperlinks[i], "';}")
}),
collapse = ""),
"});",
div_id, ".on('click');")
))
to_eval <- paste0("output$", div_id ," <- renderUI({tags$script(\"",
js_statement,
"\")})")
if(running_in_shiny == TRUE){
eval(parse(text = to_eval), envir = parent.frame())
} else {
cat(to_eval)
}
} |
get_several_artists<-function(artist_ids_df, ids_label = 1, access_token = DSpoty::get_spotify_access_token()){
uris<-artist_ids_df[,ids_label] %>% split(., ceiling(seq_along(.)/50)) %>% .$`1` %>% apply(., paste, MARGIN=2, collapse = ',')
res<-lmap(seq_len(length(uris)), function(x){
res1<-RETRY('GET',
url = str_glue('https://api.spotify.com/v1/artists/'),
query = list(ids=uris[[x]], type = 'artist', access_token= access_token),
quiet = TRUE) %>%
content %>%
.$artists
})
artista<-map_df(seq_len(length(res)), function(this_row){
artist<-res[[this_row]]
list(
artist_name = artist$name,
artist_uri = artist$id,
artist_img = if(length(artist$images)>0){artist$images[[1]]$url} else {NA},
num_followers = if(length(artist$followers[[2]])>0) {as.character(artist$followers[[2]])} else{NA},
spotify_url = artist$external_urls$spotify,
popularity = as.character(artist$popularity),
musical_genre = if(length(artist$genres)>0){str_replace_all(str_c(unlist(artist$genres), collapse = "-")," ","_")} else {NA}
)
}) %>%
filter(.,!duplicated(tolower(artist_uri))) %>%
filter(.,!duplicated(tolower(artist_name)))
return(artista)
} |
context('submodules')
test_that('submodules can be loaded one by one', {
on.exit(clear_mods())
result = capture.output(box::use(mod/nested/a/b))
expect_equal(result, 'a/b/__init__.r')
result = capture.output(box::use(mod/nested/a/b/c))
expect_equal(result, 'a/b/c/__init__.r')
result = capture.output(box::use(mod/nested/a/b/d))
expect_equal(result, 'a/b/d/__init__.r')
})
test_that('module can export nested submodules', {
box::use(mod/b)
expect_equal(b$answer, 42L)
}) |
company_information <- function(x) {
doc <- if (is(x, "xml_node")) {
x
} else {
browse_edgar(x)
}
entry_xpath <- "company-info"
info_pieces <- list(
"name" = "conformed-name",
"cik" = "cik",
"fiscal_year_end" = "fiscal-year-end",
"company_href" = "cik-href",
"sic" = "assigned-sic",
"sic_description" = "assigned-sic-desc",
"state_location" = "state-location",
"state_incorporation" = "state-of-incorporation",
"mailing_city" = "//address[@type='mailing']/city",
"mailing_state" = "//address[@type='mailing']/state",
"mailing_zip" = "//address[@type='mailing']/zip",
"mailing_street" = "//address[@type='mailing']/street1",
"mailing_street2" = "//address[@type='mailing']/street2",
"business_city" = "//address[@type='business']/city",
"business_state" = "//address[@type='business']/state",
"business_zip" = "//address[@type='business']/zip",
"business_street" = "//address[@type='business']/street1",
"business_street2" = "//address[@type='business']/street2",
"business_phone" = "//address[@type='business']/phone"
)
res <- map_xml(doc, entry_xpath, info_pieces)
return(res)
} |
parity <- function(number) {
list(parity = if (as.integer(number) %% 2 == 0) "even" else "odd")
}
no_arguments <- function() {
list(animal = "dog", breed = "corgi")
}
expect_setup_failure <- function(endpoint_function, ...) {
eval(bquote({
expect_error(
endpoint_function(...),
"The AWS Lambda runtime is not configured"
)
}))
}
basic_lambda_config <- function(handler = "sqrt",
runtime_api = "red_panda",
task_root = "giraffe",
direct_handler = NULL,
log_threshold = test_debug_level,
...) {
setup_logging(log_threshold = log_threshold)
env_vars <- if (is.null(direct_handler)) {
c(
"AWS_LAMBDA_RUNTIME_API" = runtime_api,
"LAMBDA_TASK_ROOT" = task_root,
"_HANDLER" = handler
)
} else {
c(
"AWS_LAMBDA_RUNTIME_API" = runtime_api,
"LAMBDA_TASK_ROOT" = task_root
)
}
withr::with_envvar(env_vars,
withr::with_environment(
parent.frame(),
lambda_config(handler = direct_handler, ...)
)
)
}
mock_response <- function(input,
expected_response_body,
expected_response_headers = default_response_headers,
request_id = "abc123",
timeout_seconds = 0.5,
config = basic_lambda_config()) {
webmockr::enable(quiet = TRUE)
withr::defer(webmockr::disable(quiet = TRUE))
invocation_endpoint <- get_next_invocation_endpoint(config)
response_endpoint <- get_response_endpoint(config, request_id)
webmockr::stub_request("get", invocation_endpoint) %>%
webmockr::to_return(
body = input,
headers = list("lambda-runtime-aws-request-id" = request_id),
status = 200
)
webmockr::stub_request("post", response_endpoint) %>%
webmockr::wi_th(
headers = expected_response_headers,
body = expected_response_body
) %>%
webmockr::to_return(status = 200)
start_listening(
config = config,
timeout_seconds = timeout_seconds
)
requests <- webmockr::request_registry()
n_responses <- requests$times_executed(
webmockr::RequestPattern$new("post", response_endpoint)
)
n_responses >= 1
}
mock_invocation_error <- function(input,
expected_error_body,
request_id = "abc123",
timeout_seconds = 0.5,
config = basic_lambda_config()) {
webmockr::enable(quiet = TRUE)
withr::defer(webmockr::disable(quiet = TRUE))
invocation_endpoint <- get_next_invocation_endpoint(config)
invocation_error_endpoint <- get_invocation_error_endpoint(config, request_id)
webmockr::stub_request("get", invocation_endpoint) %>%
webmockr::to_return(
body = input,
headers = list("lambda-runtime-aws-request-id" = request_id),
status = 200
)
webmockr::stub_request("post", invocation_error_endpoint) %>%
webmockr::wi_th(
headers = list(
"Accept" = "application/json, text/xml, application/xml, */*",
"Content-Type" = "application/vnd.aws.lambda.error+json"
),
body = expected_error_body
) %>%
webmockr::to_return(status = 202)
start_listening(config = config, timeout_seconds = timeout_seconds)
requests <- webmockr::request_registry()
n_responses <- requests$times_executed(
webmockr::RequestPattern$new("post", invocation_error_endpoint)
)
n_responses >= 1
}
trigger_initialisation_error <- function(expected_error,
task_root = "giraffe",
handler = "sqrt",
direct_handler = NULL,
deserialiser = NULL,
serialiser = NULL) {
webmockr::enable(quiet = TRUE)
withr::defer(webmockr::disable(quiet = TRUE))
lambda_runtime_api <- "red_panda"
request_id <- "abc123"
invocation_endpoint <- paste0(
"http://", lambda_runtime_api, "/2018-06-01/runtime/invocation/next"
)
initialisation_error_endpoint <- paste0(
"http://", lambda_runtime_api, "/2018-06-01/runtime/init/error"
)
webmockr::stub_request("get", invocation_endpoint) %>%
webmockr::to_return(
body = list(),
headers = list("lambda-runtime-aws-request-id" = request_id),
status = 200
)
webmockr::stub_request("post", initialisation_error_endpoint) %>%
webmockr::wi_th(
headers = list(
"Accept" = "application/json, text/xml, application/xml, */*",
"Content-Type" = "application/vnd.aws.lambda.error+json"
),
body = as_json(
list(
errorMessage = expected_error,
errorType = "simpleError",
stackTrace = list()
)
)
) %>%
webmockr::to_return(status = 202)
error_message <- tryCatch(
basic_lambda_config(
runtime_api = "red_panda",
task_root = task_root,
handler = handler,
direct_handler = direct_handler,
deserialiser = deserialiser,
serialiser = serialiser
),
error = function(e) e$message
)
if (error_message != expected_error) {
stop(error_message)
}
requests <- webmockr::request_registry()
request_pattern <- webmockr::RequestPattern$new(
"post",
initialisation_error_endpoint
)
return(requests$times_executed(request_pattern) == 1)
} |
library(BART)
data(ACTG175)
ex <- is.na(ACTG175$cd496) | ACTG175$cd40<200 | ACTG175$cd40>500
table(ex)
y <- ((ACTG175$cd496-ACTG175$cd40)/ACTG175$cd40)[!ex]
summary(y)
y <- 1*(y > -0.5)
a <- table(y, ACTG175$arms[!ex])
b <- apply(a, 2, sum)
a/rbind(b, b)
train <- as.matrix(ACTG175)[!ex, -c(1, 10, 14:15, 17, 18, 20:27)]
train <- cbind(1*(ACTG175$strat[!ex]==1), 1*(ACTG175$strat[!ex]==2),
1*(ACTG175$strat[!ex]==3), train)
dimnames(train)[[2]][1:3] <- paste0('strat', 1:3)
train <- cbind(1*(ACTG175$arms[!ex]==0), 1*(ACTG175$arms[!ex]==1),
1*(ACTG175$arms[!ex]==2), 1*(ACTG175$arms[!ex]==3), train)
dimnames(train)[[2]][1:4] <- paste0('arm', 0:3)
N <- nrow(train)
test0 <- train; test0[ , 1:4] <- 0; test0[ , 1] <- 1
test1 <- train; test1[ , 1:4] <- 0; test1[ , 2] <- 1
test2 <- train; test2[ , 1:4] <- 0; test2[ , 3] <- 1
test3 <- train; test3[ , 1:4] <- 0; test3[ , 4] <- 1
test <- rbind(test0, test1, test2, test3)
set.seed(21)
post <- mc.lbart(train, y, test, mc.cores=8)
itr <- cbind(post$prob.test.mean[(1:N)],
post$prob.test.mean[N+(1:N)],
post$prob.test.mean[2*N+(1:N)],
post$prob.test.mean[3*N+(1:N)])
itr.pick <- integer(N)
for(i in 1:N) itr.pick[i] <- which(itr[i, ]==max(itr[i, ]))-1
table(itr.pick)
diff. <- apply(post$prob.test[ , 2*N+(1:N)]-
post$prob.test[ , N+(1:N)], 2, mean)
plot(sort(diff.), type='h',
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks',
xlab='Arm 2 (1) Preferable to the Right (Left)',
ylab='Prob.Diff.: Arms 2 - 1')
library(rpart)
library(rpart.plot)
var <- as.data.frame(train[ , -(1:4)])
dss <- rpart(diff. ~ var$age+var$gender+var$race+var$wtkg+
var$karnof+var$symptom+var$hemo+var$homo+var$drugs+var$z30+
var$oprior+var$strat1+var$strat2+var$strat3,
method='anova', control=rpart.control(cp=0.05))
rpart.plot(dss, type=3, extra=101)
print(dss)
all0 <- apply(post$prob.test[ , (1:N)], 1, mean)
all1 <- apply(post$prob.test[ , N+(1:N)], 1, mean)
all2 <- apply(post$prob.test[ , 2*N+(1:N)], 1, mean)
all3 <- apply(post$prob.test[ , 3*N+(1:N)], 1, mean)
BART.itr <- apply(post$prob.test[ , c(N+which(itr.pick==1), 2*N+which(itr.pick==2))], 1, mean)
test <- train
test[ , 1:4] <- 0
test[var$drugs==1, 2] <- 1
test[ , 3] <- 1-test[ , 2]
table(test[ , 2], test[ , 3])
BART.itr.simp <- predict(post, newdata=test, mc.cores=8)
BART.itr.simp$prob <- apply(BART.itr.simp$prob.test, 1, mean)
plot(density(BART.itr), xlab='Value', lwd=2, xlim=c(0.7, 0.95),
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks')
lines(density(BART.itr.simp$prob), col='brown', lwd=2)
lines(density(all0), col='green', lwd=2)
lines(density(all1), col='red', lwd=2)
lines(density(all2), col='blue', lwd=2)
lines(density(all3), col='yellow', lwd=2)
legend('topleft', legend=c('All Arm 0 (ZDV only)',
'All Arm 1 (ZDV+DDI)',
'All Arm 2 (ZDV+DDC)',
'All Arm 3 (DDI only)',
'BART ITR simple',
'BART ITR'),
col=c('green', 'red', 'blue', 'yellow', 'brown', 'black'),
lty=1, lwd=2) |
dplyr::`%>%`
NULL
NULL
NULL
NULL
glue_stop <- function(..., .sep = "") {
stop(glue::glue(..., .sep, .envir = parent.frame()), call. = FALSE)
}
string_length <- function(x) {
split <- unlist(strsplit(x, ""))
length(split)
}
index_attributes <- function() {
c("index_quo", "index_time_zone")
}
make_dummy_dispatch_obj <- function(x) {
structure(list(), class = x)
}
remove_time_group <- function(x) {
if(".time_group" %in% colnames(x)) {
x[[".time_group"]] <- NULL
}
x
} |
coef.pvarhk <- function(object, ...) {
object$HK$coef
}
se.pvarhk <- function(object, ...) {
object$HK$se
}
pvalue.pvarhk <- function(object, ...) {
object$HK$pvalues
}
extract.pvarhk <- function(model, ...) {
co.m <- coef(model)
modelnames <- row.names(co.m)
se.m <- se(model)
pval.m <- pvalue(model)
equationList <- list()
for (eq in 1:length(model$dependent_vars)) {
tr <- texreg::createTexreg(
coef.names = colnames(co.m),
coef = as.vector(co.m[eq,]),
se = as.vector(se.m[eq,]),
pvalues = as.vector(pval.m[eq,]),
model.name = modelnames[eq]
)
equationList[[eq]] <- tr
}
names(equationList) <- modelnames
equationList
}
print.pvarhk <- function(x, ...) {
res <- extract(x)
print(texreg::screenreg(res, custom.model.names = names(res), digits = 4))
}
knit_print.pvarhk <- function(x, ...) {
res <- extract(x)
knitr::asis_output(texreg::htmlreg(res, custom.model.names = names(res), digits = 4))
}
summary.pvarhk <- function(object, ...)
{
x <- object
sumry <- list()
sumry$model_name <- "Hahn Kuehrsteiner Panel VAR estimation"
sumry$transformation <- x$transformation
sumry$groupvariable <- x$panel_identifier[1]
sumry$timevariable <- x$panel_identifier[2]
sumry$nof_observations <- x$nof_observations
sumry$obs_per_group_min <- x$obs_per_group_min
sumry$obs_per_group_avg <- x$obs_per_group_avg
sumry$obs_per_group_max <- x$obs_per_group_max
sumry$nof_groups = x$nof_groups
sumry$results <- extract(x)
class(sumry) <- "summary.pvarhk"
sumry
}
print.summary.pvarhk <- function(x, ...) {
cat("---------------------------------------------------\n")
cat(x$model_name, "\n")
cat("---------------------------------------------------\n")
cat("Transformation:", x$transformation,"\n")
cat("Group variable:", x$groupvariable,"\n")
cat("Time variable:",x$timevariable,"\n")
cat("Number of observations =", x$nof_observations,"\n")
cat("Number of groups =", x$nof_groups, "\n")
cat("Obs per group: min =",x$obs_per_group_min,"\n")
cat(" avg =",x$obs_per_group_avg,"\n")
cat(" max =",x$obs_per_group_max,"\n")
print(texreg::screenreg(x$results, custom.model.names = names(x$results), digits = 4))
cat("\n")
}
knit_print.summary.pvarhk <- function(x, ...) {
res <- paste0(c("<p><b>",x$model_name,"</b></p>",
"<p>Transformation: <em>",x$transformation,"</em><br>",
"Group variable: <em>",x$groupvariable,"</em><br>",
"Time variable: <em>",x$timevariable,"</em><br>",
"Number of observations = <em>",x$nof_observations,"</em><br>",
"Number of groups = <em>",x$nof_groups,"</em><br>",
"Obs per group: min = <em>",x$obs_per_group_min,"</em><br>",
"Obs per group: avg = <em>",x$obs_per_group_avg,"</em><br>",
"Obs per group: max = <em>",x$obs_per_group_max,"</em><br>",
"</p>",
texreg::htmlreg(x$results, custom.model.names = names(x$results), digits = 4, caption = "", center = FALSE),
"</p>"
)
)
knitr::asis_output(res)
} |
require(copula)
source(system.file("Rsource", "utils.R", package="copula"))
dDiagF <- copula:::dDiagFrank
meths <- eval(formals(dDiagF)$method)
(meths <- meths[meths != "auto"])
tt <- 2^(-32:-2)
str(u <- sort(c(tt, seq(1/512, 1-1/512, length= 257), 1 - tt)))
(taus <- c(10^(-4:-2), (1:5)/10, (12:19)/20, 1 - 10^(-2:-5)))
thetas <- copFrank@iTau(taus)
taus <- copFrank@tau(thetas <- signif(thetas, 2))
noquote(cbind(theta = thetas, tau = formatC(taus, digits = 3, width= -6)))
d.set <- c(2:4, 7, 10, 15, 25, 35, 50, 75, 120, 180, 250)
str(m.tu <- as.matrix(d.tu <- expand.grid(th = thetas, u = u)))
tu.attr <- attr(d.tu, "out.attrs")
str(rNum <- sapply(meths, function(METH)
sapply(d.set, function(d)
dDiagF(u=m.tu[,"u"], theta = m.tu[,"th"], d=d, method = METH)),
simplify = "array"))
rNum. <- rNum
rNum <- rNum.
(dim(rNum) <- c(tu.attr$dim, dim(rNum)[-1]))
names(dim(rNum))[3:4] <- c("d","meth")
dim(rNum)
dimnames(rNum) <- list(tu.attr$dimnames$th, NULL, paste("d",d.set, sep="="), meths)
str(rNum)
filR <- "Frank-dDiag.rda"
if(isMMae <- identical("maechler",Sys.getenv("USER"))) {
resourceDir <- "~/R/D/R-forge/copula/www/resources"
if(file.exists(ff <- file.path(resourceDir, filR)))
cat("Will use ", (filR <- ff),"\n")
}
develR <- isMMae
if(canGet(filR)) attach(filR) else {
stopifnot(requireNamespace("Rmpfr"))
m.M <- Rmpfr::mpfr(m.tu, precBits = 512)
stopifnot(dim(m.M) == dim(m.tu),
identical(dimnames(m.M), dimnames(m.tu)))
print(system.time({
r.mpfr <- lapply(d.set, function(d) {
cat(sprintf("d = %4d:",d))
CT <- system.time(r <- dDiagF(u=m.M[,"u"], theta = m.M[,"th"],
d=d, method = "polyFull"))[[1]]
cat(formatC(CT, digits=5, width=8), " [Ok]\n")
r
})
}))
length(r.Xct <- do.call(c, r.mpfr))
object.size(r.Xct)
object.size(r.xct <- as(r.Xct,"numeric"))
dim (r.xct) <- dim (rNum) [1:3]
dimnames(r.xct) <- dimnames(rNum)[1:3]
objL1 <- c("u", "taus", "thetas", "d.set",
"m.tu", "meths", "rNum", "r.xct")
objL2 <- c(objL1, "m.M", "r.Xct")
sFileW <- {
if(isMMae) file.path("~/R/Pkgs/copula", "demo", "Frank-dDiag-mpfr.rda")
else tempfile("nacop-Frank-dDiag-mpfr", fileext="rda")}
if(develR) {
if(!exists("resourceDir") || !file.exists(resourceDir))
stop("need writable pkg dir for developer")
sFileR.dev <- file.path(resourceDir, filR)
save(list = objL1, file = sFileR.dev)
dim (r.Xct) <- dim (rNum) [1:3]
dimnames(r.Xct) <- dimnames(rNum)[1:3]
save(list = objL2, file = sFileW)
} else {
save(list = objL1, file = sFileW)
}
}
dim(rNum)
stopifnot(prod(dim(rNum)[1:3]) == length(r.xct))
n.c <- nCorrDigits(r.xct, rNum)
str(n.c)
p.nCorr <- function(nc, d, i.th, u, type="l",
legend.loc = "bottomleft")
{
stopifnot(is.numeric(nc), length(di <- dim(nc)) == 4,
d == round(d), is.character(names(di)),
length(u) == di[["u"]])
dnam <- (dn <- dimnames(nc))[[3]]
stopifnot((c.d <- paste("d",d,sep="=")) %in% dnam)
names(dn) <- names(di)
th.nam <- sub("^th=","", dn[["th"]])
for(jd in dnam[dnam %in% c.d]) {
dd <- as.integer(sub("^d=", "", jd))
for(it in i.th) {
matplot(u, nc[it,,jd,], type=type)
TH <- as.numeric(th.nam[it])
mtext(bquote(theta == .(TH) ~~~~ d == .(dd)), line = 1)
legend(legend.loc, legend = dn[["meth"]],
lty=1:5, col=1:6,
bty = "n")
}
}
}
p.nCorr(n.c, d=3, i.th=12, u=u)
p.nCorr(n.c, i.th= 16, d=120, u=u, leg = "right")
p.nCorr(n.c, i.th= 4, d=120, u=u, leg = "left")
p.nCorr(n.c, i.th= 10, d=120, u=u, leg = "left")
p.nCorr(n.c, i.th= 12, d=120, u=u, leg = "left")
if(dev.interactive())
getOption("device")()
p.nCorr(n.c, i.th= 12, d= 7, u=u, leg = "left")
if(doPDF <- !dev.interactive(orNone=TRUE)) pdf("dDiag-Frank-accuracy.pdf")
p.nCorr(n.c, i.th= which(abs(taus - 0.75) < .01),
d= d.set, u=u, leg = "left")
p.nCorr(n.c, i.th= seq_along(thetas), d= c(2, 4, 10, 50, 180),
u=u, leg = "left")
if(doPDF) dev.off() |
DS.macro.inf.pgu <-
function(DS.GF.obj, num.modes =1 , iters = 25,
method = c("mean","mode"), pred.type = c("posterior","prior")){
switch(DS.GF.obj$LP.type,
"L2" = {
method = match.arg(method)
switch(method,
"mode" = {
out <- list()
modes.mat <- matrix(0, nrow = iters, ncol = num.modes)
if(sum(DS.GF.obj$LP.par^2) == 0){
m.new = 0
out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior)
if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1])
out$model.modes <- out$model.modes[-1]
} else {
m.new = length(DS.GF.obj$LP.par)
out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior)
if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){
out$model.modes <- out$model.modes[-1]}
}
for(i in 1:iters){
len.mode = num.modes+1
while(len.mode != num.modes){
par.g <- c(NA,NA)
while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){
ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set,
y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set)
possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par),
error = function(e) e )
er.check <- !inherits(possibleError, "error")
if(er.check == TRUE){
par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par)
} else {
par.g <- c(NA, NA)
}
}
new.LPc <- DS.prior.pgu(y.new, max.m = m.new,
start.par = par.g)
if(sum(new.LPc$LP.par^2) == 0){
modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$parm.prior)
} else {
modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$ds.prior)
}
len.mode <- length(modes.new)
}
modes.mat[i,] <- modes.new
}
out$boot.modes <- modes.mat
out$mode.sd <- apply(modes.mat,2,sd)
out$prior.fit <- DS.GF.obj$prior.fit
class(out) <- "DS_GF_macro_mode"
return(out)
},
"mean" = {
out <- list()
if(sum(DS.GF.obj$LP.par^2) == 0){
m.new = 0
out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2]
} else {
m.new = length(DS.GF.obj$LP.par)
out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals,
DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int
}
par.mean.vec <- NULL
for(i in 1:iters){
par.g <- c(NA,NA)
while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){
ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set,
y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set)
possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par),
error = function(e) e )
er.check <- !inherits(possibleError, "error")
if(er.check == TRUE){
par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par)
} else {
par.g <- c(NA, NA)
}
}
new.LPc <- DS.prior.pgu(y.new, max.m = m.new,
start.par = par.g)
if(sum(new.LPc$LP.par^2) == 0){
par.mean.vec[i] <- par.g[1]*par.g[2]
} else {
par.mean.vec[i] <- sintegral(new.LPc$prior.fit$theta.vals,
new.LPc$prior.fit$theta.vals*new.LPc$prior.fit$ds.prior)$int
}
}
out$boot.mean <- par.mean.vec
out$mean.sd <- sd(par.mean.vec)
out$prior.fit <- DS.GF.obj$prior.fit
class(out) <- "DS_GF_macro_mean"
return(out)
}
)
},
"MaxEnt" = {
method = match.arg(method)
switch(method,
"mode" = {
out <- list()
modes.mat <- matrix(0, nrow = iters, ncol = num.modes)
if(sum(DS.GF.obj$LP.par^2) == 0){
m.new = 0
out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior)
if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1])
out$model.modes <- out$model.modes[-1]
} else {
m.new = length(DS.GF.obj$LP.par)
out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior)
if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){
out$model.modes <- out$model.modes[-1]}
}
for(i in 1:iters){
len.mode = num.modes+1
while(len.mode != num.modes){
L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2)))
L2.norm <- L2.norm.thres + 1
while(L2.norm > L2.norm.thres){
par.g <- c(NA,NA)
while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){
ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set,
y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set)
possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par),
error = function(e) e )
er.check <- !inherits(possibleError, "error")
if(er.check == TRUE){
par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par)
} else {
par.g <- c(NA, NA)
}
}
new.LPc <- DS.prior.pgu(y.new, max.m = m.new,
start.par = par.g)
L2.norm <- sqrt(sum((new.LPc$LP.par)^2))
}
if(sum(new.LPc$LP.par^2) == 0){
modes.new <- new.LPc$prior.fit$theta.vals[which.max(new.LPc$prior.fit$parm.prior)]
} else {
new.LP.ME <- maxent.obj.convert(new.LPc)
modes.new <- Local.Mode(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$ds.prior)
}
len.mode <- length(modes.new)
}
modes.mat[i,] <- modes.new
}
out$boot.modes <- modes.mat
out$mode.sd <- apply(modes.mat,2,sd)
out$prior.fit <- DS.GF.obj$prior.fit
class(out) <- "DS_GF_macro_mode"
return(out)
},
"mean" = {
out <- list()
if(sum(DS.GF.obj$LP.par^2) == 0){
m.new = 0
out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2]
} else {
m.new = length(DS.GF.obj$LP.par)
out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals,
DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int
}
par.mean.vec <- NULL
for(i in 1:iters){
L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2)))
L2.norm <- L2.norm.thres + 1
while(L2.norm > L2.norm.thres){
par.g <- c(NA,NA)
while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){
ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set,
y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set)
possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par),
error = function(e) e )
er.check <- !inherits(possibleError, "error")
if(er.check == TRUE){
par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par)
} else {
par.g <- c(NA, NA)
}
}
new.LPc <- DS.prior.pgu(y.new, max.m = m.new,
start.par = par.g)
L2.norm <- sqrt(sum((new.LPc$LP.par)^2))
}
if(sum(new.LPc$LP.par^2) == 0){
par.mean.vec[i] <- par.g[1]*par.g[2]
} else {
new.LP.ME <- maxent.obj.convert(new.LPc)
par.mean.vec[i] <- sintegral(new.LP.ME$prior.fit$theta.vals,
new.LP.ME$prior.fit$theta.vals*new.LP.ME$prior.fit$ds.prior)$int
}
}
out$boot.mean <- par.mean.vec
out$mean.sd <- sd(par.mean.vec)
out$prior.fit <- DS.GF.obj$prior.fit
class(out) <- "DS_GF_macro_mean"
return(out)
}
)
}
)
} |
graphab_metric <- function(proj_name,
graph,
metric,
dist = NULL,
prob = 0.05,
beta = 1,
cost_conv = FALSE,
return_val = TRUE,
proj_path = NULL,
alloc_ram = NULL){
if(!is.null(proj_path)){
chg <- 1
wd1 <- getwd()
setwd(dir = proj_path)
} else {
chg <- 0
proj_path <- getwd()
}
if(!inherits(proj_name, "character")){
if(chg == 1){setwd(dir = wd1)}
stop("'proj_name' must be a character string")
} else if (!(paste0(proj_name, ".xml") %in% list.files(path = paste0("./", proj_name)))){
if(chg == 1){setwd(dir = wd1)}
stop("The project you refer to does not exist.
Please use graphab_project() before.")
}
proj_end_path <- paste0(proj_name, "/", proj_name, ".xml")
if(!inherits(graph, "character")){
if(chg == 1){setwd(dir = wd1)}
stop("'graph' must be a character string")
} else if (!(paste0(graph, "-voronoi.shp") %in% list.files(path = paste0("./", proj_name)))){
if(chg == 1){setwd(dir = wd1)}
stop("The graph you refer to does not exist")
} else if (length(list.files(path = paste0("./", proj_name), pattern = "-voronoi.shp")) == 0){
if(chg == 1){setwd(dir = wd1)}
stop("There is not any graph in the project you refer to.
Please use graphab_graph() before.")
}
list_all_metrics <- c("PC", "IIC", "dPC", "F", "BC", "IF", "Dg", "CCe", "CF")
list_glob_metrics <- list_all_metrics[1:3]
list_loc_metrics <- list_all_metrics[4:length(list_all_metrics)]
list_dist_metrics <- c("PC", "F", "BC", "IF", "dPC")
if(metric %in% list_dist_metrics){
if(is.null(dist)){
if(chg == 1){setwd(dir = wd1)}
stop(paste0("To compute ", metric, ", specify a distance associated to
a dispersal probability (default=0.05)"))
} else if(!inherits(dist, c("numeric", "integer"))){
if(chg == 1){setwd(dir = wd1)}
stop("'dist' must be a numeric or integer value")
} else if(!inherits(prob, c("numeric", "integer"))){
if(chg == 1){setwd(dir = wd1)}
stop("'prob' must be a numeric or integer value")
} else if(!inherits(beta, c("numeric", "integer"))){
if(chg == 1){setwd(dir = wd1)}
stop("'beta' must be a numeric or integer value")
} else if(beta < 0 || beta > 1){
if(chg == 1){setwd(dir = wd1)}
stop("'beta' must be between 0 and 1")
} else if(prob < 0 || prob > 1){
if(chg == 1){setwd(dir = wd1)}
stop("'prob' must be between 0 and 1")
}
}
if(metric == "dPC"){
if(cost_conv){
if(chg == 1){setwd(dir = wd1)}
stop("Option 'cost_conv = TRUE' is not available with the metric dPC")
}
}
if(metric == "CF"){
if(beta < 0 || beta > 1){
if(chg == 1){setwd(dir = wd1)}
stop("'beta' must be between 0 and 1")
}
}
if(!inherits(metric, "character")){
if(chg == 1){setwd(dir = wd1)}
stop("'metric' must be a character string")
} else if(!(metric %in% list_all_metrics)){
if(chg == 1){setwd(dir = wd1)}
stop(paste0("'metric' must be ", paste(list_all_metrics, collapse = " or ")))
} else if(metric %in% list_loc_metrics){
level <- "patch"
} else if(metric %in% list_glob_metrics){
level <- "graph"
}
if(!is.logical(cost_conv)){
if(chg == 1){setwd(dir = wd1)}
stop("'cost_conv' must be a logical (TRUE or FALSE).")
}
if(!is.logical(return_val)){
if(chg == 1){setwd(dir = wd1)}
stop("'return_val' must be a logical (TRUE or FALSE).")
}
gr <- get_graphab(res = FALSE, return = TRUE)
if(gr == 1){
message("Graphab has been downloaded")
}
java.path <- Sys.which("java")
version <- "graphab-2.6.jar"
path_to_graphab <- paste0(rappdirs::user_data_dir(), "/graph4lg_jar/", version)
cmd <- c("-Djava.awt.headless=true", "-jar", path_to_graphab,
"--project", proj_end_path,
"--usegraph", graph)
if(level == "graph"){
cmd <- c(cmd, "--gmetric", metric)
} else if (level == "patch"){
cmd <- c(cmd, "--lmetric", metric)
}
if(metric %in% list_dist_metrics){
if(cost_conv){
cmd <- c(cmd,
paste0("d={", dist, "}"),
paste0("p=", prob),
paste0("beta=", beta))
} else {
cmd <- c(cmd,
paste0("d=", dist),
paste0("p=", prob),
paste0("beta=", beta))
}
} else if (metric == "CF"){
cmd <- c(cmd,
paste0("beta=", beta))
}
if(metric == "dPC"){
cmd[8] <- "--delta"
cmd[13] <- "obj=patch"
}
if(!is.null(alloc_ram)){
if(inherits(alloc_ram, c("integer", "numeric"))){
cmd <- c(paste0("-Xmx", alloc_ram, "g"), cmd)
} else {
if(chg == 1){setwd(dir = wd1)}
stop("'alloc_ram' must be a numeric or an integer")
}
}
rs <- system2(java.path, args = cmd, stdout = TRUE)
if(length(rs) == 1){
if(rs == 1){
message("An error occurred")
} else {
message(paste0("Metric '", metric, "' has been computed in the project ",
proj_name))
}
} else {
message(paste0("Metric '", metric, "' has been computed in the project ",
proj_name))
}
if(return_val){
if(level == "graph"){
if(metric != "dPC"){
val <- as.numeric(stringr::str_split(rs[2], pattern = ":")[[1]][2])
vec_res <- c(paste0("Project : ", proj_name),
paste0("Graph : ", graph),
paste0("Metric : ", metric))
if(metric %in% list_dist_metrics){
vec_res <- c(vec_res,
paste0("Dist : ", dist),
paste0("Prob : ", prob),
paste0("Beta : ", beta))
}
vec_res <- c(vec_res,
paste0("Value : ", val))
res <- vec_res
} else if (metric == "dPC") {
name_txt <- paste0("delta-dPC_d", dist, "_p", prob, "_", graph, ".txt")
res_dpc <- utils::read.table(file = paste0("./", proj_name, "/",
name_txt),
header = TRUE)[-1, ]
vec_res <- c(paste0("Project : ", proj_name),
paste0("Graph : ", graph),
paste0("Metric : ", metric),
paste0("Dist : ", dist),
paste0("Prob : ", prob),
paste0("Beta : ", beta))
res <- list(vec_res, res_dpc)
}
} else if (level == "patch"){
name_met <- gsub(stringr::str_split(rs[3], pattern = ":")[[1]][2],
pattern = " ", replacement = "")
tab <- utils::read.csv(file = paste0(proj_name, "/patches.csv"))
df_res <- tab[, c(1,
which(colnames(tab) == paste0(name_met, "_", graph)))]
vec_res <- c(paste0("Project : ", proj_name),
paste0("Graph : ", graph),
paste0("Metric : ", metric))
if(metric %in% list_dist_metrics){
vec_res <- c(vec_res,
paste0("Dist : ", dist),
paste0("Prob : ", prob),
paste0("Beta : ", beta))
} else if (metric == "CF"){
vec_res <- c(vec_res,
paste0("Beta : ", beta))
}
res <- list(vec_res, df_res)
}
return(res)
}
if(chg == 1){
setwd(dir = wd1)
}
} |
construct.splitSelect <- function(object, fn_call, x, y, intercept=TRUE, family=family){
class(object) <- append("splitSelect", class(object))
object$num_splits <- nrow(object$splits)
if(intercept)
object$intercepts <- object$betas[1,]
object$call <- fn_call
object$family <- family
return(object)
}
construct.cv.splitSelect <- function(object, fn_call, x, y, intercept=TRUE, family=family){
class(object) <- append("cv.splitSelect", class(object))
object$num_splits <- nrow(object$splits)
if(intercept)
object$intercepts <- object$betas[1,]
object$call <- fn_call
object$family <- family
return(object)
} |
context("literature")
test_that("/literature/gwas", {
skip_on_cran()
url <- getOption("epigraphdb.api.url")
trait <- "Body mass index"
semmed_predicate <- NULL
r <- httr::RETRY("GET", glue::glue("{url}/literature/gwas"),
query = list(
trait = trait,
semmed_predicate = semmed_predicate
),
config = httr::add_headers(.headers = c("client-type" = "R", "ci" = "true"))
)
expect_equal(httr::status_code(r), 200)
expect_true(length(httr::content(r)) > 0)
})
test_that("literature_gwas", {
skip_on_cran()
trait <- "Body mass index"
expect_error(
literature_gwas(
trait = trait
),
NA
)
}) |
treenode.pls <- function (xtree, node, boot.val = TRUE, br = 500)
{
if (class(xtree) != "xtree.pls")
stop("\nAn object of class 'xtree.pls' was expected")
if (missing(node))
stop("\nargument 'node' (number of node) is missing")
if (mode(node)!="numeric" || length(node)!=1 || node<=1 || (node%%1)!=0)
stop("\nInvalid number of 'node'. Must be an integer larger than 1")
if (boot.val) {
if (!is.null(br)) {
if(!is_positive_integer(br) || length(br) != 1L || br < 10) {
warning("Warning: Invalid argument 'br'. Default 'br=500' is used.")
br = 500
}
} else
br = 500
}
x = xtree$model$data
inner = as.matrix(xtree$model$inner)
outer = xtree$model$outer
mode = xtree$model$mode
scaling = xtree$model$scaling
scaled = xtree$model$scaled
scheme = xtree$model$scheme
MOX = xtree$MOX
nodes = xtree$nodes
x.node = x[unlist(nodes[node]),]
pls=plspm(x.node,inner,outer,mode,scaling,scheme,scaled=scaled,boot.val = boot.val,br=br)
cor.lat=round(cor(pls$scores),3)
diag(cor.lat) = sqrt(pls$inner_summary[,5])
disc_val<-round(cor.lat,3)
disc_val[upper.tri(cor.lat)]<-""
disc_val<-as.data.frame(disc_val)
res=list(Reliability_indexes_and_unidimensionality =round(cbind(pls$unidim[,-(1:2)][,c(1:4)]),3), Internal_consistency_and_R2=round(pls$inner_summary[,c(2,5)],3),
loading=round(pls$boot$loading,3), weights=round(pls$boot$weights,3),discriminant_validity=disc_val, path_coef=round(pls$boot$paths,3),
total_effects=round(pls$boot$total,3) )
cat("\n")
cat("---------------------------------------------")
cat("\n")
cat("---------------------------------------------")
cat("\n")
cat("PLS-SEM RESULTS FOR PATHMOX TERMINAL NODE: ",node,"\n")
cat("\n")
cat("---------------------------------------------")
cat("\n")
cat("---------------------------------------------")
cat("\n")
cat("\n")
cat("\n")
return(res)
} |
.dt_row_groups_key <- "_row_groups"
dt_row_groups_get <- function(data) {
dt__get(data, .dt_row_groups_key)
}
dt_row_groups_set <- function(data, row_groups) {
dt__set(data, .dt_row_groups_key, row_groups)
}
dt_row_groups_init <- function(data) {
stub_df <- dt_stub_df_get(data = data)
if (any(!is.na(stub_df[["group_id"]]))) {
row_groups <- unique(stub_df[["group_id"]])
} else {
row_groups <- character(0)
}
data <-
row_groups %>%
dt_row_groups_set(data = data)
data
} |
source('~/git/derivmkts/R/greeks.R')
library(testthat)
load('~/git/derivmkts/tests/testthat/option_testvalues.Rdata')
barrierchecks <- FALSE
barrierchecks <- TRUE
tol <- 5e-07
tol2 <- 1e-04
test_that('greeks works bscall', {
correct <- greeksvals[['bscall']]
unknown <- greeks(bscall(s=s, k=kseq, v=v,
r=r, tt=tt, d=d),
initcaps=TRUE)
expect_equal(correct, unknown, tolerance=tol)
}
)
print('bscall greeks okay')
test_that('tidy greeks works bscall', {
correct <- greeksvals2[['bscalltidy']]
unknown <- greeks(bscall(s=s, k=kseq, v=v,
r=r, tt=tt, d=d),
complete=TRUE, initcaps=FALSE)
expect_equal(correct, unknown, tolerance=tol)
}
)
print('complete bscall greeks okay')
test_that('long tidy greeks works bscall', {
correct <- greeksvals2[['bscalltidylong']]
unknown <- greeks(bscall(s=s, k=kseq0, v=v,
r=r, tt=tt, d=d),
long=TRUE,
initcaps=FALSE)
expect_equivalent(correct, unknown, tolerance=tol)
}
)
print('complete long bscall greeks okay')
test_that('greeks2 works bscall', {
correct <- greeksvals2[['bscall']]
unknown <- greeks2(bscall, greeksinputs)
expect_equal(correct, unknown, tolerance=tol)
}
)
print('bscall greeks2 okay')
if (barrierchecks) {
test_that('greeks works assetuicall', {
correct <- greeksvals[['assetuicall']]
colnames(correct) <- tolower(colnames(correct))
unknown <-
greeks2(assetuicall, list(s=40, k=kseq, v=v,
r=r, tt=tt, d=d, H=Hseq2)
)
expect_equal(correct, unknown, tolerance=tol2)
}
)
print('assetuicall greeks okay')
test_that('greeks2 works assetuicall', {
correct <- greeksvals2[['assetuicalltidy']]
correct$funcname <- tolower(correct$funcname)
unknown <- greeks(assetuicall(s=s, k=kseq, v=v,
r=r, tt=tt, d=d, H=Hseq2),
complete=TRUE, initcaps=FALSE)
expect_equal(correct, unknown, tolerance=tol2)
}
)
print('assetuicall greeks2 okay')
test_that('greeks2 works assetuicall', {
correct <- greeksvals2[['assetuicall']]
colnames(correct) <- tolower(colnames(correct))
unknown <- greeks(assetuicall(s=s, k=kseq, v=v,
r=r, tt=tt, d=d, H=Hseq2),
initcaps=TRUE)
expect_equal(correct, unknown, tolerance=tol2)
}
)
print('assetuicall greeks2 okay')
} |
fast_filter_variables <- function(data_set, level = 3, keep_cols = NULL, verbose = TRUE, ...) {
function_name <- "fast_filter_variables"
args <- list(...)
data_set_name <- get_data_set_name_from_args(args)
data_set <- check_and_return_datatable(data_set = data_set, data_set_name = data_set_name)
is.verbose_level(verbose, max_level = 2, function_name = function_name)
keep_cols <- real_cols(data_set = data_set, cols = keep_cols, function_name = function_name)
is.filtering_level(level, function_name = function_name)
if (level >= 1) {
if (verbose) {
printl(function_name, ": I check for constant columns.")
}
constant_cols <- which_are_constant(data_set, keep_cols = keep_cols, verbose = verbose >= 2)
if (length(constant_cols) > 0) {
if (verbose) {
printl(function_name, ": I delete ", length(constant_cols),
" constant column(s) in ", data_set_name, ".")
}
set(data_set, NULL, constant_cols, NULL)
}
}
if (level >= 2) {
if (verbose) {
printl(function_name, ": I check for columns in double.")
}
double_cols <- which_are_in_double(data_set, keep_cols = keep_cols, verbose = verbose >= 2)
if (length(double_cols) > 0) {
if (verbose) {
printl(function_name, ": I delete ", length(double_cols),
" column(s) that are in double in ", data_set_name, ".")
}
set(data_set, NULL, double_cols, NULL)
}
}
if (level >= 3) {
if (verbose) {
printl(function_name, ": I check for columns that are bijections of another column.")
}
bijection_cols <- which_are_bijection(data_set, keep_cols = keep_cols, verbose = verbose >= 2)
if (length(bijection_cols) > 0) {
if (verbose) {
printl(function_name, ": I delete ", length(bijection_cols),
" column(s) that are bijections of another column in ", data_set_name, ".")
}
set(data_set, NULL, bijection_cols, NULL)
}
}
if (level >= 4) {
if (verbose) {
printl(function_name, ": I check for columns that are included in another column.")
}
included_cols <- which_are_included(data_set, keep_cols = keep_cols, verbose = verbose >= 2)
if (length(included_cols) > 0) {
if (verbose) {
printl(function_name, ": I delete ", length(included_cols),
" column(s) that are bijections of another column in ", data_set_name, ".")
}
set(data_set, NULL, included_cols, NULL)
}
}
return(data_set)
}
get_data_set_name_from_args <- function(args) {
data_set_name <- "data_set"
if (length(args) > 0) {
if (! is.null(args[["data_set_name"]])) {
data_set_name <- args[["data_set_name"]]
}
}
return(data_set_name)
}
is.filtering_level <- function(level, function_name = "is.filtering_level") {
if (! is.numeric(level) || level < 1 || level > 4) {
stop(paste0(function_name, ": level should be 1, 2, 3 or 4."))
}
}
fast_round <- function(data_set, cols = "auto", digits = 2, verbose = TRUE) {
function_name <- "fast_round"
data_set <- check_and_return_datatable(data_set)
if (! is.numeric(digits)) {
stop(paste0(function_name, ": digits should be an integer."))
}
is.verbose(verbose)
cols <- real_cols(data_set, cols = cols, function_name = function_name, types = c("numeric", "integer"))
digits <- round(digits, 0)
if (verbose) {
pb <- init_progress_bar(function_name, cols)
}
for (col in cols) {
set(data_set, NULL, col, round(data_set[[col]], digits))
if (verbose) {
add_a_tick_to_progress_bar(pb)
}
}
return(data_set)
}
fast_handle_na <- function(data_set, set_num = 0, set_logical = FALSE,
set_char = "", verbose = TRUE) {
function_name <- "fast_handle_na"
data_set <- check_and_return_datatable(data_set)
is.verbose(verbose)
num_fun <- function.maker(set_num, "numeric", function_name, "set_num")
logical_fun <- function.maker(set_logical, "logical", function_name, "set_logical")
char_fun <- function.maker(set_char, "character", function_name, "set_char")
if (verbose) {
pb <- init_progress_bar(function_name, names(data_set))
}
for (col in names(data_set)) {
if (is.numeric(data_set[[col]])) {
set(data_set, which(is.na(data_set[[col]])), col, num_fun(data_set[[col]]))
}
if (is.logical(data_set[[col]])) {
set(data_set, which(is.na(data_set[[col]])), col, logical_fun(data_set[[col]]))
}
if (is.character(data_set[[col]])) {
set(data_set, which(is.na(data_set[[col]])), col, char_fun(data_set[[col]]))
}
if (is.factor(data_set[[col]])) {
if (sum(is.na(data_set[[col]])) > 0) {
set(data_set, NULL, col, addNA(data_set[[col]]))
levels(data_set[[col]])[is.na(levels(data_set[[col]]))] <- "NA"
}
}
if (verbose) {
add_a_tick_to_progress_bar(pb)
}
}
return(data_set)
}
fast_is_equal <- function(object1, object2) {
if (any(class(object1) != class(object2))) {
return(FALSE)
}
if (length(object1) != length(object2)) {
return(FALSE)
}
if (is.data.frame(object1) || is.list(object1)) {
for (i in seq_len(length(object1))) {
if (! fast_is_equal(object1[[i]], object2[[i]])) {
return(FALSE)
}
}
return(TRUE)
}
if (is.factor(object1)) {
if (! identical(levels(object1), levels(object2))) {
return(FALSE)
}
}
return(exponential_equality_check(object1, object2))
}
exponential_equality_check <- function(object1, object2) {
exp_factor <- 10
max_power <- floor(log(length(object1)) / log(exp_factor)) + 1
for (i in 1 : max_power) {
indexes <- (exp_factor ^ (i - 1)) : min(exp_factor ^ i - 1, length(object1))
if (! identical(object1[indexes], object2[indexes])) {
return(FALSE)
}
}
return(TRUE)
}
fast_is_bijection <- function(object1, object2) {
nrows <- length(object1)
exp_factor <- 10
max_power <- floor(log(nrows) / log(exp_factor)) + 1
empty_object_of_class_1 <- get(paste0("as.", class(object1)[1]))(character())
empty_object_of_class_2 <- get(paste0("as.", class(object2)[1]))(character())
unique_couples <- data.table(object1 = empty_object_of_class_1, object2 = empty_object_of_class_2)
for (i in 1 : max_power) {
indexes <- (exp_factor ^ (i - 1)) : min(exp_factor ^ i - 1, nrows)
n1 <- uniqueN(c(object1[indexes], unique_couples[["object1"]]))
n2 <- uniqueN(c(object2[indexes], unique_couples[["object2"]]))
if (n2 != n1) {
return(FALSE)
}
potential_unique_couples <- rbind(data.table(object1 = object1[indexes],
object2 = object2[indexes]), unique_couples)
unique_couples <- potential_unique_couples[, unique(.SD), .SDcols = c("object1", "object2")]
n12 <- nrow(unique_couples)
if (n12 != n1) {
return(FALSE)
}
}
return(TRUE)
}
fast_is_there_less_than <- function(object, n_values = 1) {
unique_elements <- NULL
exp_factor <- 10
object_length <- length(object)
max_power <- floor(log(object_length) / log(exp_factor)) + 1
for (i in 1 : max_power) {
indexes <- (exp_factor ^ (i - 1)) : min(exp_factor ^ i - 1, object_length)
unique_elements <- unique(c(unique_elements, unique(object[indexes])))
if (length(unique_elements) > n_values) {
return(FALSE)
}
}
return(TRUE)
} |
observe({
val <- input$itemanalysis_DDplot_groups_slider
updateSliderInput(session, "itemanalysis_DDplot_range_slider",
min = 1,
max = val,
step = 1,
value = c(1, val)
)
})
observe({
val <- input$report_itemanalysis_DDplot_groups_slider
updateSliderInput(session, "report_itemanalysis_DDplot_range_slider",
min = 1,
max = val,
step = 1,
value = c(1, val)
)
})
output$itemanalysis_DDplot_text <- renderUI({
range1 <- input$itemanalysis_DDplot_range_slider[[1]]
range2 <- input$itemanalysis_DDplot_range_slider[[2]]
if (any(range1 != 1, range2 != 3, input$itemanalysis_DDplot_groups_slider != 3)) {
HTML(paste0(
"Discrimination is defined as a difference in average (scaled) item score between the ",
"<b>", range1, "</b>",
ifelse(range1 >= 4, "-th", switch(range1, "1" = "-st", "2" = "-nd", "3" = "-rd")),
" and <b>", range2, "</b>",
ifelse(range2 >= 4, "-th", switch(range2, "1" = "-st", "2" = "-nd", "3" = "-rd")),
" group out of total number of ",
"<b>", input$itemanalysis_DDplot_groups_slider, "</b>",
" groups. "
))
}
})
itemanalysis_DDplot <- reactive({
correct <- ordinal()
average.score <- (input$itemanalysis_DDplot_difficulty == "AVGS")
validate(need(
input$itemanalysis_DDplot_range_slider[[2]] <= input$itemanalysis_DDplot_groups_slider,
""
))
DDplot(Data = correct,
item.names = item_numbers(),
k = input$itemanalysis_DDplot_groups_slider,
l = input$itemanalysis_DDplot_range_slider[[1]],
u = input$itemanalysis_DDplot_range_slider[[2]],
discrim = input$itemanalysis_DDplot_discrimination,
average.score = average.score,
thr = switch(input$itemanalysis_DDplot_threshold,
"TRUE" = input$itemanalysis_DDplot_threshold_value,
"FALSE" = NULL
)
)
})
report_itemanalysis_DDplot <- reactive({
correct <- ordinal()
if (input$customizeCheck) {
average.score <- (input$report_itemanalysis_DDplot_difficulty == "AVGS")
DDplot(Data = correct,
item.names = item_numbers(),
k = input$report_itemanalysis_DDplot_groups_slider,
l = input$report_itemanalysis_DDplot_range_slider[[1]],
u = input$report_itemanalysis_DDplot_range_slider[[2]],
discrim = input$report_itemanalysis_DDplot_discrimination
)
} else {
itemanalysis_DDplot()
}
})
output$itemanalysis_DDplot <- renderPlotly({
p <- itemanalysis_DDplot() %>%
ggplotly(tooltip = c("item", "fill", "value", "yintercept"))
for (i in 1:2) {
for (j in 1:length(p$x$data[[i]][["text"]])) {
p$x$data[[i]][["text"]][j] <-
str_remove(
str_replace(
str_remove_all(p$x$data[[i]][["text"]][j], "parameter: |value: "),
"item",
"Item"
),
"(?<=\\.\\d{3}).*"
)
}
}
if (input$itemanalysis_DDplot_threshold) {
p$x$data[[3]][["text"]] <-
str_replace(p$x$data[[3]][["text"]], "yintercept", "Threshold")
}
p %>% plotly::config(displayModeBar = FALSE)
})
output$itemanalysis_DDplot_download <- downloadHandler(
filename = function() {
"fig_DDplot.png"
},
content = function(file) {
ggsave(file,
plot = itemanalysis_DDplot() +
theme(text = element_text(size = setting_figures$text_size)),
device = "png",
height = setting_figures$height, width = setting_figures$width,
dpi = setting_figures$dpi
)
}
)
itemanalysis_cronbach_note <- reactive({
cronbach <- list()
cronbach$est <- round(psych::alpha(ordinal())$total[1], 2)
cronbach$sd <- round(psych::alpha(ordinal())$total[8], 2)
cronbach
})
output$itemanalysis_cronbach_note <- renderUI({
HTML(
paste0(
"<sup>1</sup>Estimate (SD) of Cronbach's \\(\\alpha\\) for the test as a whole is: ",
itemanalysis_cronbach_note()$est,
" (",
itemanalysis_cronbach_note()$sd,
")."
)
)
})
output$itemanalysis_table_text <- renderUI({
range1 <- input$itemanalysis_DDplot_range_slider[[1]]
range2 <- input$itemanalysis_DDplot_range_slider[[2]]
num.groups <- input$itemanalysis_DDplot_groups_slider
HTML(paste0(
"<b>Explanation:<br>Diff.</b> ",
"– item difficulty estimated as an average item score divided by its range, ",
"<b>Avg. score</b> ",
"– average item score, ",
"<b>SD</b> ",
"– standard deviation, ",
"<b>ULI</b> ",
"– Upper-Lower Index, ",
if (num.groups != 3 | range1 != 1 | range2 != 3) {
paste0(
"<b>gULI</b> ",
"– generalized ULI, difference between the difficulty recorded in the ", range1,
ifelse(range1 >= 4, "-th", switch(range1, "1" = "-st", "2" = "-nd", "3" = "-rd")),
" and ", range2,
ifelse(range2 >= 4, "-th", switch(range2, "1" = "-st", "2" = "-nd", "3" = "-rd")),
" group out of total number of ", num.groups, " groups, "
)
},
"<b>RIT</b> ",
"– Pearson correlation between item and total score, ",
"<b>RIR</b> ",
"– Pearson correlation between item and rest of the items, ",
"<b>Rel.</b> ",
"– item reliability index, ",
"<b>Rel. drop</b> ",
"– as previous, but scored without the respective item, ",
"<b>I-C cor.</b> ",
"– item-criterion correlation, ",
"<b>Val. index</b> ",
"– item validity index, ",
"<b>\\(\\alpha\\) drop </b> ",
"– Cronbach\'s \\(\\alpha\\) of test without given item (the value for the test as a whole is presented in the note below), ",
"<b>Missed</b> ",
"– percentage of missed responses on the particular item, ",
"<b>Not-reached</b> ",
"– percentage of respondents that did not reach the item nor the subsequent ones"
))
})
itemanalysis_table <- reactive({
k <- input$itemanalysis_DDplot_groups_slider
l <- input$itemanalysis_DDplot_range_slider[[1]]
u <- input$itemanalysis_DDplot_range_slider[[2]]
item_crit_cor <- if (any(crit_wo_val() == "missing", na.rm = TRUE)) {
"none"
} else {
unlist(crit_wo_val())
}
tab <-
ItemAnalysis(Data = ordinal(),
criterion = item_crit_cor,
k, l, u,
minscore = minimal(),
maxscore = maximal()
)
tab <- tab[, !(colnames(tab) %in% c("Prop.max.score"))]
if (item_crit_cor[1] == "none") {
colnames(tab) <- c(
"Diff.", "Avg. score", "SD", "Min", "Max", "obsMin", "obsMax",
"gULI", "ULI", "RIT", "RIR",
"Rel.", "Rel. drop",
"Alpha drop",
"Missed [%]", "Not-reached [%]"
)
} else {
colnames(tab) <- c(
"Diff.", "Avg. score", "SD", "Min", "Max", "obsMin", "obsMax",
"gULI", "ULI", "RIT", "RIR",
"I-C cor.", "Val. index",
"Rel.", "Rel. drop",
"Alpha drop",
"Missed [%]", "Not-reached [%]"
)
}
remove_gULI <- (k == 3 & l == 1 & u == 3)
if (remove_gULI) {
tab <- tab[, !(colnames(tab) %in% "gULI")]
}
row.names(tab) <- item_names()
tab
})
report_itemanalysis_table <- reactive({
a <- nominal()
k <- key()
correct <- ordinal()
range1 <- ifelse(input$customizeCheck,
input$report_itemanalysis_DDplot_range_slider[[1]],
input$itemanalysis_DDplot_range_slider[[1]]
)
range2 <- ifelse(input$customizeCheck,
input$report_itemanalysis_DDplot_range_slider[[2]],
input$itemanalysis_DDplot_range_slider[[2]]
)
num.groups <- ifelse(input$customizeCheck,
input$report_itemanalysis_DDplot_groups_slider,
input$itemanalysis_DDplot_groups_slider
)
tab <- ItemAnalysis(Data = correct)
tab <- data.table(
item_numbers(),
tab[, c("Difficulty", "Mean", "SD", "ULI", "RIT", "RIR", "Alpha.drop")]
)
tab <- cbind(tab, gDiscrim(Data = correct, k = num.groups, l = range1, u = range2))
colnames(tab) <- c(
"Item", "Difficulty", "Average score", "SD", "Discrimination ULI",
"Discrimination RIT", "Discrimination RIR", "Alpha Drop",
"Customized Discrimination"
)
tab
})
output$itemanalysis_table_coef <- renderTable(
{
tab <- itemanalysis_table()
colnames(tab)[which(colnames(tab) == "Alpha drop")] <- "\\(\\mathit{\\alpha}\\) drop\\(\\mathrm{^1}\\)"
tab
},
rownames = TRUE
)
output$itemanalysis_table_download <- downloadHandler(
filename = function() {
"Item_Analysis.csv"
},
content = function(file) {
data <- itemanalysis_table()
write.csv(data, file)
write(
paste0(
"Note: Estimate (SD) of Cronbach's alpha for the test as a whole is: ",
itemanalysis_cronbach_note()$est,
" (",
itemanalysis_cronbach_note()$sd,
")."
),
file,
append = TRUE
)
}
)
observe({
item_count <- ncol(binary())
updateSliderInput(
session = session,
inputId = "distractor_item_slider",
max = item_count
)
})
distractor_admissible_groups <- reactive({
sc <- total_score()
sc_quant <- lapply(1:5, function(i) quantile(sc, seq(0, 1, by = 1 / i), na.rm = TRUE))
sc_quant_unique <- sapply(sc_quant, function(i) !any(duplicated(i)))
groups <- c(1:5)[sc_quant_unique]
groups
})
distractor_change_cut_indicator <- reactiveValues(change = FALSE)
observeEvent(!(input$distractor_group_slider %in% distractor_admissible_groups()), {
if (!(input$distractor_group_slider %in% distractor_admissible_groups())) {
distractor_change_cut_indicator$change <- TRUE
c <- max(distractor_admissible_groups(), na.rm = TRUE)
updateSliderInput(session, "distractor_group_slider", value = c)
}
})
output$distractor_groups_alert <- renderUI({
if (distractor_change_cut_indicator$change) {
txt <- paste0(
'<font color = "orange">The cut of criterion variable was not unique. The maximum number of
groups for which criterion variable is unique is ',
max(distractor_admissible_groups(), na.rm = TRUE), ".</font>"
)
HTML(txt)
} else {
txt <- ""
HTML(txt)
}
})
output$distractor_text <- renderUI({
txt1 <- paste("Respondents are divided into ")
txt2 <- paste("<b>", input$distractor_group_slider, "</b>")
txt3 <- paste("groups by their total score. For each group, we subsequently display a proportion
of respondents who have selected a given response.
In case of multiple-choice items, the correct answer should be selected more often by respondents with a higher total score
than by those with lower total scores, i.e.,")
txt4 <- paste("<b>", "solid line should be increasing.", "</b>")
txt5 <- paste("The distractor should work in the opposite direction, i.e.,")
txt6 <- paste("<b>", "dotted lines should be decreasing.", "<b>")
HTML(paste(txt1, txt2, txt3, txt4, txt5, txt6))
})
distractor_plot <- reactive({
i <- input$distractor_item_slider
plotDistractorAnalysis(
Data = nominal(),
key = key(),
num.group = input$distractor_group_slider,
item = i,
item.name = item_names()[i],
multiple.answers = input$distractor_type == "Combinations",
criterion = total_score()
) + xlab("Group by total score")
})
output$distractor_plot <- renderPlotly({
g <- distractor_plot()
p <- ggplotly(g)
for (i in 1:length(p$x$data)) {
text <- p$x$data[[i]]$text
text <- lapply(strsplit(text, split = "<br />"), unique)
text <- unlist(lapply(text, paste, collapse = "<br />"))
p$x$data[[i]]$text <- text
}
p$elementId <- NULL
p %>% plotly::config(displayModeBar = FALSE)
})
output$distractor_plot_download <- downloadHandler(
filename = function() {
paste0("fig_DistractorPlot_", item_names()[input$distractor_item_slider], ".png")
},
content = function(file) {
ggsave(file,
plot = distractor_plot() +
theme(text = element_text(size = setting_figures$text_size)),
device = "png",
height = setting_figures$height, width = setting_figures$width,
dpi = setting_figures$dpi
)
}
)
distractor_table_counts <- reactive({
num.group <- input$distractor_group_slider
a <- nominal()
k <- key()
item <- input$distractor_item_slider
sc <- total_score()
DA <- DistractorAnalysis(Data = a, key = k, num.groups = num.group, criterion = sc)[[item]]
df <- DA %>%
addmargins() %>%
as.data.frame.matrix() %>%
add_column(.before = 1, Response = as.factor(rownames(.)))
colnames(df) <- c("Response", paste("Group", 1:ifelse(num.group > (ncol(df) - 2), ncol(df) - 2, num.group)), "Total")
levels(df$Response)[nrow(df)] <- "Total"
rownames(df) <- NULL
df
})
output$distractor_table_counts <- renderTable(
{
distractor_table_counts()
},
digits = 0
)
distractor_table_proportions <- reactive({
a <- nominal()
k <- key()
num.group <- input$distractor_group_slider
item <- input$distractor_item_slider
sc <- total_score()
DA <- DistractorAnalysis(Data = a, key = k, num.groups = num.group, p.table = TRUE, criterion = sc)[[item]]
df <- DA %>%
as.data.frame.matrix() %>%
add_column(.before = 1, Response = as.factor(rownames(.)))
colnames(df) <- c("Response", paste("Group", 1:ifelse(num.group > (ncol(df) - 1), ncol(df) - 1, num.group)))
rownames(df) <- NULL
df
})
output$distractor_table_proportions <- renderTable({
distractor_table_proportions()
})
distractor_barplot_item_response_patterns <- reactive({
a <- nominal()
k <- key()
num.group <- 1
item <- input$distractor_item_slider
sc <- total_score()
DA <- DistractorAnalysis(Data = a, key = k, num.groups = num.group, p.table = TRUE, criterion = sc)[[item]]
df <- DA %>%
as.data.frame.matrix() %>%
add_column(.before = 1, Response = as.factor(rownames(.)))
colnames(df) <- c("Response", "Proportion")
rownames(df) <- NULL
ggplot(df, aes(x = Response, y = Proportion)) +
geom_bar(stat = "identity") +
xlab("Item response pattern") +
ylab("Relative frequency") +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0)) +
theme_app() +
ggtitle(item_names()[item])
})
output$distractor_barplot_item_response_patterns <- renderPlotly({
g <- distractor_barplot_item_response_patterns()
p <- ggplotly(g)
for (i in 1:length(p$x$data)) {
text <- p$x$data[[i]]$text
text <- lapply(strsplit(text, split = "<br />"), unique)
text <- unlist(lapply(text, paste, collapse = "<br />"))
p$x$data[[i]]$text <- text
}
p$elementId <- NULL
p %>% plotly::config(displayModeBar = FALSE)
})
output$distractor_barplot_item_response_patterns_download <- downloadHandler(
filename = function() {
paste0("fig_ItemResponsePatterns_", item_names()[input$distractor_item_slider], ".png")
},
content = function(file) {
ggsave(file,
plot = distractor_barplot_item_response_patterns() +
theme(text = element_text(size = setting_figures$text_size)),
device = "png",
height = setting_figures$height, width = setting_figures$width,
dpi = setting_figures$dpi
)
}
)
distractor_histogram <- reactive({
a <- nominal()
k <- key()
num.groups <- input$distractor_group_slider
sc <- total_score()
sc.level <- cut(sc, quantile(sc, seq(0, 1, by = 1 / num.groups), na.rm = TRUE), include.lowest = TRUE)
df <- data.frame(Score = sc, Group = sc.level)
col <- c("darkred", "red", "orange2", "gold1", "green3")
col <- switch(input$distractor_group_slider,
"1" = col[4],
"2" = col[4:5],
"3" = col[c(2, 4:5)],
"4" = col[2:5],
"5" = col
)
ggplot(df, aes(x = Score, fill = Group, group = Group)) +
geom_histogram(binwidth = 1, color = "black") +
scale_fill_manual("", values = col) +
labs(
x = "Total score",
y = "Number of respondents"
) +
scale_y_continuous(
expand = c(0, 0),
limits = c(0, max(table(sc), na.rm = TRUE) + 0.01 * nrow(a))
) +
scale_x_continuous(
limits = c(-0.5 + min(sc, na.rm = TRUE), max(sc, na.rm = TRUE) + 0.5)
) +
theme_app()
})
output$distractor_histogram <- renderPlotly({
g <- distractor_histogram()
p <- ggplotly(g)
for (i in 1:length(p$x$data)) {
text <- p$x$data[[i]]$text
text <- lapply(strsplit(text, split = "<br />"), unique)
text <- unlist(lapply(text, paste, collapse = "<br />"))
text <- gsub("count", "Count", text)
text <- gsub("Score", "Total score", text)
p$x$data[[i]]$text <- text
}
p$elementId <- NULL
p %>% plotly::config(displayModeBar = FALSE)
})
output$distractor_histogram_download <- downloadHandler(
filename = function() {
"fig_HistrogramByDistractorGroups.png"
},
content = function(file) {
ggsave(file,
plot = distractor_histogram() +
theme(text = element_text(size = setting_figures$text_size)),
device = "png",
height = setting_figures$height, width = setting_figures$width,
dpi = setting_figures$dpi
)
}
)
distractor_table_total_score_by_group <- reactive({
sc <- total_score()
num.group <- input$distractor_group_slider
sc.level <- quantile(sc, seq(0, 1, by = 1 / num.group), na.rm = TRUE)
tab <- table(cut(sc,
sc.level,
include.lowest = TRUE,
labels = sc.level[-1]
))
tab <- t(data.frame(tab))
tab <- matrix(round(as.numeric(tab), 2), nrow = 2)
rownames(tab) <- c("Max points", "Count")
colnames(tab) <- paste("Group", 1:num.group)
tab
})
output$distractor_table_total_score_by_group <- renderTable(
{
distractor_table_total_score_by_group()
},
include.colnames = TRUE,
include.rownames = TRUE,
digits = 0
)
report_distractor_change_cut_indicator <- reactiveValues(change = FALSE)
observeEvent(list(input$customizeCheck, !(input$report_distractor_group_slider %in% distractor_admissible_groups())), {
if (!(input$report_distractor_group_slider %in% distractor_admissible_groups())) {
report_distractor_change_cut_indicator$change <- TRUE
c <- max(distractor_admissible_groups(), na.rm = TRUE)
updateSliderInput(session, "report_distractor_group_slider", value = c)
}
})
output$report_distractor_groups_alert <- renderUI({
if (report_distractor_change_cut_indicator$change) {
txt <- paste0('<font color = "orange">The cut of criterion variable was not unique. The maximum number of
groups, for which criterion variable is unique is ', max(distractor_admissible_groups(), na.rm = TRUE), ".</font>")
HTML(txt)
} else {
txt <- ""
HTML(txt)
}
})
report_distractor_plot <- reactive({
a <- nominal()
colnames(a) <- item_names()
k <- key()
sc <- total_score()
if (!input$customizeCheck) {
multiple.answers_report <- c(input$distractor_type == "Combinations")
num.group <- input$distractor_group_slider
} else {
multiple.answers_report <- c(input$report_distractor_type == "Combinations")
num.group <- input$report_distractor_group_slider
}
graflist <- list()
for (i in 1:length(k)) {
g <- plotDistractorAnalysis(
Data = a, key = k, num.group = num.group,
item = i,
item.name = item_names()[i],
multiple.answers = multiple.answers_report,
criterion = sc
) +
xlab("Group by total score")
g <- g +
ggtitle(paste("Distractor plot for item", item_numbers()[i])) +
theme_app()
graflist[[i]] <- g
}
graflist
}) |
.spawn_multi_selection_graph <- function(all_memory) {
graph <- make_graph(edges=character(0), isolates=names(all_memory))
for (x in names(all_memory)) {
instance <- all_memory[[x]]
for (f in c(.selectRowSource, .selectColSource)) {
parent <- slot(instance, f)
if (parent %in% names(all_memory)) {
graph <- .add_interpanel_link(graph, x, parent, field=f)
}
}
}
if (!is_dag(graph)) {
stop("multiple selection dependencies cannot be cyclic")
}
graph
}
.spawn_single_selection_graph <- function(all_memory) {
graph <- make_graph(edges=character(0), isolates=names(all_memory))
for (x in names(all_memory)) {
instance <- all_memory[[x]]
fields <- .singleSelectionSlots(instance)
for (f in fields) {
parent <- slot(instance, f$source)
if (parent %in% names(all_memory)) {
graph <- .add_interpanel_link(graph, x, parent, field=f$parameter)
}
}
}
graph
}
.add_interpanel_link <- function(graph, panel_name, parent_name, field) {
if (parent_name %in% names(V(graph))) {
idx <- get.edge.ids(graph, c(parent_name, panel_name))
if (idx==0L) {
graph <- add_edges(graph, c(parent_name, panel_name), attr=list(fields=list(field)))
} else {
E(graph)$fields[[idx]] <- union(E(graph)$fields[[idx]], field)
}
}
graph
}
.delete_interpanel_link <- function(graph, panel_name, parent_name, field) {
if (parent_name %in% names(V(graph))) {
idx <- get.edge.ids(graph, c(parent_name, panel_name))
if (idx!=0L) {
fields <- E(graph)$fields[[idx]]
remaining <- setdiff(fields, field)
if (length(remaining)) {
E(graph)$fields[[idx]] <- remaining
} else {
graph <- delete_edges(graph, idx)
}
}
}
graph
}
.get_direct_children <- function(graph, panel_name) {
children <- names(adjacent_vertices(graph, panel_name, mode="out")[[1]])
children <- setdiff(children, panel_name)
if (!length(children)) {
return(list())
}
ids <- get.edge.ids(graph, as.vector(rbind(panel_name, children)))
output <- E(graph)$fields[ids]
names(output) <- children
output
}
.choose_new_parent <- function(graph, panel_name, new_parent_name, old_parent_name, field) {
graph <- .delete_interpanel_link(graph, panel_name, old_parent_name, field)
.add_interpanel_link(graph, panel_name, new_parent_name, field)
}
.establish_eval_order <- function(graph) {
iso <- V(graph)[degree(graph, mode="out") == 0]
graph <- delete.vertices(graph, iso)
names(topo_sort(graph, mode="out"))
}
.has_child <- function(graph) {
names(V(graph)[degree(graph, mode="out") != 0])
}
.spawn_dynamic_multi_selection_list <- function(all_memory) {
multi_rows <- multi_cols <- list()
for (x in all_memory) {
panel_name <- .getEncodedName(x)
if (slot(x, .selectRowDynamic)) {
multi_rows[[panel_name]] <- .selectRowSource
}
if (slot(x, .selectColDynamic)) {
multi_cols[[panel_name]] <- .selectColSource
}
}
list(row=multi_rows, column=multi_cols)
}
.spawn_dynamic_single_selection_list <- function(all_memory) {
single_feat <- single_samp <- list()
for (x in all_memory) {
all_singles <- .singleSelectionSlots(x)
cur_feat <- cur_samp <- character(0)
for (s in all_singles) {
if (is.null(s$dimension)) {
next
}
if (is.null(s$dynamic) || !x[[s$dynamic]]) {
next
}
if (s$dimension=="feature") {
cur_feat <- c(cur_feat, s$source)
} else {
cur_samp <- c(cur_samp, s$source)
}
}
panel_name <- .getEncodedName(x)
if (length(cur_feat)) {
single_feat[[panel_name]] <- cur_feat
}
if (length(cur_samp)) {
single_samp[[panel_name]] <- cur_samp
}
}
list(feature=single_feat, sample=single_samp)
}
.add_panel_to_dynamic_sources <- function(listing, panel_name, source_type, field) {
existing <- listing[[source_type]][[panel_name]]
listing[[source_type]][[panel_name]] <- union(existing, field)
listing
}
.delete_panel_from_dynamic_sources <- function(listing, panel_name, source_type, field) {
existing <- listing[[source_type]][[panel_name]]
existing <- setdiff(existing, field)
if (!length(existing)) {
existing <- NULL
}
listing[[source_type]][[panel_name]] <- existing
listing
} |
plotDoseResponse.survDataCstExp <- function(x,
xlab = "Concentration",
ylab = "Survival probability",
main = NULL,
target.time = NULL,
style = "ggplot",
log.scale = FALSE,
remove.someLabels = FALSE,
addlegend = TRUE,
...) {
if (is.null(target.time)) target.time <- max(x$time)
if (!target.time %in% x$time || target.time == 0)
stop("[target.time] is not one of the possible time !")
if (style == "generic" && remove.someLabels)
warning("'remove.someLabels' argument is valid only in 'ggplot' style.",
call. = FALSE)
x <- cbind(aggregate(cbind(Nsurv, Ninit) ~ time + conc, x, sum),
replicate = 1)
x$resp <- x$Nsurv / x$Ninit
xf <- filter(x, x$time == target.time)
conf.int <- survConfInt(xf, log.scale)
sel <- if(log.scale) xf$conc > 0 else TRUE
x <- xf[sel, ]
transf_data_conc <- optLogTransform(log.scale, x$conc)
display.conc <- (function() {
x <- optLogTransform(log.scale, x$conc)
if(log.scale) exp(x) else x
})()
x$color <- as.numeric(as.factor(x$replicate))
if (style == "generic") {
plot(transf_data_conc, seq(0, max(conf.int["qsup95",]),
length.out = length(transf_data_conc)),
type = "n",
xaxt = "n",
yaxt = "n",
main = main,
xlab = xlab,
ylab = ylab)
axis(side = 1, at = transf_data_conc,
labels = display.conc)
axis(side = 2, at = unique(round(pretty(c(0, max(x$resp))))),
labels = unique(round(pretty(c(0, max(x$resp))))))
points(transf_data_conc, x$resp,
pch = 20)
segments(transf_data_conc, x$resp,
transf_data_conc, conf.int["qsup95", ])
segments(transf_data_conc, x$resp,
transf_data_conc, conf.int["qinf95", ])
if (addlegend) {
legend("bottomleft", pch = c(20, NA),
lty = c(NA, 1),
lwd = c(NA, 1),
col = c(1, 1),
legend = c("Observed values", "Confidence intervals"),
bty = "n")
}
}
else if (style == "ggplot") {
valCols <- fCols(x, fitcol = NA, cicol = NA)
df <- data.frame(x,
transf_data_conc,
display.conc,
Points = "Observed values")
dfCI <- data.frame(conc = transf_data_conc,
qinf95 = conf.int["qinf95",],
qsup95 = conf.int["qsup95",],
Conf.Int = "Confidence intervals")
fd <- ggplot(df) +
geom_point(aes(x = transf_data_conc, y = resp, fill = Points),
data = df, col = valCols$cols1) +
geom_segment(aes(x = conc, xend = conc, y = qinf95,
yend = qsup95,
linetype = Conf.Int),
dfCI, col = valCols$cols3) +
scale_fill_hue("") +
scale_linetype(name = "") +
expand_limits(x = 0, y = 0) + ggtitle(main) +
theme_minimal() +
labs(x = xlab,
y = ylab) +
scale_x_continuous(breaks = unique(df$transf_data_conc),
labels = if (remove.someLabels) {
exclude_labels(unique(df$display.conc))
} else {
unique(df$display.conc)
}
) +
scale_y_continuous(breaks = unique(round(pretty(c(0, max(df$resp)))))) +
expand_limits(x = 0, y = 0)
if (addlegend) {
fd
} else {
fd + theme(legend.position = "none")
}
}
else stop("Unknown plot style")
}
survConfInt <- function(x, log.scale) {
ci <- apply(x, 1, function(x) {
binom.test(x["Nsurv"], x["Ninit"])$conf.int
})
rownames(ci) <- c("qinf95", "qsup95")
colnames(ci) <- x$conc
if (log.scale) ci <- ci[ ,colnames(ci) != 0]
return(ci)
} |
to_broom_names = function(data) {
lookup = c(
.variable = "term",
.value = "estimate",
.prediction = ".fitted",
.lower = "conf.low",
.upper = "conf.high"
)
select_all(data, ~ lookup[.] %||% .)
}
from_broom_names = function(data) {
lookup = c(
term = ".variable",
estimate = ".value",
.fitted = ".prediction",
conf.low = ".lower",
conf.high = ".upper"
)
select_all(data, ~ lookup[.] %||% .)
}
to_ggmcmc_names = function(data) {
lookup = c(
.chain = "Chain",
.iteration = "Iteration",
.variable = "Parameter",
.value = "value"
)
select_all(data, ~ lookup[.] %||% .)
}
from_ggmcmc_names = function(data) {
lookup = c(
Chain = ".chain",
Iteration = ".iteration",
Parameter = ".variable",
value = ".value"
)
select_all(data, ~ lookup[.] %||% .)
} |
NULL
raudkePplot<- function(Ce,Qe){
.Deprecated("raudkepanalysis")
x <- 1/(1+Ce)^2
y <- 1/Qe
fit72<- lm(y~x)
plot(y~x, main="Raudke-Prausniiz Analysis", xlab="1/Ce", ylab="1/Qe")
abline(fit72,col="black")
} |
plot.gdina <- function( x, ask=FALSE, ... )
{
probitem <- x$probitem
I <- max( probitem$itemno )
for (ii in 1:I){
pii <- probitem[ probitem$itemno==ii, ]
graphics::barplot( pii$prob, ylim=c(0,1), xlab="Skill Pattern",
names.arg=pii$skillcomb,
main=paste0( "Item ", pii[1,"item" ], " (Rule ", x$rule[ii], ")\n",
"Attributes ", pii[1,"partype.attr"] ), ask=ask )
}
} |
mppm <- local({
mppm <- function(formula, data, interaction=Poisson(), ...,
iformula=NULL,
random=NULL,
weights=NULL,
use.gam=FALSE,
reltol.pql=1e-3,
gcontrol=list()
) {
cl <- match.call()
callstring <- paste(short.deparse(sys.call()), collapse="")
if(!inherits(formula, "formula"))
stop(paste("Argument", dQuote("formula"), "should be a formula"))
stopifnot(is.hyperframe(data))
data.sumry <- summary(data, brief=TRUE)
npat <- data.sumry$ncases
if(npat == 0)
stop(paste("Hyperframe", sQuote("data"), "has zero rows"))
if(!is.null(iformula) && !inherits(iformula, "formula"))
stop(paste("Argument", sQuote("iformula"), "should be a formula or NULL"))
if(has.random <- !is.null(random)) {
if(!inherits(random, "formula"))
stop(paste(sQuote("random"), "should be a formula or NULL"))
if(use.gam)
stop("Sorry, random effects are not available in GAMs")
}
if(! (is.interact(interaction) || is.hyperframe(interaction)))
stop(paste("The argument", sQuote("interaction"),
"should be a point process interaction object (class",
dQuote("interact"),
"), or a hyperframe containing such objects", sep=""))
if(is.null(weights)) {
weights <- rep(1, npat)
} else {
check.nvector(weights, npat, things="rows of data", oneok=TRUE)
if(length(weights) == 1L) weights <- rep(weights, npat)
}
backdoor <- list(...)$backdoor
if(is.null(backdoor) || !is.logical(backdoor))
backdoor <- FALSE
checkvars(formula, data.sumry$col.names,
extra=c("x","y","id","marks"), bname="data")
if(length(formula) < 3)
stop(paste("Argument", sQuote("formula"),
"must have a left hand side"))
Yname <- formula[[2]]
trend <- formula[c(1,3)]
if(!is.name(Yname))
stop("Left hand side of formula should be a single name")
Yname <- paste(Yname)
if(!inherits(trend, "formula"))
stop("Internal error: failed to extract RHS of formula")
allvars <- variablesinformula(trend)
itags <-
if(is.hyperframe(interaction)) names(interaction) else "Interaction"
ninteract <- length(itags)
if(is.null(iformula)) {
if(ninteract > 1)
stop(paste("interaction hyperframe has more than 1 column;",
"you must specify the choice of interaction",
"using argument", sQuote("iformula")))
iused <- TRUE
iformula <- as.formula(paste("~", itags))
} else {
if(length(iformula) > 2)
stop(paste("The interaction formula",
sQuote("iformula"),
"should not have a left hand side"))
permitted <- paste(sQuote("interaction"),
"or permitted name in", sQuote("data"))
checkvars(iformula, itags, extra=c(data.sumry$dfnames, "id"),
bname=permitted)
ivars <- variablesinformula(iformula)
iused <- itags %in% ivars
if(sum(iused) == 0)
stop("No interaction specified in iformula")
allvars <- c(allvars, ivars)
}
if(!is.null(random)) {
if(length(random) > 2)
stop(paste("The random effects formula",
sQuote("random"),
"should not have a left hand side"))
checkvars(random, itags, extra=c(data.sumry$col.names, "x", "y", "id"),
bname="either data or interaction")
allvars <- c(allvars, variablesinformula(random))
}
allvars <- unique(allvars)
data <- cbind.hyperframe(data, id=factor(1:npat))
data.sumry <- summary(data, brief=TRUE)
allvars <- unique(c(allvars, "id"))
Y <- data[, Yname, drop=TRUE]
if(npat == 1) Y <- solist(Y)
Yclass <- data.sumry$classes[Yname]
if(Yclass == "ppp") {
Y <- solapply(Y, quadscheme, ...)
} else if(Yclass == "quad") {
Y <- as.solist(Y)
} else {
stop(paste("Column", dQuote(Yname), "of data",
"does not consist of point patterns (class ppp)",
"nor of quadrature schemes (class quad)"),
call.=FALSE)
}
datanames <- names(data)
used.cov.names <- allvars[allvars %in% datanames]
has.covar <- (length(used.cov.names) > 0)
if(has.covar) {
dfvar <- used.cov.names %in% data.sumry$dfnames
imvar <- data.sumry$types[used.cov.names] == "im"
if(any(nbg <- !(dfvar | imvar)))
stop(paste("Inappropriate format for",
ngettext(sum(nbg), "covariate", "covariates"),
paste(sQuote(used.cov.names[nbg]), collapse=", "),
": should contain image objects or vector/factor"))
covariates.hf <- data[, used.cov.names, drop=FALSE]
has.design <- any(dfvar)
dfvarnames <- used.cov.names[dfvar]
datadf <-
if(has.design)
as.data.frame(covariates.hf, discard=TRUE, warn=FALSE)
else NULL
if(has.design) {
if(any(nbg <- matcolany(is.na(datadf))))
stop(paste("There are NA's in the",
ngettext(sum(nbg), "covariate", "covariates"),
commasep(dQuote(names(datadf)[nbg]))))
}
} else {
has.design <- FALSE
datadf <- NULL
}
if(is.interact(interaction)) {
ninteract <- 1
processes <- list(Interaction=interaction$name)
interaction <- hyperframe(Interaction=interaction, id=1:npat)[,1]
constant <- c(Interaction=TRUE)
} else if(is.hyperframe(interaction)) {
inter.sumry <- summary(interaction)
ninteract <- inter.sumry$nvars
nr <- inter.sumry$ncases
if(nr == 1 && npat > 1) {
interaction <- cbind.hyperframe(id=1:npat, interaction)[,-1]
inter.sumry <- summary(interaction)
} else if(nr != npat)
stop(paste("Number of rows in", sQuote("interaction"),
"=", nr, "!=", npat, "=",
"number of rows in", sQuote("data")))
ok <- (inter.sumry$classes == "interact")
if(!all(ok)) {
nbg <- names(interaction)[!ok]
nn <- sum(!ok)
stop(paste(ngettext(nn, "Column", "Columns"),
paste(sQuote(nbg), collapse=", "),
ngettext(nn, "does", "do"),
"not consist of interaction objects"))
}
ok <- unlist(lapply(as.list(interaction), consistentname))
if(!all(ok)) {
nbg <- names(interaction)[!ok]
stop(paste("Different interactions may not appear in a single column.",
"Violated by",
paste(sQuote(nbg), collapse=", ")))
}
processes <- lapply(as.list(interaction), firstname)
constant <- (inter.sumry$storage == "hyperatom")
if(any(!constant)) {
others <- interaction[,!constant]
constant[!constant] <- sapply(lapply(as.list(others), unique),
length) == 1
}
}
trivial <- unlist(lapply(as.list(interaction), allpoisson))
nondfnames <- datanames[!(datanames %in% data.sumry$dfnames)]
ip <- impliedpresence(itags, iformula, datadf, nondfnames)
if(any(rowSums(ip) > 1))
stop("iformula invokes more than one interaction on a single row")
Vnamelist <- rep(list(character(0)), ninteract)
names(Vnamelist) <- itags
Isoffsetlist <- rep(list(logical(0)), ninteract)
names(Isoffsetlist) <- itags
for(i in 1:npat) {
Yi <- Y[[i]]
covariates <-
if(has.covar) covariates.hf[i, , drop=TRUE, strip=FALSE] else NULL
if(has.design) {
covariates[dfvarnames] <-
lapply(as.list(as.data.frame(covariates[dfvarnames])),
as.im, W=Yi$data$window)
}
prep0 <- bt.frame(Yi, trend, Poisson(), ..., covariates=covariates,
allcovar=TRUE, use.gam=use.gam)
glmdat <- prep0$glmdata
for(j in (1:ninteract)[iused & !trivial]) {
inter <- interaction[i,j,drop=TRUE]
if(!is.null(ss <- inter$selfstart))
interaction[i,j] <- inter <- ss(Yi$data, inter)
prepj <- bt.frame(Yi, ~1, inter, ..., covariates=covariates,
allcovar=TRUE, use.gam=use.gam,
vnamebase=itags[j], vnameprefix=itags[j])
vnameij <- prepj$Vnames
if(i == 1)
Vnamelist[[j]] <- vnameij
else if(!identical(vnameij, Vnamelist[[j]]))
stop("Internal error: Unexpected conflict in glm variable names")
isoffset.ij <- prepj$IsOffset
if(i == 1)
Isoffsetlist[[j]] <- isoffset.ij
else if(!identical(isoffset.ij, Isoffsetlist[[j]]))
stop("Internal error: Unexpected conflict in offset indicators")
glmdatj <- prepj$glmdata
if(nrow(glmdatj) != nrow(glmdat))
stop("Internal error: differing numbers of rows in glm data frame")
iterms.ij <- glmdatj[vnameij]
subset.ij <- glmdatj$.mpl.SUBSET
glmdat <- cbind(glmdat, iterms.ij)
glmdat$.mpl.SUBSET <- glmdat$.mpl.SUBSET & subset.ij
}
if(i == 1) {
moadf <- glmdat
} else {
recognised <- names(glmdat) %in% names(moadf)
if(any(!recognised)) {
newnames <- names(glmdat)[!recognised]
zeroes <- as.data.frame(matrix(0, nrow(moadf), length(newnames)))
names(zeroes) <- newnames
moadf <- cbind(moadf, zeroes)
}
provided <- names(moadf) %in% names(glmdat)
if(any(!provided)) {
absentnames <- names(moadf)[!provided]
zeroes <- as.data.frame(matrix(0, nrow(glmdat), length(absentnames)))
names(zeroes) <- absentnames
glmdat <- cbind(glmdat, zeroes)
}
m.isfac <- sapply(as.list(glmdat), is.factor)
g.isfac <- sapply(as.list(glmdat), is.factor)
if(any(uhoh <- (m.isfac != g.isfac)))
errorInconsistentRows("values (factor and non-factor)",
colnames(moadf)[uhoh])
if(any(m.isfac)) {
m.levels <- lapply(as.list(moadf)[m.isfac], levels)
g.levels <- lapply(as.list(glmdat)[g.isfac], levels)
clash <- !mapply(identical, x=m.levels, y=g.levels)
if(any(clash))
errorInconsistentRows("factor levels",
(colnames(moadf)[m.isfac])[clash])
}
moadf <- rbind(moadf, glmdat)
}
}
moadf$caseweight <- weights[moadf$id]
if(backdoor)
return(moadf)
fmla <- prep0$trendfmla
if(!all(trivial))
fmla <- paste(fmla, "+", as.character(iformula)[[2]])
fmla <- as.formula(fmla)
for(j in (1:ninteract)[iused]) {
vnames <- Vnamelist[[j]]
tag <- itags[j]
isoffset <- Isoffsetlist[[j]]
if(any(isoffset)) {
vnames[isoffset] <- paste("offset(", vnames[isoffset], ")", sep="")
}
if(trivial[j])
moadf[[tag]] <- 0
else if(!identical(vnames, tag)) {
if(length(vnames) == 1)
vn <- paste("~", vnames[1])
else
vn <- paste("~(", paste(vnames, collapse=" + "), ")")
vnr <- as.formula(vn)[[2]]
vnsub <- list(vnr)
names(vnsub) <- tag
fmla <- eval(substitute(substitute(fom, vnsub), list(fom=fmla)))
if(has.random && tag %in% variablesinformula(random))
random <- eval(substitute(substitute(fom, vnsub), list(fom=random)))
}
}
fmla <- as.formula(fmla)
assign("glmmsubset", moadf$.mpl.SUBSET, envir=environment(fmla))
for(nama in colnames(moadf))
assign(nama, moadf[[nama]], envir=environment(fmla))
glmmsubset <- .mpl.SUBSET <- moadf$.mpl.SUBSET
.mpl.W <- moadf$.mpl.W
caseweight <- moadf$caseweight
want.trend <- prep0$info$want.trend
if(want.trend && use.gam) {
fitter <- "gam"
ctrl <- do.call(gam.control, resolve.defaults(gcontrol, list(maxit=50)))
FIT <- gam(fmla, family=quasi(link=log, variance=mu),
weights=.mpl.W * caseweight,
data=moadf, subset=(.mpl.SUBSET=="TRUE"),
control=ctrl)
deviants <- deviance(FIT)
} else if(!is.null(random)) {
fitter <- "glmmPQL"
ctrl <- do.call(lmeControl, resolve.defaults(gcontrol, list(maxIter=50)))
attr(fmla, "ctrl") <- ctrl
fixed <- 42
FIT <- hackglmmPQL(fmla, random=random,
family=quasi(link=log, variance=mu),
weights=.mpl.W * caseweight,
data=moadf, subset=glmmsubset,
control=attr(fixed, "ctrl"),
reltol=reltol.pql)
deviants <- -2 * logLik(FIT)
} else {
fitter <- "glm"
ctrl <- do.call(glm.control, resolve.defaults(gcontrol, list(maxit=50)))
FIT <- glm(fmla, family=quasi(link="log", variance="mu"),
weights=.mpl.W * caseweight,
data=moadf, subset=(.mpl.SUBSET=="TRUE"),
control=ctrl)
deviants <- deviance(FIT)
}
env <- list2env(moadf, parent=sys.frame(sys.nframe()))
environment(FIT$terms) <- env
W <- with(moadf, .mpl.W * caseweight)
SUBSET <- moadf$.mpl.SUBSET
Z <- (moadf$.mpl.Y != 0)
maxlogpl <- -(deviants/2 + sum(log(W[Z & SUBSET])) + sum(Z & SUBSET))
result <- list(Call = list(callstring=callstring, cl=cl),
Info =
list(
has.random=has.random,
has.covar=has.covar,
has.design=has.design,
Yname=Yname,
used.cov.names=used.cov.names,
allvars=allvars,
names.data=names(data),
is.df.column=(data.sumry$storage == "dfcolumn"),
rownames=row.names(data),
correction=prep0$info$correction,
rbord=prep0$info$rbord
),
Fit=
list(
fitter=fitter,
use.gam=use.gam,
fmla=fmla,
FIT=FIT,
moadf=moadf,
Vnamelist=Vnamelist,
Isoffsetlist=Isoffsetlist
),
Inter =
list(
ninteract=ninteract,
interaction=interaction,
iformula=iformula,
iused=iused,
itags=itags,
processes=processes,
trivial=trivial,
constant=constant
),
formula=formula,
trend=trend,
iformula=iformula,
random=random,
npat=npat,
data=data,
Y=Y,
maxlogpl=maxlogpl,
datadf=datadf)
class(result) <- c("mppm", class(result))
return(result)
}
checkvars <- function(f, b, extra=NULL, bname=short.deparse(substitute(b))){
fname <- short.deparse(substitute(f))
fvars <- variablesinformula(f)
bvars <- if(is.character(b)) b else names(b)
bvars <- c(bvars, extra)
nbg <- !(fvars %in% bvars)
if(any(nbg)) {
nn <- sum(nbg)
stop(paste(ngettext(nn, "Variable", "Variables"),
commasep(dQuote(fvars[nbg])),
"in", fname,
ngettext(nn, "is not one of the", "are not"),
"names in", bname))
}
return(NULL)
}
consistentname <- function(x) {
xnames <- unlist(lapply(x, getElement, name="name"))
return(length(unique(xnames)) == 1)
}
firstname <- function(z) { z[[1]]$name }
allpoisson <- function(x) all(sapply(x, is.poisson.interact))
marklevels <- function(x) { levels(marks(x)) }
errorInconsistentRows <- function(what, offending) {
stop(paste("There are inconsistent",
what,
"for the",
ngettext(length(offending), "variable", "variables"),
commasep(sQuote(offending)),
"between different rows of the hyperframe 'data'"),
call.=FALSE)
}
mppm
})
is.mppm <- function(x) {
inherits(x, "mppm")
}
coef.mppm <- function(object, ...) {
coef(object$Fit$FIT)
}
fixef.mppm <- function(object, ...) {
if(object$Fit$fitter == "glmmPQL")
fixef(object$Fit$FIT)
else
coef(object$Fit$FIT)
}
ranef.mppm <- function(object, ...) {
if(object$Fit$fitter == "glmmPQL")
ranef(object$Fit$FIT)
else
as.data.frame(matrix(, nrow=object$npat, ncol=0))
}
print.mppm <- function(x, ...) {
print(summary(x, ..., brief=TRUE))
}
is.poisson.mppm <- function(x) {
trivial <- x$Inter$trivial
iused <- x$Inter$iused
all(trivial[iused])
}
quad.mppm <- function(x) {
as.solist(x$Y)
}
data.mppm <- function(x) {
solapply(x$Y, getElement, name="data")
}
is.marked.mppm <- function(X, ...) {
any(sapply(data.mppm(X), is.marked))
}
is.multitype.mppm <- function(X, ...) {
any(sapply(data.mppm(X), is.multitype))
}
windows.mppm <- function(x) {
solapply(data.mppm(x), Window)
}
logLik.mppm <- function(object, ..., warn=TRUE) {
if(warn && !is.poisson.mppm(object))
warning(paste("log likelihood is not available for non-Poisson model;",
"log-pseudolikelihood returned"))
ll <- object$maxlogpl
attr(ll, "df") <- length(fixef(object))
class(ll) <- "logLik"
return(ll)
}
AIC.mppm <- function(object, ..., k=2, takeuchi=TRUE) {
ll <- logLik(object, warn=FALSE)
pen <- attr(ll, "df")
if(takeuchi && !is.poisson(object)) {
vv <- vcov(object, what="all")
J <- vv$fisher
H <- vv$internals$A1
JiH <- try(solve(H, J), silent=TRUE)
if(!inherits(JiH, "try-error"))
pen <- sum(diag(JiH))
}
return(- 2 * as.numeric(ll) + k * pen)
}
extractAIC.mppm <- function(fit, scale = 0, k = 2, ..., takeuchi = TRUE)
{
edf <- length(coef(fit))
aic <- AIC(fit, k = k, takeuchi = takeuchi)
c(edf, aic)
}
getCall.mppm <- function(x, ...) { x$Call$cl }
terms.mppm <- function(x, ...) { terms(formula(x)) }
nobs.mppm <- function(object, ...) { sum(sapply(data.mppm(object), npoints)) }
simulate.mppm <- function(object, nsim=1, ..., verbose=TRUE) {
subs <- subfits(object)
nr <- length(subs)
sims <- list()
if(verbose) {
splat("Generating simulated realisations of", nr, "models..")
state <- list()
}
for(irow in seq_len(nr)) {
model.i <- subs[[irow]]
dont.complain.about(model.i)
sims[[irow]] <- do.call(simulate,
resolve.defaults(list(object=quote(model.i),
nsim=nsim, drop=FALSE),
list(...),
list(progress=FALSE)))
if(verbose) state <- progressreport(irow, nr, state=state)
}
sim1list <- lapply(sims, "[[", i=1)
h <- hyperframe("Sim1"=sim1list)
if(nsim > 1) {
for(j in 2:nsim) {
simjlist <- lapply(sims, "[[", i=j)
hj <- hyperframe(Sim=simjlist)
names(hj) <- paste0("Sim", j)
h <- cbind(h, hj)
}
}
return(h)
}
model.matrix.mppm <- function(object, ..., keepNA=TRUE, separate=FALSE) {
df <- object$Fit$moadf
FIT <- object$Fit$FIT
environment(FIT) <- list2env(df)
ok <- complete.cases(df) & df$.mpl.SUBSET
nok <- sum(ok)
nfull <- nrow(df)
if(keepNA) {
mm <- model.matrix(FIT, ..., subset=NULL, na.action=NULL)
nr <- nrow(mm)
if(nr != nfull) {
if(nr == nok) {
mmfull <- matrix(NA, nfull, ncol(mm), dimnames=list(NULL, colnames(mm)))
mmfull[ok,] <- mm
mm <- mmfull
} else {
stop(paste("Internal error: model matrix has wrong number of rows:",
nr, "should be", nfull, "or", nok),
call.=FALSE)
}
}
} else {
mm <- model.matrix(FIT, ...)
if(nrow(mm) != nok)
stop("Internal error: model matrix has wrong number of rows", call.=FALSE)
df <- df[ok, , drop=FALSE]
}
ctr <- attr(mm, "contrasts")
if(is.null(ctr) && !is.null(ctr <- FIT[["contrasts"]]))
attr(mm, "contrasts") <- ctr
ass <- attr(mm, "assign")
if(is.null(ass)) {
ass <- FIT[["assign"]]
if(length(ass) == ncol(mm)) {
attr(mm, "assign") <- ass
} else {
ass <- NULL
warning("Unable to determine 'assign' in model.matrix.mppm", call.=FALSE)
}
}
if(separate) {
id <- df$id
mm <- split.data.frame(mm, id)
if(!is.null(ass))
mm <- lapply(mm, "attr<-", which="assign", value=ass)
if(!is.null(ctr))
mm <- lapply(mm, "attr<-", which="contrasts", value=ctr)
}
return(mm)
} |
run.control <- function(check_tpl=TRUE,
write_files=TRUE,
checkparam=c("stop","warn","write","ignore"),
checkdata=c("stop","warn","write","ignore"),
compile=TRUE,
run=TRUE,
read_files=TRUE,
clean_files="all") {
checkparam <- match.arg(checkparam)
checkdata <- match.arg(checkdata)
if (is.logical(clean_files)) {
if (clean_files) clean_files <- "all"
else clean_files <- "none"
}
c(check_tpl=check_tpl,checkparam=checkparam,checkdata=checkdata,
write_files=write_files,compile=compile,run=run,read_files=read_files,
clean_files=clean_files)
} |
test_that("ISR() obtains the estimators of the PCA-based missing data with HC", {
library(MASS)
set.seed(88)
etatol=0.9
n=100;p=10;per=0.1
mu=as.matrix(runif(p,0,10))
sigma=as.matrix(runif(p,0,1))
ro=as.matrix(c(runif(round(p/2),-1,-sqrt(0.75)),runif(p-round(p/2),sqrt(0.75),1)))
RO=ro%*%t(ro);diag(RO)=1
Sigma=sigma%*%t(sigma)*RO
X0=data=mvrnorm(n,mu,Sigma)
m=round(per*n*p,digits=0)
mr=sample(1:(n*p),m,replace=FALSE)
X0[mr]=NA;data0=X0
n=nrow(X0);p=ncol(X0)
mr=which(is.na(X0)==TRUE)
m=nrow(as.matrix(mr))
cm0=colMeans(X0,na.rm=T)
ina=as.matrix(mr%%n)
jna=as.matrix(floor((mr+n-1)/n))
data0[is.na(data0)]=cm0[ceiling(which(is.na(X0))/n)]
X=as.matrix(data0)
Z=scale(X,center=TRUE,scale=FALSE)
niter=0;d=1;tol=1e-5;nb=10
while((d>=tol) & (niter<=nb)){
niter=niter+1
Zold=Z
lambda=svd(cor(Z))$d
l=lambda/sum(lambda)
J=rep(l,times=p);dim(J)=c(p,p)
upper.tri(J,diag=T);J[lower.tri(J)]=0
eta=matrix(colSums(J),nrow = 1,ncol = p,byrow = FALSE)
k=which(eta>=etatol)[1]
Ak=matrix(svd(Z)$v[,1:k],p,k)
Lambdak=diag(sqrt(lambda[1:k]),k,k)
for( i in 1:n){
M=is.na(X0[i,])
job=which(M==FALSE);jna=which(M==TRUE)
piob=nrow(as.matrix(job));pina=nrow(as.matrix(jna))
while((piob>0)&(pina>0)){
Qi=matrix(0,p,p)
for( u in 1:piob){
Qi[job[u],u]=1
}
for( v in 1:pina){
Qi[jna[v],v+piob]=1
}
zQi=Z[i,]%*%Qi
ZQi=Z%*%Qi
AQi=t(t(Ak)%*%Qi)
ziob=matrix(zQi[,1:piob],1,piob)
zina=matrix(zQi[,piob+(1:pina)],1,pina)
Ziob=matrix(ZQi[,1:piob],n,piob,byrow=FALSE)
Zina=matrix(ZQi[,piob+(1:pina)],n,pina,byrow=FALSE)
Aiob=matrix(AQi[1:piob,],piob,k,byrow=FALSE)
Aina=matrix(AQi[piob+(1:pina),],pina,k,byrow=FALSE)
Ti=Ziob%*%Aiob;Ti
betaihat=ginv(t(Ti)%*%Ti)%*%t(Ti)%*%Zina;betaihat
zinahat=ziob%*%Aiob%*%betaihat;zinahat
ZQi[i,piob+(1:pina)]=zinahat
Z=Zi=ZQi%*%t(Qi)
pina=0
}
}
ZISR=Znew=Z
d=sqrt(sum(diag((t(Zold-Znew)%*%(Zold-Znew)))))
}
XISR=Xnew=Znew+matrix(rep(1,n*p),ncol=p)%*%diag(cm0)
}) |
get.my.pPropType <- function(type){
if(!any(type[1] %in% .CF.CT$type.p)){
stop("type is not found.")
}
ret <- eval(parse(text = paste("my.pPropType.", type[1], sep = "")))
assign("my.pPropType", ret, envir = .cubfitsEnv)
ret
}
my.pPropType.lognormal_fix <- function(n.G, log.phi.Obs, phi.Curr,
p.Curr, hp.param){
nu.Phi.Curr <- p.Curr[2]
sigma.Phi.Curr <- p.Curr[3]
log.phi.Obs.mean <- hp.param$log.phi.Obs.mean
log.phi.Curr <- log(phi.Curr)
if(.CF.CONF$estimate.Phi.noise)
{
sigmaW.Curr <-
sqrt(1 / rgamma(1, shape = (n.G - 1) / 2,
rate = sum((log.phi.Obs - log.phi.Curr)^2) / 2))
}else{
sigmaW.Curr <- p.Curr[1]
}
sigma.Phi.Curr <-
sqrt(1 / rgamma(1, shape = (n.G - 1) / 2,
rate = sum((log.phi.Curr - log.phi.Obs.mean)^2) / 2))
nu.Phi.Curr <- log.phi.Obs.mean + rnorm(1) * sigma.Phi.Curr / sqrt(n.G)
my.update.acceptance("p", 1)
my.update.adaptive("p", 1)
ret <- c(sigmaW.Curr, nu.Phi.Curr, sigma.Phi.Curr)
ret
} |
santaR_auto_fit <- function(inputData,ind,time,group=NA,df,ncores=0,CBand=TRUE,pval.dist=TRUE,pval.fit=FALSE,nBoot=1000,alpha=0.05,nPerm=1000,nStep=5000,alphaPval=0.05,forceParIndTimeMat=FALSE) {
if( is.factor(ind) ){
message("Error: Check input, 'ind' should not be a factor")
stop("Check input, 'ind' should not be a factor")
}
if( is.factor(time) ){
message("Error: Check input, 'time' should not be a factor")
stop("Check input, 'time' should not be a factor")
}
if (any(!is.na(group))) {
grouping <- get_grouping( ind=ind, group=group )
} else {
grouping <- NA
pval.dist <- FALSE
pval.fit <- FALSE
}
if( ncores!=0 | forceParIndTimeMat ) {
cl <- parallel::makeCluster( ncores )
doParallel::registerDoParallel( cl )
}
tot.time <- Sys.time()
ttime <- Sys.time()
if( forceParIndTimeMat ) {
res.in <- foreach::foreach( x=iterators::iter(inputData, by='col'), .export=c('get_ind_time_matrix'), .inorder=TRUE) %dopar% get_ind_time_matrix(x, ind, time)
names(res.in) <- colnames(inputData)
} else {
res.in <- apply( inputData, 2, function(x) get_ind_time_matrix( Yi=as.numeric(x), ind=ind, time=time))
}
ttime2 <- Sys.time()
message('Input data generated: ',round(as.double(difftime(ttime2,ttime)),2),' ',units( difftime(ttime2,ttime)))
ttime <- Sys.time()
if( ncores!=0 ) {
res.spline <- foreach::foreach( x=res.in, .export=c('santaR_fit'), .inorder=TRUE) %dopar% santaR_fit( x, df=df, grouping=grouping, verbose=FALSE)
names(res.spline) <- names(res.in)
} else {
res.spline <- lapply(res.in, function(x) santaR_fit( x, df=df, grouping=grouping, verbose=FALSE))
}
ttime2 <- Sys.time()
message('Spline fitted: ',round(as.double(difftime(ttime2,ttime)),2),' ',units( difftime(ttime2,ttime)))
if( CBand ) {
ttime <- Sys.time()
if( ncores!=0 ) {
res.spline <- foreach::foreach( x=res.spline, .export=c('santaR_CBand'), .inorder=TRUE) %dopar% santaR_CBand(x, nBoot=nBoot, alpha=alpha)
names(res.spline) <- names(res.in)
} else {
res.spline <- lapply(res.spline, function(x) santaR_CBand(x, nBoot=nBoot, alpha=alpha))
}
ttime2 <- Sys.time()
message('ConfBands done: ',round(as.double(difftime(ttime2,ttime)),2),' ',units( difftime(ttime2,ttime)))
}
if( pval.dist ) {
ttime <- Sys.time()
if( ncores!=0 ) {
res.spline <- foreach::foreach( x=res.spline, .export=c('santaR_pvalue_dist'), .inorder=TRUE) %dopar% santaR_pvalue_dist(x, nPerm=nPerm, nStep=nStep, alpha=alphaPval)
names(res.spline) <- names(res.in)
} else {
res.spline <- lapply(res.spline, function(x) santaR_pvalue_dist(x, nPerm=nPerm, nStep=nStep, alpha=alphaPval))
}
ttime2 <- Sys.time()
message('p-val dist done: ',round(as.double(difftime(ttime2,ttime)),2),' ',units( difftime(ttime2,ttime)))
}
if( pval.fit ) {
ttime <- Sys.time()
if( ncores!=0 ) {
res.spline <- foreach::foreach( x=res.spline, .export=c('santaR_pvalue_fit'), .inorder=TRUE) %dopar% santaR_pvalue_fit(x, nPerm=nPerm, alpha=alphaPval)
names(res.spline) <- names(res.in)
} else {
res.spline <- lapply(res.spline, function(x) santaR_pvalue_fit(x, nPerm=nPerm, alpha=alphaPval))
}
ttime2 <- Sys.time()
message('p-val fit done: ',round(as.double(difftime(ttime2,ttime)),2),' ',units( difftime(ttime2,ttime)))
}
tot.time2 <- Sys.time()
message('total time: ',round(as.double(difftime(tot.time2,tot.time)),2),' ',units( difftime(tot.time2,tot.time)))
if( ncores!=0 | forceParIndTimeMat ) {
parallel::stopCluster( cl )
}
return( res.spline )
} |
version_aw <- function(){
"v1beta"
}
ga_data <- function(
propertyId,
metrics,
date_range = NULL,
dimensions = NULL,
dim_filters = NULL,
dimensionDelimiter = "/",
met_filters = NULL,
orderBys = NULL,
limit = 100,
page_size = 100000L,
realtime = FALSE,
raw_json = NULL) {
if(!is.null(raw_json)){
if(is.list(raw_json)){
raw_json_txt <- jsonlite::toJSON(raw_json, auto_unbox = TRUE)
} else {
raw_json_txt <- raw_json
}
myMessage("Making API request with raw JSON: ", raw_json_txt, level = 3)
if(realtime) return(ga_aw_realtime(propertyId, raw_json))
return(do_runreport_req(propertyId, raw_json))
}
assert_that(is.integer(page_size),
page_size <= 100000)
dimensionFilter <- as_filterExpression(dim_filters)
metricFilter <- as_filterExpression(met_filters)
metricAggregations <- c("TOTAL","MAXIMUM","MINIMUM")
dims <- gaw_dimension(dimensions, delimiter = dimensionDelimiter)
mets <- gaw_metric(metrics)
if(realtime){
brrr <- RunRealtimeReport(
dimensions = dims,
metrics = mets,
limit = limit,
dimensionFilter = dimensionFilter,
metricFilter = metricFilter,
metricAggregations = metricAggregations,
orderBys = orderBys,
returnPropertyQuota = TRUE
)
myMessage("Realtime Report Request", level = 3)
res <- ga_aw_realtime(propertyId, brrr)
return(res)
}
dates <- gaw_dates(date_range)
brrr <- RunReportRequest(
metrics = mets,
dimensions = dims,
dateRanges = dates,
limit = limit,
dimensionFilter = dimensionFilter,
metricFilter = metricFilter,
metricAggregations = metricAggregations,
orderBys = orderBys,
keepEmptyRows = TRUE,
returnPropertyQuota = TRUE
)
ga_aw_report(propertyId, brrr, page_size)
}
ga_aw_realtime <- function(propertyId, requestObj){
url <-
sprintf("https://analyticsdata.googleapis.com/%s/properties/%s:runRealtimeReport",
version_aw(), propertyId)
f <- gar_api_generator(url, "POST",
data_parse_function = parse_realtime)
o <- f(the_body = requestObj)
o
}
ga_aw_report <- function(propertyId, requestObj, page_size){
request_limit <- requestObj$limit
if(request_limit == -1 || page_size < request_limit){
requestObj$limit <- page_size
}
o <- do_runreport_req(propertyId, requestObj)
rowCount <- attr(o, "rowCount")
to_fetch <- min(rowCount, request_limit)
if(request_limit == -1){
to_fetch <- rowCount
}
if(to_fetch < page_size) return(o)
pages <- (to_fetch %/% page_size)
offsets <- seq(from = page_size, by = page_size, length.out = pages)
o_pages <- lapply(offsets, function(x){
myMessage("Paging API from offset [", x,"]", level = 3)
remaining_rows <- to_fetch - x
if(remaining_rows < page_size){
requestObj$limit <- remaining_rows
}
requestObj$offset <- x
do_runreport_req(propertyId, requestObj)
})
ooo <- c(list(o), o_pages)
bind_rows(ooo)
}
do_runreport_req <- function(property, requestObj){
url <-
sprintf("https://analyticsdata.googleapis.com/%s/properties/%s:runReport",
version_aw(), property)
f <- gar_api_generator(url, "POST",
data_parse_function = parse_runreport)
f(the_body = requestObj)
}
parse_realtime <- function(x){
if(no_rows(x)) return(data.frame())
dim_names <- x$dimensionHeaders$name
met_names <- x$metricHeaders$name
parse_rows(x, dim_names, met_names)
}
parse_runreport <- function(o){
if(no_rows(o)) return(data.frame())
dim_names <- o$dimensionHeaders$name
met_names <- o$metricHeaders$name
parse_rows(o, dim_names, met_names)
}
no_rows <- function(o){
if(is.null(o$rows)){
myMessage("No data found", level = 3)
return(TRUE)
}
FALSE
}
row_types <- function(res, met_names){
if("date" %in% names(res)){
res$date <- as.Date(res$date, format = "%Y%m%d")
}
if("firstTouchDate" %in% names(res)){
res$firstTouchDate <- as.Date(res$firstTouchDate, format = "%Y%m%d")
}
res %>% mutate(across(met_names, as.numeric))
}
get_field_values <- function(x, name){
o <- lapply(x, function(y) setNames(y$value, name))
bind_rows(o)
}
my_bind_cols <- function(x, y){
if(nrow(x) == 0){
return(y)
}
if(nrow(y) == 0){
return(x)
}
bind_cols(x, y)
}
parse_aggregations <- function(agg, dim_names, met_names){
if(is.null(agg)) return(NULL)
dds <- get_field_values(agg$dimensionValues, name = dim_names)
mms <- get_field_values(agg$metricValues, name = met_names)
res <- my_bind_cols(dds, mms)
res <- row_types(res, met_names)
res
}
parse_rows <- function(o, dim_names, met_names){
quota_messages(o)
dds <- get_field_values(o$rows$dimensionValues, name = dim_names)
mms <- get_field_values(o$rows$metricValues, name = met_names)
res <- my_bind_cols(dds, mms)
res <- row_types(res, met_names = met_names)
dl <- attr(res, "metadata")[["dataLossFromOtherRow"]]
if(!is.null(dl) && dl){
myMessage("Warning: some buckets of dimension combinations are rolled into '(other)' row. This can happen for high cardinality reports.", level = 3)
}
if(!is.null(o$metadata) && length(o$metadata) > 1){
attr(res, "metadata") <- o$metadata
}
attr(res, "metricAggregations") <- list(
totals = parse_aggregations(o$totals, dim_names, met_names),
maximums = parse_aggregations(o$maximums, dim_names, met_names),
minimums = parse_aggregations(o$minimums, dim_names, met_names)
)
myMessage("Downloaded [",nrow(res), "] of total [", o$rowCount,"] rows",
level = 3)
attr(res, "rowCount") <- o$rowCount
if(!is.null(res[["dateRange"]]) &&
all(unique(res$dateRange) == "date_range_0")){
res$dateRange <- NULL
}
res
}
ga_data_aggregations <- function(df,
type = c("all","totals",
"maximums","minimums",
"count")){
type <- match.arg(type)
if(is.null(attr(df, "metricAggregations"))){
stop("No aggregations found. Is the data.frame from ga_data()?",
call. = FALSE)
}
ma <- attr(df, "metricAggregations")
if(type == "all"){
return(ma)
}
ma[[type]]
} |
OptSig.anova <-
function(K=NULL,n=NULL,f=NULL,p=0.5,k=1,Figure=TRUE){
alphavec=seq(0.00001,1,0.00001)
powervec=pwr.anova.test(k=K,n=n,f=f,sig.level=alphavec,power=NULL)$power
betavec=1-powervec
M=E.loss(alphavec,betavec,p,k,Figure)
alphas=M$alpha.opt
return(list(alpha.opt = alphas, beta.opt = M$beta.opt))}
|
CNOT4_02 <- function(a){
cnot4_02 = TensorProd(CNOT3_02(diag(8)),diag(2))
result = cnot4_02 %*% a
result
} |
options( width=150, max.print=250 )
library(ggplot2)
R <- readRDS("LRDS/salbmResults0.rds")
Narm <- R$Narm
K <- R$K
alphas <- R$alphas
mina <- min(alphas)
maxa <- max(alphas)
M1RL <- as.data.frame(R$Main1RL )
M1wts <- as.data.frame(R$Main1wts)
M2RL <- as.data.frame(R$Main2RL )
M2wts <- as.data.frame(R$Main2wts)
R1 <- M1RL[ M1RL[,"type"]==2, c("alpha","k","type","Est")]
R2 <- M2RL[ M2RL[,"type"]==2, c("alpha","k","type","Est")]
k <- K
b <- R1[ R1[,"k"] == k & R1[,"alpha"] == mina, "Est"]
loc1 <- c( mina + 2, b )
b <- R2[ R2[,"k"] == k & R2[,"alpha"] == mina, "Est"]
loc2 <- c( mina + 2, b )
loc <- rbind(loc1,loc2)
loc <- as.data.frame(loc)
names(loc) <- c("alpha","Est")
loc[,"txt"] <- c("trt = 1", "trt = 2")
rownames(loc) <- NULL
nplt <- function( dat, name, ylim = c(0,1), h=4.0, w=6, ylab,
col = c("
alphas <- dat[,"alpha"]
dat[,"colk"] <- as.character( dat[,"trt"] )
theme_set(theme_minimal())
pdf(file=name, height=h, width=w)
h <- ggplot( dat, aes(x=alpha,y=Est,group=colk,color=colk)) +
geom_line(size=1.2,color="
geom_point(size=2.0,alpha=0.7) +
geom_text( data = loc, aes(x=alpha,y=Est,group=txt,label=txt),
hjust=0, vjust=2, color="
scale_x_continuous( name = expression(alpha),breaks=seq(mina,maxa,by=5)) +
scale_y_continuous( name = eval(parse(text=ylab))) +
scale_color_manual( values= col ) +
coord_cartesian(xlim=c(mina,maxa), ylim = ylim) +
theme(legend.position="none",
axis.text.x=element_text(size=10),
axis.text.y=element_text(size=10),
axis.title.x=element_text(size=11,margin=margin(10,0,3,0)),
axis.title.y=element_text(size=11,margin=margin(0,10,0,3)))
print(h)
dev.off()
return(invisible())
}
ylab <- "expression('E['~Sigma~Y[k]~'|'~alpha~']')";
col <- c("
R1[,"trt"] <- 1
R1 <- R1[order(R1[,"k"],R1[,"alpha"]),]
rownames(R1) <- NULL
R2[,"trt"] <- 2
R2 <- R2[order(R2[,"k"],R2[,"alpha"]),]
rownames(R2) <- NULL
dta <- rbind(R1,R2)
dta <- dta[ dta[,"k"] == K, ]
nplt( dat = dta , name = "Plots/BoundsPlotS.pdf", ylim = c(2.0,6.0), ylab = ylab, col = col ) |
binary_row <- function(
list_obj
, row_var
, col_var=NULL
, newdata=FALSE
, rowlabel=NULL
, summary=NULL
, reference=NULL
, compact=TRUE
, missing=NULL
, overall=NULL
, comparison=NULL
, digits=2
, indent=5
){
if (is.null(summary)){
summary <- list_obj[["default_binary_summary"]]
}
if (is.null(missing)){
missing <- list_obj[["missing"]]
}
if (is.null(overall)){
overall <- list_obj[["overall"]]
}
if (is.null(comparison)){
comparison <- list_obj[["comparison"]]
if (comparison == TRUE){
comparison <- binary_diff
}
}
if (is.null(col_var)){
col_var <- list_obj[["col_var"]]
num_col <- list_obj[['num_col']]
} else {
if (class(newdata) == 'logical'){
num_col <- list_obj[['data']][col_var] %>%
filter(!is.na(list_obj[['data']][col_var])) %>%
unique() %>%
nrow()
}
}
if (class(newdata) == 'logical'){
data <- list_obj[['data']][,c(row_var, col_var)]
} else {
data <- newdata[,c(row_var, col_var)]
if (!is.null(col_var)){
num_col <- data[col_var] %>%
filter(!is.na(data[col_var])) %>%
unique() %>%
nrow()
} else {
num_col <- 1
}
}
if (is.null(rowlabel)){
if (is.null(dim(data))) {
if (!is.null(attr(data, "label"))){
rowlabel <- attr(data, "label")
} else {
rowlabel <- row_var
}
} else {
if (!is.null(attr(data[,1], "label"))) {
rowlabel <- attr(data[,1], "label")
} else {
rowlabel <- row_var
}
}
}
if (!is.null(col_var)){
data[,2] <- as.factor(data[,2])
}
if (is.null(reference)){
if (is.null(col_var)){
reference = sort(unique(data))[1]
} else {
reference = sort(unique(data[,1]))[1]
}
}
binary_out <- summary(data,
reference = reference,
rowlabel = rowlabel,
compact = compact,
missing = missing,
digits = digits)
if (overall == FALSE){
binary_out <- binary_out[,-ncol(binary_out)]
}
if (class(comparison) == "function" & num_col > 1){
comp <- comparison(data, num_col, reference, digits)
for (i in 1:ncol(comp)){
binary_out$compare <- ""
binary_out$compare[1] <- comp[i]
binary_out$compare <- as.character(binary_out$compare)
colnames(binary_out)[ncol(binary_out)] <- colnames(comp)[i]
}
colnames(binary_out)[ncol(binary_out)] <- "Compare: All Groups"
}
idt <- paste(rep(" ", indent), collapse="")
binary_out[,1] <- ifelse(binary_out[,2]=="" & binary_out[,1] != "", paste0(idt, binary_out[,1]), binary_out[,1])
list_obj[[length(list_obj) + 1]] <- binary_out
return(list_obj)
} |
c_list_of <- function(x) {
if (length(x) == 0) {
return(attr(x, "ptype"))
}
vec_c(!!!x, .name_spec = zap())
}
unnest_col <- function(x, col, ptype) {
col_data <- x[[col]]
out <- x[rep(seq_len(nrow(x)), lengths(col_data)), ]
if (length(col_data) > 0) {
col_data <- unlist(col_data, recursive = FALSE, use.names = FALSE)
if (!identical(col_data[0], ptype)) {
abort(paste0(
"Internal: unnest_col() ptype mismatch, must be ",
class(ptype)[[1]],
", not ",
class(col_data[0])[[1]]
))
}
} else {
col_data <- ptype
}
out[[col]] <- col_data
out
}
unnest_list_of_df <- function(x, col) {
col_data <- x[[col]]
stopifnot(is_list_of(col_data))
out <- x[rep(seq_len(nrow(x)), map_int(col_data, vec_size)), setdiff(names(x), col)]
out <- vec_cbind(out, c_list_of(col_data))
out
}
unnest_df <- function(x, col, ptype) {
col_data <- x[[col]]
out <- x[rep(seq_len(nrow(x)), map_int(col_data, vec_size)), setdiff(names(x), col)]
if (length(col_data) > 0) {
col_data <- vec_rbind(!!!col_data)
if (!identical(col_data[0, ], ptype)) {
abort(paste0(
"Internal: unnest_df() ptype mismatch."
))
}
} else {
col_data <- ptype
}
out <- vec_cbind(out, col_data)
out
} |
SIRVector <- function(pars = NULL, init = NULL, time = NULL, ...) {
if (is.null(pars)) {
stop("undefined 'pars'")
}
if (is.null(pars)) {
stop("undefined 'inits'")
}
if (is.null(pars)) {
stop("undefined 'time'")
}
SolveSIRMosVecfu <- function(pars = NULL, init = NULL, time = NULL) {
SolveSIRMosVec.fu <- function(time, init, pars) {
with(as.list(c(init, pars)), {
dXH = vH - XH * r * (betaHM * YM) - muH * XH
dXM = vM - XM * r * (betaMH * YH) - muM * XM
dYH = XH * r * (betaHM * YM) - gamma * YH - muH * YH
dYM = XM * r * (betaMH * YH) - muM * YM
list(c(dXH, dXM, dYH, dYM))
})
}
init <- c(init['XH'], init['XM'], init['YH'], init['YM'])
output <- ode(times = time,
func = SolveSIRMosVec.fu,
y = init, parms = pars, ...)
return(output)
}
output <- SolveSIRMosVecfu(pars = pars, init = init, time = time)
return(list(model = SolveSIRMosVecfu,
pars = pars,
init = init,
time = time,
results = as.data.frame(output)))
} |
Tau2Rho <-function(family,theta){
N=100000
switch(family,
"gaussian" = {
u = copula::rCopula(N,copula::normalCopula(theta[1], dim = 2))
},
"t" = {
u = copula::rCopula(N,copula::tCopula(theta[1], df=theta[2], dim = 2))
},
"clayton" = {
u = copula::rCopula(N,copula::claytonCopula(theta[1], dim = 2))
},
"frank" = {
u = copula::rCopula(N,copula::frankCopula(theta[1], dim = 2))
},
"gumbel" = {
u = copula::rCopula(N,copula::gumbelCopula(theta[1], dim = 2))
}
)
rho <- stats::cor(u, method = "spearman")[1,2]
return(rho)
} |
test.g_plus <- function() {
dataPath <- file.path(path.package(package="clusterCrit"),"unitTests","data","testsInternal_400_4.Rdata")
load(file=dataPath, envir=.GlobalEnv)
idx <- intCriteria(traj_400_4, part_400_4[[4]], c("G_plus"))
cat(paste("\nFound idx =",idx))
val <- 2.38694956623705e-08
cat(paste("\nShould be =",val,"\n"))
checkEqualsNumeric(idx[[1]],val)
} |
setGeneric("readWorksheet",
function(object, sheet, startRow = 0, startCol = 0, endRow = 0, endCol = 0,
autofitRow = TRUE, autofitCol = TRUE, region = NULL,
header = TRUE, rownames = NULL, colTypes = character(0), forceConversion = FALSE,
dateTimeFormat = getOption("XLConnect.dateTimeFormat"), check.names = TRUE,
useCachedValues = FALSE, keep = NULL, drop = NULL, simplify = FALSE,
readStrategy = "default")
standardGeneric("readWorksheet"))
setMethod("readWorksheet",
signature(object = "workbook", sheet = "numeric"),
function(object, sheet, startRow = 0, startCol = 0, endRow = 0, endCol = 0,
autofitRow = TRUE, autofitCol = TRUE, region = NULL, header = TRUE,
rownames = NULL, colTypes = character(0), forceConversion = FALSE,
dateTimeFormat = getOption("XLConnect.dateTimeFormat"), check.names = TRUE,
useCachedValues = FALSE, keep = NULL, drop = NULL, simplify = FALSE,
readStrategy = "default") {
if(!is.null(region)) {
idx = rg2idx(region)
startRow = idx[,1]
startCol = idx[,2]
endRow = idx[,3]
endCol = idx[,4]
}
boundingBoxDim = getBoundingBox(object, sheet, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol,
autofitRow = autofitRow, autofitCol = autofitCol)
startRow = boundingBoxDim[1, ]
startCol = boundingBoxDim[2, ]
endRow = boundingBoxDim[3, ]
endCol = boundingBoxDim[4, ]
numcols = ifelse(endCol == 0, 0, endCol - startCol + 1)
subset <- getColSubset(object, sheet, startRow, endRow, startCol, endCol, header, numcols, keep, drop)
dataFrame <- xlcCall(object, "readWorksheet", as.integer(sheet - 1), as.integer(startRow - 1),
as.integer(startCol - 1), as.integer(endRow - 1), as.integer(endCol - 1), header,
.jarray(classToXlcType(colTypes)), forceConversion, dateTimeFormat, useCachedValues, subset,
readStrategy, .simplify = FALSE)
dataFrame = lapply(dataFrame, dataframeFromJava, check.names = check.names)
dataFrame = extractRownames(dataFrame, rownames)
dataFrame =
mapply(df = dataFrame, simplify = rep(simplify, length.out = length(dataFrame)),
FUN = function(df, simplify) {
if(simplify) unlist(df, use.names = FALSE)
else df
}, SIMPLIFY = FALSE
)
if(length(dataFrame) == 1) dataFrame[[1]]
else dataFrame
}
)
setMethod("readWorksheet",
signature(object = "workbook", sheet = "character"),
function(object, sheet, startRow = 0, startCol = 0, endRow = 0, endCol = 0,
autofitRow = TRUE, autofitCol = TRUE, region = NULL, header = TRUE,
rownames = NULL, colTypes = character(0), forceConversion = FALSE,
dateTimeFormat = getOption("XLConnect.dateTimeFormat"), check.names = TRUE,
useCachedValues = TRUE, keep = NULL, drop = NULL, simplify = FALSE,
readStrategy = "default") {
sheetNames = sheet
sheet = getSheetPos(object, sheet)
dataFrame = callGeneric()
if(length(sheet) > 1)
names(dataFrame) = sheetNames
dataFrame
}
) |
library(hamcrest)
Sys.setlocale('LC_COLLATE', 'C')
is.logical.foo <- function(...) 41L
as.vector.foo <- function(...) 99
as.vector.bar <- function(...) 98
Math.bar <- function(...) 44
Summary.bar <- function(...) 45
Ops.bar <- function(...) 46
test.is.logical.1 <- function() assertThat(is.logical(NULL), identicalTo(FALSE))
test.is.logical.2 <- function() assertThat(is.logical(logical(0)), identicalTo(TRUE))
test.is.logical.3 <- function() assertThat(is.logical(c(TRUE, TRUE, FALSE, FALSE, TRUE)), identicalTo(TRUE))
test.is.logical.4 <- function() assertThat(is.logical(structure(c(TRUE, FALSE), .Names = c("a", ""))), identicalTo(TRUE))
test.is.logical.5 <- function() assertThat(is.logical(c(TRUE, FALSE, NA)), identicalTo(TRUE))
test.is.logical.6 <- function() assertThat(is.logical(integer(0)), identicalTo(FALSE))
test.is.logical.7 <- function() assertThat(is.logical(structure(integer(0), .Names = character(0))), identicalTo(FALSE))
test.is.logical.8 <- function() assertThat(is.logical(1:3), identicalTo(FALSE))
test.is.logical.9 <- function() assertThat(is.logical(c(1L, NA, 4L, NA, 999L)), identicalTo(FALSE))
test.is.logical.10 <- function() assertThat(is.logical(c(1L, 2L, 1073741824L, 1073741824L)), identicalTo(FALSE))
test.is.logical.11 <- function() assertThat(is.logical(numeric(0)), identicalTo(FALSE))
test.is.logical.12 <- function() assertThat(is.logical(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708)), identicalTo(FALSE))
test.is.logical.13 <- function() assertThat(is.logical(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708)), identicalTo(FALSE))
test.is.logical.14 <- function() assertThat(is.logical(structure(1:2, .Names = c("a", "b"))), identicalTo(FALSE))
test.is.logical.15 <- function() assertThat(is.logical(structure(c(1.5, 2.5), .Names = c("a", "b"))), identicalTo(FALSE))
test.is.logical.16 <- function() assertThat(is.logical(c(1.5, 1.51, 0, 1.49, -30)), identicalTo(FALSE))
test.is.logical.17 <- function() assertThat(is.logical(c(1.5, 1.51, 0, 1.49, -30, NA)), identicalTo(FALSE))
test.is.logical.18 <- function() assertThat(is.logical(c(1.5, 1.51, 0, 1.49, -30, NaN)), identicalTo(FALSE))
test.is.logical.19 <- function() assertThat(is.logical(c(1.5, 1.51, 0, 1.49, -30, Inf)), identicalTo(FALSE))
test.is.logical.20 <- function() assertThat(is.logical(c(1.5, 1.51, 0, 1.49, -30, -Inf)), identicalTo(FALSE))
test.is.logical.21 <- function() assertThat(is.logical(character(0)), identicalTo(FALSE))
test.is.logical.22 <- function() assertThat(is.logical(c("4.1", "blahh", "99.9", "-413", NA)), identicalTo(FALSE))
test.is.logical.23 <- function() assertThat(is.logical(complex(0)), identicalTo(FALSE))
test.is.logical.24 <- function() assertThat(is.logical(list(1, 2, 3)), identicalTo(FALSE))
test.is.logical.25 <- function() assertThat(is.logical(list(1, 2, NULL)), identicalTo(FALSE))
test.is.logical.26 <- function() assertThat(is.logical(list(1L, 2L, 3L)), identicalTo(FALSE))
test.is.logical.27 <- function() assertThat(is.logical(list(1L, 2L, NULL)), identicalTo(FALSE))
test.is.logical.28 <- function() assertThat(is.logical(list(1, 2, list(3, 4))), identicalTo(FALSE))
test.is.logical.29 <- function() assertThat(is.logical(list(1, 2, numeric(0))), identicalTo(FALSE))
test.is.logical.30 <- function() assertThat(is.logical(list(3, "a", structure(list("b", list(TRUE, "c")), .Names = c("", "z")))), identicalTo(FALSE))
test.is.logical.31 <- function() assertThat(is.logical(structure(list(1, 2, 3), .Names = c(NA, "", "b"))), identicalTo(FALSE))
test.is.logical.32 <- function() assertThat(is.logical(pairlist(41, "a", 21L)), identicalTo(FALSE))
test.is.logical.33 <- function() assertThat(is.logical(structure(pairlist(a = 41, 42))), identicalTo(FALSE))
test.is.logical.34 <- function() assertThat(is.logical(structure(pairlist(a = 41, NULL))), identicalTo(FALSE))
test.is.logical.35 <- function() assertThat(is.logical(structure(1:12, .Dim = 3:4)), identicalTo(FALSE))
test.is.logical.36 <- function() assertThat(is.logical(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( c("a", "b", "c"), c("d", "e", "f", "g")), .Names = c("x", "y")))), identicalTo(FALSE))
test.is.logical.37 <- function() assertThat(is.logical(structure(1:3, rando.attrib = 941L)), identicalTo(FALSE))
test.is.logical.38 <- function() assertThat(is.logical(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c")))), identicalTo(FALSE))
test.is.logical.39 <- function() assertThat(is.logical(structure(1:3, .Dim = 3L, .Dimnames = structure(list( c("a", "b", "c")), .Names = "z"))), identicalTo(FALSE))
test.is.logical.40 <- function() assertThat(is.logical(structure(list("foo"), class = "foo")), identicalTo(FALSE))
test.is.logical.41 <- function() assertThat(is.logical(structure(list("bar"), class = "foo")), identicalTo(FALSE))
test.is.logical.42 <- function() assertThat(is.logical(quote(xyz)), identicalTo(FALSE))
test.is.logical.43 <- function() assertThat(is.logical(quote(sin(3.14))), identicalTo(FALSE))
test.is.logical.44 <- function() assertThat(is.logical("NaN"), identicalTo(FALSE))
test.is.logical.45 <- function() assertThat(is.logical("NABOOM!"), identicalTo(FALSE))
test.is.logical.46 <- function() assertThat(is.logical("NaNaNabooboo"), identicalTo(FALSE))
test.is.logical.47 <- function() assertThat(is.logical("-Inf"), identicalTo(FALSE))
test.is.logical.48 <- function() assertThat(is.logical("+Infinity"), identicalTo(FALSE))
test.is.logical.49 <- function() assertThat(is.logical("Infinity and beyond!"), identicalTo(FALSE))
test.is.logical.50 <- function() assertThat(is.logical("Infi"), identicalTo(FALSE))
test.is.logical.51 <- function() assertThat(is.logical("0.03f"), identicalTo(FALSE))
test.is.logical.52 <- function() assertThat(is.logical(" 0.0330 "), identicalTo(FALSE))
test.is.logical.53 <- function() assertThat(is.logical(structure("foo", class = "foo")), identicalTo(FALSE))
test.is.logical.54 <- function() assertThat(is.logical(structure(list(1L, "bar"), class = "bar")), identicalTo(FALSE)) |
mispr <- function(x, x.select=FALSE, pen=FALSE, maxit=5, m=5, track=FALSE, init.method="random", L2.fix=NULL, cv=TRUE, maxL2=2^10)
{
if(!is.data.frame(x)){
if(is.matrix(x))
x <- as.data.frame(x)
else
stop("data frame must be provided")
}
if(!is.null(L2.fix)) {if( L2.fix<0 | !is.numeric(L2.fix)) stop("L2 penalty must be non.negative value")}
if(!is.null(L2.fix) & cv==TRUE) {
cat("cv option is set automatically to FALSE since fixed value of L2 penalty is given")
cv <- FALSE
}
types <- lapply(x,class1)
attributes(types)$names <-NULL
types <- unlist(types)
if(any(types=="character")){
chrInd <- which(types=="character")
warning("At least one character variable is converted into a factor")
for(ind in chrInd){
x[,ind] <- as.factor(x[,ind])
types[ind] <- "factor"
}
}
indFac <- which(types=="factor")
for(ind in indFac){
if(length(levels(x[,ind]))==2)
types[ind] <- "binary"
else if(length(levels(x[,ind]))>2)
stop("factor with more than 2 levels detected and has not yet implemented!")
else stop("factor with less than 2 levels detected!")
}
missingSummary <- data.frame(types,apply(x,2,function(x)sum(is.na(x))))
colnames(missingSummary) <- c("type","
N <- n <- dim(x)[1]
P <- dim(x)[2]
if(dim(x)[2] < 2) stop("Less than 2 variables included in x.")
if(!any(is.na(x))) print("No missings in x. Nothing to impute")
if(any(apply(x, 1, function(x) all(is.na(x))))) stop("Unit non-responses included in x.")
factors <- vector()
for(i in 1:ncol(x)){
factors <- c(factors,is.factor(x[,i]))
}
x.na <-vector()
for(i in seq(P)){
if(na.exist(x[,i]))
x.na <- c(x.na,i)
}
w2 <- is.na(x)
if(requireNamespace("e1071"))
if(requireNamespace("MASS"))
if(requireNamespace("penalized"))
res =list()
res$m = m
res$iteration = maxit
res$imputation <- list()
res$missingSummary <- missingSummary
if(m>0){
data.input = x
for(imp in 1:m){
x=data.input
if(init.method=="median"){
x.init <- initialise(x,method="median")
} else if(init.method=="random"){
x.init <- initialise(x,method="random")
} else {stop("The value of init.method is misspecified, please choose any of two options i.e., random or median") }
x=x.init
rm(x.init)
if(track) print(head(x))
for(iteration in 1:maxit){
for(i in x.na){
if(track){
print(paste("iteration ",iteration, "; imputed dataset", imp ))
}
yPart <- x[, i, drop=FALSE]
wy <- which(w2[,i])
xPart <- x[, -i, drop=FALSE]
dataForReg <- data.frame(yPart,xPart)
if( types[i]=="numeric" ){
meth = "numeric"
} else if( types[i]=="binary" ){
meth = "bin"
}
if(length(wy) > 0){
if(track){ if(meth=="bin") print(paste("fitting model with ", colnames(dataForReg)[1], " as a binary response y.imp" )) else print(paste("fitting model with ", colnames(dataForReg)[1], " as a continuous response y.imp"))}
colnames(dataForReg)[1] <- "y.imp"
x[wy,i] <- lm.glm(xReg=dataForReg, x.select=x.select, pen=pen, index=wy, type=meth, L2.fix=L2.fix, cv=cv, maxL2=maxL2, track=track)
}
}
}
res$imputation[[imp]] <- x
}
} else
{
stop("value of m should be positive")
}
return(res)
} |
dberngamma <- function(x, prob, scale, shape){
if(length(prob)==1) prob <- rep(prob, length(x))
if(length(scale)==1) scale <- rep(scale, length(x))
if(length(shape)==1) shape <- rep(shape, length(x))
d <- 1-prob
d[x>0] <- prob[x>0]*dgamma(x[x>0], scale=scale[x>0], shape=shape[x>0])
d
}
pberngamma <- function(q, prob, scale, shape){
if(length(prob)==1) prob <- rep(prob, length(q))
if(length(scale)==1) scale <- rep(scale, length(q))
if(length(shape)==1) shape <- rep(shape, length(q))
p <- 1-prob
p[q>0] <- 1-prob[q>0]+prob[q>0]*pgamma(q[q>0], scale=scale[q>0],
shape=shape[q>0])
p
}
qberngamma <- function(p, prob, scale, shape){
if(length(prob)==1) prob <- rep(prob, length(p))
if(length(scale)==1) scale <- rep(scale, length(p))
if(length(shape)==1) shape <- rep(shape, length(p))
q <- rep(0, length(p))
cases <- p > (1-prob)
q[cases] <- qgamma((prob[cases]+p[cases]-1)/prob[cases],
scale=scale[cases], shape=shape[cases])
q
}
rberngamma <- function(n, prob, scale, shape){
if(max(length(prob), length(scale), length(shape)) > 1)
stop("parameters must be of length 1")
p <- runif(n)
q <- rep(0, length(p))
cases <- p > (1-prob)
q[cases] <- rgamma(sum(cases), scale=scale, shape=shape)
q
} |
control.gsym.point <-
function(
B = 499,
c_sampling = 0.25,
c_F = 0.25 ,
c_ELq = 0.25,
c_R = 0.25 ,
I = 2500)
list(B = B, c_sampling = c_sampling, c_F = c_F , c_ELq = c_ELq, c_R = c_R, I = I) |
convertbaselineltolr<-function(dataset,choice,covs,strs="chid",alt="alt"){
nobs<-dim(dataset)[1]
mxstr<-0
ustrs<- unique(dataset[[strs]])
for(str in ustrs){
mxstr<-max(mxstr,sum(!is.na(match(dataset[[strs]],str))))
}
altnames<-unique(dataset[[alt]])
out<-array(0,c(nobs,length(ustrs)+(length(covs)+1)*(mxstr-1)+1))
dimnames(out)<-list(NULL,c(paste("s",ustrs,sep=""),
as.vector(t(outer(altnames[-1],c("Intercept",covs),paste,sep=":"))),"y"))
for(str in ustrs){
out[str==dataset[[strs]], paste("s",str,sep="") ]<-1
}
for(jj in seq(nobs)){
for(ii in 2:length(altnames)){
if(dataset[[alt]][jj]==altnames[ii]){
out[jj,paste(altnames[ii],c("Intercept",covs),sep=":")]<-c(1,as.matrix(dataset[jj,covs]))
}
}
}
out[,"y"]<-0+dataset[,choice]
return(out)
} |
var.expDeath <-
function(contribution,incid,cox,fuzz = 0.01, Poisson = FALSE, covnames)
{
f1 = function1(cox);
times_np = f1[[1]]; deceased = f1[[2]];
covar = f1[[3]]; Omega_1 = f1[[4]];beta = f1[[5]];
S0_i = f1[[6]]; S1_i = f1[[7]]; S02_i = f1[[8]];
increment = as.numeric(contribution[[4]]);
p_incid = as.numeric(contribution[[2]]);
p_surv = as.numeric(contribution[[3]]);
ti = as.matrix(contribution[[1]][1]);
cov_incid = as.matrix(contribution[[1]][2:(1+p_incid)]);
cov_surv = as.data.frame(contribution[[1]][(2+p_incid):(1+p_incid+p_surv)]);
colnames(cov_surv) = covnames;
freq = as.matrix(contribution[[1]][,2+p_incid+p_surv]);
equal_row<-function(x,y,fuzz = 0)
{
(sum(abs(x - y)) < fuzz);
}
surv_p<-function(x,cov,time)
{
y = survfit(x,newdata=cov, se.fit = F);
return(approx(x=y$time,y=y$surv,xout=time,rule=2)$y);
}
variance1 = 0;
variance2 = 0;
if(Poisson == FALSE)
{
for(i in seq(1,length(freq))[ti!=0])
{
g = seq(1,length(incid[,1]),1)[apply(incid[,2:(1+p_incid)],1,function(x){equal_row(x,cov_incid[i,],fuzz)})];
if(incid[g,1]==0) next;
for(j in seq(i,length(freq))[ti[seq(i,length(freq))]!=0])
{
g_prime = seq(1,length(incid[,1]),1)[apply(incid[,2:(1+p_incid)],1,function(x){equal_row(x,cov_incid[j,],fuzz)})];
if(incid[g_prime,1]==0) next
facteur = 2*freq[i]*freq[j];
if(i==j) facteur = 1/2*facteur;
if(g==g_prime)
{
variance1 = variance1 + facteur*((1 - surv_p(cox,cov_surv[i,],ti[i]))*
(1 - surv_p(cox,cov_surv[j,],ti[j]))*
incid[g,1]*(1-incid[g,1])/incid[g,p_incid+2] +
(incid[g,1]*(1-incid[g,1])/incid[g,p_incid+2] + incid[g,1]**2)*
surv_p(cox,cov_surv[i,, drop = F],ti[i])*
surv_p(cox,cov_surv[j,, drop = F],ti[j])*
covariance(times_np, deceased, beta, ti[i], cov_surv[i,], ti[j], cov_surv[j,], S0_i, S1_i, S02_i, Omega_1));
}
else
{
variance2 = variance2 + facteur*incid[g,1]*incid[g_prime,1]*
surv_p(cox,cov_surv[i,, drop = F],ti[i])*
surv_p(cox,cov_surv[j,, drop = F],ti[j])*
covariance(times_np, deceased, beta, ti[i],cov_surv[i,],ti[j],cov_surv[j,], S0_i, S1_i, S02_i, Omega_1);
}
}
}
}
if(Poisson == TRUE)
{
for(i in seq(1,length(freq))[ti!=0])
{
g = seq(1,length(incid[,1]),1)[apply(incid[,2:(1+p_incid)],1,function(x){equal_row(x,cov_incid[i,],fuzz)})];
if(incid[g,1]==0) next;
for(j in seq(i,length(freq))[ti[seq(i,length(freq))]!=0])
{
g_prime = seq(1,length(incid[,1]),1)[apply(incid[,2:(1+p_incid)],1,function(x){equal_row(x,cov_incid[j,],fuzz)})];
if(incid[g_prime,1]==0) next
facteur = 2*freq[i]*freq[j];
if(i==j) facteur = 1/2*facteur;
if(g==g_prime)
{
variance1 = variance1 + facteur*((1 - surv_p(cox,cov_surv[i,],ti[i]))*
(1 - surv_p(cox,cov_surv[j,],ti[j]))*
incid[g,1]/incid[g,p_incid+2] +
(incid[g,1]/incid[g,p_incid+2] + incid[g,1]**2)*
surv_p(cox,cov_surv[i,, drop = F],ti[i])*
surv_p(cox,cov_surv[j,, drop = F],ti[j])*
covariance(times_np, deceased, beta, ti[i],cov_surv[i,],ti[j],cov_surv[j,], S0_i, S1_i, S02_i, Omega_1));
}
else
{
variance2 = variance2 + facteur*incid[g,1]*incid[g_prime,1]*
surv_p(cox,cov_surv[i,, drop = F],ti[i])*
surv_p(cox,cov_surv[j,, drop = F],ti[j])*
covariance(times_np, deceased, beta, ti[i],cov_surv[i,],ti[j],cov_surv[j,], S0_i, S1_i, S02_i, Omega_1);
}
}
}
}
return(increment**2*(variance1+variance2));
} |
library(PEcAn.all)
library(PEcAn.data.atmosphere)
library(RPostgreSQL)
for (i in dbListConnections(PostgreSQL())) db.close(i)
dbparms <- list(driver=driver, user=user, dbname=dbname, password=password, host=host)
if (raw == TRUE){
con <- db.open(dbparms)
outfolder <- paste0(dir,data.set,"/")
pkg <- "PEcAn.data.atmosphere"
fcn <- paste0("download.",fcn.data)
args <- list(data.set,outfolder,pkg,raw.host,start_year,end_year,site.id,dbparms,con)
raw.id <- do.call(fcn,args)
}
if (cf == TRUE){
con <- db.open(dbparms)
input.id <- raw.id
outfolder <- paste0(dir,data.set,"_CF/")
pkg <- "PEcAn.data.atmosphere"
fcn <- paste0("met2CF.",fcn.data)
write <- TRUE
cf.id <- convert.input(input.id,outfolder,pkg,fcn,write,username,con)
}
if (perm == TRUE){
con <- db.open(dbparms)
input.id <- cf.id
outfolder <- paste0(dir,data.set,"_CF_Permute/")
pkg <- "PEcAn.data.atmosphere"
fcn <- "permute.nc"
write <- TRUE
perm.id <- convert.input(input.id,outfolder,pkg,fcn,write,username,con)
}
if (extract == TRUE){
con <- db.open(dbparms)
input.id <- perm.id
str_ns <- paste0(newsite %/% 1000000000, "-", newsite %% 1000000000)
outfolder <- paste0("/projectnb/dietzelab/pecan.data/input/",data.set,"_CF_site_",str_ns,"/")
pkg <- "PEcAn.data.atmosphere"
fcn <- "extract.nc"
write <- TRUE
extract.id <- convert.input(input.id,outfolder,pkg,fcn,write,username,con,newsite = newsite)
}
if(nchar(model) >2){
con <- db.open(dbparms)
lst <- site.lst(newsite,con)
input.id <- extract.id
outfolder <- paste0(dir,data.set,"_",model,"_site_",str_ns,"/")
pkg <- paste0("PEcAn.",model)
fcn <- paste0("met2model.",model)
write <- TRUE
overwrite <- ""
model.id <- convert.input(input.id,outfolder,pkg,fcn,write,username,con,lst=lst,overwrite=overwrite)
}
for (i in dbListConnections(PostgreSQL())) db.close(i) |
lpls <- function(X1,X2,X3, ncomp = 2, doublecenter = TRUE, scale = c(FALSE,FALSE,FALSE),
type = c("exo"), impute = FALSE, niter = 25, subsetX2 = NULL, subsetX3 = NULL,...){
X1a <- X1
X1 <- X2
X2 <- X1a
X3 <- t(X3)
if(impute){
if(any(is.na(X1))) X1 <- svd.imp(X1)
if(any(is.na(X2))) X2 <- svd.imp(X2)
if(any(is.na(X3))) X3 <- svd.imp(X3)
}
if(!is.null(subsetX2)){
X1 <- X1[subsetX2,,drop=F]
X2 <- X2[subsetX2,,drop=F]
}
if(!is.null(subsetX3)){
X3 <- X3[subsetX3,,drop=F]
X2 <- X2[,subsetX3,drop=F]
}
X1save <- X1
X2save <- X2
X3save <- X3
X1dim <- dim(X1)
X2dim <- dim(X2)
X3dim <- dim(X3)
X1 <- scale(X1, scale=scale[2])
mX1 <- attr(X1, "scaled:center")
X3 <- scale(X3, scale=scale[3])
mX3 <- attr(X3, "scaled:center")
rowmX2 <- apply(X2,1,mean, na.rm=TRUE)
colmX2 <- apply(X2,2,mean, na.rm=TRUE)
grandmX2 <- mean(X2, na.rm=TRUE)
if(doublecenter){
X2 <- X2 - t(matrix(rep(1, X2dim[2]), ncol = 1)%*%rowmX2) -
matrix(rep(1,X2dim[1]), ncol = 1)%*%colmX2 +
matrix(grandmX2, nrow=X2dim[1], ncol = X2dim[2])
} else {
X2 <- X2 - matrix(grandmX2,nrow=X2dim[1],ncol=X2dim[2])
}
X2 <- scale(X2, scale = scale[1])
attributes(X1save) <- attributes(X1)
attributes(X2save) <- attributes(X2)
attributes(X3save) <- attributes(X3)
dlist <- list(X1 = as.matrix(t(X1)), X2 = as.matrix(X2), X3 = as.matrix(X3))
T11 <- T12 <- T21 <- T22 <- T31 <- T32 <- numeric(0)
W21 <- W22 <- numeric(0)
P1 <- P3 <- P21 <- P22 <- numeric(0)
D <- diag(rep(1,ncomp))
X1totvar <- X2totvar <- X3totvar <- rep(0,ncomp+1)
for(a in 1:ncomp){
X1totvar[a] <- sum(dlist$X1^2, na.rm=TRUE)
X2totvar[a] <- sum(dlist$X2^2, na.rm=TRUE)
X3totvar[a] <- sum(dlist$X3^2, na.rm=TRUE)
latent <- extractscores(dlist,niter=niter)
T11 <- cbind(T11, vecnorm(latent[[1]]$t1))
T12 <- cbind(T12, vecnorm(latent[[1]]$t2))
T21 <- cbind(T21, vecnorm(latent[[2]]$t1))
T22 <- cbind(T22, vecnorm(latent[[2]]$t2))
T31 <- cbind(T31, vecnorm(latent[[3]]$t1))
T32 <- cbind(T32, vecnorm(latent[[3]]$t2))
if(type=="exo_ort"){
P1 <- cbind(P1, projectonto(dlist$X1,T21[,a]))
P3 <- cbind(P3, projectonto(dlist$X3,T22[,a]))
P21 <- cbind(P21, projectonto(dlist$X2,T21[,a]))
P22 <- cbind(P22, projectonto(dlist$X2,T22[,a]))
d <- drop(solve(crossprod(T21[,a]))%*%t(T21[,a])%*%P22[,a])
D[a,a] <- d
dlist$X1 <- dlist$X1 - P1[,a]%*%t(T21[,a])
dlist$X3 <- dlist$X3 - T22[,a]%*%t(P3[,a])
dlist$X2 <- dlist$X2 - T21[,a]%*%t(P21[,a]) - P22[,a]%*%t(T22[,a]) + T21[,a]%*%t(T22[,a])*drop(d)
}
if(type=="exo"){
P1 <- projectonto(t(X1),T21)
P3 <- projectonto(t(X3),T22)
P21 <- projectonto(t(X2),T21)
P22 <- projectonto(X2,T22)
D <- solve(crossprod(T21))%*%t(T21)%*%P22
dlist$X1 <- t(X1 - T21%*%t(P1))
dlist$X3 <- X3 - T22%*%t(P3)
dlist$X2 <- X2 - T21%*%D%*%t(T22)
}
if(type=="endo"){
P1 <- projectonto(t(X1),T12)
P3 <- projectonto(t(X3),T31)
D <- solve(crossprod(T12))%*%t(T12)%*%projectonto(X2, T31)
dlist$X1 <- t(X1 - T12%*%t(P1))
dlist$X3 <- X3 - T31%*%t(P3)
dlist$X2 <- X2 - T12%*%D%*%t(T31)
}
}
X1totvar[ncomp+1] <-sum(dlist$X1^2, na.rm=TRUE)
X2totvar[ncomp+1] <-sum(dlist$X2^2, na.rm=TRUE)
X3totvar[ncomp+1] <-sum(dlist$X3^2, na.rm=TRUE)
X1varprop <- diff((X1totvar[1]-X1totvar)/(X1totvar[1]))
X2varprop <- diff((X2totvar[1]-X2totvar)/(X2totvar[1]))
X3varprop <- diff((X3totvar[1]-X3totvar)/(X3totvar[1]))
B1 <- B3 <- Ca <- NULL
if(type!="endo"){
B1 <- T31%*%solve(t(P21)%*%T31)%*%t(P1)
B3 <- T12%*%solve(t(P22)%*%T12)%*%t(P3)
suppressWarnings({
R1 <- cor(X1,T21, use="pairwise.complete.obs")
R21 <- t(cor(T21,X2, use="pairwise.complete.obs"))
R22 <- t(cor(T22,t(X2), use="pairwise.complete.obs"))
R3 <- cor(X3,T22, use="pairwise.complete.obs")
R2rmean <- cor(rowmX2,T21, use="pairwise.complete.obs")
R2cmean <- cor(colmX2,T22, use="pairwise.complete.obs")
})
} else if(type=="endo"){
V1 <- T11%*%solve(t(P1)%*%T11)
V3 <- T32%*%solve(t(P3)%*%T32)
Ca <- V1%*%D%*%t(V3)
suppressWarnings({
R1 <- cor(X1,T12, use="pairwise.complete.obs")
R21 <- t(cor(T12,X2, use="pairwise.complete.obs"))
R22 <- t(cor(T31,t(X2), use="pairwise.complete.obs"))
R3 <- cor(X3,T31, use="pairwise.complete.obs")
R2rmean <- cor(rowmX2,T12, use="pairwise.complete.obs")
R2cmean <- cor(colmX2,T31, use="pairwise.complete.obs")
})
}
res <- list(call=match.call())
res$ncomp <- ncomp
res$coefficients <- list(B1=B1, B3=B3, C=Ca)
res$blockScores <- list(T11=T11, T12=T12, T21=T21, T22=T22, T31=T31, T32=T32)
res$blockLoadings<- list(P1=P1, P3=P3, P21=P21, P22=P22, D=D)
res$corloadings <- list(R1=R1, R21=R21, R22=R22, R3=R3, R2rmean=R2rmean, R2cmean=R2cmean)
res$means <- list(mX1=mX1, mX3=mX3, grandmX2=grandmX2, rowmX2=rowmX2, colmX2=colmX2)
res$data <- list(X1=X1save, X2=X2save, X3=X3save)
res$residuals <- dlist
res$options <- list(doublecenter=doublecenter, scale=scale, type=type)
res$vars <- list(X1varprop=X1varprop, X2varprop=X2varprop, X3varprop=X3varprop)
res$info <- list(method = "L-PLS",
scores = "Not used", loadings = "Not used",
blockScores = "Block scores", blockLoadings = "Block loadings")
class(res) <- c('lpls', 'multiblock','list')
return(res)
}
extractscores <- function(datalist, niter = 25, truncperc = NULL, truncvec = NULL){
nmat <- length(datalist)
dims <- lapply(datalist, dim)
dimok <- TRUE
for(ii in 1:(nmat-1)){
dimok <- ifelse(dims[[ii]][2]==dims[[(ii+1)]][1], TRUE, FALSE)
}
if(!dimok) stop("Dimension mismatch\n")
scorelist<-list()
for(ii in 1:nmat){
scorelist[[ii]]<-list(t1 = matrix(0, nrow = dims[[ii]][1], ncol = 1),
t2 = matrix(0, nrow = dims[[ii]][2], ncol = 1))
}
scorelist[[1]]$t1 <- as.matrix(rnorm(dims[[1]][1], 0, 1))
for(k in 1:niter){
scorelist[[1]]$t2 <- projectonto(datalist[[1]], scorelist[[1]]$t1)
for(j in 2:nmat){
scorelist[[j]]$t2 <- projectonto(datalist[[j]], scorelist[[(j-1)]]$t2)
}
scorelist[[nmat]]$t1 <- projectonto(datalist[[nmat]], scorelist[[nmat]]$t2)
for(j in (nmat-1):1){
scorelist[[j]]$t1 <- projectonto(datalist[[j]], scorelist[[(j+1)]]$t1)
}
}
return(scorelist)
}
projectonto <- function(A,b){
A.na <- any(is.na(A))
if(is.null(dim(A))) A <- matrix(A, ncol = 1)
if(is.null(dim(b))) b <- matrix(b, ncol = 1)
if(!any(dim(A)==dim(b)[1])) stop("Non-matching dimensions")
q <- dim(b)[2]
if(A.na && q>1){
svd1 <- svd(b)
b <- b%*%svd1$v
}
if(dim(A)[1]==dim(b)[1]) A <- t(A)
if(!A.na){
proj <- A%*%b%*%solve(crossprod(b))
} else {
miss <- which(is.na(A))
A[miss] <- 0
if(q==1){
bb <- t(b^2)
ones <- matrix(1,dim(A)[2],dim(A)[1])
ones[miss] <- 0
btbinv <- 1/drop(bb%*%ones)
proj <- (A%*%b)*btbinv
} else if(q>1){
proj <- numeric()
for(i in 1:q){
bb <- t(b[,i]^2)
ones <- matrix(1,dim(A)[2],dim(A)[1])
ones[miss] <- 0
btbinv <- 1/drop(bb%*%ones)
proj <- cbind(proj,(A%*%b[,i])*btbinv)
}
proj <- proj%*%t(svd1$v)
}
}
return(proj)
}
vecnorm <- function(vec){
vec / sqrt(drop(crossprod(vec)))
}
svd.imp <- function(X, max.niter=50, expl.min=0.98, interactive=FALSE, tol=1e-3, ploteval=FALSE){
ncomp = min(dim(X))
missing <- which(is.na(X))
X.scaled <- scale(X,scale=FALSE)
colmeans <- attr(X.scaled,"scaled:center")
meanmat <- matrix(1,nrow=dim(X)[1],ncol=1)%*%colmeans
X.imp <- X
impvals <- meanmat[missing]
X.imp[missing] <- impvals
initiate <- TRUE
j<-1
relchange <- 1
change <- numeric()
while(relchange > tol & j<=max.niter){
uvd <- svd(X.imp)
if(initiate){
ssx <- rep(0,ncomp)
for(i in 1:ncomp){
D <- matrix(0,i,i)
diag(D) <- uvd$d[1:i]
ssx[i] <- sum((uvd$u[,1:i,drop=F]%*%D%*%t(uvd$v[,1:i]))^2)
initiate <- FALSE
}
ssxtot <- sum(X.imp^2)
explvar <- ssx/ssxtot
if(interactive){
plot(1:ncomp,explvar)
ncomp <- readline("Choose number of components for imputation \n")
ncomp <- as.numeric(ncomp)
}else{
ncomp <- min(which(explvar > expl.min))
}
}
D <- matrix(0,ncomp,ncomp)
diag(D) <- uvd$d[1:ncomp]
Xhat <- uvd$u[,1:ncomp,drop=F]%*%D%*%t(uvd$v[,1:ncomp,drop=F])
impvallength <- sqrt(sum((impvals)^2))
change[j] <- relchange <- sqrt(sum((impvals-Xhat[missing])^2))
impvals <- Xhat[missing]
X.imp[missing] <- impvals
if(ploteval){
plot(0:j,c(1,change/impvallength),ylab="Change",main=paste("Relative change in imputed values using",ncomp,"components\n"),xlab="iteration")
}
j <- j+1
}
X.imp
} |
Frank <- compiler::cmpfun(function(param, dim = 2L, density = FALSE)
{
if (param < 0)
stop("Wrong 'param' input")
verif <- eval(parse(text = paste0(dim, "L")))
if (!is.integer(verif) || dim <= 1)
stop("The dimension must be an integer greater than or equal to 2")
phi <- "log(1 - (alpha) * exp(-(z))) / log(1 - (alpha))"
phi.inv <- "-log((1 - (1 - (alpha))^(z)) / (alpha))"
dep.param <- "(1 - exp(-alpha))"
param.th <- "(1 - exp(-alpha))"
phi <- stringr::str_replace_all(phi, "alpha", dep.param)
phi.inv <- stringr::str_replace_all(phi.inv, "alpha", dep.param)
rBiv <- function(n, alpha, u) -log(1 - (runif(n) * (exp(-alpha) - 1)) / (runif(n) * (exp(-alpha * u) - 1) - exp(-alpha * u))) / alpha
th <- function(z, alpha) copula::rlog(z, alpha)
param <- as.character(param)
if (density)
{
tt <- LOG(1/10, 1:dim, NULL)
uu <- paste("u", 1:dim, sep = "")
expr1 <- numeric(dim)
for (i in 1:dim)
expr1[i] <- stringr::str_replace_all(tt@Der("z", 1, "LaplaceInv"), "z", uu[i])
expr1 <- paste("(", expr1, ")", sep = "", collapse = " * ")
nu <- numeric(dim)
for(i in 1:dim)
nu[i] <- stringr::str_replace_all(tt@LaplaceInv, "z", uu[i])
nu <- paste("(", nu, ")", sep = "", collapse = " + ")
expr2 <- stringr::str_replace_all(tt@Der("z", dim, "Laplace"), "z", nu)
densit <- paste("(", expr1, ") * (", expr2, ")", sep = "")
densit <- stringr::str_replace_all(densit, "alpha", dep.param)
new("frank",
phi = phi,
phi.inv = phi.inv,
rBiv = rBiv,
theta = th,
depend = dep.param,
dimension = dim,
parameter = param,
dens = densit,
par.th = param.th,
name = "Frank copula")
}
else
{
new("frank",
phi = phi,
phi.inv = phi.inv,
rBiv = rBiv,
theta = th,
depend = dep.param,
dimension = dim,
parameter = param,
par.th = param.th,
name = "Frank copula")
}
}) |
rp.checkbox <- function(panel, variable, action = I, labels = NULL, names = NULL,
title = NULL, initval = rep(FALSE, length(labels)), pos = NULL,
doaction = FALSE, foreground = NULL, background = NULL,
font = NULL, parentname = deparse(substitute(panel)),
name = paste("checkbox", .nc(), sep=""), ...) {
if (!exists(panel$panelname, .rpenv, inherits = FALSE))
panelname <- deparse(substitute(panel))
else
panelname <- panel$panelname
varname <- deparse(substitute(variable))
if (is.null(labels)) labels <- varname
if (!rp.isnull(panelname, varname)) {
variable <- rp.var.get(panelname, varname)
if (is.null(names)) {
if (!is.null(names(variable)))
names <- names(variable)
else
names <- labels
}
}
else {
if (length(initval) == 0) initval <- FALSE
if (is.null(names)) names <- labels
variable <- initval
}
names(variable) <- names
rp.var.put(panelname, varname, variable)
if (is.null(pos) & length(list(...)) > 0) pos <- list(...)
f <- function(val) {
valexisting <- rp.var.get(panelname, varname)
names(val) <- names(valexisting)
rp.var.put(panelname, varname, val)
panel <- rp.control.get(panelname)
panel <- action(panel)
rp.control.put(panelname, panel)
}
if (rp.widget.exists(panelname, parentname))
parent <- rp.widget.get(panelname, parentname)
else
parent <- panel
if (is.list(pos) && !is.null(pos$grid))
parent <- rp.widget.get(panelname, pos$grid)
widget <- w.checkbox(parent, action = f, labels = labels, names = names, title = title,
initval = variable, pos = pos,
foreground = foreground, background = background, font = font)
rp.widget.put(panelname, name, widget)
if (doaction) f(initval)
if (.rpenv$savepanel) rp.control.put(panelname, panel)
invisible(panelname)
}
w.checkbox <- function(parent, action = I, labels, names, title,
initval = rep(FALSE, length(labels)),
pos = NULL, foreground = NULL, background = "white", font = NULL) {
widget <- w.createwidget(parent, pos, background, title)
widget$.type <- "checkgroup"
widget$.var <- c()
widget$.cb <- list()
f <- function(...) {
variable <- c()
for (j in (1:length(labels)))
variable[j] <- !(handshake(tclvalue, widget$.var[[j]]) == '0')
names(variable) <- names
action(variable)
}
for (i in (1:length(labels))) {
if (initval[i] == TRUE)
widget$.var[i] <- list(handshake(tclVar, '1'))
else
widget$.var[i] <- list(handshake(tclVar, '0'))
cb <- w.createwidget(widget, pos = list(column = 0, row = i - 1, sticky = "news",
width = as.integer(handshake(.Tcl,
paste('font measure systemfont "', labels[[i]], '"', sep = "") )),
height = 2 + as.integer(handshake(.Tcl,
'font metrics systemfont -linespace'))
), background)
cb$.type <- "checkbutton"
cb$.widget <- handshake(tkcheckbutton, widget$.handle, command = f, text = labels[[i]],
variable = widget$.var[[i]])
w.appearancewidget(cb, font, foreground, background)
widget$.cb[i] <- list(cb)
}
invisible(widget)
} |
nvsd <-
function(X, y, fold=10, step.size=0.01, stop.alpha=0.05, stop.var.count=20, max.model.var.count=10, roughening.method="DCOL", do.plot=F, pred.method="MARS")
{
nonlin.pred<-function(x, y, x.new, method=c("MARS", "RF", "SVM"))
{
if(is.null(nrow(x)))
{
x<-matrix(x, nrow=1)
x.new<-matrix(x.new, nrow=1)
}
this.x<-as.data.frame(t(x))
this.test.x<-as.data.frame(t(x.new))
if(method=="MARS") e<-earth(x=this.x, y=y)
else if(method=="RF") e<-randomForest(this.x, y, ntree=max(500, 4*row(this.x)))
else if(method=="SVM") e<-svm(x=this.x, y=y)
ee<-predict(e, this.test.x)
ee
}
find.cut<-function(x,y)
{
pred <- prediction(x, y)
perf <- performance(pred,"tpr","fpr")
opt.cut = function(perf, pred){
cut.ind = mapply(FUN=function(x, y, p){
d = (x - 0)^2 + (y-1)^2
ind = which(d == min(d))[1]
c(sensitivity = y[[ind]], specificity = 1-x[[ind]],
cutoff = p[[ind]])
}, [email protected], [email protected], pred@cutoffs)
}
opt.cut(perf,pred)[3,1]
}
grp<-rep(1:fold, length(y))[1:length(y)]
grp<-sample(grp, length(y), replace=FALSE)
y.pred<-new("list")
for(i in 1:stop.var.count) y.pred[[i]]<-matrix(NA, nrow=1, ncol=length(y))
b<-stage.forward(X, y, stop.alpha=stop.alpha, stop.var.count=stop.var.count, step.size=step.size, roughening.method=roughening.method, do.plot=F)
if(length(b$found.pred) > 0)
{
for(m in 1:fold)
{
this.X<-X[,grp != m]
this.y<-y[grp != m]
for(j in 1:min(length(b$found.pred), max.model.var.count))
{
x.train<-this.X[b$found.pred[1:j],]
y.train<-this.y
x.test<-X[b$found.pred[1:j], grp == m]
predicted<-nonlin.pred(x.train, y.train, x.test, method=pred.method)
if(length(table(y))==2)
{
predicted.0<-nonlin.pred(x.train, y.train, x.train, method=pred.method)
predicted<-1*(predicted>find.cut(predicted.0, y.train))
}
y.pred[[j]][grp == m]<-predicted
}
}
for(j in 1:min(length(b$found.pred), max.model.var.count))
{
y.pred[[j]][is.na(y.pred[[j]])]<-Inf
}
ssr<-matrix(NA, nrow=1, ncol=stop.var.count)
for(j in 1:stop.var.count)
{
ssr[1,j]<-sum((y-y.pred[[j]][1,])^2)
}
n.var.err<-apply(ssr,2,min)
n.var.choice<-which(n.var.err == min(n.var.err,na.rm=T))[1]
return(list(selected.pred=b$found.pred[1:n.var.choice], all.pred=b$found.pred))
}else{
return(list(selected.pred=NULL, all.pred=NULL))
}
} |
summary.immer_ccml <- function( object, digits=3, file=NULL, ... )
{
immer_osink( file=file )
cat("-----------------------------------------------------------------\n")
immer_summary_print_package_rsession(pack="immer")
cat( object$description, "\n\n")
immer_summary_print_call(CALL=object$CALL)
immer_summary_print_computation_time(object=object )
cat( "Number of iterations ","=", object$nlminb_result$iterations, "\n" )
cat( "Convergence code ","=", object$nlminb_result$convergence, "\n" )
cat("\n")
cat( "Objective function value ","=", round( object$objective, 2 ), "\n" )
cat( "Number of person-rater-interactions ","=", object$ic$ND, "\n" )
cat( "Number of persons ","=", object$ic$N, "\n" )
cat( "Number of items ","=", object$ic$I, "\n" )
cat( "Number of raters ","=", object$ic$R, "\n\n" )
cat( "Number of estimated item parameters ","=", object$ic$np, "\n" )
cat("\n")
immer_ccml_summary_print_ic(object=object)
cat("-----------------------------------------------------------------\n")
cat("Item Parameters \n")
immer_summary_print_objects(obji=object$item, from=2, digits=digits, rownames_null=TRUE)
cat("-----------------------------------------------------------------\n")
cat("Basis Item Parameters \n")
immer_summary_print_objects(obji=object$xsi_out, from=1, digits=digits, rownames_null=FALSE)
immer_csink( file=file )
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(ggplot2)
theme_set(theme_bw())
library(liminal)
data(pdfsense)
pcs <- prcomp(pdfsense[, 7:ncol(pdfsense)])
res <- data.frame(
component = 1:56,
variance_explained = cumsum(pcs$sdev / sum(pcs$sdev))
)
ggplot(res, aes(x = component, y = variance_explained)) +
geom_point() +
scale_x_continuous(
breaks = seq(0, 60, by = 5)
) +
scale_y_continuous(
labels = function(x) paste0(100*x, "%")
)
pdfsense <- dplyr::bind_cols(
pdfsense,
as.data.frame(pcs$x)
)
pdfsense$Type <- factor(pdfsense$Type)
set.seed(3099)
start <- clamp_sd(as.matrix(dplyr::select(pdfsense, PC1, PC2)), sd = 1e-4)
tsne <- Rtsne::Rtsne(
dplyr::select(pdfsense, PC1:PC56),
pca = FALSE,
normalize = TRUE,
perplexity = 50,
exaggeration_factor = nrow(pdfsense) / 100,
Y_init = start
)
tsne_embedding <- as.data.frame(tsne$Y)
tsne_embedding <- dplyr::rename(tsne_embedding, tsneX = V1, tsneY = V2)
tsne_embedding$Type <- pdfsense$Type
ggplot(tsne_embedding,
aes(x = tsneX, y = tsneY, color = Type)) +
geom_point() +
scale_color_manual(values = limn_pal_tableau10()) |
orcid_services <- function(orcid, put_code = NULL,
format = "application/json", summary = FALSE, ...) {
pth <- path_picker(put_code, summary, "service")
orcid_putcode_helper(pth, orcid, put_code, format, ...)
} |
svc <- paws::qldb()
test_that("list_journal_s3_exports", {
expect_error(svc$list_journal_s3_exports(), NA)
})
test_that("list_journal_s3_exports", {
expect_error(svc$list_journal_s3_exports(MaxResults = 20), NA)
})
test_that("list_ledgers", {
expect_error(svc$list_ledgers(), NA)
})
test_that("list_ledgers", {
expect_error(svc$list_ledgers(MaxResults = 20), NA)
}) |
allocolo<-function(mlkm,pg,mlkmpre,pgpre,colopre,coloind,colofall,paletti)
{
lkmpre<-mlkmpre$lkm
lkm<-mlkm$lkm
modecolo<-matrix("",lkm,1)
if (!is.null(colopre)){
dist<-matrix(NA,lkm,lkmpre)
for (i in 1:lkm){
for (j in 1:lkmpre){
cent<-pg$center[,mlkm$modloc[i]]
centpre<-pgpre$center[,mlkmpre$modloc[j]]
dist[i,j]<-etais(cent[1:2],centpre[1:2])
}
}
}
if (is.null(colopre)){
for (k in 1:lkm){
modecolo[k]<-paletti[k]
}
coloind<-lkm
}
else if (lkm>=lkmpre){
for (k in 1:lkmpre){
minimi<-min(dist,na.rm=TRUE)
argmin<-which(minimi==dist)[1]
yind<-ceiling(argmin/lkm)
xind<-argmin-(yind-1)*lkm
dist[xind,]<-NA
modecolo[k]<-colopre[yind]
}
k<-lkmpre+1
while (k<=lkm){
modecolo[k]<-paletti[coloind+k-lkmpre]
k<-k+1
}
coloind<-lkm
}
else{
for (k in 1:lkm){
minimi<-min(dist,na.rm=TRUE)
argmin<-which(minimi==dist)[1]
yind<-ceiling(argmin/lkm)
xind<-argmin-(yind-1)*lkm
dist[xind,]<-NA
modecolo[k]<-colopre[yind]
}
colofall<-lkm
}
return(list(modecolo=modecolo,coloind=coloind,colofall=colofall))
} |
par(mar = c(1, 1, 1, 1))
circos.par("default.track.height" = 0.1)
circos.initializeWithIdeogram(plotType = NULL)
bed = generateRandomBed(nr = 100)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, type = "l", ...)
})
bed1 = generateRandomBed(nr = 100)
bed2 = generateRandomBed(nr = 100)
bed_list = list(bed1, bed2)
circos.genomicTrackPlotRegion(bed_list, panel.fun = function(region, value, ...) {
i = getI(...)
circos.genomicLines(region, value, col = i, ...)
})
circos.genomicTrackPlotRegion(bed_list, stack = TRUE, panel.fun = function(region, value, ...) {
i = getI(...)
circos.genomicLines(region, value, col = i, ...)
})
bed = generateRandomBed(nr = 100, nc = 4)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, col = 1:4, ...)
})
circos.genomicTrackPlotRegion(bed, stack = TRUE, panel.fun = function(region, value, ...) {
i = getI(...)
circos.genomicLines(region, value, col = i, ...)
})
bed = generateRandomBed(nr = 100)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, type = "segment", lwd = 2, ...)
})
circos.clear()
circos.par("default.track.height" = 0.1)
circos.initializeWithIdeogram(plotType = NULL)
bed = generateRandomBed(nr = 20)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, ...)
})
bed = generateRandomBed(nr = 100)
bed = cbind(bed[1:3], rep(1, nrow(bed)), bed[4])
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, ...)
})
circos.genomicTrackPlotRegion(bed, numeric.column = 5, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, ...)
})
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicLines(region, value, numeric.column = 1, ...)
})
circos.clear()
circos.par("default.track.height" = 0.1)
circos.initializeWithIdeogram(plotType = NULL)
bed = generateRandomBed(nr = 100, nc = 0)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, pch = 16, cex = 0.5, ...)
})
bed = cbind(bed, rep("text", nrow(bed)))
circos.genomicTrackPlotRegion(bed, numeric.column = 4, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, pch = 16, cex = 0.5, ...)
})
bed1 = generateRandomBed(nr = 100, nc = 1)
bed2 = generateRandomBed(nr = 100, nc = 0)
bed_list = list(bed1, bed2)
circos.genomicTrackPlotRegion(bed_list, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, pch = 16, cex = 0.5, ...)
})
circos.clear()
circos.par("default.track.height" = 0.1)
circos.initializeWithIdeogram(plotType = NULL)
bed = generateRandomBed(nr = 100, nc = 0)
circos.genomicTrackPlotRegion(bed, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, ...)
})
bed = cbind(bed, rep("text", nrow(bed)))
circos.genomicTrackPlotRegion(bed, numeric.column = 4, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, ...)
})
bed1 = generateRandomBed(nr = 100, nc = 1)
bed2 = generateRandomBed(nr = 100, nc = 0)
bed_list = list(bed1, bed2)
circos.genomicTrackPlotRegion(bed_list, panel.fun = function(region, value, ...) {
circos.genomicPoints(region, value, ...)
})
circos.clear() |
dscore.default <- function(x, ...)
{
if(all(is.numeric(x)) & any(x>1 | x<0))
stop("argument 'x' should be a vector containing probabilities (e.g. values in [0,1]")
v <- c(0:(2*length(x)))
ans <- dpoisbinom(v, rep(x, each=2))
names(ans) <- paste(v, "alleles")
class(ans) <- "dscore"
ans
} |
check_design_opt <- function(design_opt_input) {
design_opt <- list(rules = NULL,
actions = NULL,
min = NA,
max = NA,
min_fit = 0,
obligatory = 0,
sd_entropy = NA,
designs = 1,
max_iter = 1e5,
seed = NA)
design_opt[names(design_opt_input)] <- design_opt_input
return(design_opt)
} |
test_that("read in PNG file in binary format", {
df <- c("fig/fig1.png", "fig/fig2.png")
png_vec_in <- rtf_read_figure(df)
png_in_1 <- readBin(df[1], what = "raw", size = 1, signed = TRUE, endian = "little", n = 1e8)
png_in_2 <- readBin(df[2], what = "raw", size = 1, signed = TRUE, endian = "little", n = 1e8)
png_lst <- list(png_in_1, png_in_2)
attr(png_vec_in, "fig_format") <- NULL
expect_equal(png_vec_in, png_lst)
}) |
".Build.terms" <-
function(x, coefs, cov = NULL, assign, collapse = TRUE)
{
cov.true <- !is.null(cov)
if(collapse) {
fit <- drop(x %*% coefs)
if(cov.true) {
var <- ((x %*% cov) * x) %*% rep(1., length(coefs))
list(fit = fit, se.fit = drop(sqrt(var)))
}
else fit
}
else {
constant <- attr(x, "constant")
if(!is.null(constant))
constant <- sum(constant * coefs)
if(missing(assign))
assign <- attr(x, "assign")
if(is.null(assign))
stop("Need an 'assign' list")
fit <- array(0., c(nrow(x), length(assign)), list(dimnames(
x)[[1.]], names(assign)))
if(cov.true)
se <- fit
TL <- sapply(assign, length)
simple <- TL == 1.
complex <- TL > 1.
if(any(simple)) {
asss <- unlist(assign[simple])
ones <- rep(1., nrow(x))
fit[, simple] <- x[, asss] * outer(ones, coefs[asss])
if(cov.true)
se[, simple] <- abs(x[, asss]) * outer(ones,
sqrt(diag(cov))[asss])
}
if(any(complex)) {
assign <- assign[complex]
for(term in names(assign)) {
TT <- assign[[term]]
xt <- x[, TT]
fit[, term] <- xt %*% coefs[TT]
if(cov.true)
se[, term] <- sqrt(drop(((xt %*% cov[
TT, TT]) * xt) %*% rep(1.,
length(TT))))
}
}
attr(fit, "constant") <- constant
if(is.null(cov))
fit
else list(fit = fit, se.fit = se)
}
} |
md_stock_symbol_hk = function(source="163", return_price=FALSE) {
symbol = exchange = market_symbols = stock_list_hk2 = NULL
if (source == "163") {
fun_listcomp_hk = function(urli, mkt_board) {
dt = V1 = name = NULL
doc = readLines(urli, warn = FALSE)
datetime = as.Date(sub(".+time\":\"([0-9\\-]+).+", "\\1", doc))
listcomp = data.table(dt = doc)[
, strsplit(sub(".+\\[\\{(.+)\\}\\].+", "\\1", dt), "\\},\\{")
][, c("eps", "exchange_rate", "financedata.net_profit", "financedata.totalturnover_", "high", "low", "market_capital", "name", "open", "pe", "percent", "price", "symbol", "turnover", "updown", "volume", "yestclose", "zf", "no") := tstrsplit(V1, ",", fixed=TRUE)
][, lapply(.SD, function(x) gsub("\".+\"\\:|\\}|\"", "", x))
][, `:=`(
V1 = NULL, date = datetime, board = mkt_board,
name = stri_unescape_unicode(name),
market = "stock", exchange = "hkex"
)][, c("market", "exchange", "board", "symbol", "name", "date", "open", "high", "low", "price", "percent", "updown", "volume", "turnover", "exchange_rate", "zf", "pe", "market_capital", "eps", "financedata.net_profit", "financedata.totalturnover_"), with=FALSE]
return(listcomp)
}
urls = c(
main = "http://quotes.money.163.com/hk/service/hkrank.php?host=/hk/service/hkrank.php&page=0&query=CATEGORY:MAIN;TYPE:1;EXCHANGE_RATE:_exists_true&fields=no,time,SYMBOL,NAME,PRICE,PERCENT,UPDOWN,OPEN,YESTCLOSE,HIGH,LOW,VOLUME,TURNOVER,EXCHANGE_RATE,ZF,PE,MARKET_CAPITAL,EPS,FINANCEDATA.NET_PROFIT,FINANCEDATA.TOTALTURNOVER_&sort=SYMBOL&order=desc&count=300000&type=query&callback=callback_1620346970&req=12219",
gem = "http://quotes.money.163.com/hk/service/hkrank.php?host=/hk/service/hkrank.php&page=0&query=CATEGORY:GEM;TYPE:1;EXCHANGE_RATE:_exists_true&fields=no,SYMBOL,NAME,PRICE,PERCENT,UPDOWN,OPEN,YESTCLOSE,HIGH,LOW,VOLUME,TURNOVER,EXCHANGE_RATE,ZF,PE,MARKET_CAPITAL,EPS,FINANCEDATA.NET_PROFIT,FINANCEDATA.TOTALTURNOVER_&sort=SYMBOL&order=desc&count=20000&type=query&callback=callback_2057363736&req=12220"
)
stock_list_hk = mapply(fun_listcomp_hk, urls, names(urls), SIMPLIFY = FALSE)
stock_list_hk = rbindlist(stock_list_hk)
} else if (source=="sina") {
fun_listcomp_hk_sina = function(urli) {
num = doc = V1 = symbol = NULL
dt = data.table(
doc = readLines(urli, warn = FALSE)
)[, doc := iconv(doc, "GB18030", "UTF-8")
][, doc := gsub("(\\[\\{)|(\\]\\})", "", doc)
][, strsplit(doc, "\\},\\{")
][, (c("symbol","name","engname","tradetype","lasttrade","prevclose","open","high","low","volume","currentvolume","amount","ticktime","buy","sell","high_52week","low_52week","eps","dividend","stocks_sum","pricechange","changepercent")) := tstrsplit(V1, ",", fixed=TRUE)
][, V1 := NULL
][, lapply(.SD, function(x) gsub(".+:|\"", "", x))
][, `:=`(
market = "stock", exchange = "hkex",
board = ifelse(substr(symbol,1,2)=="08", "gem", "main")
)]
return(dt)
}
url_hk <- c(
"http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHKStockData?page=1&num=100000&sort=symbol&asc=1&node=qbgg_hk&_s_r_a=init"
)
stock_list_hk = fun_listcomp_hk_sina(url_hk)
}
stock_list_hk = stock_list_hk[, symbol := paste(symbol, substr(exchange,1,2) ,sep=".")]
if (return_price == FALSE) stock_list_hk = stock_list_hk[, c("market", "exchange", "board", "symbol", "name"), with=FALSE]
return(stock_list_hk)
}
symbol_163_format = function(df_symbol) {
type = . = id = name = symbol = tags = market = submarket = region = exchange = board = prov = indu = sec = mkt = syb = syb3 = NULL
prov_indu_163 = setDT(copy(prov_indu_163))
if (all(c('province', 'industry', 'sector') %in% names(df_symbol))) {
df_symbol = merge(df_symbol, prov_indu_163[type=="prov",.(province=id, prov=name)], by = "province", all.x = TRUE)
df_symbol = merge(df_symbol, prov_indu_163[type=="indu",.(industry=id, indu=name)], by = "industry", all.x = TRUE)
df_symbol = merge(df_symbol, prov_indu_163[type=="indu",.(sector=id, sec=name)], by = "sector", all.x = TRUE)
}
if (!('market' %in% names(df_symbol))) {
df_symbol = copy(df_symbol)[, `:=`(market = ifelse(grepl("\\^", symbol), "index", "stock") )]
}
df_symbol = merge(
df_symbol[
, syb := sub(".*?(\\d+).*","\\1", symbol)
][nchar(syb)==6, syb3 := substr(syb,1,3)],
tags_dt()[, c("exchange","submarket","board") := tstrsplit(tags,",")
][,.(market=mkt, syb3, exchange, submarket, board)],
all.x = TRUE, by = c('syb3', 'market')
)[order(-market, exchange, symbol)
][, (c('syb','syb3')) := NULL]
return(df_symbol)
}
md_stock_symbol_163 = function() {
. = board = exchange = indu = market = name = prov = sec = submarket = symbol = NULL
df_syb = md_stock_spotall_163(symbol = c('a', 'b', 'index'), only_symbol=TRUE, show_tags=TRUE)[,.(
market, submarket, exchange, board, symbol, name, sector = sec, industry = indu, province = prov
)]
return(df_syb)
}
md_stock_symbol_nasdaq = function(exchange) {
. = symbol = name = sector = industry = country = ipoyear = marketCap = NULL
url = sprintf(
"https://api.nasdaq.com/api/screener/stocks?tableonly=true&exchange=%s&download=true",
toupper(exchange))
dat = fromJSON(url)
dat2 = setDT(dat$data$rows)[,.(market='stock', exchange=exchange, board=NA, symbol, name, sector, industry, cap_market=marketCap, ipoyear, country)]
return(dat2)
}
md_stock_symbol_exchange = function(XCHG=NULL, print_step=1L) {
exchange = NULL
exchange_list = c('sse','szse', 'hkex', "amex", "nasdaq", "nyse")
while ((is.null(XCHG) || length(XCHG)==0)) {
XCHG = select_rows_df(dt = setDT(list(exchange = exchange_list)), column = 'exchange')[,exchange]
}
XCHG = intersect(tolower(XCHG), exchange_list)
i = 1
exc_len = length(XCHG)
dat_lst = NULL
if (any(c("sse", "szse") %in% XCHG)) {
temp = md_stock_symbol_163()[exchange %in% XCHG]
exc = intersect(c("sse", "szse"),XCHG)
for (e in exc) {
if ((print_step > 0) & (i %% print_step == 0)) cat(sprintf('%s %s\n', paste0(format(c(i, exc_len)), collapse = '/'), e))
i = i+1
dat_lst[[e]] = temp[exchange == e]
}
}
if (any("hkex" %in% XCHG)) {
exc = intersect(c('hkex'),XCHG)
for (e in exc) {
if ((print_step > 0) & (i %% print_step == 0)) cat(sprintf('%s %s\n', paste0(format(c(i, exc_len)), collapse = '/'), e))
i = i+1
dat_lst[[e]] = md_stock_symbol_hk()
}
}
if (any(c("amex", "nasdaq", "nyse") %in% XCHG)) {
exc = intersect(c("amex", "nasdaq", "nyse"),XCHG)
for (e in exc) {
if ((print_step > 0) & (i %% print_step == 0)) cat(sprintf('%s %s\n', paste0(format(c(i, exc_len)), collapse = '/'), e))
i = i+1
dat_lst[[e]] = md_stock_symbol_nasdaq(e)
}
}
return(dat_lst)
}
stk_syb_idx1 = function(syb) {
exchange = NULL
url = sprintf("http://www.csindex.com.cn/uploads/file/autofile/cons/%scons.xls",syb)
dat = load_read_xl(url)
setDT(dat)
setnames(dat, c("date","index_symbol","index_name","index_name_en","stock_symbol","stock_name", "stock_name_en","exchange"))
dat = dat[, exchange := ifelse(exchange=="SHH","sse", ifelse(exchange=="SHZ","szse", exchange))]
return(dat)
}
md_stock_symbol_index = function(symbol, print_step=1L) {
dat_list = load_dat_loop(symbol, "stk_syb_idx1", args = list(), print_step=print_step)
return(dat_list)
}
md_stock_symbol = function(exchange=NULL, index=NULL) {
if (is.null(index)) {
dt = md_stock_symbol_exchange(exchange)
} else {
dt = md_stock_symbol_index(index)
}
return(dt)
} |
get.partdep.x <- function(pmethod, x, y, n.apartdep, grid.levels, pred.names)
{
if(pmethod != "partdep" && pmethod != "apartdep")
return(NA)
partdep.x <-
if(pmethod == "partdep" || nrow(x) <= n.apartdep)
x
else {
stopifnot(nrow(x) == NROW(y))
index <- order(as.numeric(y), sample.int(NROW(y)))
index <- index[seq.int(1, nrow(x), length.out=n.apartdep)]
x[index, , drop=FALSE]
}
if(!is.null(grid.levels)) {
check.grid.levels.arg(x, grid.levels, pred.names)
for(ipred in seq_len(ncol(x))) {
grid.val <- get.fixed.gridval.for.partdep(x[[ipred]], ipred,
pred.names[ipred], grid.levels)
if(!is.na(grid.val))
partdep.x[[ipred]] <- grid.val
}
}
partdep.x
}
check.grid.class <- function(x1, xgrid, predname)
{
class.x1 <- class(x1)[1]
class.xgrid <- class(xgrid)[1]
if(!(class.x1 == class.xgrid ||
(class.x1 == "integer" && class.xgrid == "numeric"))) {
cat("\n")
stopf("class(%s) == \"%s\" but class(xgrid) == \"%s\"",
predname, class.x1, class.xgrid)
}
}
degree1.partdep.yhat <- function(object,
type, nresponse, pmethod, inverse.func, trace,
partdep.x, xframe, ipred, pred.names, resp.levs,
...)
{
trace0(trace, "calculating %s for %s%s",
pmethod, pred.names[ipred], if(trace >= 2) "\n" else " ")
xgrid <- xframe[[ipred]]
nxgrid <- length(xgrid)
stopifnot(nxgrid >= 1)
check.grid.class(partdep.x[[ipred]], xgrid, pred.names[ipred])
expanded.partdep.x <- partdep.x[rep(1:nrow(partdep.x), times=nxgrid), , drop=FALSE]
expanded.partdep.x[[ipred]] <- rep(xgrid, each=nrow(partdep.x))
yhats <- plotmo_predict(object, expanded.partdep.x, nresponse,
type, resp.levs, trace, inverse.func, ...)$yhat
trace0(trace, "\n")
colMeans(matrix(yhats, ncol=nxgrid), na.rm=TRUE)
}
degree2.partdep.yhat <- function(object,
type, nresponse, pmethod, inverse.func, trace,
partdep.x, x1grid, ipred1, x2grid, ipred2,
pred.names, resp.levs,
...)
{
trace0(trace, "calculating %s for %s:%s %s",
pmethod, pred.names[ipred1], pred.names[ipred2],
if(trace >= 0 && trace < 2) "0" else if(trace >= 2) "\n")
n1 <- length(x1grid)
stopifnot(n1 >= 1)
check.grid.class(partdep.x[[ipred1]], x1grid, pred.names[ipred1])
n2 <- length(x2grid)
stopifnot(n2 >= 1)
check.grid.class(partdep.x[[ipred2]], x2grid, pred.names[ipred2])
yhat <- matrix(0., nrow=n1, ncol=n2)
pacifier.i <- n1 / 10
pacifier.digit <- -1
expanded.partdep.x <- partdep.x[rep(1:nrow(partdep.x), times=n2), , drop=FALSE]
for(i in 1:n1) {
while(pacifier.i < i) {
if(trace >= 0 && pacifier.digit != floor(10 * pacifier.i / n1)) {
pacifier.digit <- floor(10 * pacifier.i / n1)
cat(pacifier.digit)
}
pacifier.i <- pacifier.i + n1 / 10
}
expanded.partdep.x[[ipred1]] <- x1grid[i]
expanded.partdep.x[[ipred2]] <- rep(x2grid, each=nrow(partdep.x))
yhats <- plotmo_predict(object, expanded.partdep.x, nresponse,
type, resp.levs, trace, inverse.func, ...)$yhat
yhats <- matrix(yhats, ncol=n2)
yhat[i,] <- colMeans(yhats, na.rm=TRUE)
if(trace > 0)
trace <- 0
}
trace0(trace, "0\n")
matrix(yhat, nrow=n1 * n2, ncol=1)
} |
GSTTest <- function(x, ...) UseMethod("GSTTest")
GSTTest.default <-
function(x,
g,
dist=c("Chisquare", "KruskalWallis"),
...)
{
if (is.list(x)) {
if (length(x) < 2L)
stop("'x' must be a list with at least 2 elements")
DNAME <- deparse(substitute(x))
x <- lapply(x, function(u) u <- u[complete.cases(u)])
k <- length(x)
l <- sapply(x, "length")
if (any(l == 0))
stop("all groups must contain data")
g <- factor(rep(1 : k, l))
if(is.null(x$dist)){
dist <- "Chisquare"
} else {
dist <- x$dist
}
x <- unlist(x)
}
else {
if (length(x) != length(g))
stop("'x' and 'g' must have the same length")
DNAME <- paste(deparse(substitute(x)), "and",
deparse(substitute(g)))
OK <- complete.cases(x, g)
x <- x[OK]
g <- g[OK]
if (!all(is.finite(g)))
stop("all group levels must be finite")
g <- factor(g)
k <- nlevels(g)
if (k < 2)
stop("all observations are in the same group")
}
dist <- match.arg(dist)
ord <- order(x)
gord <- g[ord]
n <- tapply(x[ord], gord, length)
N <- sum(n)
a <- rep(seq(ceiling(N / 4)), each=2)
b <- rep(c(0, 1), ceiling(N)/4)
suppressWarnings(
rk.up <- c(1, (a * 4 + b))[1:ceiling(N / 2)]
)
suppressWarnings(
rk.down <- rev(c(a * 4 + b - 2)[1:floor(N / 2)])
)
r <- c(rk.up, rk.down)
T <- tapply(r, gord, sum)
if(sum(T) != N * (N + 1) /2) {
warning("Does not sum up to check sum!")
}
C <- gettiesKruskal(x)
if (C != 1) warning("Ties are present. Quantiles were corrected for ties.")
H <- (12 / (N * (N + 1))) *
sum(T * T / n) - 3 * (N + 1)
PSTAT <- H / C
if (dist == "Chisquare"){
PARMS <- k - 1
PVAL <- pchisq(PSTAT, df = PARMS, lower.tail = FALSE)
names(PSTAT) <- "chi-squared"
names(PARMS) <- "df"
} else if (dist == "KruskalWallis"){
U <- sum(1 / n)
c <- k
PARMS <- c(c, U, N)
PVAL <- pKruskalWallis(PSTAT, c = c,
N = N, U = U,
lower.tail = FALSE)
names(PSTAT) <- "H"
names(PARMS) <- c("k", "U", "N")
}
METHOD <- paste("Generalized Siegel-Tukey test of homogeneity of scales")
ans <- list(method = METHOD, data.name = DNAME, p.value = PVAL,
statistic = PSTAT, parameter = PARMS)
class(ans) <- "htest"
ans
}
GSTTest.formula <-
function(formula, data, subset, na.action,
dist=c("Chisquare", "KruskalWallis"),
...)
{
mf <- match.call(expand.dots=FALSE)
m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1L]] <- quote(stats::model.frame)
if(missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
mf <- eval(mf, parent.frame())
if(length(mf) > 2L)
stop("'formula' should be of the form response ~ group")
DNAME <- paste(names(mf), collapse = " by ")
dist <- match.arg(dist)
names(mf) <- NULL
y <- do.call("GSTTest", c(as.list(mf), dist = dist))
y$data.name <- DNAME
y
} |
cluster_heatmap<-function(data){
string_db<-STRINGdb::STRINGdb$new(version="11.0",species=9606,score_threshold=700)
db_interactors<-string_db$map(data,"Symbol",removeUnmappedRows = FALSE)
db_interactors$"Interactor_list"<-lapply(db_interactors$"STRING_id", function(x){string_db$get_neighbors(x)})
matrix<-matrix(0, length(db_interactors$"Symbol"),length(db_interactors$"Symbol"))
colnames(matrix)<-db_interactors$"Symbol"
rownames(matrix)<-db_interactors$"Symbol"
interactor_list<-list()
for(index in seq(1:nrow(db_interactors))){
id_list<-unlist(db_interactors[index,"Interactor_list"])
symbol<-db_interactors[index,"Symbol"]
if(any(db_interactors$"STRING_id"%in%id_list)){
matches<-db_interactors$"STRING_id"[db_interactors$"STRING_id"%in%id_list]
for(match in matches){
match_symbol<-db_interactors[which(db_interactors$"STRING_id"==match),"Symbol"]
interactor_list[[symbol]]<-match_symbol
matrix[symbol, match_symbol]<-1
}
} }
stats::heatmap(matrix, scale = "none", col = c("lightyellow","red"), main = "Interactor heatmap for all genes")
interactor_matrix<-matrix[names(interactor_list),unique(unlist(interactor_list))]
stats::heatmap(interactor_matrix, scale = "none", col = c("lightyellow","red"), main = "Interactor heatmap")
} |
fitRMU_MHmcmc <- function(result=stop("An output from fitRMU() must be provided"),
n.iter=10000,
parametersMCMC=stop("A parameter set from fitRMU_MHmcmc_p() must be provided"),
n.chains = 1,
n.adapt = 0, thin=1,
adaptive=FALSE,
adaptive.lag=500,
adaptive.fun=function(x) {ifelse(x>0.234, 1.3, 0.7)},
trace=FALSE,
traceML=FALSE,
intermediate=NULL, filename="intermediate.Rdata", previous=NULL) {
if (is.character(previous)) {
itr <- NULL
load(previous)
previous <- itr
rm(itr)
print("Continue previous mcmc run")
}
if (class(result)!="fitRMU") {
warning("An output from fitRMU() must be provided")
return()
}
fun <- getFromNamespace(".LikelihoodRMU", ns="phenology")
print(parametersMCMC)
out <- MHalgoGen(n.iter=n.iter, parameters=parametersMCMC, n.chains = n.chains, n.adapt = n.adapt,
thin=thin, trace=trace, traceML=traceML, likelihood=fun,
adaptive = adaptive, adaptive.fun = adaptive.fun, adaptive.lag = adaptive.lag,
fixed.parameters=result$fixed.parameters.computing,
RMU.data=result$RMU.data, model.trend=result$model.trend,
model.SD=result$model.SD,
colname.year=result$colname.year, RMU.names=result$RMU.names)
fin <- try(summary(out), silent=TRUE)
if (class(fin)=="try-error") {
lp <- rep(NA, nrow(out$parametersMCMC$parameters))
names(lp) <- rownames(out$parametersMCMC$parameters)
out <- c(out, SD=list(lp))
} else {
out <- c(out, SD=list(fin$statistics[,"SD"]))
}
class(out) <- "mcmcComposite"
return(out)
} |
visuOutGP <- function (ogp, selecmod = NULL, id = 1,
prioMinMax = 'data', opt3D = 'TRUE',
maxPages = NULL, seeEq = 1)
{
if (is.null(selecmod)) {
nmod <- sum(ogp$okMod == id)
cat(nmod, 'models identified as id = ', id, ":", "\n")
cat(which(ogp$okMod == 1), "\n")
which(ogp$okMod == id)
seemod <- which(ogp$okMod == id)
}
else {
nmod <- length(selecmod)
seemod <- selecmod
}
if (is.null(selecmod)) {
maxPages = 4
}
nVar <- dim(ogp$models[[1]])[2]
pMax <- dim(ogp$models[[1]])[1]
dMax <- p2dMax(nVar, pMax)
modInfo <- matrix(0, ncol = 3, nrow = 0)
IstepMax <- NULL
Np <- NULL
for (imod in 1:length(ogp$okMod) ) {
block <- paste("IstepMax <- dim(ogp$stockoutreg$model", imod, ")[1]", sep="")
eval((parse(text = block)))
block <- paste("Np <- sum(ogp$models$mToTest", imod, "!=0)", sep="")
eval((parse(text = block)))
if (!is.null(IstepMax)) {
modInfo = rbind(modInfo, c(ogp$okMod[imod], Np, IstepMax))
}
else {
modInfo = rbind(modInfo, c(ogp$okMod[imod], Np, 0))
}
}
fdat <- ogp$filtdata
for (i in 1:dim(ogp$filtdata)[2]) {
fdat[ogp$Wfiltdata==0,i] <- NaN
}
firstOk <- which(is.nan(ogp$Wfiltdata)==0)[1]
if (nmod <= 24) {
dev.new()
op <- par(mfrow = c(4, 6), pty = "s")
if (nmod <= 20) op <- par(mfrow = c(4, 5), pty = "s")
if (nmod <= 18) op <- par(mfrow = c(3, 6), pty = "s")
if (nmod <= 15) op <- par(mfrow = c(3, 5), pty = "s")
if (nmod <= 12) op <- par(mfrow = c(3, 4), pty = "s")
if (nmod <= 9) op <- par(mfrow = c(3, 3), pty = "s")
if (nmod <= 6) op <- par(mfrow = c(3, 2), pty = "m")
if (nmod <= 4) op <- par(mfrow = c(2, 2), pty = "m")
if (nmod == 2) op <- par(mfrow = c(2, 1), pty = "m")
if (nmod == 1) op <- par(mfrow = c(1, 1), pty = "m")
for (imod in seemod) {
block0 <- paste("Model ", imod, " (Np = ", modInfo[imod, 2], ")", sep="")
if (prioMinMax == 'data') {
plot(fdat[,1], fdat[,2], type='l', col='green',
xlab='X1', ylab='X2', main = block0)
lines(fdat[firstOk,1], fdat[firstOk,2],
type='p', col='green',
xlab='X1', ylab='X2', main = block0, cex = 1.2)
block <- paste(
"lines(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], type='l', col='red')", sep="")
eval((parse(text = block)))
block <- paste(
"lines(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], type='p', cex = 1.2, col='red')", sep="")
eval((parse(text = block)))
if (opt3D) {
plot3d(fdat[,1], fdat[,2], fdat[,3], type='l', col='green',
xlab='X1', ylab='X2', zlab='X3', main = block0)
plot3d(fdat[firstOk,1], fdat[firstOk,2], fdat[firstOk,3],
type='p', size = 5, col='green',
xlab='X1', ylab='X2', zlab='X3', main = block0, add = TRUE)
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], ogp$stockoutreg$model", imod,
"[,4], type='l', col='red', add = TRUE)", sep="")
eval((parse(text = block)))
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], ogp$stockoutreg$model", imod,
"[1,4], type='p', size = 5, col='red', add = TRUE)", sep="")
eval((parse(text = block)))
}
}
else if (prioMinMax == 'dataonly') {
plot(fdat[,1], fdat[,2], type='l', col='green',
xlab='X1', ylab='X2', main = block0)
lines(fdat[firstOk,1], fdat[firstOk,2],
type='p', col='green',
xlab='X1', ylab='X2', main = block0, cex = 1.2)
if (opt3D) {
plot3d(fdat[,1], fdat[,2], fdat[,3],
type='l', col='green',
xlab='X1', ylab='X2', zlab='X3', main = block0)
plot3d(fdat[firstOk,1], fdat[firstOk,2], fdat[firstOk,3],
type='p', size = 5, col='green',
xlab='X1', ylab='X2', zlab='X3', main = block0)
}
}
else if (prioMinMax == 'model') {
block <- paste(
"plot(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], type='l', col='red', xlab='X1', ylab='X2', main = block0)", sep="")
eval((parse(text = block)))
block <- paste(
"lines(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], type='p', cex = 1.2, col='red', xlab='X1', ylab='X2', main = block0)", sep="")
eval((parse(text = block)))
lines(fdat[,1], fdat[,2], type='l', col='green')
lines(fdat[firstOk,1], fdat[firstOk,2],
type='p', col='green', cex = 1.2)
if (opt3D) {
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], ogp$stockoutreg$model", imod,
"[,4], type='l', col='red', xlab='X1', ylab='X2', zlab='X3', main = block0)", sep="")
eval((parse(text = block)))
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], ogp$stockoutreg$model", imod,
"[1,4], type='p', size = 5, col='red', xlab='X1', ylab='X2', zlab='X3', main = block0, add = TRUE)", sep="")
eval((parse(text = block)))
plot3d(fdat[,1], fdat[,2], fdat[,3],
type='l', col='green', add = TRUE)
plot3d(fdat[firstOk,1], fdat[firstOk,2], fdat[firstOk,3],
type='p', size = 5, col='green', add = TRUE)
}
}
else if (prioMinMax == 'modelonly') {
block <- paste(
"plot(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], type='l', col='red', xlab='X1', ylab='X2', main = block0)", sep="")
eval((parse(text = block)))
block <- paste(
"plot(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], type='p', cex = 1.2, col='red', xlab='X1', ylab='X2', main = block0)", sep="")
eval((parse(text = block)))
if (opt3D) {
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[,2], ogp$stockoutreg$model", imod,
"[,3], ogp$stockoutreg$model", imod,
"[,4], type='l', col='red', xlab='X1', ylab='X2', zlab='X3', main = block0)", sep="")
eval((parse(text = block)))
block <- paste(
"plot3d(ogp$stockoutreg$model", imod,
"[1,2], ogp$stockoutreg$model", imod,
"[1,3], ogp$stockoutreg$model", imod,
"[1,4], type='p', size = 5, col='red', xlab='X1', ylab='X2', zlab='X3', main = block0, add = TRUE)", sep="")
eval((parse(text = block)))
}
}
}
}
else {
if (ceiling(nmod / 24) > maxPages) {
for (iPage in 1:maxPages) {
visuOutGP(ogp,
selecmod = which(ogp$okMod == 1)[((iPage-1)*24+1):((iPage)*24)],
seeEq = seeEq)
}
warning('Too many models nmod = ', nmod,'. By default the fonction ',
'can display four pages 24 models each (that is nmod <= 96).',
'Too have more page, please use the option maxPages = ',
ceiling(nmod / 24))
}
else {
maxPages <- ceiling(nmod / 24)
for (iPage in 1:maxPages) {
if (iPage < maxPages) {
visuOutGP(ogp,
selecmod = which(ogp$okMod == 1)[((iPage-1)*24+1):((iPage)*24)],
seeEq = seeEq)
}
else if (iPage == maxPages) {
visuOutGP(ogp,
selecmod = which(ogp$okMod == 1)[((iPage-1)*24+1):nmod],
seeEq = seeEq)
}
}
}
}
if (seeEq == 1) {
cat('Equations of', "\n")
ic <- NULL
for (imod in seemod) {
block <- paste("
" (Np = ", modInfo[imod,2],
"):", sep="")
cat(block, "\n")
block <- paste("ic <- ogp$stockoutreg$model", imod,
"[1,]", sep="")
eval((parse(text = block)))
cat("
block <- paste(ic, sep="")
cat(block, "\n")
cat("
block <- paste(
"visuEq(ogp$models$model", imod,
")", sep="")
eval((parse(text = block)))
}
}
invisible(t(modInfo))
} |
show_connection <- function() {
cat("url =", get("url", envir = atsdEnv))
cat("\nuser =", get("user", envir = atsdEnv))
cat("\npassword =", get("password", envir = atsdEnv))
verify <- get("verify", envir = atsdEnv)
if (is.na(verify)) {
cat("\nverify = NA")
} else if (verify) {
cat("\nverify = yes")
} else {
cat("\nverify = no")
}
cat("\nencryption =", get("encryption", envir = atsdEnv))
} |
seriesExtent <- function(s, type = c('vector', 'raster'), timeout = 60) {
if(!requireNamespace('rgdal', quietly=TRUE))
stop('please install the `rgdal` package', call.=FALSE)
type <- match.arg(type)
s <- gsub(pattern=' ', replacement='_', x = tolower(s), fixed = TRUE)
res <- switch(
type,
vector = {.vector_extent(s, timeout = timeout)},
raster = {.raster_extent(s, timeout = timeout)}
)
return(res)
}
.vector_extent <- function(s, timeout) {
u <- URLencode(paste0('https://casoilresource.lawr.ucdavis.edu/series-extent-cache/json/', s, '.json'))
tf <- tempfile(fileext='.json')
res <- tryCatch(
suppressWarnings(
download.file(url=u, destfile=tf, extra=c(timeout = timeout), quiet=TRUE)
),
error = function(e) {e}
)
if(inherits(res, 'error')){
message('no data returned')
return(NULL)
}
x <- rgdal::readOGR(dsn=tf, verbose=FALSE)
unlink(tf)
x <- spChFIDs(x, as.character(x$series))
return(x)
}
.raster_extent <- function(s, timeout) {
u <- URLencode(paste0('https://casoilresource.lawr.ucdavis.edu/series-extent-cache/grid/', s, '.tif'))
tf <- tempfile(fileext='.tif')
res <- tryCatch(
suppressWarnings(
download.file(url = u, destfile = tf, extra = c(timeout = timeout), quiet=TRUE, mode = 'wb')
),
error = function(e) {e}
)
if(inherits(res, 'error')){
message('no data returned')
return(NULL)
}
x <- suppressWarnings(
raster(tf, verbose=FALSE)
)
x <- readAll(x)
names(x) <- gsub(pattern='_', replacement=' ', x = s, fixed = TRUE)
unlink(tf)
return(x)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
eval = "dplyr" %in% rownames(installed.packages())
)
library(ftExtra)
ft <- iris[1:2, ] %>% as_flextable
ft
ft %>% separate_header()
ft %>% separate_header(sep = "e")
ft %>% span_header() |
pseudotime.knetl <- function (x = NULL,
dist.method = "euclidean",
k = 5,
abstract = TRUE,
data.type = "pca",
dims = 1:20,
conds.to.plot = NULL,
my.layout = "layout_with_fr",
node.size = 10,
cluster.membership = FALSE,
interactive = TRUE,
node.colors = NULL,
edge.color = "gray",
out.name = "Pseudotime.Abstract.KNetL",
my.seed = 1
) {
start_time1 <- Sys.time()
if(data.type == "pca") {
DATA = (t([email protected]))[dims, ]
message(paste("Getting PCA data"))
}
if(data.type == "umap") {
DATA <- t([email protected][1:2])
message(paste("Getting UMAP data"))
}
if(data.type == "tsne") {
DATA <- t([email protected])
message(paste("Getting tSNE data"))
}
MYtitle = "Pseudotime Abstract KNetL (PAK)"
MyClusters <- [email protected]
if (!is.null(conds.to.plot)) {
Conditions <- data.frame(do.call('rbind', strsplit(as.character(colnames(DATA)),'_',fixed=TRUE)))[1]
Conditions <- as.character(as.matrix(Conditions))
Conditions <- as.data.frame(cbind(colnames(DATA),Conditions))
colnames(Conditions) <- c("row","conds")
Conditions <- subset(Conditions, Conditions$conds %in% conds.to.plot)
Conditions <- as.character(Conditions$row)
DATA <- as.data.frame(t(DATA))
DATA <- subset(DATA, rownames(DATA) %in% Conditions)
DATA <- t(DATA)
MYtitle = paste(MYtitle," (",conds.to.plot,")", sep="")
MyClusters <- subset(MyClusters, rownames(MyClusters) %in% Conditions)
}
message(paste(" Calculating", dist.method,"distance ..."))
My.distances = as.matrix(dist(t(DATA),dist.method))
ncells=dim(DATA)[2]
cell.num = k
pb <- progress_bar$new(total = ncells,
format = "[:bar] :current/:total (:percent) :elapsedfull eta: :eta",
clear = FALSE, width= 60)
message(paste(" Finding",cell.num, "neighboring cells per cell ..."))
KNN1 = lapply(1:ncells, function(findKNN){
pb$tick()
MyOrd <- order(My.distances[,findKNN])[2:cell.num]
MyOrd.IDs <- row.names(My.distances)[MyOrd]
MyOrd.IDs.clust <- as.numeric(as.matrix(subset(MyClusters, row.names(MyClusters) %in% MyOrd.IDs)))
MyDist <- My.distances[MyOrd]
MyRoot <- rep(findKNN,cell.num-1)
MYRoot.ID <- colnames(My.distances)[findKNN]
MYRoot.IDs <- rep(MYRoot.ID,length(MyRoot))
MYRoot.clust <- as.numeric(as.matrix(subset(MyClusters, row.names(MyClusters) %in% MYRoot.ID)))
MYRoot.clusts <- rep(MYRoot.clust,length(MyRoot))
data <- cbind(MyRoot,MyOrd,MyDist,MYRoot.IDs,MyOrd.IDs,MYRoot.clusts,MyOrd.IDs.clust)
colnames(data)<- c("from","to","weight","from.id","to.id","from.clust","to.clust")
data <- as.data.frame(data)
})
if (abstract == TRUE) {
message(" Generating abstract graph ...")
data <- do.call("rbind", KNN1)
df <- as.data.frame(table(data[6:7]))
colnames(df) <- c("from","to","weight")
df <- subset(df, df$weight > 5)
gg <- graph.data.frame(df, directed=FALSE)
message(" Simplifying graph ...")
gg <- simplify(gg)
}
if (abstract == FALSE) {
message(" Generating graph ...")
data <- do.call("rbind", KNN1)
df <- as.data.frame(data[1:3])
colnames(df) <- c("from","to","weight")
gg <- graph.data.frame(df, directed=FALSE)
}
if (is.null(node.colors)) {
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
n = max(MyClusters$clusters)
colbar = gg_color_hue(n)
} else {
colbar = node.colors
}
if (abstract == FALSE) {
colbar <- colbar[MyClusters$clusters]
}
MYedgeWith <- log2(as.numeric(E(gg)$weight) + 1)
message("Drawing layout and generating plot ...")
if (interactive == TRUE) {
graph = gg
set.seed(my.seed)
L <- get(my.layout)(graph)
vs <- V(graph)
es <- as.data.frame(get.edgelist(graph))
Ne <- length(es[1]$V1)
Xn <- L[,1]
Yn <- L[,2]
edge_shapes <- list()
for(i in 1:Ne) {
v0 <- es[i,]$V1
v1 <- es[i,]$V2
edge_shape = list(
type = "line",
line = list(color = rep(edge.color),
width = MYedgeWith[i]),
x0 = Xn[match(v0,names(vs))],
y0 = Yn[match(v0,names(vs))],
x1 = Xn[match(v1,names(vs))],
y1 = Yn[match(v1,names(vs))],
opacity = 0.5,
layer="below"
)
edge_shapes[[i]] <- edge_shape}
if (abstract == FALSE) {
network <- plot_ly(type = "scatter",
x = Xn,
y = Yn,
mode = "markers+text",
opacity = 1,
marker = list(size = (node.size/2), color = colbar),
)
network <- layout(network,shapes = edge_shapes,
xaxis = list(title = "", showgrid = FALSE,
showticklabels = FALSE, zeroline = FALSE),
yaxis = list(title = "", showgrid = FALSE,
showticklabels = FALSE, zeroline = FALSE)) %>%
layout(plot_bgcolor = "white") %>%
layout(paper_bgcolor = "white") %>%
layout(title = MYtitle)
}
if (abstract == TRUE) {
network <- plot_ly(type = "scatter",
x = Xn,
y = Yn,
mode = "markers+text",
opacity = 1,
marker = list(size = (node.size * 2), color = colbar),
text = names(vs),)
network <- layout(network,shapes = edge_shapes,
xaxis = list(title = "", showgrid = FALSE,
showticklabels = FALSE, zeroline = FALSE),
yaxis = list(title = "", showgrid = FALSE,
showticklabels = FALSE, zeroline = FALSE)) %>%
layout(plot_bgcolor = "white") %>%
layout(paper_bgcolor = "white") %>%
layout(title = MYtitle)
}
OUT.PUT <- paste(out.name, ".html", sep="")
htmlwidgets::saveWidget(ggplotly(network), OUT.PUT)
} else {
rm(.Random.seed, envir=.GlobalEnv)
set.seed(my.seed)
if (cluster.membership == TRUE) {
ceb <- cluster_fast_greedy(as.undirected(gg))
return(
plot(ceb,gg, layout=get(my.layout),
vertex.size=node.size,
vertex.color=colbar,
edge.width=MYedgeWith,
main = MYtitle,
edge.color=edge.color))
}
if (cluster.membership == FALSE) {
if (abstract == FALSE) {
return(
plot(gg, layout=layout_nicely,
vertex.size=(node.size/2),
vertex.label=NA,
margin=0,
vertex.color=colbar))
}
return(
plot(gg, layout=get(my.layout),
vertex.size=node.size,
vertex.color=colbar,
edge.width=MYedgeWith,
main = MYtitle,
edge.color=edge.color))
}
}
} |
corrPartClass <- R6::R6Class(
"corrPartClass",
inherit = corrPartBase,
private = list(
.init=function() {
private$.initCorrTable()
},
.run=function() {
results <- private$.compute()
private$.populateCorrTable(results)
},
.compute = function() {
vars <- self$options$vars
nVars <- length(vars)
hyp <- self$options$hypothesis
controls <- self$options$controls
type <- self$options$type
results <- list()
if (nVars > 1) {
for (i in 1:nVars) {
rowVar <- vars[[i]]
for (j in 1:nVars) {
if (j >= i)
next
colVar <- vars[[j]]
resLst <- private$.test(rowVar, colVar, controls, type, hyp)
results[[rowVar]][[colVar]] <- resLst[, 1]
if (type == 'semi')
results[[colVar]][[rowVar]] <- resLst[, 2]
}
}
}
return(results)
},
.initCorrTable = function() {
matrix <- self$results$matrix
vars <- self$options$vars
nVars <- length(vars)
type <- self$options$type
for (i in seq_along(vars)) {
var <- vars[[i]]
matrix$addColumn(name=paste0(var, '[r]'), title=var,
type='number', format='zto', visible='(pearson)')
matrix$addColumn(name=paste0(var, '[rp]'), title=var,
type='number', format='zto,pvalue', visible='(pearson && sig)')
matrix$addColumn(name=paste0(var, '[rho]'), title=var,
type='number', format='zto', visible='(spearman)')
matrix$addColumn(name=paste0(var, '[rhop]'), title=var,
type='number', format='zto,pvalue', visible='(spearman && sig)')
matrix$addColumn(name=paste0(var, '[tau]'), title=var,
type='number', format='zto', visible='(kendall)')
matrix$addColumn(name=paste0(var, '[taup]'), title=var,
type='number', format='zto,pvalue', visible='(kendall && sig)')
matrix$addColumn(name=paste0(var, '[n]'), title=var,
type='integer', visible='(n)')
}
for (i in seq_along(vars)) {
var <- vars[[i]]
values <- list()
if (type != 'semi') {
for (j in seq(i, nVars)) {
v <- vars[[j]]
values[[paste0(v, '[r]')]] <- ''
values[[paste0(v, '[rp]')]] <- ''
values[[paste0(v, '[rho]')]] <- ''
values[[paste0(v, '[rhop]')]] <- ''
values[[paste0(v, '[tau]')]] <- ''
values[[paste0(v, '[taup]')]] <- ''
values[[paste0(v, '[n]')]] <- ''
}
}
values[[paste0(var, '[r]')]] <- '\u2014'
values[[paste0(var, '[rp]')]] <- '\u2014'
values[[paste0(var, '[rho]')]] <- '\u2014'
values[[paste0(var, '[rhop]')]] <- '\u2014'
values[[paste0(var, '[tau]')]] <- '\u2014'
values[[paste0(var, '[taup]')]] <- '\u2014'
values[[paste0(var, '[n]')]] <- '\u2014'
matrix$setRow(rowKey=var, values)
}
hyp <- self$options$hypothesis
flag <- self$options$flag
controls <- self$options$controls
nControls <- length(controls)
if (length(controls) > 0) {
matrix$setNote('controls', jmvcore::format('controlling for {}', listItems(controls)))
}
if (hyp == 'pos') {
matrix$setNote('hyp', 'H\u2090 is positive correlation')
if (flag)
matrix$setNote('flag', '* p < .05, ** p < .01, *** p < .001, one-tailed')
}
else if (hyp == 'neg') {
matrix$setNote('hyp', 'H\u2090 is negative correlation')
if (flag)
matrix$setNote('flag', '* p < .05, ** p < .01, *** p < .001, one-tailed')
}
else {
matrix$setNote('hyp', NULL)
if (flag)
matrix$setNote('flag', '* p < .05, ** p < .01, *** p < .001')
}
if ( ! flag)
matrix$setNote('flag', NULL)
if (type == 'part' && nControls > 0) {
titleMatrix <- "Partial Correlation"
} else if (type == 'semi' && nControls > 0) {
titleMatrix <- "Semipartial Correlation"
matrix$setNote('part', 'variation from the control variables is only removed from the variables in the columns')
} else {
titleMatrix <- "Correlation"
}
pearson <- self$options$pearson
spearman <- self$options$spearman
kendall <- self$options$kendall
n <- self$options$n
sig <- self$options$sig
if ( ! sum(pearson, spearman, kendall) > 1 && ! n && ! sig) {
if (pearson)
titleMatrix <- jmvcore::format("{} - Pearson's r", titleMatrix)
else if (spearman)
titleMatrix <- jmvcore::format("{} - Spearman's rho", titleMatrix)
else if (kendall)
titleMatrix <- jmvcore::format("{} - Kendall's Tau B", titleMatrix)
}
matrix$setTitle(titleMatrix)
},
.populateCorrTable = function(results) {
matrix <- self$results$matrix
vars <- self$options$vars
nVars <- length(vars)
flag <- self$options$flag
type <- self$options$type
if (nVars > 1) {
for (i in 1:nVars) {
rowVarName <- vars[[i]]
for (j in 1:nVars) {
if (i == j || (type != 'semi' && j > i))
next
values <- list()
colVarName <- vars[[j]]
result = results[[rowVarName]][[colVarName]]
values[[paste0(colVarName, '[r]')]] <- result$r
values[[paste0(colVarName, '[rp]')]] <- result$rp
values[[paste0(colVarName, '[rho]')]] <- result$rho
values[[paste0(colVarName, '[rhop]')]] <- result$rhop
values[[paste0(colVarName, '[tau]')]] <- result$tau
values[[paste0(colVarName, '[taup]')]] <- result$taup
values[[paste0(colVarName, '[n]')]] <- result$n
matrix$setRow(rowNo=i, values)
if (flag) {
if (result$rp < .001)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[r]'), '***')
else if (result$rp < .01)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[r]'), '**')
else if (result$rp < .05)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[r]'), '*')
if (result$rhop < .001)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[rho]'), '***')
else if (result$rhop < .01)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[rho]'), '**')
else if (result$rhop < .05)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[rho]'), '*')
if ( ! self$options$kendall)
{}
else if (result$taup < .001)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[tau]'), '***')
else if (result$taup < .01)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[tau]'), '**')
else if (result$taup < .05)
matrix$addSymbol(rowNo=i, paste0(colVarName, '[tau]'), '*')
}
}
}
}
},
.cleanData = function(var1, var2) {
dataRaw <- self$data
controls <- self$options$controls
data <- list()
data[[var1]] <- jmvcore::toNumeric(dataRaw[[var1]])
data[[var2]] <- jmvcore::toNumeric(dataRaw[[var2]])
for (control in controls) {
data[[control]] <- jmvcore::toNumeric(dataRaw[[control]])
}
attr(data, 'row.names') <- seq_len(length(data[[1]]))
attr(data, 'class') <- 'data.frame'
data <- jmvcore::naOmit(data)
return(data)
},
.test = function(var1, var2, controls, type, hyp) {
data <- private$.cleanData(var1, var2)
var1 <- data[[var1]]
var2 <- data[[var2]]
nSubj <- length(data[[1]])
nResR <- 1 + as.integer(type == 'semi')
nCtrV <- length(controls)
if (nCtrV == 0)
rdta <- cbind(var1, var2)
else
rdta = cbind(var1, var2, data[, controls])
results <- replicate(nResR, list(r = NaN, rp = 1, rho = NaN, rhop = 1,
tau = NaN, taup = 1, n = nSubj))
suppressWarnings({
for (method in c('pearson', 'spearman', 'kendall')) {
if (method == 'kendall' && !self$options$kendall)
next
try({
cvx <- cov(rdta, method = method)
if (det(cvx) < .Machine$double.eps)
icvx = ginv(cvx)
else
icvx = solve(cvx)
if (method == 'pearson')
statNm <- 'r'
else if (method == 'spearman')
statNm <- 'rho'
else if (method == 'kendall')
statNm <- 'tau'
if (type == 'part') {
results[[statNm, 1]] <- -cov2cor(icvx)[1, 2]
} else {
spcor <- -cov2cor(icvx) / sqrt(diag(cvx)) / sqrt(abs(diag(icvx) - t(t(icvx ^ 2) / diag(icvx))))
results[[statNm, 1]] <- spcor[1, 2]
results[[statNm, 2]] <- spcor[2, 1]
}
for (i in 1:nResR) {
if (hyp == 'corr') {
if (method == 'kendall') {
results[paste0(statNm, 'p'), i] <- 2 * pnorm(-abs(results[[statNm, i]] / sqrt(2 * (2 * (nSubj - nCtrV) + 5) / (9 * (nSubj - nCtrV) * (nSubj - 1 - nCtrV)))))
} else {
results[paste0(statNm, 'p'), i] <- 2 * pt(-abs(results[[statNm, i]] * sqrt((nSubj - 2 - nCtrV) / (1 - results[[statNm, i]] ^ 2))), (nSubj - 2 - nCtrV))
}
} else if ((hyp == 'neg' && results[statNm, i] < 0) || (hyp == 'pos' && results[statNm, i] > 0)) {
if (method == 'kendall') {
results[paste0(statNm, 'p'), i] <- pnorm(-abs(results[[statNm, i]] / sqrt(2 * (2 * (nSubj - nCtrV) + 5) / (9 * (nSubj - nCtrV) * (nSubj - 1 - nCtrV)))))
} else {
results[paste0(statNm, 'p'), i] <- pt(-abs(results[[statNm, i]] * sqrt((nSubj - 2 - nCtrV) / (1 - results[[statNm, i]] ^ 2))), (nSubj - 2 - nCtrV))
}
}
}
})
}
})
return(results)
}
)
) |
"mff" <-
function(a,b,m=nrow(a)) {
if (missing(a)) messagena("a")
if (missing(b)) messagena("b")
k <- ncol(a)
n <- ncol(b)
mda <- nrow(a)
mdb <- nrow(b)
mdc <- m
c <- matrix(single(1),mdc,n)
f.res <- .Fortran("mffz",
a=to.single(a),
b=to.single(b),
c=to.single(c),
m=to.integer(m),
k=to.integer(k),
n=to.integer(n),
mda=to.integer(mda),
mdb=to.integer(mdb),
mdc=to.integer(mdc))
list(c=f.res$c)
} |
context("Custom Vision training and prediction")
custvis_url <- Sys.getenv("AZ_TEST_CUSTOMVISION_URL")
custvis_key <- Sys.getenv("AZ_TEST_CUSTOMVISION_KEY")
storage <- Sys.getenv("AZ_TEST_STORAGE_ACCT")
custvis_sas <- Sys.getenv("AZ_TEST_CUSTOMVISION_SAS")
custvis_pred_resid <- Sys.getenv("AZ_TEST_CUSTOMVISION_PRED_RESID")
custvis_pred_url <- Sys.getenv("AZ_TEST_CUSTOMVISION_PRED_URL")
custvis_pred_key <- Sys.getenv("AZ_TEST_CUSTOMVISION_PRED_KEY")
if(custvis_url == "" || custvis_key == "" || storage == "" || custvis_sas == "" ||
custvis_pred_resid == "" || custvis_pred_url == "" || custvis_pred_key == "")
skip("Tests skipped: resource details not set")
projname <- paste0(sample(letters, 10, TRUE), collapse="")
cans <- paste0(storage, "customvision/", 1:5, ".jpg", custvis_sas)
cartons <- paste0(storage, "customvision/", 33:37, ".jpg", custvis_sas)
tags <- rep(c("can", "carton"), each=5)
endp <- customvision_training_endpoint(custvis_url, key=custvis_key)
test_that("Model training works",
{
expect_is(endp, c("customvision_training_endpoint", "cognitive_endpoint"))
expect_true(is_empty(list_projects(endp)))
proj <- create_classification_project(endp, projname, export_target="standard")
expect_is(proj, "classification_project")
Sys.sleep(2)
img_ids <- add_images(proj, c(cans, cartons), tags)
expect_type(img_ids, "character")
img_df <- list_images(proj, "tagged", as="dataframe")
expect_is(img_df, "data.frame")
img_df <- img_df[match(img_ids, img_df$id), ]
img_tags <- do.call(rbind.data.frame, img_df$tags)$tagName
expect_identical(img_tags, tags)
Sys.sleep(2)
mod <- train_model(proj)
expect_is(mod, "customvision_model")
show <- show_model(mod)
expect_type(show, "list")
perf <- show_training_performance(mod)
expect_type(perf, "list")
})
test_that("Training endpoint prediction and export works",
{
proj <- get_project(endp, projname)
mod <- get_model(proj)
expect_is(mod, "customvision_model")
pred1 <- predict(mod, cans)
expect_type(pred1, "character")
expect_identical(length(pred1), length(cans))
pred2 <- predict(mod, "../../inst/images/can1.jpg", type="prob")
expect_is(pred2, "matrix")
expect_type(pred2, "double")
expect_identical(dim(pred2), c(1L, 2L))
pred3 <- predict(mod, cans[1], type="list")
expect_is(pred3, "list")
expect_true(all(sapply(pred3, is.data.frame)))
expect_error(predict(mod, c(cans, "../../inst/images/can1.jpg")))
exp_url <- export_model(mod, "tensorflow lite", destfile=NULL)
expect_true(is_url(exp_url))
})
test_that("Prediction endpoint works",
{
proj <- get_project(endp, projname)
mod <- get_model(proj)
expect_silent(publish_model(mod, projname, custvis_pred_resid))
pred_endp <- customvision_prediction_endpoint(custvis_pred_url, key=custvis_pred_key)
expect_is(pred_endp, "customvision_prediction_endpoint")
svc <- classification_service(pred_endp, proj, projname)
pred1 <- predict(svc, cans)
expect_type(pred1, "character")
expect_identical(length(pred1), length(cans))
})
mod <- get_model(get_project(endp, projname))
unpublish_model(mod, confirm=FALSE)
delete_project(endp, projname, confirm=FALSE) |
setSelection.parameterDef <-
function(x,...){
temp<-list(...)
i<-NULL
j<-NULL
flag<-
foreach( i = temp, .combine=c ) %:% foreach(j=i, .combine=c ) %do% !(is.numeric(j) & length(j)==1)
if ( sum(flag)!=0)
stop("selection Parameter must be numeric scaler")
if (length(temp)==0)
stop("Nothing to set")
if (length(x$banker)!=0 && length(intersect(names(temp),names(x$banker)))>0 ){
warning("Same variables name as banker parameter. banker paramter will be removed")
x$banker <- x$banker[[names(x$banker) %in% names(temp)]]
}
repeated<-names(temp) %in% names(x$selection)
x$selection<-c(x$selection,temp[!repeated])
if (sum(repeated)>0){
warning(paste("\nOriginal value of ",names(temp)[repeated] ," is replaced"))
foreach (i = names(temp)[repeated]) %do% {
x$selection[[i]]<-temp[[i]]
}
}
x
} |
library(hamcrest)
expected <- c(-0x1.2763f05570461p+1 + 0x0p+0i, -0x1.1e5e72d18d226p+0 + -0x1.1239764b6b8d8p-2i,
0x1.745539cb5fd84p-1 + -0x1.72776d8b759cap-1i, 0x1.6252c67a642eap-4 + 0x1.05e7648c63537p-5i,
0x1.6a19246cbf78p-8 + 0x1.2414691fe3461p-2i, 0x1.9b5a98a9edb1cp-3 + -0x1.f475aacbfa0c4p-1i,
0x1.2aed1bc895087p-1 + 0x0p+0i, 0x1.9b5a98a9edb0cp-3 + 0x1.f475aacbfa0c4p-1i,
0x1.6a19246cbf74p-8 + -0x1.2414691fe3464p-2i, 0x1.6252c67a64306p-4 + -0x1.05e7648c63527p-5i,
0x1.745539cb5fd83p-1 + 0x1.72776d8b759ccp-1i, -0x1.1e5e72d18d226p+0 + 0x1.1239764b6b8d7p-2i
)
assertThat(stats:::fft(z=c(-0.160079704513844, -0.209564461138627, -0.252441123424499,
-0.14837468584751, -0.361860085340984, 0.0448021418465043, 0.117009480618862,
-0.0255479628574397, 0.134217864388091, -0.574117433515573, -0.338795004593553,
-0.532986415870729))
, identicalTo( expected, tol = 1e-6 ) ) |
MLCDF = function (ysA, ysB, pik_A, pik_B, domains_A, domains_B, xsA, xsB, xA, xB, ind_samA, ind_samB, ind_domA, ind_domB, N, N_ab = NULL, met = "linear", conf_level = NULL){
ysA <- as.data.frame(ysA)
ysB <- as.data.frame(ysB)
xsA <- as.matrix(xsA)
xsB <- as.matrix(xsB)
xA <- as.matrix(xA)
xB <- as.matrix(xB)
if (any(is.na(ysA)))
stop("There are missing values in sample from frame A.")
if (any(is.na(ysB)))
stop("There are missing values in sample from frame B.")
if (any(is.na(pik_A)))
stop("There are missing values in pikl from frame A.")
if (any(is.na(pik_B)))
stop("There are missing values in pikl from frame B.")
if (any(is.na(domains_A)))
stop("There are missing values in domains from frame A.")
if (any(is.na(domains_B)))
stop("There are missing values in domains from frame B.")
if (nrow(ysA) != length(pik_A) | nrow(ysA) != length(domains_A) | length(domains_A) != length(pik_A))
stop("Arguments from frame A have different sizes.")
if (nrow(ysB) != length(pik_B) | nrow(ysB) != length(domains_B) | length(domains_B) != length(pik_B))
stop("Arguments from frame B have different sizes.")
if (ncol(ysA) != ncol(ysB))
stop("Number of variables does not match.")
if (length(which(domains_A == "a")) + length(which(domains_A == "ab")) != length(domains_A))
stop("Domains from frame A are not correct.")
if (length(which(domains_B == "b")) + length(which(domains_B == "ba")) != length(domains_B))
stop("Domains from frame B are not correct.")
cl <- match.call()
estimations <- list()
interv <- list()
c <- ncol(ysA)
R <- ncol(xA)
n_A <- nrow(ysA)
n_B <- nrow(ysB)
n <- n_A + n_B
N_A <- nrow(xA)
N_B <- nrow(xB)
ones_ab_A <- Domains (rep (1, n_A), domains_A, "ab")
ones_ab_B <- Domains (rep (1, n_B), domains_B, "ba")
Vhat_Nhat_ab_A <- varest(ones_ab_A, pik = pik_A)
Vhat_Nhat_ab_B <- varest(ones_ab_B, pik = pik_B)
eta_0 <- Vhat_Nhat_ab_B / (Vhat_Nhat_ab_A + Vhat_Nhat_ab_B)
domains <- factor(c(as.character(domains_A), as.character(domains_B)))
delta_a <- Domains (rep (1, n), domains, "a")
delta_ab <- Domains (rep (1, n), domains, "ab")
delta_b <- Domains (rep (1, n), domains, "b")
delta_ba <- Domains (rep (1, n), domains, "ba")
for (k in 1:c){
ys <- factor(c(as.character(ysA[,k]),as.character(ysB[,k])))
y_sA <- as.factor(ysA[,k])
y_sB <- as.factor(ysB[,k])
lev <- sort(levels(ys))
levA <- sort(levels(y_sA))
levB <- sort(levels(y_sB))
m <- length(lev)
mA <- length(levA)
mB <- length(levB)
mat <- matrix (NA, 2, m)
rownames(mat) <- c("Class Tot.", "Prop.")
colnames(mat) <- lev
z <- disjunctive(ys)
pik <- c(pik_A, pik_B)
d <- 1/pik
modA <- multinom(formula = y_sA ~ 0 + xsA, weights = 1/pik_A, trace = FALSE)
beta_tilde_A <- rbind(rep(0, R), summary(modA)$coefficients)
modB <- multinom(formula = y_sB ~ 0 + xsB, weights = 1/pik_B, trace = FALSE)
beta_tilde_B <- rbind(rep(0, R), summary(modB)$coefficients)
denomA <- rowSums(exp(xA %*% t(beta_tilde_A)))
denomB <- rowSums(exp(xB %*% t(beta_tilde_B)))
pA <- exp (xA %*% t(beta_tilde_A)) / denomA
pB <- exp (xB %*% t(beta_tilde_B)) / denomB
if (mA < m){
common <- which(lev %in% levA)
pA2 <- matrix(0, N_A, m)
pA2[,common] <- pA
pA <- pA2
}
if (mB < m){
common <- which(lev %in% levB)
pB2 <- matrix(0, N_B, m)
pB2[,common] <- pB
pB <- pB2
}
psA <- pA[ind_samA,]
psB <- pB[ind_samB,]
ps <- rbind(psA, psB)
pA[ind_domA == "ab",] <- eta_0 * pA[ind_domA == "ab",]
pB[ind_domB == "ba",] <- (1 - eta_0) * pB[ind_domB == "ba",]
if (is.null(N_ab)){
Xs <- cbind(delta_a + delta_ab + delta_ba, delta_b + delta_ab + delta_ba, ps * (delta_a + delta_ab), ps * (delta_b + delta_ba))
total <- c(N_A, N_B, colSums(pA), colSums(pB))
}
else {
Xs <- cbind(delta_a, delta_ab, delta_ba, delta_b, ps * (delta_a + delta_ab), ps * (delta_b + delta_ba))
total <- c(N_A - N_ab, eta_0 * N_ab, (1 - eta_0) * N_ab, N_B - N_ab, colSums(pA), colSums(pB))
}
g <- calib (Xs, d, total, method = met)
mat[1,] <- colSums (g * d * z)
mat[2,] <- 1/N * mat[1,]
estimations[[k]] <- mat
if (!is.null(conf_level)){
alpha <- ginv(t(Xs) %*% diag(d) %*% Xs) %*% t(Xs) %*% diag(d) %*% z
e <- z - Xs %*% alpha
e <- e * d
e[domains == "ab",] <- eta_0 * e[domains == "ab",]
e[domains == "ba",] <- (1 - eta_0) * e[domains == "ba",]
Vhat_AMLCDF <- apply(e, 2, var)
Vhat_PMLCDF <- 1/N^2 * Vhat_AMLCDF
interval <- matrix (NA, 6, m)
rownames(interval) <- c("Class Tot.", "Lower Bound", "Upper Bound", "Prop.", "Lower Bound", "Upper Bound")
colnames(interval) <- lev
interval[1,] <- mat[1,]
interval[2,] <- mat[1,] + qnorm(1 - (1 - conf_level) / 2) * sqrt(Vhat_AMLCDF)
interval[3,] <- mat[1,] - qnorm(1 - (1 - conf_level) / 2) * sqrt(Vhat_AMLCDF)
interval[4,] <- mat[2,]
interval[5,] <- mat[2,] + qnorm(1 - (1 - conf_level) / 2) * sqrt(Vhat_PMLCDF)
interval[6,] <- mat[2,] - qnorm(1 - (1 - conf_level) / 2) * sqrt(Vhat_PMLCDF)
interv[[k]] <- interval
}
}
results = list(Call = cl, Est = estimations, ConfInt = interv)
class(results) = "EstimatorMDF"
attr(results, "attributesMDF") = conf_level
return(results)
} |
filterpts <- function(dset, box, keepin=FALSE){
ndimr <- length(box[[1]])
lmat <- matrix(nrow=nrow(dset),ncol=ndimr)
for (i in 1:ndimr){
lmat[,i] <- dset[,box[[1]][i]] > box[[2]][i,1] & dset[,box[[1]][i]] < box[[2]][i,2]
}
if(keepin){
return(dset[apply(lmat,1,all),])
}else{
return(dset[!apply(lmat,1,all),])
}
}
|
setGeneric("isSheetVisible",
function(object, sheet) standardGeneric("isSheetVisible"))
setMethod("isSheetVisible",
signature(object = "workbook", sheet = "numeric"),
function(object, sheet) {
!isSheetHidden(object, sheet) && !isSheetVeryHidden(object, sheet)
}
)
setMethod("isSheetVisible",
signature(object = "workbook", sheet = "character"),
function(object, sheet) {
!isSheetHidden(object, sheet) && !isSheetVeryHidden(object, sheet)
}
) |
MeasureSurvSongTPR = R6Class("MeasureSurvSongTPR",
inherit = MeasureSurvAUC,
public = list(
initialize = function() {
ps = ps(
times = p_dbl(0),
lp_thresh = p_dbl(default = 0),
type = p_fct(c("incident", "cumulative"), default = "incident")
)
ps$values = list(lp_thresh = 0, type = "incident")
super$initialize(
id = "surv.song_tpr",
properties = c("requires_task", "requires_train_set", "requires_learner"),
man = "mlr3proba::mlr_measures_surv.song_tpr",
param_set = ps
)
}
),
private = list(
.score = function(prediction, learner, task, train_set, ...) {
if (is.null(self$param_set$values$times)) {
stop("`times` must be non-NULL")
}
tpr = super$.score(
prediction = prediction,
learner = learner,
task = task,
train_set = train_set,
FUN = survAUC::sens.sh,
type = self$param_set$values$type,
...
)
tpr[, findInterval(self$param_set$values$lp_thresh, sort(unique(prediction$lp)))]
}
)
) |
read_plate <- function(file, well_ids_column = "Wells") {
check_that_only_one_file_is_provided(file)
check_file_path(file)
check_that_file_is_non_empty(file)
check_well_ids_column_name(well_ids_column)
plate_size <- guess_plate_size(file)
raw_file_list <- get_list_of_plate_layouts(file, plate_size)
result <- convert_all_layouts(raw_file_list, plate_size)
result <- combine_list_to_dataframe(result, plate_size)
colnames(result)[colnames(result) == "wellIds"] <- well_ids_column
class(result) <- c("tbl_df", "tbl", "data.frame")
result
}
convert_all_layouts <- function(raw_file_list, plate_size) {
convert <- function(f, layout_number) {
tryCatch(
expr = convert_plate_to_column(f, plate_size),
error = function(e) {
e <- paste0("Error in layout
e$message)
stop(e, call. = FALSE)
}
)
}
Map(f = convert, raw_file_list, 1:length(raw_file_list))
}
calculate_number_of_plates <- function(raw_file, number_of_rows) {
is_integer <- function(x) x %% 1 == 0
result <- (length(raw_file) + 1) / (number_of_rows + 2)
if (is_integer(result)) {
return(result)
} else {
result <- (length(raw_file)) / (number_of_rows + 2)
if (raw_file[length(raw_file)] == "" || is_integer(result)) {
return(result)
} else {
stop(paste0("File length is incorrect. Must be a multiple of the ",
"number of rows in the plate plus a header row for each ",
"plate and a blank row between plates."),
call. = FALSE)
}
}
}
get_list_of_plate_layouts <- function(file, plate_size) {
raw_file <- read_lines(file)
number_of_rows <- number_of_rows(plate_size)
number_of_plates <- calculate_number_of_plates(raw_file, number_of_rows)
raw_file_list <- lapply(1:number_of_plates, FUN =
function(plate) {
first_row <- (plate - 1) * (number_of_rows + 1) + plate
last_row <- first_row + number_of_rows
raw_file[first_row:last_row]
}
)
raw_file_list
}
check_unique_plate_names <- function(result) {
plate_names <- vapply(result, FUN = function(x) colnames(x)[2],
FUN.VALUE = "character")
if(any(duplicated(plate_names))) {
duplicates <- which(duplicated(plate_names))
result <- lapply(1:length(result), FUN = function(n) {
if (n %in% duplicates) {
new_name <- paste0(colnames(result[[n]])[2], ".", n)
colnames(result[[n]])[2] <- new_name
result[[n]]
} else {
result[[n]]
}
})
}
return(result)
}
combine_list_to_dataframe <- function(result, plate_size) {
if (length(result) == 1) {
result <- result[[1]]
} else {
result <- check_unique_plate_names(result)
result <- Reduce(function(x, y) merge(x, y, by = "wellIds", all = TRUE),
result)
}
keep <- rowSums(!is.na(result)) > 1
result <- result[keep, ]
sort_by_well_ids(result, "wellIds", plate_size)
} |
epmeans <- function(elist, k=2){
clist = elist_epmeans(elist)
myk = round(k)
myn = length(clist)
mylength = 1000
qseq = seq(from=1e-6, to=1-(1e-6), length.out=mylength)
qmat = array(0,c(myn,mylength))
for (n in 1:myn){
qmat[n,] = as.vector(stats::quantile(clist[[n]], qseq))
}
tmpcpp = cpp_kmeans(qmat, myk)$means
mylist1 = list()
mylist2 = list()
for (n in 1:myn){
mylist1[[n]] = stats::ecdf(as.vector(qmat[n,]))
}
for (k in 1:myk){
mylist2[[k]] = stats::ecdf(as.vector(tmpcpp[k,]))
}
pdistmat = dist2_wasserstein(mylist1, mylist2, 1)
label = base::apply(pdistmat, 1, which.min)
output = list()
output$cluster = as.integer(label)
output$centers = mylist2
return(output)
}
|
canonicalize <- function(intervals)
{
errorCheck(intervals, FALSE)
makeCanonicalRep(1:nrow(intervals), intervals[, 'left'], intervals[, 'right'])
} |
fg_milb_pitcher_game_logs <- function(playerid, year) {
url_basic <- paste0("http://www.fangraphs.com/statsd-legacy.aspx?playerid=",
playerid,
"&season=",
year,
"&position=P","&type=-1")
url <- paste0("https://cdn.fangraphs.com/api/players/game-log?position=P&type=-1&&gds=&gde=&z=1637230004112&playerid=",
playerid,
"&season=",
year)
res <- httr::RETRY("GET", url)
resp <- res %>%
httr::content(as = "text", encoding = "UTF-8")
payload <- jsonlite::fromJSON(resp)[['minor']] %>%
as.data.frame()
payload <- payload[-1,]
suppressWarnings(
payload <- payload %>%
tidyr::separate(.data$Team, into = c("Team","Level"),sep=" ")
)
player_name <- url_basic %>%
xml2::read_html() %>%
rvest::html_elements("h1") %>%
rvest::html_text()
payload <- payload %>%
dplyr::mutate(
player_name = player_name,
minor_playerid = playerid) %>%
dplyr::select(.data$player_name, .data$minor_playerid, tidyr::everything())
return(payload)
}
milb_pitcher_game_logs_fg <- fg_milb_pitcher_game_logs |
context("id")
simple_vectors <- list(
letters,
sample(letters),
1:26
)
test_that("for vector, equivalent to rank", {
for (case in simple_vectors) {
rank <- rank(case, ties = "min")
rank_df <- id(as.data.frame(case))
expect_that(rank, is_equivalent_to(rank_df))
}
})
test_that("duplicates numbered sequentially", {
for (case in simple_vectors) {
rank <- rep(rank(case, ties = "min"), each = 2)
rank_df <- id(as.data.frame(rep(case, each = 2)))
expect_that(rank, is_equivalent_to(rank_df))
}
})
test_that("n calculated correctly", {
n <- function(x) attr(id(x), "n")
for (case in simple_vectors) {
expect_that(n(as.data.frame(case)), equals(26))
}
})
test_that("for vector + constant, equivalent to rank", {
for (case in simple_vectors) {
rank <- rank(case, ties = "min")
after <- id(data.frame(case, x = 1))
before <- id(data.frame(x = 1, case))
expect_that(rank, is_equivalent_to(before))
expect_that(rank, is_equivalent_to(after))
}
})
test_that("grids are correctly ranked", {
df <- rev(expand.grid(1:10, 1:2))
expect_that(id(df), is_equivalent_to(1:20))
expect_that(id(df, drop = T), is_equivalent_to(1:20))
})
test_that("NAs are placed last", {
expect_that(id_var(c(NA, 1)), is_equivalent_to(c(2, 1)))
})
test_that("factor with missing levels has correct count", {
id <- id_var(factor(1, NA))
expect_equal(attr(id, "n"), 1)
})
test_that("zero length input gives single number", {
expect_that(id(character()), is_equivalent_to(integer()))
})
test_that("zero column data frame gives seq_len(nrow)", {
df <- as.data.frame(matrix(nrow = 10, ncol = 0))
expect_equivalent(id(df), 1:10)
})
test_that("empty list doesn't affect n", {
out <- id(list(integer(), 1:5))
expect_equivalent(out, 1:5)
expect_equal(attr(out, "n"), 5)
}) |
get_taxa_meta <-
function(nexml, what='href'){
out <- lapply(nexml@otus, function(otus)
sapply(otus@otu, function(otu) slot(otu@meta[[1]], what)))
unname(unlist(out, recursive = FALSE))
}
get_otu_meta <- get_taxa_meta
get_taxa_meta_list <-
function(nexml, what='href'){
out <- lapply(nexml@otus, function(otus){
out <- sapply(otus@otu, function(otu) slot(otu@meta[[1]], what))
names(out) <- name_by_id(otus@otu)
out
})
names(out) <- name_by_id(nexml@otus)
out
}
get_otu_meta_list <- get_taxa_meta_list |
ModuleStopIfNotDataFrame <- function(data) {
if (is.data.frame(data) == FALSE) {
stop("The data argument needs to be a data frame (no quote).")
}
}
ModuleReturnVarsExist <- function(vars, data) {
varsNotInData <- setdiff(vars, names(data))
if (length(varsNotInData) > 0) {
warning("The data frame does not have: ",
paste0(varsNotInData, sep = " "), " Dropped")
vars <- intersect(vars, names(data))
}
logiAllNaVars <- sapply(X = data[vars],
FUN = function(VAR) {
all(is.na(VAR))
},
simplify = TRUE)
if (any(logiAllNaVars)) {
warning("These variables only have NA/NaN: ",
paste0(vars[logiAllNaVars], sep = " "), " Dropped")
vars <- vars[!logiAllNaVars]
}
return(vars)
}
ModuleStopIfNoVarsLeft <- function(vars) {
if (length(vars) < 1) {stop("No valid variables.")}
}
ModuleReturnFalseIfNoStrata <- function(strata, test) {
if(missing(strata)) {
test <- FALSE
}
return(test)
}
ModuleReturnStrata <- function(strata, data) {
if(missing(strata)) {
strata <- rep("Overall", nrow(data))
} else {
strata <- unique(strata)
strata <- ModuleReturnVarsExist(strata, data)
if (length(strata) == 0) {
stop("None of the stratifying variables are present in the data frame.")
} else {
logiSingleLevelOnly <-
lapply(data[c(strata)],
function(VEC) {
nLevels <- ifelse(test = is.factor(VEC),
yes = nlevels(VEC),
no = nlevels(factor(VEC)))
nLevels == 1
})
logiSingleLevelOnly <- unlist(logiSingleLevelOnly)
if (any(logiSingleLevelOnly)) {
warning("These variables have only one valid level: ",
paste0(strata[logiSingleLevelOnly], sep = " "), " Dropped")
strata <- strata[!logiSingleLevelOnly]
}
if (length(strata) == 0) {
stop("None of the stratifying variables have 2+ valid levels.")
}
strata <- data[c(strata)]
}
}
return(strata)
}
ModuleCreateTableForOneVar <- function(x) {
freqRaw <- table(x)
freq <- data.frame(level = names(freqRaw),
stringsAsFactors = FALSE)
freq$n <- length(x)
freq$miss <- sum(is.na(x))
freq$p.miss <- (freq$miss / freq$n) * 100
freq$freq <- freqRaw
freq$percent <- freqRaw / sum(freqRaw) * 100
freq$cum.percent <- cumsum(freqRaw) / sum(freqRaw) * 100
freq <- freq[c("n","miss","p.miss","level","freq","percent","cum.percent")]
return(freq)
}
ModuleIncludeNaAsLevel <- function(data) {
logiAnyNA <- (colSums(is.na(data)) > 0)
data[logiAnyNA] <-
lapply(data[logiAnyNA],
function(var) {
if (all(!is.na(levels(var)))) {
var <- factor(var, c(levels(var), NA),
exclude = NULL)
}
var
})
data
}
ModuleCreateStrataVarName <- function(obj) {
paste0(names(attr(obj, "dimnames")), collapse = ":")
}
ModuleCreateStrataVarAsFactor <- function(result, strata) {
dfStrataLevels <- expand.grid(attr(result, "dimnames"))
strataLevels <- apply(X = dfStrataLevels, MARGIN = 1, FUN = paste0, collapse = ":")
strataVar <- as.character(interaction(strata, sep = ":"))
strataVar <- factor(strataVar, levels = strataLevels)
return(strataVar)
}
ModuleCreateOverallColumn <- function(call) {
call$strata <- NULL
call$addOverall <- FALSE
return(eval(call))
}
ModuleReapplyNameAndDimAttributes <- function(result, strataVarName, levelsStrataVar) {
attributes(result)$names <- c(attributes(result)$names[1], levelsStrataVar)
attributes(result) <- c(attributes(result), list(strataVarName = strataVarName))
attr(result, "dim") <- length(attr(result, "names"))
overall_dimnames <- list(attr(result, "names"))
names(overall_dimnames) <- attr(result, "strataVarName")
dimnames(result)<- overall_dimnames
return(result)
}
ModuleTryCatchWE <- function(expr) {
W <- NULL
w.handler <- function(w) {
W <<- w
invokeRestart("muffleWarning")
}
list(value = withCallingHandlers(tryCatch(expr, error = function(e) e),
warning = w.handler),
warning = W)
}
ModuleTestSafe <- function(obj, testFunction, testArgs = NULL) {
out <- ModuleTryCatchWE(do.call(testFunction, args = c(list(obj), testArgs))$p.value)
pValue <- ifelse(is.numeric(out$value), out$value, NA)
if (any(class(obj) %in% "xtabs")) {
if (dim(obj)[1] == 1) {
return(NA)
} else {
pValue
}
} else {
pValue
}
}
ModuleSasSkewness <- function(x) {
out <- ModuleTryCatchWE(e1071::skewness(x, na.rm = TRUE, type = 2))
ifelse(is.numeric(out$value), out$value, NaN)
}
ModuleSasKurtosis <- function(x) {
out <- ModuleTryCatchWE(e1071::kurtosis(x, na.rm = TRUE, type = 2))
ifelse(is.numeric(out$value), out$value, NaN)
}
ModuleApproxExactTests <- function(result, strata, dat, strataVarName,
testApprox, argsApprox,
testExact, argsExact) {
strataVar <- ModuleCreateStrataVarAsFactor(result, strata)
listXtabs <- sapply(X = names(dat),
FUN = function(var) {
formula <- as.formula(paste0("~ `", var, "` + ", "strataVar"))
xtabs(formula = formula, data = dat)
},
simplify = FALSE)
for (i in seq_along(listXtabs)) {
names(dimnames(listXtabs[[i]]))[2] <- strataVarName
}
pValues <-
sapply(X = listXtabs,
FUN = function(xtabs) {
data.frame(pApprox = ModuleTestSafe(xtabs, testApprox, argsApprox),
pExact = ModuleTestSafe(xtabs, testExact, argsExact))
},
simplify = FALSE)
pValues <- do.call(rbind, pValues)
list(pValues = pValues, xtabs = listXtabs)
}
ModulePercentMissing <- function(data) {
unlist(lapply(data, function(x) {sum(is.na(x)) / length(x) * 100}))
} |
importList <- function(x, ask = TRUE ) {
if( !methods::is(x,"list") & !methods::is(x,"data.frame")) stop( '"x" must be a list or data frame')
if( !methods::is(ask,"logical") | length(ask) !=1 ) {
stop( '"ask" must be a single logical value')
}
envir = parent.frame()
vars <- names(x)
vars <- make.unique(vars)
vars <- make.names(vars)
if( ask ) {
cat("Names of variables to be created:\n")
print(vars)
ans <- NA
while( ! (ans %in% c("y","n") ) ) {
ans <- readline("Create these variables? [y/n] ")
}
if (ans == "n") {
return( invisible(0) )
}
}
for (v in seq_along(vars)) {
assign(x = vars[v], value = x[[v]], envir = envir)
}
return( invisible(1) )
} |
mcgd.lr <- function(y,
var.type,
lambda1 = NULL,
maxit = 100,
thresh = 1e-6,
theta0 = NULL,
trace.it = T){
y <- as.matrix(y)
d <- dim(y)
n <- d[1]
p <- d[2]
p1 <- sum(var.type == "gaussian")
p2 <- sum(var.type == "binomial")
p3 <- sum(var.type == "poisson")
omega <- !is.na(y)
if(is.null(theta0)) theta0 <- matrix(rep(0, n * p), nrow = n)
R0 <- svd(theta0, nu = 1, nv = 1)$d[1]
if(is.null(lambda1)){
sigma <- sum((y-mean(y, na.rm = T))^2, na.rm = T)/(n*p)
beta <- sum(is.na(y))/sum(!is.na(y))*max(n,p)
lambda1 <- 2*sigma*sqrt(beta*log(n+p))
}
theta <- theta0
R <- R0
objective <- NULL
error <- 1
iter <- 0
list.theta <- list()
list.R <- list()
y0 <- y
y0[is.na(y0)] <- 0
low_bound <- 0
ypois <- y0[, var.type == "poisson"]
upper <- 12
lower <- -12
if(p2>0){
low_bound <- low_bound - n*sum(var.type == "binomial")*(-2*max(abs(upper), abs(lower)) + log(1+exp(-2*max(abs(upper), abs(lower)))))
}
if(p3>0){
low_bound <- low_bound - sum(ypois[!(ypois==0)]*(1-log(ypois[!(ypois==0)])))
}
obj0 <- low_bound
if(p1>0){
obj0 <- obj0 + (1 / 2) * sum((y[, var.type == "gaussian"] - theta[, var.type == "gaussian"])^2,
na.rm = T)
}
if(p2>0){
obj0 <- obj0 + sum(- (y[, var.type == "binomial"] * theta[, var.type == "binomial"]) +
log(1 + exp(theta[, var.type == "binomial"])), na.rm = T)
}
if(p3>0){
obj0 <- obj0 + sum(- (y[, var.type == "poisson"] * theta[, var.type == "poisson"]) +
exp(theta[, var.type == "poisson"]), na.rm = T)
}
U <- obj0/lambda1
while((error > thresh) && (iter < maxit)){
iter <- iter + 1
list.theta[[iter]] <- theta
list.R[[iter]] <- R
theta.tmp <- theta
R.tmp <- R
grad <- matrix(rep(0, n*p), nrow = n)
if(p1>0){
grad[, var.type == "gaussian"] <- -omega[, var.type == "gaussian"]*(y0 - theta)[, var.type == "gaussian"]
}
if(p2>0){
grad[, var.type == "binomial"] <- -omega[, var.type == "binomial"] *( y0 - exp(theta)/(1+exp(theta)))[, var.type == "binomial"]
}
if(p3>0){
grad[, var.type == "poisson"] <- - omega[, var.type == "poisson"]*(y0 - exp(theta))[, var.type == "poisson"]
}
step <- 2
flag <- TRUE
obj0 <- low_bound
if(p1>0){
obj0 <- obj0 + (1 / 2) * sum((y[, var.type == "gaussian"] - theta[, var.type == "gaussian"])^2,
na.rm = T)
}
if(p2>0){
obj0 <- obj0 + sum(- (y[, var.type == "binomial"] * theta[, var.type == "binomial"]) +
log(1 + exp(theta[, var.type == "binomial"])), na.rm = T)
}
if(p3>0){
obj0 <- obj0 + sum(- (y[, var.type == "poisson"] * theta[, var.type == "poisson"]) +
exp(theta[, var.type == "poisson"]), na.rm = T)
}
obj0 <- obj0 + lambda1*R
grad_theta <- matrix(rep(0, n*p), nrow = n)
if(p1>0){
grad_theta[, var.type == "gaussian"] <- -omega[, var.type == "gaussian"]*(y0 - theta)[, var.type == "gaussian"]
}
if(p2>0){
grad_theta[, var.type == "binomial"] <- -omega[, var.type == "binomial"] *( y0 - exp(theta)/(1+exp(theta)))[, var.type == "binomial"]
}
if(p3>0){
grad_theta[, var.type == "poisson"] <- - omega[, var.type == "poisson"]*(y0 - exp(theta))[, var.type == "poisson"]
}
svd_theta <- rARPACK::svds(grad_theta, k=1, nu = 1, nv = 1)
D_t <- - svd_theta$u%*%t(svd_theta$v)
step <- 2
flag <- TRUE
obj0 <- low_bound
if(p1>0){
obj0 <- obj0 + (1 / 2) * sum((y[, var.type == "gaussian"] - theta[, var.type == "gaussian"])^2,
na.rm = T)
}
if(p2>0){
obj0 <- obj0 + sum(- (y[, var.type == "binomial"] * theta[, var.type == "binomial"]) +
log(1 + exp(theta[, var.type == "binomial"])), na.rm = T)
}
if(p3>0){
obj0 <- obj0 + sum(- (y[, var.type == "poisson"] * theta[, var.type == "poisson"]) +
exp(theta[, var.type == "poisson"]), na.rm = T)
}
obj0 <- obj0 + lambda1*R
while((flag )){
step <- 0.5*step
if(lambda1 >= - sum(D_t*grad_theta)){
R_hat <- 0
theta_hat <- matrix(rep(0, n*p), nrow = n)
if(norm(theta_hat - theta.tmp, type = "F")^2==0){
beta <- 1
} else {
beta <- min(1, step)
}
theta <- theta.tmp + beta*(theta_hat - theta.tmp)
R <- R.tmp + beta*(R_hat - R.tmp)
} else{
R_hat <- U
theta_hat <- U*D_t
if(norm(theta_hat - theta.tmp, type = "F")^2==0){
beta <- 1
theta <- theta.tmp + beta*(theta_hat - theta.tmp)
R <- R.tmp + beta*(R_hat - R.tmp)
} else {
beta <- min(1, step)
theta <- theta.tmp + beta*(theta_hat - theta.tmp)
R <- R.tmp + beta*(R_hat - R.tmp)
}
}
obj <- low_bound
if(p1>0){
obj <- obj + (1 / 2) * sum((y[, var.type == "gaussian"] - theta[, var.type == "gaussian"])^2,
na.rm = T)
}
if(p2>0){
obj <- obj + sum(- (y[, var.type == "binomial"] * theta[, var.type == "binomial"]) +
log(1 + exp(theta[, var.type == "binomial"])), na.rm = T)
}
if(p3>0){
obj <- obj + sum(- (y[, var.type == "poisson"] * theta[, var.type == "poisson"]) +
exp(theta[, var.type == "poisson"]), na.rm = T)
}
obj <- obj + lambda1*R
flag <- (obj > obj0 + thresh * abs(obj0))
}
obj <- low_bound
if(p1>0){
obj <- obj + (1 / 2) * sum((y[, var.type == "gaussian"] - theta[, var.type == "gaussian"])^2,
na.rm = T)
}
if(p2>0){
obj <- obj + sum(- (y[, var.type == "binomial"] * theta[, var.type == "binomial"]) +
log(1 + exp(theta[, var.type == "binomial"])), na.rm = T)
}
if(p3>0){
obj <- obj + sum(- (y[, var.type == "poisson"] * theta[, var.type == "poisson"]) +
exp(theta[, var.type == "poisson"]), na.rm = T)
}
obj <- obj + lambda1*R
objective <- c(objective, obj)
U <- obj/lambda1
if(iter == 1){
error <- 1
} else {
if(abs(objective[iter]) == 0) {
error <- abs(objective[iter]-objective[iter - 1])
} else {
error <- abs(objective[iter]-objective[iter - 1]) /abs(objective[iter])
}
}
if(trace.it && (iter%%10 == 0) ){
print(paste("iter ", iter, ": error ", error, " - objective: ", objective[iter]))
}
}
yy <- theta
yy[, var.type == "poisson"] <- exp(yy[, var.type == "poisson"])
yy[, var.type == "binomial"] <- exp(yy[, var.type == "binomial"])/(1+exp(yy[, var.type == "binomial"]))
y.imputed <- y
y.imputed[is.na(y)] <- yy[is.na(y)]
return(list(y.imputed = y.imputed,
theta = theta))
} |
sensmodel <- function(peaksens, range = c(300, 700), lambdacut = NULL, Bmid = NULL,
oiltype = NULL, beta = TRUE, om = NULL, integrate = TRUE, sensnames = NULL) {
if (!is.null(lambdacut)) {
if (is.null(Bmid) & is.null(oiltype)) stop("Bmid or oiltype must be included when including a lambdacut vector", call. = FALSE)
if (length(lambdacut) != length(peaksens)) stop("lambdacut must be same length as peaksens", call. = FALSE)
}
if (!is.null(Bmid) & is.null(lambdacut)) {
stop("lambdacut has to be provided together with Bmid")
}
if (!is.null(lambdacut) & !is.null(Bmid) & !is.null(oiltype)) {
stop("only 2 of lambdacut, Bmid, and oiltype can be provided")
}
if (!is.null(lambdacut) & !is.null(oiltype)) {
if (length(lambdacut) != length(oiltype)) stop("lambdacut and oiltype must be of same length")
}
if (!is.null(lambdacut) & !is.null(Bmid)) {
if (length(lambdacut) != length(Bmid)) stop("lambdacut and Bmid must be of same length")
}
sensecurves <- matrix(ncol = length(peaksens), nrow = (range[2] - range[1] + 1))
wl <- range[1]:range[2]
for (i in seq_along(peaksens)) {
peak <- 1 / (exp(69.7 * (.8795 + .0459 * exp(-(peaksens[i] - range[1])^2 / 11940) - (peaksens[i] / wl)))
+ exp(28 * (.922 - peaksens[i] / wl)) + exp(-14.9 * (1.104 - (peaksens[i] / wl))) + .674)
if (beta) {
betaband <- 0.26 * exp(-((wl - (189 + 0.315 * peaksens[i])) / (-40.5 + 0.195 * peaksens[i]))^2)
peak <- peak + betaband
}
peak <- peak / max(peak)
if (!is.null(lambdacut) & !is.null(Bmid)) {
if (is.na(lambdacut[i]) & !is.na(Bmid[i])) {
warning("NA in lambdacut not paired with NA in Bmid, value of Bmid omitted")
T.oil <- 1
} else {
T.oil <- exp(-exp(-2.89 * Bmid[i] * (wl - lambdacut[i]) + 1.08))
peak <- peak * T.oil
}
}
if (!is.null(lambdacut) & !is.null(oiltype)) {
if (oiltype[i] == "T") {
T.oil <- 1
} else {
if (oiltype[i] == "C") oil <- c(0.99, 24.38)
if (oiltype[i] == "Y") oil <- c(0.9, 70.03)
if (oiltype[i] == "R") oil <- c(0.99, 28.65)
if (oiltype[i] == "P") oil <- c(0.96, 33.57)
T.oil <- exp(-exp(-2.89 * (.5 / ((oil[1] * lambdacut[i] + oil[2]) - lambdacut[i])) *
(wl - lambdacut[i]) + 1.08))
}
peak <- peak * T.oil
}
if (integrate) {
peak <- peak / sum(peak)
}
if (!is.null(om)) {
if (length(om) == 1) {
if (om == "bird") {
T.e <- log(8.928 * 10^-13 * wl^5 - 2.595 * 10^-9 *
wl^4 + 3.006 * 10^-6 *
wl^3 - .001736 * wl^2 + .5013 *
wl - 55.56)
T.e[which(T.e < 0)] <- 0
peak <- peak * T.e
}
}
else {
T.e <- om
peak <- peak * T.e
}
}
sensecurves[, i] <- peak
}
sensecurves <- as.data.frame(sensecurves)
if (!is.null(sensnames)) {
if (length(sensnames) != length(sensecurves)) {
message("The length of argument 'sensnames' does not equal the number of curves specified by 'peaksens'. Reverting to default names.")
sensnames <- NULL
} else {
names(sensecurves) <- sensnames
}
}
if (is.null(sensnames)) {
names(sensecurves) <- paste0("lmax", peaksens)
}
sensecurves <- cbind(wl, sensecurves)
class(sensecurves) <- c("sensmod", "rspec", "data.frame")
if (is.null(om)) {
attr(sensecurves, "om") <- FALSE
} else {
attr(sensecurves, "om") <- TRUE
}
sensecurves
} |
lnre.cost.gof <- function (model, spc, m.max=15)
{
N <- N(spc)
V <- V(spc)
m.vec <- seq_len(m.max)
Vm <- Vm(spc, m.vec)
E.Vm <- EVm(model, m.vec, N)
E.V <- EV(model, N)
E.Vm.2N <- EVm(model, seq_len(2 * m.max), 2 * N)
E.V.2N <- EV(model, 2 * N)
err.vec <- c(V, Vm) - c(E.V, E.Vm)
cov.Vm.Vk <- diag(E.Vm, nrow=m.max) -
outer(m.vec, m.vec, function (m, k) choose(m+k, m) * E.Vm.2N[m+k] / 2^(m+k))
cov.Vm.V <- E.Vm.2N[m.vec] / 2^(1:m.max)
R <- rbind(c(VV(model, N), cov.Vm.V),
cbind(cov.Vm.V, cov.Vm.Vk))
t(err.vec) %*% solve(R, err.vec)
}
lnre.cost.chisq <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
E.Vplus <- E.V - sum(E.Vm)
V.Vm <- VVm(model, 1:m.max, N)
V.V <- VV(model, N)
V.Vplus <- V.V - sum(V.Vm)
V.Vm <- pmax(V.Vm, 9)
V.Vplus <- max(V.Vplus, 9)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
O.Vplus <- O.V - sum(O.Vm)
X2 <- sum( (O.Vm - E.Vm)^2 / V.Vm ) + (O.Vplus - E.Vplus)^2 / V.Vplus
X2
}
lnre.cost.linear <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
abs(E.V - O.V) + sum( abs(E.Vm - O.Vm) )
}
lnre.cost.smooth.linear <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
sqrt(1 + (E.V - O.V)^2) + sum( sqrt(1 + (E.Vm - O.Vm)^2) )
}
lnre.cost.mse <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
( (E.V - O.V)^2 + sum((E.Vm - O.Vm)^2) ) / (1 + m.max)
} |
context("setShadow")
test_that("setBackgroundColor works", {
tag <- setShadow(class = "box")
expect_is(tag, "shiny.tag")
expect_length(tag$children, 1)
tag <- setShadow(id = "my-progress")
expect_is(tag, "shiny.tag")
expect_length(tag$children, 1)
}) |
gr.SGB <-
function(x,d,u,V,weight,...){
D <- NCOL(u)
n <- NROW(u)
D1 <- D-1
npar <- length(x)
r <- NCOL(d)-1
shape1 <- x[1]
R <- r*D1
beta <- matrix(x[2:(D+R)], ncol=D1,byrow=TRUE)
shape2 <- as.vector(x[-(1:(D+R))])
P <- sum(shape2)
inV <- ginv(V)
b <- exp((d%*%beta)%*%inV)
b <- b/rowSums(b)
z <- (u/b)^shape1
z <- z/rowSums(z)
logub <- as.matrix(log(u/b))
Kb <- sum(weight*z*logub)
dl_dbeta <- shape1*inV %*% t(P*z-rep(1,n)%*%t(shape2)) %*% (weight*d )
dl_dbeta <- as.vector(dl_dbeta)
names(dl_dbeta) <- paste(sort(rep(paste("dl_dbeta",0:r,sep=""),D1)),rep(1:D1,r),sep="")
dl_dshape1 <- n*D1/shape1 + sum(weight * logub %*% shape2)- P*Kb
names(dl_dshape1) <- "dl_dshape1"
dl_dshape2 <- n*(digamma(P)-digamma(shape2)) + colSums(weight*log(z))
names(dl_dshape2) <- paste("dl_dshape2",1:D,sep="")
return(c(dl_dshape1, dl_dbeta, dl_dshape2))
} |
pdbart = function (
x.train, y.train,
xind=1:ncol(x.train), levs=NULL, levquants=c(.05,(1:9)/10,.95),
pl=TRUE, plquants=c(.05,.95),
...
)
{
n = nrow(x.train)
nvar = length(xind)
nlevels = rep(0,nvar)
if(is.null(levs)) {
levs = list()
for(i in 1:nvar) {
ux = unique(x.train[,xind[i]])
if(length(ux) < length(levquants)) levs[[i]] = sort(ux)
else levs[[i]] = unique(quantile(x.train[,xind[i]],probs=levquants))
}
}
nlevels = unlist(lapply(levs,length))
x.test=NULL
for(i in 1:nvar) {
for(v in levs[[i]]) {
temp = x.train
temp[,xind[i]] = v
x.test = rbind(x.test,temp)
}
}
pdbrt = bart(x.train,y.train,x.test,...)
fdr = list()
cnt=0
for(j in 1:nvar) {
fdrtemp=NULL
for(i in 1:nlevels[j]) {
cind = cnt + ((i-1)*n+1):(i*n)
fdrtemp = cbind(fdrtemp,(apply(pdbrt$yhat.test[,cind],1,mean)))
}
fdr[[j]] = fdrtemp
cnt = cnt + n*nlevels[j]
}
if(is.null(colnames(x.train))) xlbs = paste('x',xind,sep='')
else xlbs = colnames(x.train)[xind]
if('sigma' %in% names(pdbrt)) {
retval = list(fd = fdr,levs = levs,xlbs=xlbs,
bartcall=pdbrt$call,yhat.train=pdbrt$yhat.train,
first.sigma=pdbrt$first.sigma,sigma=pdbrt$sigma,
yhat.train.mean=pdbrt$yhat.train.mean,sigest=pdbrt$sigest,y=pdbrt$y)
} else {
retval = list(fd = fdr,levs = levs,xlbs=xlbs,
bartcall=pdbrt$call,yhat.train=pdbrt$yhat.train,
y=pdbrt$y)
}
class(retval) = 'pdbart'
if(pl) plot(retval,plquants=plquants)
return(retval)
} |
lama_select <- function(.data, ...) {
UseMethod("lama_select")
}
lama_select.lama_dictionary <- function(.data, ...) {
args <- rlang::quos(...)
err_handler <- composerr(
text_1 = "Error while calling 'lama_select'",
text_2 = "Use unquoted arguments e.g. 'lama_select(.data, x, y, z)'.",
sep_2 = " "
)
if (length(args) == 0)
err_handler("Selected translation names are missing.")
key <- as.character(sapply(seq_len(length(args)), function(i) {
err_handler <- composerr_parent(
paste(
"Invalid argument at position",
stringify(i + 1)
),
err_handler
)
x <- args[[i]]
if (!rlang::quo_is_symbol(x))
err_handler(paste(
"The expression",
stringify(rlang::quo_name(x)),
"could not be parsed."
))
rlang::quo_name(x)
}))
check_select(.data, key, err_handler)
new_lama_dictionary(.data[key])
}
lama_select_ <- function(.data, key) {
UseMethod("lama_select_")
}
lama_select_.lama_dictionary <- function(.data, key) {
err_handler <- composerr("Error while calling 'lama_select_'")
if (!is.character(key) || length(key) == 0)
err_handler("The object given in the argument 'key' must be a character vector.")
check_select(.data, key, err_handler)
new_lama_dictionary(.data[key])
}
check_select <- function(.data, key, err_handler) {
if (!is.lama_dictionary(.data))
err_handler("The object given in the argument '.data' must be a lama_dictionary class object.")
invalid <- !key %in% names(.data)
if (any(invalid))
err_handler(paste0(
"The following translation names could not be ",
"found in the lama_dictionary object: ",
stringify(key[invalid]),
".\nOnly the following variable translations exist: ",
stringify(names(.data)),
"."
))
duplicates <- table(key)
duplicates <- names(duplicates[duplicates > 1])
if (length(duplicates) > 0)
err_handler(paste0(
"The following translation names are used more than once: ",
stringify(duplicates),
"."
))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.