code
stringlengths 1
13.8M
|
---|
patients_keywords <- c('patients', 'individuals', 'subjects',
'biopsies', 'biopsy', 'participant',
'children', 'trial', 'humans', 'women')
calculate_score_patients <- function(df,
keywords = patients_keywords,
case = FALSE,
threshold = NULL,
indicate = FALSE,
discard = FALSE,
col.abstract = Abstract) {
if(!is.null(threshold) & !is.numeric(threshold)) {
stop("'threshold' must be an integer >= 0")
}
if(indicate == TRUE & is.null(threshold)) {
threshold <- 1
}
if(discard == TRUE & is.null(threshold)) {
threshold <- 1
}
df_patient <- df %>%
dplyr::mutate(Patient_score = purrr::map_int({{col.abstract}}, ~ calculate_score(string = .x,
keywords = keywords,
case = case)))
if (indicate == TRUE) {
df_patient <- df_patient %>%
dplyr::mutate(Patient_p = ifelse(Patient_score >= threshold, "Yes", "No"))
}
if (discard == TRUE) {
df_patient <- df_patient %>%
dplyr::filter(Patient_score >= threshold)
return(df_patient)
} else {
return(df_patient)
}
}
plot_score_patients <- function(df,
keywords = patients_keywords,
case = FALSE,
bins = NULL,
colour = "steelblue3",
col.abstract = Abstract,
col.pmid = PMID,
title = NULL) {
if(is.null(title)) {
title <- "Patient score distribution"
}
df_patients <- df %>%
dplyr::mutate(Patient_score = purrr::map_int({{col.abstract}}, ~ calculate_score(string = .x,
keywords = keywords,
case = case)))
if (is.null(bins)) {
bins <- max(df_patients$Patient_score) - min(df_patients$Patient_score)
}
df_patients <- df_patients %>%
dplyr::select({{col.pmid}}, Patient_score) %>%
dplyr::distinct()
plot <- ggplot(df_patients, aes(x = Patient_score)) +
geom_histogram(bins = bins,
fill = colour,
center = 0,
binwidth = 1) +
theme_classic() +
xlab("Patient score") +
ylab("
ggtitle(title) +
scale_x_continuous(expand = c(0,0),
breaks = scales::pretty_breaks()) +
scale_y_continuous(expand = c(0,0))
return(plot)
} |
require(igraph)
require(spdep)
require(fdrtool)
require(GOstats)
require(locfdr)
require(mvtnorm)
require(caTools)
gene_fdrtest <- function(gene.data){
name <- gene.data$gene_id_all
coef_val <- gene.data$t_data
z.cent <- coef_val - median(coef_val)
fdr_result <- data.frame(fdr = locfdr::locfdr(z.cent, nulltype = 0, plot = 4)$fdr, name)
return(fdr_result)
}
cal_lmi_data <- function(gene_expr, gene_graph){
n_hop_matrix<-function(gene_graph, hop_n){
dis_mat <- igraph::shortest.paths(gene_graph)
dis_mat[dis_mat >hop_n] <- 0
dis_mat[dis_mat == hop_n] <- 0.5
return(dis_mat)
}
dis_mat <- n_hop_matrix(gene_graph, hop_n = 2)
listw_obj <- spdep::mat2listw(dis_mat, style = 'W')
gene_expr<-t(apply(gene_expr, 1, function(gene_expr)(gene_expr-min(gene_expr))/(max(gene_expr)-min(gene_expr))))
lmi_data <- double()
for (i in seq(1,ncol(gene_expr),1)){
lmi<-spdep::localmoran(gene_expr[,i],listw = listw_obj)
lmi_data <- cbind(lmi_data,lmi[,1])
}
return(lmi_data)
}
significant_genes <- function(fdr_obj, thres){
sel.entrez <- fdr_obj$name[which(fdr_obj$fdr<thres)]
return(sel.entrez)
}
DNLC_statistics <- function(gene_graph, gene_expr='x', clinic_data='y', confounder_matrix = NULL ,lmi_data = NULL)
{
if(is.null(confounder_matrix))
confounder_matrix <- rep(1, length(clinic_data))
if(is.null(lmi_data))
{
lmi_data = cal_lmi_data(gene_expr, gene_graph)
}
gene_ids <- igraph::V(gene_graph)$name
if(is.null(gene_ids))
gene_ids = seq(1,nrow(gene_expr))
ans = double()
for (i in seq(1,nrow(gene_expr),1))
{
ans <- cbind(ans, summary(lm(clinic_data~lmi_data[i,]+confounder_matrix))$coef[2,3])
}
return(list(gene_id_all=gene_ids, t_data=ans) )
}
init_simulation_gene_net <- function( base_correlation = 0.4, change_correlation = 0.8, sample_size = 100, num_gene = 5000, change_gene_num=5)
{
n_hop_matrix<-function(gene_graph, hop_n){
dis_mat <- igraph::shortest.paths(gene_graph)
dis_mat[dis_mat >hop_n] <- 0
dis_mat[dis_mat == hop_n] <- 0.5
return(dis_mat)
}
netdensity = 1
gene_graph <- igraph::barabasi.game(num_gene, m = netdensity)
deg_data <- igraph::degree(gene_graph)
simu_sel_gene_list = numeric()
neigh_list_3 <- numeric()
simu_gene_num = change_gene_num
times = 100
while(length(simu_sel_gene_list) < simu_gene_num)
{
sel_gene <- sample(which(deg_data<= 10 °_data >= 5), 1)
if(sel_gene %in% neigh_list_3)
{
times = times - 1
if(times<0)
{
return(NULL)
}
next()
}
simu_sel_gene_list <- c(simu_sel_gene_list, sel_gene)
neigh_list_3 <- c(neigh_list_3, unlist(igraph::neighborhood(gene_graph, order = 3, nodes = sel_gene, mode = 'all')) )
}
neigh_list <- numeric()
for(sel_gene in simu_sel_gene_list)
{
neigh_list <- c(neigh_list, unlist(igraph::neighborhood(gene_graph, order = 1, nodes = sel_gene, mode = 'all')) )
}
gene_code_list <- rnorm(num_gene, mean = 0, sd = 0)
for(gid in neigh_list)
{
gene_code_list[gid] <- 1
}
for(gid in simu_sel_gene_list){
gene_code_list[gid] <- 2
}
s <- igraph::shortest.paths(gene_graph)
s1 <- base_correlation^(s)
x <- t(mvtnorm::rmvnorm(n = sample_size, mean = rep(0,num_gene), sigma = s1, method = "chol"))
x <- t(apply(x, 1, function(x)(x-min(x))/(max(x)-min(x))))
y <- c(rnorm(sample_size, mean = 0, sd = 0 ), rnorm(sample_size, mean = 1, sd = 0))
dis_mat <- n_hop_matrix(gene_graph = gene_graph, hop_n = 2)
listw_obj <- spdep::mat2listw(dis_mat, style = 'W')
origin_lmi_data <- double()
for (i in seq(1, ncol(x), 1)){
lmi <- spdep::localmoran(x[,i],listw = listw_obj)
origin_lmi_data <- cbind(origin_lmi_data, lmi[,1])
}
for (i in neigh_list){
for (j in neigh_list){
s1[i,j] <- change_correlation^s[i,j]
}
}
x1 = x
x <- t(mvtnorm::rmvnorm(n = sample_size, mean = rep(0,num_gene), sigma = s1, method = "chol"))
x <- t(apply(x, 1, function(x)(x-min(x))/(max(x)-min(x))))
y <- c(rnorm(sample_size, mean = 0, sd = 0), rnorm(sample_size, mean = 1, sd = 0))
lmi_data <- double()
for (i in seq(1,ncol(x),1)){
lmi <- spdep::localmoran(x[,i], listw = listw_obj)
lmi_data <- cbind(lmi_data,lmi[,1])
}
lmi_matrix <- cbind(lmi_data, origin_lmi_data)
return(list(gene_graph = gene_graph, lmi_matrix = lmi_matrix, patient_matrix = y, neigh_list=neigh_list, gene_expr = cbind(x,x1)))
} |
gofGetHybrid <- function(result, p_values = NULL, nsets = NULL) {
if (!inherits(result, "gofCOP")) {
stop(
"Please input an object of class 'gofCOP'. Such an object will be returned by
functions of this package. If you input an object obtained from 'gof()', then
input the result for all copula."
)
}
if (length(nsets) > 1) {
stop("'nsets' has to be a single integer entry.")
}
res_list <- list()
for (j in seq_along(result)) {
if (length(result[[j]]) == 7) {
tmp <- rownames(result[[j]]$res.tests)
index <- which(startsWith(tmp, "hybrid"))
if (length(index) > 0) {
res_length <- length(tmp[-index])
} else {
res_length <- length(tmp)
}
} else {
res_length <- 1
}
num_tests <- length(p_values) + res_length
if (num_tests <= 1) {
stop(
"The input should contain information of at least two different tests."
)
}
if (!is.null(nsets)) {
if (nsets < 1 | nsets > num_tests) {
stop(
"Please set nsets larger or equal than 1 and smaller or equal than the
number of single tests. Otherwise hybrid testing is not meaningful."
)
}
}
which_comb <- list()
for (i in seq_len(2^num_tests)) {
which_comb[[i]] <- which(as.integer(intToBits(i)) == 1)
}
comb_exist <- which_comb[which(unlist(lapply(which_comb, length)) > 1)]
s_res_names <- rownames(result[[j]]$res.tests)
s_res_p <- result[[j]]$res.tests[, 1]
index <- which(startsWith(s_res_names, "hybrid"))
if (length(index) > 0) {
s_res_names <- s_res_names[-index]
s_res_p <- s_res_p[-index]
}
s_p_names <- if (!is.null(p_values)) {
if (is.null(names(p_values))) {
paste0("Test_", LETTERS[1:length(p_values)])
} else {
names(p_values)
}
} else {
NULL
}
s_names <- c(s_res_names, s_p_names)
p <- c(s_res_p, p_values)
if (!is.null(nsets)) {
if (nsets > 1) {
index <- which(lapply(comb_exist, FUN = function(x) {
length(x) == nsets
}) == TRUE)
comb_wanted <- comb_exist[index]
for (i in seq_along(comb_wanted)) {
p <- c(p, min(nsets * min(p[comb_wanted[[i]]]), 1))
}
comb_names <- paste("hybrid(",
lapply(comb_wanted, paste, collapse = ", "), ")",
sep = "")
res <- matrix(p, ncol = 1, dimnames = list(c(s_names, comb_names),
"p.value"))
} else {
res <- matrix(p, ncol = 1, dimnames = list(c(s_names), "p.value"))
}
} else {
for (i in seq_along(comb_exist)) {
p <- c(p, min(length(comb_exist[[i]]) * min(p[comb_exist[[i]]]), 1))
}
comb_names <- paste("hybrid(",
lapply(comb_exist, paste, collapse = ", "), ")",
sep = "")
res <- matrix(p, ncol = 1, dimnames = list(c(s_names, comb_names),
"p.value"))
}
res_list[[j]] <- list(
method = "Hybrid test p-values for given single tests.",
copula = result[[j]]$copula,
margins = result[[j]]$margins,
param.margins = result[[j]]$param.margins,
theta = result[[j]]$theta,
df = result[[j]]$df,
res.tests = res
)
}
names(res_list) <- names(result)
return(structure(
class = "gofCOP",
res_list
))
} |
test_that("multiplication works", {
load(system.file("extdata/meta_data.RData", package = "dataquieR"),
envir = environment())
load(system.file("extdata/study_data.RData", package = "dataquieR"),
envir = environment())
meta_data[meta_data[[LABEL]] == "EATING_PREFS_0", RECODE] <-
"0"
meta_data[meta_data[[LABEL]] == "MEAT_CONS_0", RECODE] <-
"1| 2|3 | 4 "
m_study_data <- util_replace_codes_by_NA(study_data, meta_data)$study_data
d_study_data <- util_dichotomize(m_study_data, meta_data)
x <- d_study_data[,
prep_map_labels(c("EATING_PREFS_0", "MEAT_CONS_0"),
from = LABEL, to = VAR_NAMES, meta_data = meta_data)]
expect_equal(
d_study_data[["v00022"]],
ifelse(is.na(m_study_data[["v00022"]]),
NA,
ifelse(m_study_data[["v00022"]] %in% 0,
0,
1
)
)
)
expect_equal(
d_study_data[["v00023"]],
ifelse(is.na(m_study_data[["v00023"]]),
NA,
ifelse(m_study_data[["v00023"]] %in% 1:4,
0,
1
)
)
)
}) |
Menu.steepest <- function(){
.activeModel <- ActiveModel()
degree <- get(.activeModel)$order
initializeDialog(window=top, title=gettextRcmdr("Steepest slope analysis"))
if (degree==2) typerbVariable <- tclVar("canonical.path")
else typerbVariable <- tclVar("steepest")
if (tclvalue(typerbVariable)=="steepest")
explainVariable <- tclVar("positive values only, separate by blank\nsteps from all xs at 0")
else
explainVariable <- tclVar("positive values only, separate by blank\none direction from all xs at 0 or\n+/- directions from stationary point")
if (degree==2){
typerbFrame <- ttklabelframe(top,text=gettextRcmdr("Where to start steepest slope ?"))
midrbButton <- tkradiobutton(typerbFrame, text="steepest slope from all xs at 0",variable=typerbVariable, value="steepest")
statrbButton <- tkradiobutton(typerbFrame, text="steepest slope from stationary point",variable=typerbVariable, value="canonical.path")
tkgrid(midrbButton, sticky ="w")
tkgrid(statrbButton, sticky ="w")
}
dirrbVariable <- tclVar("ascent")
dirrbFrame <- ttklabelframe(top,text=gettextRcmdr("Up or Down ?"))
uprbButton <- tkradiobutton(dirrbFrame, text="steepest ascent",variable=dirrbVariable, value="ascent")
downrbButton <- tkradiobutton(dirrbFrame, text="steepest descent",variable=dirrbVariable, value="descent")
tkgrid(uprbButton, sticky ="w")
tkgrid(downrbButton, sticky ="w")
if (degree==2) tkgrid(typerbFrame, dirrbFrame, sticky="w")
else tkgrid(ttklabel(top, text="Steepest slope starts at all xs at 0"), dirrbFrame, sticky="w")
if (!exists(".move.distances", where="RcmdrEnv"))
putRcmdr(".move.distances", seq(0,5,0.5))
distVar <- tclVar(paste(.move.distances, collapse=" "))
distEntry <- tkentry(top, width="50", textvariable=distVar)
distlab <- ttklabel(top, text="Step widths for steepest directions")
distexplain <- ttklabel(top, textvariable=explainVariable)
tkgrid(distlab, distEntry,sticky="w")
tkgrid(tklabel(top, text="NOTE:"), distexplain,sticky="e")
tkgrid.configure(distlab, sticky="e")
tkgrid.configure(distexplain, sticky="w")
onOK <- function(){
dist <- as.numeric(strsplit(tclvalue(distVar), " ", fixed=TRUE)[[1]])
if (tclvalue(typerbVariable)=="canonical.path")
dist <- sort(unique(c(-dist, dist)))
command <- paste(tclvalue(typerbVariable), "(",.activeModel,", descent=", tclvalue(dirrbVariable)=="descent",
", dist=c(", paste(dist, collapse=","), "))")
hilf <- doItAndPrint(command)
if (class(hilf)[1]=="try-error") {
errorCondition(window=top,recall=Menu.steepest, message=gettextRcmdr(hilf))
return()
}
closeDialog(window=top)
tkwm.deiconify(CommanderWindow())
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="Menu.steepest")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
dialogSuffix(window=top, rows=2, columns=2)
} |
f.apply <-
function ( FUN=NULL, simplify = TRUE, ... ) {
arrFiles<-as.matrix(sort(tk_choose.files()))
iLast<-dim(arrFiles)[1]
if (iLast<1) return(
invisible(tk_messageBox(type="ok", "You should select at least one file!", caption="Problems"))
)
sapply(X=arrFiles, FUN=FUN, simplify = simplify, ...)->n.files
if(length(n.files)!=iLast) {
tk_messageBox(type="ok", "There is some kind of problems!", caption="Problems")
return(n.files)}
} |
rmodd_summary <- function (x, rm = "FALSE", strict= "FALSE", cutoff=80,n=3 ) {
z1<-c(mean(x),stats::median(x),length(x),stats::sd(x),stats::sd(x)/mean(x)*100)
if(rm=="FALSE"){names(z1)<-c("mean","median","n","sd","cv")
return(z1)}
if(rm=="TRUE"){
if(z1[5]< cutoff & strict == "FALSE") {names(z1)<-c("mean","median","n","sd","cv")
return(z1)}
if(z1[5]> cutoff & strict == "FALSE") {
Q <- stats::quantile(x,probs=c(0.25,0.75),na.rm=FALSE)
iqr <- stats::IQR(x)
up <- Q[2]+1.5*iqr
low<- Q[1]-1.5*iqr
x<- subset(x, (x > low & x < up))
z1<-c(mean(x),stats::median(x),length(x),stats::sd(x),stats::sd(x)/mean(x)*100)
names(z1)<-c("mean","median","n","sd","cv")
return(z1)
}
zn<-z1
cycle<-0
while (abs(z1[5])> cutoff & strict == "TRUE") {
cycle<-cycle+1
up_P<-1-0.1*cycle
low_P<-0.1*cycle
temp1<-x[which(!(x> stats::quantile(x,probs=up_P)))]
z2<-c(mean(temp1),stats::median(temp1),length(temp1),stats::sd(temp1)/mean(temp1)*100)
d2<-abs(zn[2]-z2[2])
temp2<-x[which(!(x < stats::quantile(x,probs=low_P)))]
z3<-c(mean(temp2),stats::median(temp2),length(temp2),stats::sd(temp2)/mean(temp2)*100)
d3<-abs(zn[2]-z3[2])
if (d2<d3) {out<-which(!(x < stats::quantile(x,probs=low_P) | x >= stats::quantile(x,probs=up_P)))}
if(d2>d3){out<-which(!(x <= stats::quantile(x,probs=low_P) | x > stats::quantile(x,probs=up_P)))}
if (d2==d3){out<-which(!(x < stats::quantile(x,probs=low_P) | x > stats::quantile(x,probs=up_P)))}
x<-x[out]
z1new<-c(mean(x),stats::median(x),length(x),stats::sd(x),stats::sd(x)/mean(x)*100)
if(z1new[3]<=n){break}
z1<-z1new
names(z1)<-c("mean","median","n","sd","cv")
}
return(z1)
}
} |
"target" |
context("test-seed-cipher")
test_that("Caesar encryption works", {
expect_equal(seed_cipher("Veni Vidi Vici.",
seed = 64),
"BhXQGBQ,QGBQ Q_")
test_that("Caesar encryption works", {
expect_equal(seed_cipher(c("Veni Vidi Vici.",
"Vici. Vidi Veni",
"The best way of avenging thyself is not to become like the wrong doer."),
seed = 64),
c("BhXQGBQ,QGBQ Q_",
"BQ Q_GBQ,QGBhXQ",
"-0hG+h
})
test_that("Caesar deencryption works", {
expect_equal(seed_cipher(c("BhXQGBQ,QGBQ Q_",
"-0hG+h
seed = 64,
decrypt = TRUE),
c("Veni Vidi Vici.",
"The best way of avenging thyself is not to become like the wrong doer."))
})
}) |
memmodel <- function(i.data,
i.seasons = 10,
i.type.threshold = 5,
i.level.threshold = 0.95,
i.tails.threshold = 1,
i.type.intensity = 6,
i.level.intensity = c(0.40, 0.90, 0.975),
i.tails.intensity = 1,
i.type.curve = 2,
i.level.curve = 0.95,
i.type.other = 3,
i.level.other = 0.95,
i.method = 2,
i.param = 2.8,
i.centering = -1,
i.n.max = -1,
i.type.boot = "norm",
i.iter.boot = 10000,
i.mem.info = T) {
if (is.null(dim(i.data))) {
memmodel.output <- NULL
cat("Incorrect number of dimensions, input must be a data.frame.
")
} else if (!(ncol(i.data) > 1)) {
memmodel.output <- NULL
cat("Incorrect number of dimensions, at least two seasons of data required.
")
} else {
datos <- i.data[apply(i.data, 2, function(x) sum(x, na.rm = T) > 0)]
if (NCOL(datos) == 0) {
memmodel.output <- NULL
cat("No colums with valid values.
")
} else {
if (is.matrix(datos)) datos <- as.data.frame(datos)
if (is.null(i.seasons)) i.seasons <- NA
if (!is.na(i.seasons)) if (i.seasons > 0) datos <- datos[(max((dim(datos)[2]) - i.seasons + 1, 1)):(dim(datos)[2])]
datos <- as.data.frame(apply(datos, 2, fill.missing))
semanas <- dim(datos)[1]
anios <- NCOL(datos)
if (NCOL(datos) < 2) {
memmodel.output <- NULL
cat("Al least two columns required.
")
} else {
if (is.na(i.n.max)) {
n.max <- max(1, round(30 / anios, 0))
} else {
if (i.n.max == -1) {
n.max <- max(1, round(30 / anios, 0))
} else if (i.n.max == 0) {
n.max <- semanas
} else {
n.max <- i.n.max
}
}
if (is.null(i.method)) i.method <- 2
if (is.na(i.method)) i.method <- 2
if (is.null(i.param)) i.param <- 2.8
if (is.na(i.param)) i.param <- 2.8
optimo <- apply(datos, 2, memtiming, i.n.values = n.max, i.method = i.method, i.param = i.param)
datos.duracion.real <- extraer.datos.optimo.map(optimo)
ic.duracion <- iconfianza(as.numeric(datos.duracion.real[1, ]), i.level.other, i.type.other, T, i.type.boot, i.iter.boot, 2)
ic.duracion <- rbind(ic.duracion, c(floor(ic.duracion[1]), round(ic.duracion[2]), ceiling(ic.duracion[3])))
ic.porcentaje <- iconfianza(as.numeric(datos.duracion.real[2, ]), i.level.other, i.type.other, T, i.type.boot, i.iter.boot, 2)
duracion.media <- ic.duracion[2, 2]
if (is.na(i.centering) | i.centering == -1) duracion.centrado <- duracion.media else duracion.centrado <- i.centering
semana.inicio <- as.integer(rownames(datos)[1])
gripe <- array(dim = c(7, anios, 3), dimnames = list(
"indicators" = c("epidemic start", "epidemic end", "sum of epidemic values", "sum of values", "covered percentage", "sum of pre-epidemic values", "sum of post-epidemic values"),
"seasons" = names(datos),
"type" = c("real epidemic", "mean length epidemic", "centered length epidemic")
))
datos.duracion.media <- extraer.datos.curva.map(optimo, duracion.media)
datos.duracion.centrado <- extraer.datos.curva.map(optimo, duracion.centrado)
ic.inicio <- iconfianza(as.numeric(datos.duracion.real[4, ]), i.level.other, i.type.other, T, i.type.boot, i.iter.boot, 2)
ic.inicio <- rbind(ic.inicio, c(floor(ic.inicio[1]), round(ic.inicio[2]), ceiling(ic.inicio[3])))
ic.inicio <- rbind(ic.inicio, c(semana.absoluta(ic.inicio[2, 1], semana.inicio), semana.absoluta(ic.inicio[2, 2], semana.inicio), semana.absoluta(ic.inicio[2, 3], semana.inicio)))
ic.inicio <- ic.inicio[c(2, 3, 1), ]
inicio.medio <- ic.inicio[1, 2]
ic.inicio.centrado <- iconfianza(as.numeric(datos.duracion.centrado[4, ]), i.level.other, i.type.other, T, i.type.boot, i.iter.boot, 2)
ic.inicio.centrado <- rbind(ic.inicio.centrado, c(floor(ic.inicio.centrado[1]), round(ic.inicio.centrado[2]), ceiling(ic.inicio.centrado[3])))
ic.inicio.centrado <- rbind(ic.inicio.centrado, c(semana.absoluta(ic.inicio.centrado[2, 1], semana.inicio), semana.absoluta(ic.inicio.centrado[2, 2], semana.inicio), semana.absoluta(ic.inicio.centrado[2, 3], semana.inicio)))
ic.inicio.centrado <- ic.inicio.centrado[c(2, 3, 1), ]
inicio.centrado <- ic.inicio.centrado[1, 2]
for (j in 1:anios) {
gripe[1, j, 1] <- datos.duracion.real[4, j]
gripe[2, j, 1] <- datos.duracion.real[5, j]
gripe[3, j, 1] <- datos.duracion.real[3, j]
gripe[4, j, 1] <- sum(datos[, j], na.rm = TRUE)
gripe[5, j, 1] <- datos.duracion.real[2, j]
if (gripe[1, j, 1] > 1) gripe[6, j, 1] <- sum(datos[1:(gripe[1, j, 1] - 1), j], na.rm = TRUE) else gripe[6, j, 1] <- 0
if (gripe[2, j, 1] < semanas) gripe[7, j, 1] <- sum(datos[(gripe[2, j, 1] + 1):semanas, j], na.rm = TRUE) else gripe[7, j, 1] <- 0
gripe[1, j, 2] <- datos.duracion.media[4, j]
gripe[2, j, 2] <- datos.duracion.media[5, j]
gripe[3, j, 2] <- datos.duracion.media[3, j]
gripe[4, j, 2] <- sum(datos[, j], na.rm = TRUE)
gripe[5, j, 2] <- datos.duracion.media[2, j]
if (gripe[1, j, 2] > 1) gripe[6, j, 2] <- sum(datos[1:(gripe[1, j, 2] - 1), j], na.rm = TRUE) else gripe[6, j, 2] <- 0
if (gripe[2, j, 2] < semanas) gripe[7, j, 2] <- sum(datos[(gripe[2, j, 2] + 1):semanas, j], na.rm = TRUE) else gripe[7, j, 2] <- 0
gripe[1, j, 3] <- datos.duracion.centrado[4, j]
gripe[2, j, 3] <- datos.duracion.centrado[5, j]
gripe[3, j, 3] <- datos.duracion.centrado[3, j]
gripe[4, j, 3] <- sum(datos[, j], na.rm = TRUE)
gripe[5, j, 3] <- datos.duracion.centrado[2, j]
if (gripe[1, j, 3] > 1) gripe[6, j, 3] <- sum(datos[1:(gripe[1, j, 3] - 1), j], na.rm = TRUE) else gripe[6, j, 3] <- 0
if (gripe[2, j, 3] < semanas) gripe[7, j, 3] <- sum(datos[(gripe[2, j, 3] + 1):semanas, j], na.rm = TRUE) else gripe[7, j, 3] <- 0
}
indices.temporada <- array(dim = c(semanas, anios, 3), dimnames = list(
"weeks" = rownames(datos),
"seasons" = names(datos),
"type" = c("real epidemic", "mean length epidemic", "centered length epidemic")
))
for (j in 1:anios) {
indices.temporada[-((datos.duracion.real[4, j]):semanas), j, 1] <- 1
indices.temporada[(datos.duracion.real[4, j]):(datos.duracion.real[5, j]), j, 1] <- 2
indices.temporada[-(1:(datos.duracion.real[5, j])), j, 1] <- 3
indices.temporada[-((datos.duracion.media[4, j]):semanas), j, 2] <- 1
indices.temporada[(datos.duracion.media[4, j]):(datos.duracion.media[5, j]), j, 2] <- 2
indices.temporada[-(1:(datos.duracion.media[5, j])), j, 2] <- 3
indices.temporada[-((datos.duracion.centrado[4, j]):semanas), j, 3] <- 1
indices.temporada[(datos.duracion.centrado[4, j]):(datos.duracion.centrado[5, j]), j, 3] <- 2
indices.temporada[-(1:(datos.duracion.centrado[5, j])), j, 3] <- 3
}
longitud.esquema <- semanas + max.fix.na(datos.duracion.centrado[4, ]) - min.fix.na(datos.duracion.centrado[4, ])
inicio.epidemia.esquema <- max.fix.na(datos.duracion.centrado[4, ])
fin.epidemia.esquema <- max.fix.na(datos.duracion.centrado[5, ])
esquema.temporadas <- array(dim = c(longitud.esquema, anios + 2, 3), dimnames = list(
"dummy weeks" = as.character(1:longitud.esquema),
"seasons" = c(names(datos), "mean season week", "mean season index"),
"type" = c("absolute week", "relative week", "values")
))
for (j in 1:anios) {
diferencia.anual <- inicio.epidemia.esquema - datos.duracion.centrado[4, j]
for (i in 1:semanas) {
esquema.temporadas[i + diferencia.anual, j, 1] <- i
esquema.temporadas[i + diferencia.anual, j, 2] <- semana.absoluta(i, semana.inicio)
esquema.temporadas[i + diferencia.anual, j, 3] <- datos[i, j]
}
}
diferencia.global <- inicio.epidemia.esquema - inicio.centrado
for (i in 1:semanas) {
if ((i + diferencia.global) >= 1 & (i + diferencia.global) <= longitud.esquema) {
esquema.temporadas[i + diferencia.global, anios + 1, 1] <- i
esquema.temporadas[i + diferencia.global, anios + 1, 2] <- semana.absoluta(i, semana.inicio)
esquema.temporadas[i + diferencia.global, anios + 1, 3] <- i
}
}
esquema.temporadas[, anios + 2, ] <- 3
esquema.temporadas[1:(diferencia.global + inicio.medio - 1), anios + 2, ] <- 1
esquema.temporadas[(diferencia.global + inicio.medio):(diferencia.global + inicio.medio + duracion.media - 1), anios + 2, ] <- 2
temporadas.moviles <- esquema.temporadas[, c(1:anios), 3]
temporadas.moviles.recortada <- array(dim = c(semanas, anios), dimnames = list(
"dummy weeks" = as.character(1:semanas),
"seasons" = names(datos)
))
for (j in 1:anios) {
for (i in 1:semanas) {
if ((i + diferencia.global) >= 1 & (i + diferencia.global) <= longitud.esquema) {
temporadas.moviles.recortada[i, j] <- temporadas.moviles[i + diferencia.global, j]
} else {
temporadas.moviles.recortada[i, j] <- NA
}
}
}
iy <- is.na(temporadas.moviles.recortada)
temporadas.moviles.recortada.no.ceros <- temporadas.moviles.recortada
temporadas.moviles.recortada.no.ceros[iy] <- NA
curva.tipo <- t(apply(temporadas.moviles.recortada.no.ceros, 1, iconfianza, nivel = i.level.curve, tipo = i.type.curve, ic = T, tipo.boot = i.type.boot, iteraciones.boot = i.iter.boot, colas = 2))
pre.datos <- as.vector(as.matrix(extraer.datos.pre.epi(optimo)))
post.datos <- as.vector(as.matrix(extraer.datos.post.epi(optimo)))
epi.datos <- as.vector(as.matrix(extraer.datos.epi(optimo)))
epi.datos.2 <- as.vector(as.matrix(apply(datos, 2, max.n.valores, n.max = n.max)))
pre.post.datos <- rbind(pre.datos, post.datos)
pre.d <- pre.datos[!is.na(pre.datos)]
post.d <- post.datos[!is.na(post.datos)]
epi.d <- epi.datos[!is.na(epi.datos)]
epi.d.2 <- epi.datos.2[!is.na(epi.datos.2)]
pre.i <- iconfianza(pre.d, nivel = i.level.threshold, tipo = i.type.threshold, ic = T, tipo.boot = i.type.boot, iteraciones.boot = i.iter.boot, colas = i.tails.threshold)
post.i <- iconfianza(post.d, nivel = i.level.threshold, tipo = i.type.threshold, ic = T, tipo.boot = i.type.boot, iteraciones.boot = i.iter.boot, colas = i.tails.threshold)
epi.intervalos <- numeric()
for (niv in i.level.intensity) epi.intervalos <- rbind(epi.intervalos, c(niv, iconfianza(epi.d, nivel = niv, tipo = i.type.intensity, ic = T, colas = i.tails.intensity)))
epi.intervalos.2 <- numeric()
for (niv in i.level.intensity) epi.intervalos.2 <- rbind(epi.intervalos.2, c(niv, iconfianza(epi.d.2, nivel = niv, tipo = i.type.intensity, ic = T, colas = i.tails.intensity)))
pre.post.intervalos <- rbind(pre.i, post.i)
memmodel.output <- list(
pre.post.intervals = pre.post.intervalos,
ci.length = ic.duracion,
ci.percent = ic.porcentaje,
ci.start = ic.inicio,
mean.length = duracion.media,
mean.start = inicio.medio,
centered.length = duracion.centrado,
centered.start = inicio.centrado,
moving.epidemics = temporadas.moviles.recortada,
epi.intervals = epi.intervalos,
epi.intervals.full = epi.intervalos.2,
typ.curve = curva.tipo,
n.max = n.max,
n.seasons = anios,
n.weeks = semanas,
data = datos,
start.week = semana.inicio,
epi.data = epi.datos,
epi.data.nona = epi.d,
epi.data.full = epi.datos.2,
epi.data.nona.full = epi.d.2,
optimum = optimo,
real.length.data = datos.duracion.real,
seasons.data = gripe,
season.indexes = indices.temporada,
season.scheme = esquema.temporadas,
seasons.moving = temporadas.moviles,
pre.post.data = pre.post.datos,
pre.data.nona = pre.d,
post.data.nona = post.d,
epidemic.thresholds = as.numeric(pre.post.intervalos[, 3]),
intensity.thresholds = as.numeric(epi.intervalos[, 4]),
param.data = i.data,
param.seasons = i.seasons,
param.type.threshold = i.type.threshold,
param.level.threshold = i.level.threshold,
param.tails.threshold = i.tails.threshold,
param.type.intensity = i.type.intensity,
param.level.intensity = i.level.intensity,
param.tails.intensity = i.tails.intensity,
param.type.curve = i.type.curve,
param.level.curve = i.level.curve,
param.type.other = i.type.other,
param.level.other = i.level.other,
param.method = i.method,
param.param = i.param,
param.centering = i.centering,
param.n.max = i.n.max,
param.type.boot = i.type.boot,
param.iter.boot = i.iter.boot,
param.mem.info = i.mem.info
)
memmodel.output$call <- match.call()
class(memmodel.output) <- "mem"
}
}
}
return(memmodel.output)
}
print.mem <- function(x, ...) {
threshold <- as.data.frame(round(t(x$pre.post.intervals[1:2, 3]), 2))
colnames(threshold) <- c("Pre", "Post")
rownames(threshold) <- "Threshold"
values <- as.data.frame(round(x$epi.intervals[, 4], 2))
colnames(values) <- "Threshold"
rownames(values) <- paste(c("Medium", "High", "Very high"), " (", round(x$epi.intervals[, 1] * 100, 1), "%)", sep = "")
cat("Call:\n")
print(x$call)
cat("\nEpidemic threshold:\n")
print(threshold)
cat("\nIntensity thresholds:\n")
print(values)
}
summary.mem <- function(object, ...) {
threshold <- as.data.frame(round(t(object$pre.post.intervals[1:2, 3]), 2))
colnames(threshold) <- c("Pre", "Post")
rownames(threshold) <- "Threshold"
values <- as.data.frame(round(object$epi.intervals[, 4], 2))
colnames(values) <- "Threshold"
rownames(values) <- paste(c("Medium", "High", "Very high"), " (", round(object$epi.intervals[, 1] * 100, 1), "%)", sep = "")
cat("Call:\n", sep = "")
print(object$call)
cat("\nParameters:\n", sep = "")
cat("\t- General:\n", sep = "")
cat("\t\t+ Number of seasons restriction: ", if (object$param.seasons == -1 | is.na(object$param.seasons)) "Unrestricted (maximum)" else paste("Restricted to ", object$param.seasons, sep = ""), "\n", sep = "")
cat("\t\t+ Number of seasons used: ", object$n.seasons, "\n", sep = "")
cat("\t\t+ Seasons used: ", paste(names(object$data), collapse = ", "), "\n", sep = "")
cat("\t\t+ Number of weeks: ", object$n.weeks, "\n", sep = "")
cat("\t- Confidence intervals:\n", sep = "")
cat("\t\t+ Epidemic threshold: ", output.ci(object$param.type.threshold, object$param.level.threshold, object$param.tails.threshold), "\n", sep = "")
cat("\t\t+ Intensity: ", output.ci(object$param.type.intensity, object$param.level.intensity, object$param.tails.intensity), "\n", sep = "")
cat("\t\t+ Curve: ", output.ci(object$param.type.curve, object$param.level.curve, 2), "\n", sep = "")
cat("\t\t+ Others: ", output.ci(object$param.type.other, object$param.level.other, 2), "\n", sep = "")
cat("\t- Epidemic timing calculation:\n", sep = "")
cat("\t\t+ Method: ", object$param.method, "\n", sep = "")
cat("\t\t+ Parameter: ", object$param.param, "\n", sep = "")
cat("\t- Epidemic threshold calculation:\n", sep = "")
cat("\t\t+ Pre-epidemic values: ", if (is.na(object$param.n.max)) {
paste("Optimized: ", object$n.max, sep = "")
} else {
if (object$param.n.max == -1) paste("Optimized: ", object$n.max, sep = "") else object$n.max
}, "\n", sep = "")
cat("\t\t+ Tails of CI: ", object$param.tails.threshold, "\n", sep = "")
cat("\t- Intensity thresholds calculation:\n", sep = "")
cat("\t\t+ Number of values: ", if (is.na(object$param.n.max)) {
paste("Optimized: ", object$n.max, sep = "")
} else {
if (object$param.n.max == -1) paste("Optimized: ", object$n.max, sep = "") else object$n.max
}, "\n", sep = "")
cat("\t\t+ Tails of CI: ", object$param.tails.intensity, "\n", sep = "")
cat("\t\t+ Levels of CI: ", paste0(paste0(c("Medium", "High", "Very high"), ": ", round(object$epi.intervals[, 1] * 100, 1), "%"), collapse = ", "), "\n")
cat("\t- Bootstrap (if used):\n", sep = "")
cat("\t\t+ Technique: ", if (is.na(object$param.type.boot)) "-" else object$param.type.boot, "\n", sep = "")
cat("\t\t+ Bootstrap samples: ", if (is.na(object$param.iter.boot)) "-" else object$param.iter.boot, "\n", sep = "")
cat("\nEpidemic description:\n", sep = "")
cat("\t- Typical influenza epidemics starts at week ", round(object$ci.start[2, 2], 2), ". ", 100 * object$param.level.other, "% CI: [", round(object$ci.start[2, 1], 2), ",", round(object$ci.start[2, 3], 2), "]\n", sep = "")
cat("\t- Typical influenza season lasts ", round(object$ci.length[1, 2], 2), " weeks. ", 100 * object$param.level.other, "% CI: [", round(object$ci.length[1, 1], 2), ",", round(object$ci.length[1, 3], 2), "]\n", sep = "")
cat("\t- This optimal ", object$mean.length, " weeks influenza season includes the ", round(object$ci.percent[2], 2), "% of the total sum of rates\n\n", sep = "")
cat("\nEpidemic threshold:\n", sep = "")
print(threshold)
cat("\n\nIntensity thresholds:\n", sep = "")
print(values)
}
plot.mem <- function(x, ...) {
opar <- par(mfrow = c(1, 2), mar = c(4, 3, 1, 2) + 0.1, mgp = c(3, 0.5, 0), xpd = T)
semanas <- dim(x$data)[1]
anios <- dim(x$data)[2]
names.seasons <- sub("^.*\\(([^\\)]*)\\)$", "\\1", names(x$data), perl = T)
datos.graf <- x$moving.epidemics
colnames(datos.graf) <- names(x$data)
lab.graf <- (1:semanas) + x$ci.start[2, 2] - x$ci.start[1, 2]
lab.graf[lab.graf > 52] <- (lab.graf - 52)[lab.graf > 52]
lab.graf[lab.graf < 1] <- (lab.graf + 52)[lab.graf < 1]
tipos <- rep(1, anios)
anchos <- rep(2, anios)
pal <- colorRampPalette(brewer.pal(4, "Spectral"))
colores <- pal(anios)
otick <- optimal.tickmarks(0, max.fix.na(datos.graf), 10)
range.y <- c(otick$range[1], otick$range[2] + otick$by / 2)
matplot(1:semanas,
datos.graf,
type = "l",
sub = paste("Weekly incidence rates of the seasons matching their relative position in the model."),
lty = tipos,
lwd = anchos,
col = colores,
xlim = c(1, semanas),
xlab = "",
ylab = "",
axes = F,
font.main = 2,
font.sub = 1,
ylim = range.y
)
axis(1, at = seq(1, semanas, 1), labels = F, cex.axis = 0.7, col.axis = "
axis(1,
at = seq(1, semanas, 2), tick = F,
labels = as.character(lab.graf)[seq(1, semanas, 2)], cex.axis = 0.7, col.axis = "
)
axis(1,
at = seq(2, semanas, 2), tick = F,
labels = as.character(lab.graf)[seq(2, semanas, 2)], cex.axis = 0.7, line = 0.60, col.axis = "
)
mtext(1, text = "Week", line = 2, cex = 0.8, col = "
axis(2, at = otick$tickmarks, lwd = 1, cex.axis = 0.6, col.axis = "
mtext(2, text = "Weekly rate", line = 1.3, cex = 0.8, col = "
if (x$param.mem.info) mtext(4, text = paste("mem R library - Jose E. Lozano - https://github.com/lozalojo/mem", sep = ""), line = 0.75, cex = 0.6, col = "
i.temporada <- x$ci.start[1, 2]
f.temporada <- x$ci.start[1, 2] + x$mean.length - 1
lines(x = rep(i.temporada - 0.5, 2), y = range.y, col = "
lines(x = rep(f.temporada + 0.5, 2), y = range.y, col = "
lines(x = c(1, semanas), y = rep(x$epidemic.thresholds[1], 2), col = "
ya <- otick$range[2]
if ((i.temporada - 1) <= (semanas - f.temporada)) xa <- f.temporada + 1 else xa <- 1
legend(
x = xa, y = ya, inset = c(0, 0), xjust = 0, seg.len = 1,
legend = names.seasons,
bty = "n",
lty = tipos,
lwd = anchos,
col = colores,
cex = 0.75,
x.intersp = 0.5,
y.intersp = 0.6,
text.col = "
ncol = 1
)
temp1 <- memsurveillance(
i.current = data.frame(rates = x$typ.curve[, 2], row.names = rownames(x$data)),
i.epidemic.thresholds = x$epidemic.thresholds,
i.intensity.thresholds = x$intensity.thresholds,
i.mean.length = x$mean.length,
i.force.length = T,
i.graph.file = F,
i.week.report = NA,
i.equal = F,
i.pos.epidemic = T,
i.no.epidemic = F,
i.no.intensity = F,
i.epidemic.start = x$ci.start[2, 2],
i.range.x = as.numeric(c(rownames(x$data)[1], rownames(x$data)[semanas])),
i.range.x.53 = F,
i.range.y = NA,
i.no.labels = F,
i.start.end.marks = T
)
par(opar)
} |
softmax_regression <- function(input_model=NA,
labels=NA,
lambda=NA,
max_iterations=NA,
no_intercept=FALSE,
number_of_classes=NA,
test=NA,
test_labels=NA,
training=NA,
verbose=FALSE) {
IO_RestoreSettings("Softmax Regression")
if (!identical(input_model, NA)) {
IO_SetParamSoftmaxRegressionPtr("input_model", input_model)
}
if (!identical(labels, NA)) {
IO_SetParamURow("labels", to_matrix(labels))
}
if (!identical(lambda, NA)) {
IO_SetParamDouble("lambda", lambda)
}
if (!identical(max_iterations, NA)) {
IO_SetParamInt("max_iterations", max_iterations)
}
if (!identical(no_intercept, FALSE)) {
IO_SetParamBool("no_intercept", no_intercept)
}
if (!identical(number_of_classes, NA)) {
IO_SetParamInt("number_of_classes", number_of_classes)
}
if (!identical(test, NA)) {
IO_SetParamMat("test", to_matrix(test))
}
if (!identical(test_labels, NA)) {
IO_SetParamURow("test_labels", to_matrix(test_labels))
}
if (!identical(training, NA)) {
IO_SetParamMat("training", to_matrix(training))
}
if (verbose) {
IO_EnableVerbose()
} else {
IO_DisableVerbose()
}
IO_SetPassed("output_model")
IO_SetPassed("predictions")
softmax_regression_mlpackMain()
output_model <- IO_GetParamSoftmaxRegressionPtr("output_model")
attr(output_model, "type") <- "SoftmaxRegression"
out <- list(
"output_model" = output_model,
"predictions" = IO_GetParamURow("predictions")
)
IO_ClearSettings()
return(out)
} |
tscsEstimate3D <- function(matrix, newdata, h1, h2, v){
NA_id <- which(is.na(newdata[,4])==TRUE);
X <- newdata[,1];Y <- newdata[,2];Z <- newdata[,3];
N <- length(NA_id);
A <- matrix(0,N,N);
B <- rep(0,N);
for (i in 1:N)
{
XN <- X[NA_id[i]];YN <- Y[NA_id[i]];ZN <- Z[NA_id[i]];
A[i,i] <- 1;
B[i] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$intercept;
if (!is.na(newdata[which((X==XN - h1)&(Y==YN)&(Z==ZN)),4])) {
r1 <- newdata[which((X==XN - h1)&(Y==YN)&(Z==ZN)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta1*r1; } else{
s1 <- which(NA_id==which((X==XN - h1)&(Y==YN)&(Z==ZN)));
A[i,s1] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta1*(-1); }
if (!is.na(newdata[which((X==XN + h1)&(Y==YN)&(Z==ZN)),4])) {
r2 <- newdata[which((X==XN + h1)&(Y==YN)&(Z==ZN)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta2*r2; } else{
s2 <- which(NA_id==which((X==XN + h1)&(Y==YN)&(Z==ZN)));
A[i,s2] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta2*(-1); }
if (!is.na(newdata[which((X==XN)&(Y==YN - h2)&(Z==ZN)),4])) {
r3 <- newdata[which((X==XN)&(Y==YN - h2)&(Z==ZN)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta3*r3; } else{
s3 <- which(NA_id==which((X==XN)&(Y==YN - h2)&(Z==ZN)));
A[i,s3] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta3*(-1); }
if (!is.na(newdata[which((X==XN)&(Y==YN + h2)&(Z==ZN)),4])) {
r4 <- newdata[which((X==XN)&(Y==YN + h2)&(Z==ZN)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta4*r4; } else{
s4 <- which(NA_id==which((X==XN)&(Y==YN + h2)&(Z==ZN)));
A[i,s4] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta4*(-1); }
if (!is.na(newdata[which((X==XN)&(Y==YN)&(Z==ZN - v)),4])) {
r5 <- newdata[which((X==XN)&(Y==YN)&(Z==ZN - v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta5*r5; } else{
s5 <- which(NA_id==which((X==XN)&(Y==YN)&(Z==ZN - v)));
A[i,s5] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta5*(-1); }
if (!is.na(newdata[which((X==XN)&(Y==YN)&(Z==ZN + v)),4])) {
r6 <- newdata[which((X==XN)&(Y==YN)&(Z==ZN + v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta6*r6; } else{
s6 <- which(NA_id==which((X==XN)&(Y==YN)&(Z==ZN + v)));
A[i,s6] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta6*(-1); }
if (!is.na(newdata[which((X==XN + h1)&(Y==YN + h2)&(Z==ZN + v)),4])) {
r7 <- newdata[which((X==XN + h1)&(Y==YN + h2)&(Z==ZN + v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta7*r7; } else{
s7 <- which(NA_id==which((X==XN + h1)&(Y==YN + h2)&(Z==ZN + v)));
A[i,s7] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta7*(-1); }
if (!is.na(newdata[which((X==XN - h1)&(Y==YN - h2)&(Z==ZN + v)),4])) {
r8 <- newdata[which((X==XN - h1)&(Y==YN - h2)&(Z==ZN + v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta8*r8; } else{
s8 <- which(NA_id==which((X==XN - h1)&(Y==YN - h2)&(Z==ZN + v)));
A[i,s8] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta8*(-1); }
if (!is.na(newdata[which((X==XN + h1)&(Y==YN - h2)&(Z==ZN + v)),4])) {
r9 <- newdata[which((X==XN + h1)&(Y==YN - h2)&(Z==ZN + v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta9*r9; } else{
s9 <- which(NA_id==which((X==XN + h1)&(Y==YN - h2)&(Z==ZN + v)));
A[i,s9] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta9*(-1); }
if (!is.na(newdata[which((X==XN - h1)&(Y==YN + h2)&(Z==ZN + v)),4])) {
r10 <- newdata[which((X==XN - h1)&(Y==YN + h2)&(Z==ZN + v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta10*r10; } else{
s10 <- which(NA_id==which((X==XN - h1)&(Y==YN + h2)&(Z==ZN + v)));
A[i,s10] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta10*(-1); }
if (!is.na(newdata[which((X==XN + h1)&(Y==YN + h2)&(Z==ZN - v)),4])) {
r11 <- newdata[which((X==XN + h1)&(Y==YN + h2)&(Z==ZN - v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta11*r11; } else{
s11 <- which(NA_id==which((X==XN + h1)&(Y==YN + h2)&(Z==ZN - v)));
A[i,s11] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta11*(-1); }
if (!is.na(newdata[which((X==XN - h1)&(Y==YN - h2)&(Z==ZN - v)),4])) {
r12 <- newdata[which((X==XN - h1)&(Y==YN - h2)&(Z==ZN - v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta12*r12; } else{
s12 <- which(NA_id==which((X==XN - h1)&(Y==YN - h2)&(Z==ZN - v)));
A[i,s12] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta12*(-1); }
if (!is.na(newdata[which((X==XN + h1)&(Y==YN - h2)&(Z==ZN - v)),4])) {
r13 <- newdata[which((X==XN + h1)&(Y==YN - h2)&(Z==ZN - v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta13*r13; } else{
s13 <- which(NA_id==which((X==XN + h1)&(Y==YN - h2)&(Z==ZN - v)));
A[i,s13] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta13*(-1); }
if (!is.na(newdata[which((X==XN - h1)&(Y==YN + h2)&(Z==ZN - v)),4])) {
r14 <- newdata[which((X==XN - h1)&(Y==YN + h2)&(Z==ZN - v)),4];
B[i] <- B[i] + matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta14*r14; } else{
s14 <- which(NA_id==which((X==XN - h1)&(Y==YN + h2)&(Z==ZN - v)));
A[i,s14] <- matrix[which((matrix$X==XN)&(matrix$Y==YN)&(matrix$Z==ZN)),]$beta14*(-1); }
}
solution <- solve(A,B);
estimate <- data.frame(X[NA_id], Y[NA_id], Z[NA_id], solution);
names(estimate) <- c(names(newdata)[1], names(newdata)[2], names(newdata)[3], names(newdata)[4]);
complete <- newdata;
complete[NA_id,4] <- solution;
names(complete) <- c(names(newdata)[1], names(newdata)[2], names(newdata)[3], names(newdata)[4]);
return(list(estimate = estimate, complete = complete, NA_id = NA_id));
} |
test_that("flash year 2015", {
skip_on_cran()
year_link <- "https://flashresults.com/2015results.htm"
df_test <- flash_year_links(year_link)
df_standard <- data.frame(
Meet = c(
"ParaPan American Games",
"AAU Jr. Olympic Games",
"Pan American Games",
"World University Games",
"USATF Outoor Championships",
"New Balance High School Nationals",
"NCAA Track & Field Championships",
"NCAA East Preliminary",
"ACC Championships",
"Big South Championships",
"Virginia Grand Prix",
"Duke Twilight",
"Atlantic 10 Championships",
"Dogwood Classic",
"Arkansas Twilight",
"Penn Relays",
"Virginia Challenge",
"Arkansas Combined",
"Duke Invitational",
"John McDonnell Invitational",
"HPU VertKlasse Meeting",
"Raleigh Relays",
"Arkansas Spring Invitational",
"Virginia Cup",
"49er Classic",
"Wake Forest Open",
"NCAA Div I Championships",
"USATF Indoor Championships",
"ACC Championships",
"Arkansas Open",
"Atlantic 10 Championships",
"Virginia Tech Challenge",
"Tyson Invitational",
"New Balance Indoor Grand Prix",
"Texas A&M Aggie Invitational",
"Doc Hale - VT Elite Meet",
"Razorback Invitational",
"Hokie Invitational",
"Texas A&M Quadrangular Meet",
"Texas A&M Team Invitational",
"Texas A&M 13 Team Invitational",
"Virginia Tech Invitational",
"Arkansas HS Invitational",
"Arkansas -v- Texas",
"Texas A&M HS Classic",
"Arkansas Invitational",
"Reveille Invitational",
"Central American & Caribbean Games"
),
Meet_Date = c(
"August 10-14 2015",
"August 1-8 2015",
"July 21-25 2015",
"July 8-12 2015",
"June 25-28 2015",
"June 19-21 2015",
"June 10-13 2015",
"May 28-30 2015",
"May 14-16 2015",
"May 14-16 2015",
"May 8 2015",
"May 6-7 2015",
"May 2-3 2015",
"May 1-2 2015",
"May 1 2015",
"April 21-25 2015",
"April 17-18 2015",
"April 15-16 2015",
"April 11 2015",
"April 10-11 2015",
"April 3-4 2015",
"March 27-28 2015",
"March 27-28 2015",
"March 21 2015",
"March 19-21 2015",
"March 20-21 2015",
"March 13-14 2015",
"February 27-March 1 2015",
"February 26-28 2015",
"February 21 2015",
"February 21-22 2015",
"February 20-21 2015",
"February 13-14 2015",
"February 7 2015",
"February 6-7 2015",
"February 6-7 2015",
"January 30-31 2015",
"January 23-24 2015",
"January 24 2015",
"January 16-17 2015",
"January 16 2015",
"January 16-17 2015",
"January 17 2015",
"January 16 2015",
"January 9-10 2015",
"January 9 2015",
"December 13 2015",
"November 24-28 2015"
),
Location = c(
"CIBC Pan Am Athletics Stadium - Toronto, Canada",
"Dick Price Stadium - Norfolk, Virginia",
"CIBC Pan Am Athletics Stadium - Toronto, Canada",
"Gwangju World Cup Stadium - Gwangju, Korea",
"Hayward Field - Eugene, OR",
"Aggie Stadium, NC A&T University - Greensboro, NC",
"Hayward Field - Eugene, OR",
"Hodges Stadium - Jacksonville, FL",
"Mike Long Track - Tallahassee, FL",
"Dick Vert Stadium - High Point, NC",
"Lannigan Field - Charlottesville, VA",
"Morris Williams Stadium - Durham, NC",
"George Mason Stadium - Fairfax, VA",
"Lannigan Field - Charlottesville, VA",
"John McDonnell Field - Fayetteville, AR",
"Franklin Field - Philadelphia, PA",
"Lannigan Field - Charlottesville, VA",
"John McDonnell Field - Fayetteville, AR",
"Morris Williams Stadium - Durham, NC",
"John McDonnell Field - Fayetteville, AR",
"Dick Vert Stadium - High Point, NC",
"NC State - Raleigh, NC",
"John McDonnell Field - Fayetteville, AR",
"Lannigan Field - Charlottesville, VA",
"Belk Track & Field Center - Charlotte, NC",
"Kentner Stadium - Winston-Salem, NC",
"Randal Tyson Track Center - Fayetteville, AR",
"March 1 - Reggie Lewis Center - Roxbury, MA",
"Rector Field House - Blacksburg, VA",
"Randal Tyson Track Center - Fayetteville, AR",
"Mackal Field House - Kingston, RI",
"Rector Field House - Blacksburg, VA",
"Randal Tyson Track Center - Fayetteville, AR",
"Reggie Lewis Center - Roxbury, MA",
"Gilliam Indoor Track Stadium - College Station, TX",
"Rector Field House - Blacksburg, VA",
"Randal Tyson Track Center - Fayetteville, AR",
"Rector Field House - Blacksburg, VA",
"Gilliam Indoor Track Stadium - College Station, TX",
"Gilliam Indoor Track Stadium - College Station, TX",
"Gilliam Indoor Track Stadium - College Station, TX",
"Rector Field House - Blacksburg, VA",
"Randal Tyson Track Center - Fayetteville, AR",
"Randal Tyson Track Center - Fayetteville, AR",
"Gilliam Indoor Track Stadium - College Station, TX",
"Randal Tyson Track Center - Fayetteville, AR",
"Gilliam Indoor Track Stadium - College Station, TX",
"Heriberto Jara Corona Stadium - Xalapa, MEX"
),
Meet_link = c(
"http://results.toronto2015.org/PRS/en/athletics/schedule-and-results.htm",
"http://image2.aausports.org/sports/athletics/results/2015/jogames/live/",
"http://results.toronto2015.org/IRS/en/athletics/schedule-and-results.htm",
"http://www.gwangju2015.com/IRS/eng/zz/engzz_athletics_sport_overview.htm",
"https://flashresults.com/2015_Meets/Outdoor/06-25_USATF/",
"https://flashresults.com/2015_Meets/Outdoor/06-19_NBHS/",
"https://flashresults.com/2015_Meets/Outdoor/06-10_NCAA/",
"https://flashresults.com/2015_Meets/Outdoor/05-28_NCAAEast/",
"https://flashresults.com/2015_Meets/Outdoor/05-14_ACC/",
"https://flashresults.com/2015_Meets/Outdoor/05-14_BigSouth/",
"https://flashresults.com/2015_Meets/Outdoor/05-08_UVAGrandPrix/",
"https://flashresults.com/2015_Meets/Outdoor/05-06_DukeTwilight/",
"https://flashresults.com/2015_Meets/Outdoor/05_02-A10/",
"https://flashresults.com/2015_Meets/Outdoor/05-01_Dogwood/",
"https://flashresults.com/2015_Meets/Outdoor/05-01_ArkTwilight/",
"http://pennrelaysonline.com/Results/schedule.aspx",
"https://flashresults.com/2015_Meets/Outdoor/04-17_VirginiaChallenge/",
"https://flashresults.com/2015_Meets/Outdoor/04-15-15_ArkCombined/",
"https://flashresults.com/2015_Meets/Outdoor/04-11_DukeInvitational/",
"https://flashresults.com/2015_Meets/Outdoor/04-10_McDonnell/",
"https://flashresults.com/2015_Meets/Outdoor/04-03_VertKlasse/",
"https://flashresults.com/2015_Meets/Outdoor/03-27_RaleighRelays/",
"https://flashresults.com/2015_Meets/Outdoor/03-27_ArkSpringInv/",
"https://flashresults.com/2015_Meets/Outdoor/03-21_VirginiaCup/",
"https://flashresults.com/2015_Meets/Outdoor/03-19_49erClassic/",
"https://flashresults.com/2015_Meets/Outdoor/03-20_WakeOpen/",
"https://flashresults.com/2015_Meets/Indoor/03-13_NCAA/",
"https://flashresults.com/2015_Meets/Indoor/02-27_USA/",
"https://flashresults.com/2015_Meets/Indoor/02-26_ACC/",
"https://flashresults.com/2015_Meets/Indoor/02-21_ArkOpen/",
"https://flashresults.com/2015_Meets/Indoor/02-20_A10/",
"https://flashresults.com/2015_Meets/Indoor/02-20_VTChallenge/",
"https://flashresults.com/2015_Meets/Indoor/02-13_Tyson/",
"https://flashresults.com/2015_Meets/Indoor/02-07_NBGP/",
"https://flashresults.com/2015_Meets/Indoor/02-06_TamuAggie/",
"https://flashresults.com/2015_Meets/Indoor/02-06_VTDocHale/",
"http://www.flashresults.com/2015_Meets/Indoor/01-30_Razorback/",
"https://flashresults.com/2015_Meets/Indoor/01-23_VTHokie/",
"https://flashresults.com/2015_Meets/Indoor/01-24_TamuQuadrangular/",
"https://flashresults.com/2015_Meets/Indoor/01-17_TamuTeam/",
"https://flashresults.com/2015_Meets/Indoor/01-16_Tamu13Team/",
"https://flashresults.com/2015_Meets/Indoor/01-16_VTInvite/",
"http://www.flashresults.com/2015_Meets/Indoor/01-17_arkhs/",
"http://www.flashresults.com/2015_Meets/Indoor/01-16-ArkTex/",
"https://flashresults.com/2015_Meets/Indoor/01-09_TamuHS/",
"http://www.flashresults.com/2015_Meets/Indoor/01-09_arktri/",
"https://flashresults.com/2015_Meets/Indoor/12-13_Reveille/",
"http://info.veracruz2014.mx/info/eng/zz/engzz_athletics_sport_overview.htm"
)
)
expect_equivalent(df_standard, df_test)
}) |
choose_ploglik = function(est_nugget, est_par3, est_angle,
est_ratio) {
if (!est_nugget & !est_par3 & !est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_psill
} else if (!est_nugget & est_par3 & !est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_psill_par3
} else if (!est_nugget & !est_par3 & est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_psill_angle
} else if (!est_nugget & !est_par3 & !est_angle & est_ratio) {
pll = ploglik_cmodStd_r_psill_ratio
} else if (!est_nugget & est_par3 & est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_psill_angle_par3
} else if (!est_nugget & est_par3 & !est_angle & est_ratio) {
pll = ploglik_cmodStd_r_psill_ratio_par3
} else if (!est_nugget & !est_par3 & est_angle & est_ratio) {
pll = ploglik_cmodStd_r_psill_angle_ratio
} else if (!est_nugget & est_par3 & est_angle & est_ratio) {
pll = ploglik_cmodStd_r_psill_angle_ratio_par3
} else if (est_nugget & !est_par3 & !est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_lambda
} else if (est_nugget & est_par3 & !est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_lambda_par3
} else if (est_nugget & !est_par3 & est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_lambda_angle
} else if (est_nugget & !est_par3 & !est_angle & est_ratio) {
pll = ploglik_cmodStd_r_lambda_ratio
} else if (est_nugget & est_par3 & est_angle & !est_ratio) {
pll = ploglik_cmodStd_r_lambda_angle_par3
} else if (est_nugget & est_par3 & !est_angle & est_ratio) {
pll = ploglik_cmodStd_r_lambda_ratio_par3
} else if (est_nugget & !est_par3 & est_angle & est_ratio) {
pll = ploglik_cmodStd_r_lambda_angle_ratio
} else if (est_nugget & est_par3 & est_angle & est_ratio) {
pll = ploglik_cmodStd_r_lambda_angle_ratio_par3
}
return(pll)
} |
download_daily_synop <-
function(path = ".",
date,
...)
{
file <- paste0("synop.", date, ".csv")
dir.create(file.path(path, "data-raw"), showWarnings = FALSE)
utils::download.file(url = file.path(metsyn_url(), file),
destfile = file.path(path, "data-raw", paste0("daily_", file)),
...)
invisible(NULL)
} |
observeEvent(input$finalok, {
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, inputId = "var_freq_quant",
choices = names(numdata))
updateSliderInput(session = session,
inputId = 'filter_quant',
min = min(numdata),
max = max(numdata),
step = 1,
value = c(min(numdata), max(numdata))
)
} else if (ncol(num_data) < 1) {
updateSelectInput(session, inputId = "var_freq_quant",
choices = '', selected = '')
updateSliderInput(session = session,
inputId = 'filter_quant',
value = '')
} else {
updateSelectInput(session, 'var_freq_quant',
choices = names(num_data), selected = names(num_data))
updateSliderInput(session = session,
inputId = 'filter_quant',
min = min(num_data),
max = max(num_data),
step = 1,
value = c(min(num_data), max(num_data))
)
}
})
observeEvent(input$submit_part_train_per, {
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, inputId = "var_freq_quant",
choices = names(numdata))
updateSliderInput(session = session,
inputId = 'filter_quant',
min = min(numdata),
max = max(numdata),
step = 1,
value = c(min(numdata), max(numdata))
)
} else if (ncol(num_data) < 1) {
updateSelectInput(session, inputId = "var_freq_quant",
choices = '', selected = '')
updateSliderInput(session = session,
inputId = 'filter_quant',
value = '')
} else {
updateSelectInput(session, 'var_freq_quant',
choices = names(num_data), selected = names(num_data))
updateSliderInput(session = session,
inputId = 'filter_quant',
min = min(num_data),
max = max(num_data),
step = 1,
value = c(min(num_data), max(num_data))
)
}
})
d_freq_quant <- eventReactive(input$submit_fquant, {
data <- final_split$train[, input$var_freq_quant]
})
observe({
updateSliderInput(session = session,
inputId = 'filter_quant',
min = min(d_freq_quant()),
max = max(d_freq_quant()),
step = 1,
value = c(min(d_freq_quant()), max(d_freq_quant()))
)
})
fil_quant_data <- reactive({
min_data <- input$filter_quant[1]
max_data <- input$filter_quant[2]
f_data <- d_freq_quant()[d_freq_quant() >= min_data & d_freq_quant() <= max_data]
fdata <- as.data.frame(f_data)
names(fdata) <- as.character(input$var_freq_quant)
fdata
})
fquant_out <- eventReactive(input$submit_fquant, {
ko <- ds_freq_table(fil_quant_data(),
!! sym(as.character(input$var_freq_quant)),
input$bins)
ko
})
f2_title <- eventReactive(input$submit_fquant, {
h3('Histogram')
})
output$freq2_title <- renderUI({
f2_title()
})
output$freq_quant <- renderPrint({
fquant_out()
})
output$hist_freq_quant <- renderPlot({
plot(fquant_out())
}) |
vec_empty <- function(x) {
stop_defunct(paste_line(
"`vec_empty()` is defunct as of vctrs 0.2.0.",
"Please use `vec_is_empty()` instead."
))
}
vec_type <- function(x) {
warn_deprecated(c("`vec_type()` has been renamed to `vec_ptype()`."))
vec_ptype(x)
}
vec_type_common <- function(..., .ptype = NULL) {
warn_deprecated(c("`vec_type_common()` has been renamed to `vec_ptype_common()`."))
vec_ptype_common(..., .ptype = .ptype)
}
vec_type2 <- function(x, y, ...) {
warn_deprecated(c("`vec_type2()` has been renamed to `vec_ptype2()`."))
vec_ptype2(x, y, ...)
}
vec_as_index <- function(i, n, names = NULL) {
signal_soft_deprecated(paste_line(
"`vec_as_index()` is deprecated as of vctrs 0.2.2.",
"Please use `vec_as_location() instead.`"
))
n <- vec_cast(n, integer())
vec_assert(n, integer(), 1L)
i <- vec_as_subscript(i)
.Call(
vctrs_as_location,
i = i,
n = n,
names = names,
loc_negative = "invert",
loc_oob = "error",
loc_zero = "remove",
missing = "propagate",
arg = NULL
)
}
vec_repeat <- function(x, each = 1L, times = 1L) {
signal_soft_deprecated(paste_line(
"`vec_repeat()` is deprecated as of vctrs 0.3.0.",
"Please use either `vec_rep()` or `vec_rep_each()` instead."
))
vec_assert(each, size = 1L)
vec_assert(times, size = 1L)
idx <- rep(vec_seq_along(x), times = times, each = each)
vec_slice(x, idx)
} |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(1920, 1920, 1920, 1920, 1920, 1920, 1921, 1921, 1921, 1921), .Tsp = c(1920.5, 1921.25, 12), class = \"ts\"))"));
do.call(`is.list`, argv);
}, o=expected); |
context('fitEmaxB with updated prior')
options(mc.cores = parallel::detectCores())
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
prior<-emaxPrior.control(0,30,0,30,dTarget=350,p50=50,sigmalow=.1,sigmaup=30,parmDF=5)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
testout<-suppressWarnings(fitEmaxB(y,dose,prior=prior,modType=4,prot=prots,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2:3],pop[3]))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout,dosevec=c(20,80),int=2)
poppred<-emaxfun(c(20,80),pop[c(1:3)])
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(70),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-5*c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
ymean<-tapply(y,list(dose,prots),mean)
ymean<-ymean[!is.na(ymean)]
msSat<-(summary(lm(y~factor(dose)))$sigma)^2
protshort<-c(rep(1,6),rep(2,4))
nag<-table(dose,prots)
nag<-as.vector(nag[nag>0])
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout<-fitEmaxB(ymean,doselev,prior=prior,modType=4,
prot=protshort,count=nag,msSat=msSat,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2:3],pop[3]))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout,dosevec=c(20,80),int=2)
poppred<-emaxfun(c(20,80),pop[c(1:3)])
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(70),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-10*c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-0
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
ysub<-y[dose!=0]
dsub<-dose[dose!=0]
protsub<-prots[dose!=0]
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout<-fitEmaxB(ysub,dsub,prior,modType=3,prot=protsub,pboAdj=TRUE,
mcmc=mcmc,diagnostics=FALSE,nproc=3))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-pop[1:2])/se
test_that("pboadj model parameters agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
})
predout<-predict(testout,dosevec=c(20,80),int=2)
poppred<-emaxfun(c(20,80),pop)-emaxfun(0,pop)
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("pboadj predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("pboadj check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(700),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-100*c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-0
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
ysub<-y[dose!=0]
dsub<-dose[dose!=0]
protsub<-prots[dose!=0]
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
ymean<-tapply(ysub,list(dsub,protsub),mean)
ymean<-ymean[!is.na(ymean)]
msSat<-(summary(lm(y~factor(dose)))$sigma)^2
protshort<-c(rep(1,5),rep(2,3))
nag<-table(dsub,protsub)
nag<-as.vector(nag[nag>0])
dlevsub<-doselev[doselev!=0]
suppressWarnings(testout<-fitEmaxB(ymean,dlevsub,prior,modType=4,prot=protshort,
count=nag,pboAdj=TRUE,msSat=msSat,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2]))/se
test_that("pboadj4 model parameters agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
})
predout<-predict(testout,dosevec=c(20,80),int=1,dref=50)
poppred<-emaxfun(c(20,80),c(pop[1],1,pop[2],0))
popref<-emaxfun(50,c(pop[1],1,pop[2],0))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-popref))/predout$sedif
test_that("pboadj4 predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("pboadj4 check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(700),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-popref),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
nsim<-500
doselev<-c(0,5,25,50,100,350)
n<-20*c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-1
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
poppred<-emaxfun(c(20,80),pop)
popref<-emaxfun(50,pop)
modtype<-4
if(modtype==4){pparm<-c(pop[1],1,pop[2:3])
}else pparm<-pop
z<-matrix(numeric(modtype*nsim),ncol=modtype)
zabs<-matrix(numeric(nsim*2),ncol=2)
zdif<-matrix(numeric(nsim*2),ncol=2)
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5)
mcmc<-mcmc.control(chains=1,warmup=500,iter=5000,seed=53453,propInit=0.15,adapt_delta = .9)
estan<-selEstan('mrmodel')
for(i in 1:nsim){
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
ysum<-tapply(y,dose,mean)
nsum<-as.numeric(table(dose))
msSat<-tapply(y,dose,var)
msSat<-sum((nsum-1)*msSat)/(sum(nsum)-length(nsum))
ysum<-c(tapply(y[prots==1],dose[prots==1],mean),
tapply(y[prots==2],dose[prots==2],mean))
suppressWarnings(testout<-fitEmaxB(ysum,doselev,prior=prior,count=n,modType=modtype,
msSat=msSat,mcmc=mcmc,estan=estan,diagnostics=FALSE,nproc = 1))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z[i,]<-(estimate-pparm)/se
predout<-predict(testout,dosevec=c(20,80),int=1,dref=50)
zabs[i,]<-(predout$pred-poppred)/predout$se
zdif[i,]<-(predout$fitdif-(poppred-popref))/predout$sedif
}
test_that("grouped data model parameters agree within 2se",{
expect_that(0.05,
equals(as.numeric(max(apply(abs(z)>1.96,2,mean))),
tolerance=3*sqrt(.05*.95/nsim),scale=1))
})
test_that("predictions agree within 3se",{
expect_that(0.05,
equals(as.numeric(max(apply(abs(zabs)>1.96,2,mean))),
tolerance=3*sqrt(.05*.95/nsim),scale=1))
})
test_that("dif predictions agree within 2se",{
expect_that(0.05,
equals(as.numeric(max(apply(abs(zdif)>1.96,2,mean))),
tolerance=2*sqrt(.05*.95/nsim),scale=1))
})
set.seed(12357)
modType<-4
dvec1<-c(0,.1,.3,.6,1)
dvec2<-c(0,.1,.2,.4,.6,1)
nd1<-length(dvec1)
nd2<-length(dvec2)
n1<-rep(10000,nd1)
n2<-rep(10000,nd2)
parms<-c(log(0.25),1,1.4,-0.5,-0.85)
mlev1<-plogis(emaxfun(dvec1,parms[1:4]))
mlev2<-plogis(emaxfun(dvec2,parms[c(1:3,5)]))
y1<-rbinom(nd1,n1,mlev1)
y2<-rbinom(nd2,n2,mlev2)
y<-c(rep(1,nd1),rep(0,nd1),rep(1,nd2),rep(0,nd2))
counts<-c(y1,n1-y1,y2,n2-y2)
prots<-c(rep(1,2*nd1),rep(2,2*nd2))
dvec<-c(dvec1,dvec1,dvec2,dvec2)
prior<-emaxPrior.control(0,4,0,4,1.0,.5,parmDF=5,binary=TRUE)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout<-fitEmaxB(y,dvec,modType=modType,
prot=prots,
count=counts,binary=TRUE,
prior=prior,mcmc=mcmc,
diagnostics=FALSE))
pgen<-coef(testout)
estimate<-apply(pgen,2,mean)
se<-sqrt(diag(var(pgen)))
z<-(estimate-parms)/se
test_that("model parameters agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
})
predout<-predict(testout,dosevec=c(.25,.75),int=2)
poppred<-plogis(emaxfun(c(.25,.75),parms[c(1:3,5)]))
popref<-plogis(emaxfun(0,parms[c(1:3,5)]))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-popref))/predout$sedif
test_that("predictions agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
expect_lt(as.numeric(max(abs(zdif))),2.0)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*.5/sqrt(10000),scale=1))
})
set.seed(12357)
modType<-3
dvec1<-c(0,.1,.3,.6,1)
dvec2<-c(0,.1,.2,.4,.6,1)
nd1<-length(dvec1)
nd2<-length(dvec2)
n1<-rep(10000,nd1)
n2<-rep(10000,nd2)
parms<-c(log(0.25),1,1.4,-0.5,-0.85)
mlev1<-plogis(emaxfun(dvec1,parms[1:4]))
mlev2<-plogis(emaxfun(dvec2,parms[c(1:3,5)]))
y1<-rbinom(nd1,n1,mlev1)
y2<-rbinom(nd2,n2,mlev2)
y<-c(rep(1,nd1),rep(0,nd1),rep(1,nd2),rep(0,nd2))
counts<-c(y1,n1-y1,y2,n2-y2)
prots<-c(rep(1,2*nd1),rep(2,2*nd2))
dvec<-c(dvec1,dvec1,dvec2,dvec2)
prior<-emaxPrior.control(0,4,0,4,1.0,0.5,parmDF=5,binary=TRUE)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout<-fitEmaxB(y,dvec,modType=modType,
prot=prots,
count=counts,binary=TRUE,
prior=prior,mcmc=mcmc,
diagnostics=FALSE))
pgen<-coef(testout)
estimate<-apply(pgen,2,mean)
se<-sqrt(diag(var(pgen)))
z<-(estimate[1:3]-parms[c(1,3,4)])/se[1:3]
test_that("model parameters agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
})
predout<-predict(testout,dosevec=c(.25,.75),int=1)
poppred<-plogis(emaxfun(c(.25,.75),parms[c(1,3,4)]))
popref<-plogis(emaxfun(0,parms[c(1,3,4)]))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-popref))/predout$sedif
test_that("predictions agree within 2se",{
expect_lt(as.numeric(max(abs(z))),2.0)
expect_lt(as.numeric(max(abs(zdif))),2.0)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*.5/sqrt(10000),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
nd<-length(doselev)
n<-10*c(78,81,81,81,77,80)
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop.parm<-c(log(ed50),emax,e0)
modType<-4
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5)
mcmc<-mcmc.control(chains=1,warmup=500,iter=5000,seed=53453,propInit=0.15,adapt_delta = .9)
estan<-selEstan('mrmodel')
dose<-rep(doselev,n)
meanlev<-emaxfun(doselev,pop.parm)
meanrep<-emaxfun(dose,pop.parm)
clev<-0.9
nsim<-500
covci<-matrix(logical(nsim*nd),ncol=nd)
covpi<-matrix(logical(nsim*nd),ncol=nd)
covdifci<-matrix(logical(nsim*nd),ncol=nd)
covdifpi<-matrix(logical(nsim*nd),ncol=nd)
for (i in 1:nsim){
y<-rnorm(sum(n),meanrep,sdy)
ymean<-tapply(y,dose,mean)
msSat<-(summary(lm(y~factor(dose)))$sigma)^2
suppressWarnings(testout<-fitEmaxB(ymean,doselev,prior=prior,modType=modType,count=n,
mcmc=mcmc,msSat=msSat,
estan=estan,diagnostics = FALSE,nproc = 1))
if(is.null(testout)){
covci[i,]<-NA
covpi[i,]<-NA
covdifci[i,]<-NA
covdifpi[i,]<-NA
}else{
intout<-plot(testout,clev=clev,plot=FALSE)$plotdata
covci[i,]<-meanlev>=intout[,'cil'] & meanlev<=intout[,'cih']
y<-rnorm(sum(n),meanrep,sdy)
ym<-tapply(y,dose,mean)
covpi[i,]<-ym>=intout[,'pil'] & ym<=intout[,'pih']
intout<-plot(testout,clev=clev,plot=FALSE,plotDif=TRUE)$plotdata
covdifci[i,]<-meanlev-meanlev[1]>=intout[,'cil'] & meanlev-meanlev[1]<=intout[,'cih']
ym<-ym-ym[1]
covdifpi[i,]<-ym>=intout[,'pil'] & ym<=intout[,'pih']
}
}
test_that("plot.fitEmax CI for continuous data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covci,2,mean,na.rm=TRUE))),
tolerance=3*sqrt(.1*.9/nsim),scale=1))
})
test_that("plot.fitEmax PI for continuous data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covpi,2,mean,na.rm=TRUE))),
tolerance=3*sqrt(.1*.9/nsim),scale=1))
})
test_that("plot.fitEmax CI DIF for continuous data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covdifci[,-1],2,mean,na.rm=TRUE))),
tolerance=3*sqrt(.1*.9/nsim),scale=1))
})
test_that("plot.fitEmax PI DIF for continuous data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covdifpi[,-1],2,mean,na.rm=TRUE))),
tolerance=3*sqrt(.1*.9/nsim),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
nd<-length(doselev)
n<-10*c(78,81,81,81,77,80)
e0<-qlogis(.2)
ed50<-67.481113
emax<-qlogis(.95)
pop.parm<-c(log(ed50),emax,e0)
meanlev<-plogis(emaxfun(doselev,pop.parm))
y01<-c(rep(1,length(meanlev)),rep(0,length(meanlev)))
d01<-c(doselev,doselev)
clev<-0.9
nsim<-500
covci<-matrix(logical(nsim*nd),ncol=nd)
covpi<-matrix(logical(nsim*nd),ncol=nd)
covdifci<-matrix(logical(nsim*nd),ncol=nd)
covdifpi<-matrix(logical(nsim*nd),ncol=nd)
modType<-4
prior<-emaxPrior.control(0,4,0,4,350,50,parmDF=5,binary=TRUE)
mcmc<-mcmc.control(chains=1,warmup=500,iter=5000,seed=53453,propInit=0.15,adapt_delta = .9)
estan<-selEstan('mrmodel')
for (i in 1:nsim){
y<-rbinom(length(n),n,meanlev)
n01<-c(y,n-y)
suppressWarnings(testout<-fitEmaxB(y01,d01,prior,modType=4,
count=n01,diagnostics = FALSE,binary=TRUE,nproc=1))
if(is.null(testout)){
covci[i,]<-NA
covpi[i,]<-NA
covdifci[i,]<-NA
covdifpi[i,]<-NA
}else{
intout<-plot(testout,clev=clev,plot=FALSE)$plotdata
covci[i,]<-meanlev>=intout[,'cil'] & meanlev<=intout[,'cih']
ypred<-rbinom(length(n),n,meanlev)
ym<-ypred/n
covpi[i,]<-ym>=intout[,'pil'] & ym<=intout[,'pih']
intout<-plot(testout,clev=clev,plot=FALSE,plotDif=TRUE)$plotdata
covdifci[i,]<-meanlev-meanlev[1]>=intout[,'cil'] & meanlev-meanlev[1]<=intout[,'cih']
ym<-ym-ym[1]
covdifpi[i,]<-ym>=intout[,'pil'] & ym<=intout[,'pih']
}
}
test_that("plot.fitEmax CI for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covci,2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax CI for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(min(apply(covci,2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax PI for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covpi,2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax PI for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(min(apply(covpi,2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax CI DIF for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covdifci[,-1],2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax CI DIF for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(min(apply(covdifci[,-1],2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax PI DIF for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(max(apply(covdifpi[,-1],2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
test_that("plot.fitEmax PI DIF for binary data agree within 3se",{
expect_that(clev,
equals(as.numeric(min(apply(covdifpi[,-1],2,mean,na.rm=TRUE))),
tolerance=0.04,scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
x1<-rnorm(n1)
x1<-x1-mean(x1)
x2<-rnorm(n2)
x2<-x2-mean(x2)
x<-matrix(c(x1,x2),ncol=1)
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
bparm<-1
meanlev<-emaxfun(dose,pop) + x%*%bparm
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
basemu<-0
basevar<-matrix((10*sdy)^2,nrow=1,ncol=1)
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5,basemu=basemu,basevar=basevar)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout<-fitEmaxB(y,dose,prior=prior,modType=4,prot=prots,xbase=x,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2:3],pop[3],bparm))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout,dosevec=c(20,80),int=2)
poppred<-emaxfun(c(20,80),pop[c(1:3)])
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(70),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-c(78,81,81,81,77,80)
n1<-sum(n)
n2<-sum(n[1:4])
doselev<-c(doselev,doselev[1:4])
n<-c(n,n[1:4])
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
x1<-matrix(rnorm(3*n1),ncol=3)
x1<-scale(x1,center=TRUE,scale=FALSE)
x2<-matrix(rnorm(3*n2),ncol=3)
x2<-scale(x2,center=TRUE,scale=FALSE)
x<-rbind(x1,x2)
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
bparm<-c(2,-1,0.5)
meanlev<-emaxfun(dose,pop) + x%*%bparm
y<-rnorm(n1+n2,meanlev,sdy)
prots<-c(rep(1,n1),rep(2,n2))
basemu<-numeric(3)
basevar<-diag(3)*(10*sdy)^2
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5,basemu=basemu,basevar=basevar)
mcmc<-mcmc.control(chains=3,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout2<-fitEmaxB(y,dose,prior=prior,modType=4,prot=prots,xbase=x,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout2)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2:3],pop[3],bparm))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout2,dosevec=c(20,80),int=2)
poppred<-emaxfun(c(20,80),pop[c(1:3)])
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(70),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-5*c(78,81,81,81,77,80)
ntot<-sum(n)
e0<-2.465375
ed50<-67.481113
emax<-15.127726
sdy<-8.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
x<-matrix(rnorm(2*ntot),ncol=2)
x<-scale(x,center=TRUE,scale=FALSE)
bparm<-c(2,-1)
meanlev<-meanlev + x%*%bparm
y<-rnorm(ntot,meanlev,sdy)
basemu<-numeric(2)
basevar<-diag(2)*(10*sdy)^2
prior<-emaxPrior.control(0,30,0,30,350,50,0.1,30,parmDF=5,basemu=basemu,basevar=basevar)
mcmc<-mcmc.control(chains=1,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout3<-fitEmaxB(y,dose,prior=prior,modType=3,xbase=x,
mcmc=mcmc,diagnostics=FALSE))
parms<-coef(testout3)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],pop[2:3],bparm))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout3,dosevec=c(20,80),int=1)
poppred<-emaxfun(c(20,80),pop[c(1:3)])
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-e0))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=2*sdy/sqrt(70),scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-e0),tol=2*sdy/sqrt(70),scale=1))
})
set.seed(12357)
doselev<-c(0,5,25,50,100,350)
n<-5*c(78,81,81,81,77,80)
ntot<-sum(n)
e0<- -1.5
ed50<-67.481113
emax<-4.0
pop<-c(log(ed50),emax,e0)
dose<-rep(doselev,n)
meanlev<-emaxfun(dose,pop)
x<-matrix(rnorm(2*ntot),ncol=2)
x<-scale(x,center=TRUE,scale=FALSE)
bparm<-c(2,-1)
meanlev<-plogis(meanlev + x%*%bparm)
y<-rbinom(ntot,1,meanlev)
basemu<-numeric(2)
basevar<-diag(2)*(4)^2
prior<-emaxPrior.control(0,30,0,30,350,50,parmDF=5,basemu=basemu,basevar=basevar,binary=TRUE)
mcmc<-mcmc.control(chains=1,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout4b<-fitEmaxB(y,dose,prior=prior,modType=4,xbase=x,
mcmc=mcmc,diagnostics=FALSE,binary=TRUE))
parms<-coef(testout4b)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],1,pop[2:3],bparm))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout4b,dosevec=c(20,80),int=1,xvec=c(0,0))
poppred<-plogis(emaxfun(c(20,80),pop[c(1:3)]))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-plogis(e0)))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=0.05,scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-plogis(e0)),tol=0.05,scale=1))
})
set.seed(20572)
doselev<-c(0,5,25,50,100,350)
n<-4*c(78,81,81,81,77,80)
ntot<-sum(n)
e0<- -1.5
ed50<-67.481113
emax<-4.0
pop<-c(log(ed50),emax,e0)
dose<-c(rep(doselev,n/2),rep(doselev,n/2))
prot<-sort(rep(1:2,ntot/2))
meanlev<-emaxfun(dose,pop)+0.5*(prot==2)
x1<-matrix(rnorm(ntot),ncol=2)
x1<-scale(x1,center=TRUE,scale=FALSE)
x2<-matrix(rnorm(ntot),ncol=2)
x2<-scale(x2,center=TRUE,scale=FALSE)
x<-rbind(x1,x2)
bparm<-c(1.,-0.5)
meanlev<-plogis(meanlev + x%*%bparm)
y<-rbinom(ntot,1,meanlev)
basemu<-numeric(2)
basevar<-diag(2); basevar[2,1]<-.25; basevar[1,2]<-.25
basevar<-basevar*(4)^2
prior<-emaxPrior.control(0,30,0,30,350,50,parmDF=5,basemu=basemu,basevar=basevar,binary=TRUE)
mcmc<-mcmc.control(chains=1,warmup=500,iter=3000,seed=53453,propInit=0.15,adapt_delta = .9)
suppressWarnings(testout5b<-fitEmaxB(y,dose,prot=prot,prior=prior,modType=3,xbase=x,
mcmc=mcmc,diagnostics=FALSE,binary=TRUE))
parms<-coef(testout5b)
estimate<-apply(parms,2,mean)
se<-sqrt(diag(var(parms)))
z<-(estimate-c(pop[1],pop[c(2:3)],pop[3]+0.5,bparm))/se
test_that("model parameters agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
})
predout<-predict(testout5b,dosevec=c(20,80),int=1,xvec=c(0,0))
poppred<-plogis(emaxfun(c(20,80),c(pop[c(1:2)],e0)))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-plogis(e0)))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=0.05,scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-plogis(e0)),tol=0.05,scale=1))
})
predout<-predict(testout5b,dosevec=c(20,80),int=2,xvec=c(0,0))
poppred<-plogis(emaxfun(c(20,80),c(pop[c(1:2)],e0+0.5)))
z<-(predout$pred-poppred)/predout$se
zdif<-(predout$fitdif-(poppred-plogis(e0+0.5)))/predout$sedif
test_that("predictions agree within 2.5se",{
expect_lt(as.numeric(max(abs(z))),2.5)
expect_lt(as.numeric(max(abs(zdif))),2.5)
})
test_that("check absolute levels",{
expect_that(as.numeric(predout$pred),
equals(poppred,tol=0.05,scale=1))
expect_that(as.numeric(predout$fitdif),
equals((poppred-plogis(e0+0.5)),tol=0.05,scale=1))
}) |
Dist_SimuChisq <- function(s,prob,b){
idx <-which(prob==0)
if (length(idx)==0){
prob <- prob
s <- s
}else{
prob <- prob[-idx]
s <- s[,-idx]
}
MyChisqValues<-sapply(as.data.frame(t(s)), function(df){return(chisq.test(df,p=prob,simulate.p.value = T,B=b)$statistic)})
return(as.vector(MyChisqValues))
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(bliss)
set.seed(1)
param <- list(
Q=1,
n=100,
p=c(50),
beta_types=c("smooth"),
grids_lim=list(c(0,1)))
data <- sim(param)
param <- list(
iter=1e3,
burnin=2e2,
K=c(3))
res_bliss<-fit_Bliss(data=data,param=param,verbose=TRUE)
str(res_bliss)
param$ylim <- range(range(res_bliss$beta_posterior_density[[1]]$grid_beta_t),
c(-5,5))
param$cols <- rev(heat.colors(100))
image_Bliss(res_bliss$beta_posterior_density,param,q=1)
param$ylim <- range(range(res_bliss$beta_posterior_density[[1]]$grid_beta_t),
c(-5,5))
param$cols <- rev(heat.colors(100))
image_Bliss(res_bliss$beta_posterior_density,param,q=1)
lines(res_bliss$data$grids[[1]],res_bliss$Bliss_estimate[[1]],type="s",lwd=2)
lines(res_bliss$data$grids[[1]],res_bliss$Smooth_estimate[[1]],lty=2)
lines(res_bliss$data$grids[[1]],res_bliss$data$betas[[1]],col="purple",lwd=2,type="s")
param$ylim <- range(range(res_bliss$beta_posterior_density[[1]]$grid_beta_t),
c(-5,5))
param$cols <- rev(heat.colors(100))
image_Bliss(res_bliss$beta_posterior_density,param,q=1)
lines_bliss(res_bliss$data$grids[[1]],res_bliss$Bliss_estimate[[1]],lwd=3)
lines(res_bliss$data$grids[[1]],res_bliss$Smooth_estimate[[1]],lty=2)
lines_bliss(res_bliss$data$grids[[1]],res_bliss$data$betas[[1]],col="purple",lwd=3)
plot(res_bliss$alpha[[1]],type="o",xlab="time",ylab="posterior probabilities")
plot(res_bliss$alpha[[1]],type="o",xlab="time",ylab="posterior probabilities")
abline(h=0.5,col=2,lty=2)
for(i in 1:nrow(res_bliss$support_estimate[[1]])){
segments(res_bliss$support_estimate[[1]]$begin[i],0.05,
res_bliss$support_estimate[[1]]$end[i],0.05,col="red"
)
points(res_bliss$support_estimate[[1]]$begin[i],0.05,col="red",pch="|",lwd=2)
points(res_bliss$support_estimate[[1]]$end[i],0.05,col="red",pch="|",lwd=2)
}
res_bliss$support_estimate[[1]]
sessionInfo() |
coder.texte <- function( texte, ajouter.images = TRUE, proteger.balises = FALSE,
balise.CDATA = TRUE,
indentation = 2, fichier.xml ) {
if ( length( texte ) > 1 ) {
stop( "Le texte pass\u00e9 n'est pas unique.",
" Probl\u00e8me de codage ant\u00e9rieur !\n",
texte )
}
blanc <- paste0( rep( " ", indentation ), collapse = "" )
cat( file = fichier.xml, sep = "",
blanc, "<text>",
if ( TRUE == balise.CDATA ) "<![CDATA[" )
cat( file = fichier.xml, sep = "",
texte )
cat( file = fichier.xml, sep = "",
if ( TRUE == balise.CDATA ) "]]>",
"</text>\n" )
if ( TRUE == ajouter.images ) {
av.images <- grepl( "@@PLUGINFILE@@", fixed = TRUE, texte )
if ( av.images ) {
assign( "liste.images", character() , SARP.Moodle.env )
pos.images <- gregexpr( "\"@@PLUGINFILE@@/.*?\"", fixed = FALSE, texte )[[ 1 ]]
lg <- attr( pos.images, "match.length" )
lapply( 1:length( lg ),
function( i ) {
img <- substr( texte, start = pos.images[ i ], stop = pos.images[ i ] + lg[ i ] - 1 )
img <- gsub( ".*/", '', img )
img <- gsub( "\"$", '', img )
cat( file = fichier.xml, sep = "",
blanc,
coder_image.moodle( img ),
"\n" )
} )
}
}
} |
blr_confusion_matrix <- function(model, cutoff = 0.5, data = NULL, ...) UseMethod("blr_confusion_matrix")
blr_confusion_matrix.default <- function(model, cutoff = 0.5, data = NULL, ...) {
blr_check_model(model)
blr_check_values(cutoff, 0, 1)
namu <- formula(model)[[2]]
if (is.null(data)) {
data <- model$model
response <- data[[1]]
} else {
blr_check_data(data)
response <- data[[as.character(namu)]]
}
p_data <- predict(model, newdata = data, type = "response")
c_data <- as.factor(as.numeric(p_data > cutoff))
out <- table(Prediction = c_data, Reference = response)
a <- out[4]
b <- out[2]
c <- out[3]
d <- out[1]
accuracy <- (a + d) / (a + b + c + d)
no_inf_rate <- table(response)[[1]] / sum(table(response))
sensitivity <- a / (a + c)
specificity <- d / (b + d)
prevalence <- (a + c) / (a + b + c + d)
detect_rate <- a / (a + b + c + d)
detect_prev <- (a + b) / (a + b + c + d)
bal_accuracy <- (sensitivity + specificity) / 2
precision <- a / (a + b)
recall <- a / (a + c)
kappa <- blr_kappa(out)
mcnemar_p <- stats::mcnemar.test(out)$p.value
ppv <- (sensitivity * prevalence) / ((sensitivity * prevalence) +
((1 - specificity) * (1 - prevalence)))
npv <- specificity * (1 - prevalence) / (((1 - sensitivity) * prevalence) +
(specificity * (1 - prevalence)))
result <- list(
accuracy = accuracy,
balanced_accuracy = bal_accuracy,
conf_matrix = out,
detection_prevalence = detect_prev,
detection_rate = detect_rate,
mcnemar_kappa = kappa,
mcnemar_test_p_val = mcnemar_p,
negative_predicted_value = npv,
no_information_rate = no_inf_rate,
positive_predicted_value = ppv,
precision = precision,
prevalence = prevalence,
recall = recall,
sensitivity = sensitivity,
specificity = specificity)
class(result) <- "blr_confusion_matrix"
return(result)
}
print.blr_confusion_matrix <- function(x, ...) {
cat('Confusion Matrix and Statistics', '\n\n')
print(x$conf_matrix)
cat('\n\n')
cat(' Accuracy :', format(round(x$accuracy, 4), nsmall = 4), '\n')
cat(' No Information Rate :', format(round(x$no_information_rate, 4), nsmall = 4), '\n\n')
cat(' Kappa :', format(round(x$mcnemar_kappa, 4), nsmall = 4), '\n\n')
cat("McNemars's Test P-Value :", format(round(x$mcnemar_test_p_val, 4), nsmall = 4), '\n\n')
cat(' Sensitivity :', format(round(x$sensitivity, 4), nsmall = 4), '\n')
cat(' Specificity :', format(round(x$specificity, 4), nsmall = 4), '\n')
cat(' Pos Pred Value :', format(round(x$positive_predicted_value, 4), nsmall = 4), '\n')
cat(' Neg Pred Value :', format(round(x$negative_predicted_value, 4), nsmall = 4), '\n')
cat(' Prevalence :', format(round(x$prevalence, 4), nsmall = 4), '\n')
cat(' Detection Rate :', format(round(x$detection_rate, 4), nsmall = 4), '\n')
cat(' Detection Prevalence :', format(round(x$detection_prevalence, 4), nsmall = 4), '\n')
cat(' Balanced Accuracy :', format(round(x$balanced_accuracy, 4), nsmall = 4), '\n')
cat(' Precision :', format(round(x$precision, 4), nsmall = 4), '\n')
cat(' Recall :', format(round(x$recall, 4), nsmall = 4), '\n\n')
cat(" 'Positive' Class : 1")
}
blr_kappa <- function(out) {
agreement <- sum(diag(out)) / sum(out)
expected <- sum(rowSums(out) * colSums(out)) / (sum(out) ^ 2)
(agreement - expected) / (1 - expected)
} |
rank_stability <- function(x, ...) UseMethod("rank_stability") |
makeStoppingCondition = function(name, message, stop.fun, code = name, control = list()) {
assertString(name, na.ok = FALSE)
assertString(message, na.ok = FALSE)
assertFunction(stop.fun, args = "envir")
assertString(code, na.ok = FALSE)
assertList(control)
makeS3Obj(
name = name,
message = message,
stop.fun = stop.fun,
code = code,
control = control,
classes = "cma_stopping_condition"
)
}
shouldStop = function(x, envir) {
UseMethod("shouldStop")
}
shouldStop.cma_stopping_condition = function(x, envir) {
return(x$stop.fun(envir))
}
checkStoppingConditions = function(stop.ons, envir = parent.frame()) {
assertList(stop.ons, min.len = 1L, types = "cma_stopping_condition")
stop.msgs = character(0L)
codes = character(0L)
for (stop.on in stop.ons) {
if (shouldStop(stop.on, envir = envir)) {
stop.msgs = c(stop.msgs, stop.on$message)
codes = c(codes, stop.on$code)
break
}
}
return(list(stop.msgs = stop.msgs, codes = codes))
}
getDefaultStoppingConditions = function() {
return(
list(
stopOnTolX(),
stopOnNoEffectAxis(),
stopOnNoEffectCoord(),
stopOnCondCov()
)
)
} |
prune.semforest <- function(object, max.depth=NULL, num.trees=NULL, ...)
{
if (!is.null(num.trees)) {
object$forest <- object$forest[1:num.trees]
object$forest.data <- object$forest.data[1:num.trees]
}
if (!is.null(max.depth)) {
object$forest <- lapply(object$forest, prune.semtree, max.depth=max.depth)
}
return(object);
} |
skip_if_not_available("dataset")
library(dplyr, warn.conflicts = FALSE)
csv_dir <- make_temp_dir()
tsv_dir <- make_temp_dir()
test_that("Setup (putting data in the dirs)", {
dir.create(file.path(csv_dir, 5))
dir.create(file.path(csv_dir, 6))
write.csv(df1, file.path(csv_dir, 5, "file1.csv"), row.names = FALSE)
write.csv(df2, file.path(csv_dir, 6, "file2.csv"), row.names = FALSE)
expect_length(dir(csv_dir, recursive = TRUE), 2)
dir.create(file.path(tsv_dir, 5))
dir.create(file.path(tsv_dir, 6))
write.table(df1, file.path(tsv_dir, 5, "file1.tsv"), row.names = FALSE, sep = "\t")
write.table(df2, file.path(tsv_dir, 6, "file2.tsv"), row.names = FALSE, sep = "\t")
expect_length(dir(tsv_dir, recursive = TRUE), 2)
})
test_that("CSV dataset", {
ds <- open_dataset(csv_dir, partitioning = "part", format = "csv")
expect_r6_class(ds$format, "CsvFileFormat")
expect_r6_class(ds$filesystem, "LocalFileSystem")
expect_identical(names(ds), c(names(df1), "part"))
if (getRversion() >= "4.0.0") {
expect_identical(dim(ds), c(20L, 7L))
}
expect_equal(
ds %>%
select(string = chr, integer = int, part) %>%
filter(integer > 6 & part == 5) %>%
collect() %>%
summarize(mean = mean(as.numeric(integer))),
df1 %>%
select(string = chr, integer = int) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
expect_equal(
collect(ds) %>% arrange(part) %>% pull(part),
c(rep(5, 10), rep(6, 10))
)
})
test_that("CSV scan options", {
options <- FragmentScanOptions$create("text")
expect_equal(options$type, "csv")
options <- FragmentScanOptions$create("csv",
null_values = c("mynull"),
strings_can_be_null = TRUE
)
expect_equal(options$type, "csv")
dst_dir <- make_temp_dir()
dst_file <- file.path(dst_dir, "data.csv")
df <- tibble(chr = c("foo", "mynull"))
write.csv(df, dst_file, row.names = FALSE, quote = FALSE)
ds <- open_dataset(dst_dir, format = "csv")
expect_equal(ds %>% collect(), df)
sb <- ds$NewScan()
sb$FragmentScanOptions(options)
tab <- sb$Finish()$ToTable()
expect_equal(as.data.frame(tab), tibble(chr = c("foo", NA)))
csv_format <- CsvFileFormat$create(
null_values = c("mynull"),
strings_can_be_null = TRUE
)
ds <- open_dataset(dst_dir, format = csv_format)
expect_equal(ds %>% collect(), tibble(chr = c("foo", NA)))
df <- tibble(chr = c("foo", "mynull"), chr2 = c("bar", "baz"))
write.table(df, dst_file, row.names = FALSE, quote = FALSE, sep = "\t")
ds <- open_dataset(dst_dir,
format = "csv",
delimiter = "\t",
null_values = c("mynull"),
strings_can_be_null = TRUE
)
expect_equal(ds %>% collect(), tibble(
chr = c("foo", NA),
chr2 = c("bar", "baz")
))
expect_equal(
ds %>%
group_by(chr2) %>%
summarize(na = all(is.na(chr))) %>%
arrange(chr2) %>%
collect(),
tibble(
chr2 = c("bar", "baz"),
na = c(FALSE, TRUE)
)
)
})
test_that("compressed CSV dataset", {
skip_if_not_available("gzip")
dst_dir <- make_temp_dir()
dst_file <- file.path(dst_dir, "data.csv.gz")
write.csv(df1, gzfile(dst_file), row.names = FALSE, quote = FALSE)
format <- FileFormat$create("csv")
ds <- open_dataset(dst_dir, format = format)
expect_r6_class(ds$format, "CsvFileFormat")
expect_r6_class(ds$filesystem, "LocalFileSystem")
expect_equal(
ds %>%
select(string = chr, integer = int) %>%
filter(integer > 6 & integer < 11) %>%
collect() %>%
summarize(mean = mean(integer)),
df1 %>%
select(string = chr, integer = int) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
})
test_that("CSV dataset options", {
dst_dir <- make_temp_dir()
dst_file <- file.path(dst_dir, "data.csv")
df <- tibble(chr = letters[1:10])
write.csv(df, dst_file, row.names = FALSE, quote = FALSE)
format <- FileFormat$create("csv", skip_rows = 1)
ds <- open_dataset(dst_dir, format = format)
expect_equal(
ds %>%
select(string = a) %>%
collect(),
df1[-1, ] %>%
select(string = chr)
)
ds <- open_dataset(dst_dir, format = "csv", column_names = c("foo"))
expect_equal(
ds %>%
select(string = foo) %>%
collect(),
tibble(string = c(c("chr"), letters[1:10]))
)
})
test_that("Other text delimited dataset", {
ds1 <- open_dataset(tsv_dir, partitioning = "part", format = "tsv")
expect_equal(
ds1 %>%
select(string = chr, integer = int, part) %>%
filter(integer > 6 & part == 5) %>%
collect() %>%
summarize(mean = mean(as.numeric(integer))),
df1 %>%
select(string = chr, integer = int) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
ds2 <- open_dataset(tsv_dir, partitioning = "part", format = "text", delimiter = "\t")
expect_equal(
ds2 %>%
select(string = chr, integer = int, part) %>%
filter(integer > 6 & part == 5) %>%
collect() %>%
summarize(mean = mean(as.numeric(integer))),
df1 %>%
select(string = chr, integer = int) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
})
test_that("readr parse options", {
arrow_opts <- names(formals(CsvParseOptions$create))
readr_opts <- names(formals(readr_to_csv_parse_options))
expect_equal(
intersect(arrow_opts, readr_opts),
character(0)
)
expect_error(
open_dataset(tsv_dir, partitioning = "part", delim = "\t", na = "\\N"),
"supported"
)
expect_error(
open_dataset(
tsv_dir,
partitioning = "part",
format = "text",
asdfg = "\\"
),
"Unrecognized"
)
expect_error(
open_dataset(
tsv_dir,
partitioning = "part",
format = "text",
quote = "\"",
quoting = TRUE
),
"either"
)
expect_error(
open_dataset(
tsv_dir,
partitioning = "part",
format = "text",
quo = "\"",
),
"Ambiguous"
)
ds1 <- open_dataset(tsv_dir, partitioning = "part", delim = "\t")
expect_equal(
ds1 %>%
select(string = chr, integer = int, part) %>%
filter(integer > 6 & part == 5) %>%
collect() %>%
summarize(mean = mean(as.numeric(integer))),
df1 %>%
select(string = chr, integer = int) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
})
test_that("Error if no format specified and files are not parquet", {
expect_error(
open_dataset(csv_dir, partitioning = "part"),
"Did you mean to specify a 'format' other than the default (parquet)?",
fixed = TRUE
)
expect_error(
open_dataset(csv_dir, partitioning = "part", format = "parquet"),
"Parquet magic bytes not found"
)
})
test_that("Column names inferred from schema for headerless CSVs (ARROW-14063)", {
headerless_csv_dir <- make_temp_dir()
tbl <- df1[, c("int", "dbl")]
write.table(tbl, file.path(headerless_csv_dir, "file1.csv"), sep = ",", row.names = FALSE, col.names = FALSE)
ds <- open_dataset(headerless_csv_dir, format = "csv", schema = schema(int = int32(), dbl = float64()))
expect_equal(ds %>% collect(), tbl)
}) |
is_valid <- function(h3_address = NULL, simple = TRUE) {
eval_this <- data.frame(h3_address, stringsAsFactors = FALSE)
sesh$assign('evalThis', eval_this)
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_valid = h3.h3IsValid(evalThis[i].h3_address);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_valid
} else {
sesh$get('evalThis')
}
}
is_pentagon <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_pentagon = h3.h3IsPentagon(evalThis[i].h3_address);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_pentagon
} else {
sesh$get('evalThis')
}
}
is_rc3 <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_rc3 = h3.h3IsResClassIII(evalThis[i].h3_address);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_rc3
} else {
sesh$get('evalThis')
}
}
get_base_cell <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_base_cell = h3.h3GetBaseCell(evalThis[i].h3_address);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_base_cell
} else {
sesh$get('evalThis')
}
}
get_faces <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_faces = h3.h3GetFaces(evalThis[i].h3_address);
};')
if(simple == TRUE) {
unlist(sesh$get('evalThis')$h3_faces)
} else {
sesh$get('evalThis')
}
}
get_pentagons <- function(res = NULL, simple = TRUE) {
if(!any(res %in% seq(0, 15))) {
stop('Please provide a valid H3 resolution. Allowable values are 0-15 inclusive.')
}
sesh$assign('evalThis', data.frame(res, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_pentagons = h3.getPentagonIndexes(evalThis[i].res);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_pentagons
} else {
sesh$get('evalThis')
}
}
get_res <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_res = h3.h3GetResolution(evalThis[i].h3_address);
};')
if(simple == TRUE) {
sesh$get('evalThis')$h3_res
} else {
sesh$get('evalThis')
}
}
point_to_h3 <- function(input = NULL, res = NULL, simple = TRUE) {
if(!any(res %in% seq(0, 15))) {
stop('Please provide a valid H3 resolution. Allowable values are 0-15 inclusive.')
}
pts <- prep_for_pt2h3(input)
eval_this <-
data.frame('X' = rep(pts[ , 1], length(res)),
'Y' = rep(pts[ , 2], length(res)),
'h3_res' = rep(res, each = nrow(pts)),
stringsAsFactors = FALSE)
sesh$assign('evalThis', eval_this, digits = NA)
sesh$eval('var h3_address = [];
for (var i = 0; i < evalThis.length; i++) {
h3_address[i] = h3.geoToH3(evalThis[i].Y, evalThis[i].X, evalThis[i].h3_res);
};')
addys <- data.frame('n' = seq(nrow(pts)),
'res' = rep(res, each = nrow(pts)),
'h3_address' = sesh$get('h3_address'),
stringsAsFactors = FALSE)
addys <- tidyr::spread(addys, 'res', 'h3_address')
addys$n <- NULL
names(addys) <- paste0('h3_resolution_', names(addys))
if (simple == TRUE) {
if (length(res) == 1) {
unlist(addys, use.names = FALSE)
} else {
addys
}
} else {
if(inherits(input, 'sf')) {
cbind(sf::st_set_geometry(input, NULL), addys)
} else if(inherits(input, 'data.frame')) {
cbind(input[, c(3:dim(input)[2]), drop = FALSE], addys)
} else {
addys
}
}
}
h3_to_point <- function(h3_address = NULL, simple = TRUE) {
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE))
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_resolution = h3.h3GetResolution(evalThis[i].h3_address);
evalThis[i].geometry = h3.h3ToGeo(evalThis[i].h3_address);
};')
pts <- sesh$get('evalThis')
pts$geometry <- lapply(pts$geometry, function(x) {
sf::st_point(c(x[2], x[1]))
})
pts$geometry <- sf::st_sfc(pts$geometry, crs = 4326)
if(simple == TRUE) {
pts$geometry
} else {
sf::st_sf(pts)
}
}
h3_to_polygon <- function(input = NULL, simple = TRUE) {
if(inherits(input, 'data.frame')) {
h3_address <- as.character(input[[1]])
} else {
h3_address <- unlist(input, use.names = FALSE)
}
if(any(is_valid(h3_address)) == FALSE) {
stop('Invalid H3 cell index detected.')
}
sesh$assign('evalThis', data.frame(h3_address, stringsAsFactors = FALSE),
digits = NA)
sesh$eval('for (var i = 0; i < evalThis.length; i++) {
evalThis[i].h3_resolution = h3.h3GetResolution(evalThis[i].h3_address);
evalThis[i].geometry = h3.h3ToGeoBoundary(evalThis[i].h3_address, formatAsGeoJson = true);
};')
hexes <- sesh$get('evalThis')
hexes$geometry <- lapply(hexes$geometry, function(hex) {
sf::st_polygon(list(hex))
})
hexes$geometry <- sf::st_sfc(hexes$geometry, crs = 4326)
if(simple == TRUE) {
hexes$geometry
} else {
if(inherits(input, 'data.frame')) {
sf::st_sf(cbind(input[, c(2:dim(input)[2]), drop = FALSE], hexes),
stringsAsFactors = FALSE)
} else {
sf::st_sf(hexes, stringsAsFactors = FALSE)
}
}
}
get_res0 <- function() {
sesh$eval('res0 = h3.getRes0Indexes();')
sesh$get('res0')
} |
test_that("metabolites function: the output class is wrong", {
expect_true(is.vector(metabolites(
reactionList = c(
"A[c]",
"B[protein]A[m_pro]",
"C[r]",
"2 5-A[c] + 3 B[c] <=> 5 3D[c] + B[c]"
)
)))
})
test_that("metabolites function: the output value is wrong", {
expect_equal(
object = metabolites(
reactionList = c(
"A[c]",
"B[protein]A[m_pro]",
"C[r]",
"2 5-A[c] + 3 B[c] <=> 5 3D[c] + B[c]"
),
woCompartment = TRUE,uniques = FALSE
),
expected = c("A", "B[protein]A", "C", "5-A", "B","3D","B")
)
expect_equal(
object = metabolites(
reactionList = c(
"A[c]",
"B[protein]A[m_pro]",
"C[r]",
"2 5-A[c] + 3 B[c] <=> 5 3D[c] + B[c]"
),
woCompartment = TRUE,uniques = TRUE
),
expected = c("A", "B[protein]A", "C", "5-A", "B","3D")
)
expect_equal(
object = metabolites(
reactionList = c(
"A[c]",
"B[protein]A[m_pro]",
"C[r]",
"2 5-A[c] + 3 B[c] <=> 5 3D[c] + B[c]"
),
woCompartment = FALSE,uniques = TRUE
),
expected = c("A[c]", "B[protein]A[m_pro]", "C[r]", "5-A[c]", "B[c]","3D[c]")
)
expect_equal(
object = metabolites(
reactionList = c(
"A[c]",
"B[protein]A[m_pro]",
"C[r]",
"2 5-A[c] + 3 B[c] <=> 5 3D[c] + B[c]"
),
woCompartment = FALSE,uniques = FALSE
),
expected = c("A[c]", "B[protein]A[m_pro]", "C[r]", "5-A[c]", "B[c]","3D[c]","B[c]")
)
}) |
optimal_control_gradient_descent <- function(alphaStep, armijoBeta, x0, parameters, alpha1, alpha2, measData, constStr,
SD, modelFunc, measFunc, modelInput, optW, origAUC, maxIteration, plotEsti, conjGrad, eps, nnStates, verbose) {
if (.Platform$OS.type != "windows"){
temp_costate_path <- paste0(tempdir(),'/','costate.R')
temp_hidden_input_path <- paste0(tempdir(),'/','stateHiddenInput.R')
} else {
temp_costate_path <- paste0(tempdir(),'\\','costate.R')
temp_hidden_input_path <- paste0(tempdir(),'\\','stateHiddenInput.R')
}
e <- new.env()
source(temp_hidden_input_path, local = e)
source(temp_costate_path, local = e)
costate <- get('costate', envir = e)
hiddenInputState <- get('hiddenInputState', envir = e)
startOptW <- optW
if (missing(optW)) {
optW <- rep(1, length(x0))
}
if (missing(plotEsti)) {
plotEsti <- FALSE
}
if (missing(nnStates)) {
nnStates <- rep(0, length(x0))
}
times <- measData[, 1]
N <- 10 * length(times)
t0 <- times[1]
tf <- utils::tail(times, n = 1)
times <- seq(from = t0, to = tf, length.out = N)
tInt <- c(t0, tf)
measureTimes <- measData[, 1]
measureData <- measData[, -1]
alphaDynNet <- list(a1 = alpha1, a2 = alpha2)
eventTol <- 0.0
resetValue <- 0.0001
RootFunc <- eval(parse(text = createRoot(rootStates = nnStates)))
EventFunc <- eval(parse(text = createEvent(tolerance = eventTol, value = resetValue)))
if (is.null(SD)) {
measureData <- as.matrix(measureData)
Q <- matrix(data = rep(1, length(measureData)), ncol = ncol(measureData))
Q = Q / abs(measureData)
Q[is.infinite(Q)] = 0
Q[is.na(Q)] = 0
interpQ <- apply(X = Q, MARGIN = 2, FUN = function(t) stats::approx(x = measureTimes, y = t, xout = times))
interpQ = do.call(cbind, lapply(interpQ, FUN = function(t) cbind(t$y)))
Q <- interpQ
}
else {
interpSD <- apply(X = SD[,-1], MARGIN = 2, FUN = function(t) stats::approx(x = SD[, 1], y = t, xout = times))
interpSD = do.call(cbind, lapply(interpSD, FUN = function(t) cbind(t$y)))
Q <- apply(X = interpSD, MARGIN = 2, FUN = function(t)(1 / t ^ 2) / length(t))
}
if (all(is.null(names(x0)))) {
names(x0) <- paste0(rep("x", length(x0)), 1:length(x0))
}
if (!is.null(modelInput)) {
inputInterp <- list()
inputInterp <- apply(X = modelInput[, -1, drop = F], MARGIN = 2, FUN = function(x) stats::approxfun(x = modelInput[, 1], y = x, rule = 2, method = 'linear'))
}
if (grepl("Rtools", Sys.getenv('PATH')) || (.Platform$OS.type != "windows")) {
if (!is.null(modelInput)) {
inputApprox <- apply(X = modelInput[, -1, drop = F], MARGIN = 2, FUN = function(x) stats::approx(x = modelInput[, 1], y = x, xout = times, rule = 2))
inputApprox = list(cbind(times, inputApprox$u$y))
} else {
inputApprox <- list(cbind(times, rep(0, length(times))))
}
w <- matrix(rep(0, length(x0) * length(times)), ncol = length(x0))
wSplit <- split(w, rep(1:ncol(w), each = nrow(w)))
wList <- lapply(wSplit, FUN = function(x) cbind(times, x))
forcings <- c(inputApprox, wList)
if (sum(nnStates) == 0) {
solNominal = deSolve::ode(y = x0, times, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc")
} else {
solNominal = deSolve::lsoda(y = x0, times, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc", nroot = sum(nnStates),
rootfunc = "myroot", events = list(func = EventFunc, root = TRUE))
}
} else {
if (!is.null(modelInput)) {
if (sum(nnStates) == 0) {
solNominal <- as.data.frame(deSolve::ode(y = x0,
times = times,
func = modelFunc,
parms = parameters,
input = inputInterp))
} else {
solNominal <- as.data.frame(deSolve::ode(y = x0,
times = times,
func = modelFunc,
parms = parameters,
input = inputInterp,
events = list(func = EventFunc, root = TRUE),
rootfun = RootFunc))
}
} else {
if (sum(nnStates) == 0) {
solNominal <- as.data.frame(deSolve::ode(y = x0,
times = times,
func = modelFunc,
parms = parameters))
} else {
solNominal <- as.data.frame(deSolve::ode(y = x0,
times = times,
func = modelFunc,
parms = parameters,
events = list(func = EventFunc, root = TRUE),
rootfun = RootFunc))
}
}
}
Tx <- solNominal[, 1]
x <- solNominal[, -1, drop = FALSE]
w = matrix(rep(0, nrow(x) * ncol(x)), nrow = nrow(x))
colnames(w) <- paste0(rep("w", ncol(w)), 1:ncol(w))
getMeassures <- function(x, measFunc) {
if (isTRUE(all.equal(measFunc, function(x) { }))) {
message('No meassurement function defined. Assuming all states are observable.')
y = x[, -1, drop = FALSE]
} else {
y = measFunc(x[, -1, drop = FALSE])
}
y = as.data.frame(cbind(x[, 1], y))
names(y)[1] <- 't'
names(y)[-1] <- paste0(rep("y", ncol(y) - 1), 1:(ncol(y) - 1))
return(y)
}
getAlphaBacktracking <- function(oldW, W, Q, y, gradStep, J, currIter, alphaDynNet, alphaS, stepBeta, optW, para, tInt, Tp, measFunc, input, measureTimes, nnStates, rootFunc, eventFunc) {
iter = 500
alpha = alphaS
arrayJ = rep(0, iter)
time <- seq(from = tInt[1], to = tInt[2], length.out = 100)
solX <- matrix(rep(0, length(time) * (length(optW) + 1)), ncol = length(optW) + 1)
Tx <- rep(0, length(time))
x <- matrix(0, length(optW) * length(time), ncol = length(optW))
yHat <- matrix(rep(0, length(measData)), ncol = ncol(measData))
for (i in 1:iter) {
flagNext <- FALSE
newW = oldW + alpha * gradStep
input$w = apply(X = newW, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tp, y = x, method = 'linear', rule = 2))
if (grepl("Rtools", Sys.getenv('PATH')) || (.Platform$OS.type != "windows")) {
wSplit <- split(newW, rep(1:ncol(newW), each = nrow(newW)))
wList <- lapply(wSplit, FUN = function(x) cbind(times, x))
forcings <- c(inputApprox, wList)
tryCatch({
if (sum(nnStates) == 0) {
solX <- deSolve::ode(y = x0, times = time, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc")
} else {
solX <- deSolve::lsoda(y = x0, times = time, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc", nroot = sum(nnStates),
rootfunc = "myroot", events = list(func = eventFunc, root = TRUE))
}
},
error = function(cond) {
flagNext <<- TRUE
},
warning = function(cond) {
},
finally = {
}
)
} else {
input$optW = optW
tryCatch({
if (sum(nnStates) == 0) {
R.utils::captureOutput(
solX <- deSolve::ode(y = x0, times = time, func = hiddenInputState, parms = parameters, input = input)
)
} else {
R.utils::captureOutput(
solX <- deSolve::ode(y = x0,
times = time,
func = hiddenInputState,
parms = parameters,
input = input,
events = list(func = eventFunc, root = TRUE),
rootfun = rootFunc))
}
},
error = function(cond) {
message('Error during calculating the stepsize of the gradient decent:')
message('Error while solving the ode system.')
message('Try to decrease alphaStep and see if the ode can then be solved.')
},
warning = function(cond) {
message('Warning while solving the ode system with the deSolve-package:')
message('Original error message:')
message(cond)
},
finally = {
}
)
}
if (flagNext) {
next
}
Tx = solX[, 1]
x = solX[, -1, drop = FALSE]
yHat = getMeassures(solX, measFunc)
if (sum(is.nan(colSums(x))) > 0 || sum(colSums(x)) == 0) {
stop('\nThe numerical solution of the ode system failed. See above message.')
}
input$interpX = apply(X = x, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tx, y = x, rule = 2, method = 'linear'))
input$interpyHat = apply(X = yHat[, -1, drop = FALSE], MARGIN = 2, FUN = function(x) stats::approxfun(x = yHat[, 1], y = x, rule = 2, method = 'linear'))
arrayJ[i] = costFunction(measureTimes, input, alphaDynNet)
if (i > 1 && (arrayJ[i] > arrayJ[i - 1]) && (arrayJ[i] < J[currIter])) {
alpha = alphaS * stepBeta ^ (i - 2)
break
}
alpha = alpha * stepBeta
}
intAlpha1 <- alpha
intAlpha2 <- alpha * stepBeta
costAlpha1 <- arrayJ[i - 1]
costAlpha2 <- arrayJ[i]
cubicInterpolMin <- function(alphaA, alphaB, jA, jB, nnStates, rootFunc, eventFunc) {
alpha3 <- 0.5 * (alphaA + alphaB)
newW = oldW + alpha3 * gradStep
if (grepl("Rtools", Sys.getenv('PATH')) || (.Platform$OS.type != "windows")) {
wSplit <- split(newW, rep(1:ncol(newW), each = nrow(newW)))
wList <- lapply(wSplit, FUN = function(x) cbind(times, x))
forcings <- c(inputApprox, wList)
if (sum(nnStates) == 0) {
solX <- deSolve::ode(y = x0, time, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc")
} else {
solX <- deSolve::lsoda(y = x0, times = time, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc", nroot = sum(nnStates),
rootfunc = "myroot", events = list(func = eventFunc, root = TRUE))
}
} else {
input$optW <- optW
input$w <- apply(X = newW, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tp, y = x, method = 'linear', rule = 2))
time <- seq(from = tInt[1], to = tInt[2], length.out = 300)
if (sum(nnStates) == 0) {
solX <- deSolve::ode(y = x0,
times = time,
func = hiddenInputState,
parms = parameters,
input = input)
} else {
solX <- deSolve::ode(y = x0,
times = time,
func = hiddenInputState,
parms = parameters,
input = input,
events = list(func = eventFunc, root = TRUE),
rootfun = rootFunc)
}
}
Tx <- solX[, 1]
x <- solX[, -1, drop = FALSE]
yHat <- getMeassures(solX, measFunc)
if (sum(is.nan(colSums(x))) > 0) {
warning('Numeric Integration failed. Returning last working step.')
return(alphaA)
}
input$interpX <- apply(X = x, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tx, y = x, rule = 2, method = 'linear'))
input$interpyHat <- apply(X = yHat[, -1, drop = FALSE], MARGIN = 2, FUN = function(x) stats::approxfun(x = yHat[, 1], y = x, rule = 2, method = 'linear'))
j3 = costFunction(measureTimes, input, alphaDynNet)
alphaT = alpha3 - (alphaB - alphaA) / 4 * (jB - jA) / (jB - 2 * j3 + jA)
if (is.nan(alphaT) || (length(alphaT) == 0)) {
return(alphaA)
} else {
if (alphaT > 0) {
alpha = alphaT
return(alpha)
} else {
alpha <- cubicInterpolMin(alphaA = alphaA, alphaB = alpha3, jA = jA, jB = j3, nnStates = nnStates, rootFunc = rootFunc, eventFunc = eventFunc)
return(alpha)
}
}
}
alphaTemp <- cubicInterpolMin(alphaA = intAlpha1, alphaB = intAlpha2, jA = costAlpha1, jB = costAlpha2, nnStates = nnStates, rootFunc = rootFunc, eventFunc = eventFunc)
return(alphaTemp)
}
showEstimates <- function(measureTimes, AUCs, input, alpha2, J, nomSol, SD) {
tPlot <- seq(from = measureTimes[1], to = measureTimes[length(measureTimes)], length.out = 50)
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
SD = SD[,-1]
y <- sapply(input$interpY, mapply, measureTimes)
yhat <- sapply(input$interpyHat, mapply, tPlot)
w <- sapply(input$w, mapply, tPlot)
yNom <- sapply(nomSol, mapply, tPlot)
J <- unlist(J)
J = J[J != 0]
width = 2
numMeas <- ncol(y)
if ((numMeas + 3) %% 3 == 0) {
n <- (numMeas + 3) %/% 3
} else {
n <- (numMeas + 3) %/% 3 + 1
}
m <- 3
par(mfrow = c(n, m), ask = F)
barplot(unlist(AUCs[1,]), col = 'red', xlab = 'hidden inputs', main = 'AUC (a.u)')
for (i in 1:numMeas) {
yLab <- paste0('y', as.character(i))
yMax <- max(max(y[, i]), max(yhat[, i]), max(yNom[, i]))
yMin <- min(min(y[, i]), min(yhat[, i]), min(yNom[, i]))
if (is.null(SD)) {
plot(x = measureTimes, y = y[, i], type = 'p', pch = 20, col = 'black', xlab = 't', ylab = yLab, ylim = c(yMin, yMax), lwd = width)
} else {
Hmisc::errbar(x = measureTimes, y = y[, i], yplus = y[, i] + SD[, i], yminus = y[, i] - SD[, i], ylab = yLab, xlab = 't', ylim = c(yMin, yMax), add = FALSE)
}
par(new = T)
plot(x = tPlot, y = yhat[, i], type = 'l', col = 'red', xlab = 't', ylab = yLab, ylim = c(yMin, yMax), lwd = width)
par(new = T)
plot(x = tPlot, y = yNom[, i], type = 'l', col = 'blue', xlab = 't', ylab = yLab, ylim = c(yMin, yMax), lwd = width)
}
plot(J, type = 'l', xlab = 'iteration', ylab = 'J[w]', lwd = width)
matplot(x = tPlot, y = w, type = 'l', col = 'red', xlab = 't', lwd = width)
}
costFunction <- function(measureTimes, input, alphaDynNet) {
y <- sapply(input$interpY, mapply, measureTimes)
yhat <- sapply(input$interpyHat, mapply, measureTimes)
q <- sapply(input$q, mapply, measureTimes)
w <- sapply(input$w, mapply, measureTimes)
yCost <- list()
for (i in 1:ncol(yhat)) {
yCost$Start[[i]] = sum((yhat[1, i] - y[1, i]) * q[1, i] * (yhat[1, i] - y[1, i]))
yCost$Middle[[i]] = sum((yhat[, i] - y[, i]) * q[, i] * (yhat[, i] - y[, i]))
yCost$End[[i]] = sum((yhat[nrow(yhat), i] - y[nrow(y), i]) * q[nrow(q), i] * (yhat[nrow(yhat), i] - y[nrow(y), i]))
}
wCost <- list(L1 = 0, L2 = 0)
for (i in 1:ncol(w)) {
wCost$L1 = wCost$L1 + sum(abs(w[, i]))
wCost$L2 = wCost$L2 + sum(abs(w[, i] ^ 2))
}
cost = sum(unlist(yCost$Start)) + sum(unlist(yCost$Middle)) + sum(unlist(yCost$End)) + alphaDynNet$a1 * wCost$L1 + alphaDynNet$a2 * wCost$L2
return(cost)
}
yHat <- getMeassures(solNominal, measFunc)
yNominal <- apply(X = yHat[, -1, drop = FALSE], MARGIN = 2, FUN = function(x) stats::approxfun(x = yHat[, 1], y = x, rule = 2, method = 'linear'))
createConst <- function(constString, needGrad) {
trim <- function(x) gsub(pattern = '\\s', replacement = "", x = x)
cont = strsplit(x = trim(constString), split = "==")[[1]][2]
eqs <- character(length = length(needGrad))
for (i in 1:length(needGrad)) {
str <- paste0('Solve(', trim(constString), ',x', needGrad[i], ')')
eqs[i] <- Ryacas::yac_str(str)
}
eq <- trim(gsub(pattern = 'list\\(||\\)\\)', replacement = "", x = eqs))
eq = gsub(pattern = '==', replacement = '=', x = eq)
eq = gsub(pattern = "(x)([0-9]*)", replacement = 'P[,\\2]', x = eq)
eq = gsub(pattern = paste0("[*/]*[+-]*", cont), replacement = '', x = eq)
return(eq)
}
evalGrad <- function(constStr, gradM, optW) {
gradzero <- which(colSums(gradM) == 0)
optCur <- which(optW > 0)
nG <- optCur[optCur %in% gradzero]
if (length(nG) > 0) {
cP <- createConst(constString = constStr, needGrad = nG)
}
return(cP)
}
xInterp <- apply(X = x, MARGIN = 2,
FUN = function(x) stats::approxfun(x = Tx, y = x, rule = 2, method = 'linear'))
yInterp <- apply(X = measData[, -1, drop = FALSE], MARGIN = 2,
FUN = function(x) stats::approxfun(x = measData[, 1], y = x, rule = 2, method = 'linear'))
yHatInterp <- apply(X = yHat[, -1, drop = FALSE], MARGIN = 2,
FUN = function(x) stats::approxfun(x = yHat[, 1], y = x, rule = 2, method = 'linear'))
qInterp <- apply(X = Q, MARGIN = 2,
FUN = function(x) stats::approxfun(x = times, y = x, rule = 2, method = 'linear'))
wInterp <- apply(X = w, MARGIN = 2,
FUN = function(x) stats::approxfun(x = Tx, y = x, rule = 2, method = 'linear'))
if (is.null(modelInput)) {
input <- list(optW = optW, interpX = xInterp, interpY = yInterp,
interpyHat = yHatInterp, q = qInterp, w = wInterp)
} else {
uInterp <- inputInterp
input <- list(optW = optW, interpX = xInterp, interpY = yInterp,
interpyHat = yHatInterp, q = qInterp, w = wInterp, u = uInterp)
}
cP <- NULL
if (missing(maxIteration)) {
maxIter <- 100
} else {
maxIter <- maxIteration
}
J <- rep(0, maxIter)
J[1] = costFunction(measureTimes, input, alphaDynNet)
if (verbose) {
cat('\n')
cat(paste0('Cost nominal model J[w]= ', J[1], '\n'))
}
lT <- rep(0., ncol(x))
timesCostate <- seq(from = tf, to = t0, length.out = N)
solCostate <- matrix(rep(0., (length(optW) + 1) * length(timesCostate)), ncol = length(optW) + 1)
Tp <- rep(0., length(timesCostate))
P <- matrix(rep(0., length(timesCostate) * length(optW)), ncol = length(optW))
oldW <- matrix(rep(0., length(optW) * length(timesCostate)), ncol = length(optW))
inputState <- list()
inputState$optW <- optW
solX <- matrix(rep(0., length(optW) * length(times)))
alphaS = alphaStep
wApprox <- matrix(rep(0., length(times) * 2), ncol = 2)
wApprox[, 1] = times
for (i in 1:maxIter) {
tryCatch({
R.utils::captureOutput(
solCostate <- deSolve::ode(y = lT, times = timesCostate, func = costate, parms = parameters, input = input)
)
},
error = function(cond) {
message('Error while solving the costate equation of the model:')
message('Original error message')
message(cond)
},
warning = function(cond) {
message('Warning while solving the costate ode system with the deSolve-package:')
message('Original error message:')
message(cond)
},
finally = { }
)
solCostate = solCostate[nrow(solCostate):1,]
Tp = solCostate[, 1]
P = solCostate[, -1, drop = FALSE]
if (!is.null(constStr) && i == 1) {
cP = evalGrad(gradM = P, optW = optW, constStr = constStr)
}
if (!is.null(cP)) {
eval(parse(text = cP))
}
oldW = w
if (conjGrad) {
gNeg = P + alpha2 * w
if (i == 1) {
oldGrad = -gNeg
step = gNeg
}
else {
newGrad <- gNeg * (gNeg + oldGrad)
newInt <- apply(X = newGrad, MARGIN = 2, FUN = function(x) pracma::trapz(Tp, x))
oldInt <- apply(X = oldGrad, MARGIN = 2, FUN = function(x) pracma::trapz(Tp, x ^ 2))
newInt[is.nan(newInt)] <- 0
oldInt[is.nan(oldInt)] <- 0
betaTest <- sum(newInt) / sum(oldInt)
step = gNeg + betaTest * step
oldGrad = -gNeg
}
} else {
step = P + alpha2 * w
}
alpha = getAlphaBacktracking(oldW = oldW,
W = w,
Q = Q,
y = measData,
gradStep = step,
J = J,
currIter = i,
alphaDynNet = alphaDynNet,
alphaS = alphaS,
stepBeta = armijoBeta,
optW = optW,
para = parameters,
tInt = tInt,
Tp = Tp,
measFunc = measFunc,
input = input,
measureTimes = measureTimes,
nnStates = nnStates,
rootFunc = RootFunc,
eventFunc = EventFunc)
w = oldW + alpha * step
if (sum(is.na(colSums(w))) > 0) {
warning("WARNING: Numerical solution of the ode system failed.\n\t This could result out of the observability of the system.\n")
break
}
inputState$wInterp <- apply(X = w, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tp, y = x, method = 'linear', rule = 2))
if (grepl("Rtools", Sys.getenv('PATH')) || (.Platform$OS.type != "windows")) {
wSplit <- split(w, rep(1:ncol(w), each = nrow(w)))
wList <- lapply(wSplit, FUN = function(x) cbind(times, x))
forcings <- c(inputApprox, wList)
tryCatch({
if (sum(nnStates) == 0) {
R.utils::captureOutput(
solX <- deSolve::ode(y = x0, times, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc")
)
} else {
solX <- deSolve::lsoda(y = x0, times, func = "derivsc",
parms = parameters, dllname = "model", initforc = "forcc",
forcings = forcings, initfunc = "parmsc", nroot = sum(nnStates),
rootfunc = "myroot", events = list(func = EventFunc, root = TRUE))
}
},
error = function(cond) {
message('Error while solving the ode system of the model with the calculated hidden inputs:')
message('Original error message:\n')
message(cond)
},
warning = function(cond) {
message('Warning while solving the ode system with the deSolve-package:')
message('Original error message:')
message(cond)
},
finally = { }
)
} else {
if (!is.null(modelInput)) {
inputState$u <- inputInterp
}
tryCatch({
if (sum(nnStates) == 0) {
R.utils::captureOutput(
solX <- deSolve::ode(y = x0,
times = times,
func = hiddenInputState,
parms = parameters,
input = inputState)
)
} else {
R.utils::captureOutput(
solX <- deSolve::ode(y = x0,
times = times,
func = hiddenInputState,
parms = parameters,
input = inputState,
events = list(func = EventFunc, root = TRUE),
rootfun = RootFunc)
)
}
},
error = function(cond) {
message('Error while solving the ode system of the model with the calculated hidden inputs:')
message('Original error message:\n')
message(cond)
},
warning = function(cond) {
message('Warning while solving the ode system with the deSolve-package:')
message('Original error message:')
message(cond)
},
finally = { }
)
}
Tx = solX[, 1]
x = solX[, -1, drop = FALSE]
yHat <- getMeassures(solX, measFunc)
input$interpX <- apply(X = x, MARGIN = 2, FUN = function(x) stats::approxfun(x = Tx, y = x, rule = 2, method = 'linear'))
input$interpyHat <- apply(X = yHat[, -1, drop = FALSE], MARGIN = 2, FUN = function(x) stats::approxfun(x = yHat[, 1], y = x, rule = 2, method = 'linear'))
input$w <- inputState$wInterp
J[i + 1] = costFunction(measureTimes, input, alphaDynNet)
tAUC <- measureTimes
absW <- abs(sapply(input$w, mapply, tAUC))
interpAbsW <- apply(X = absW, MARGIN = 2, FUN = function(x) stats::approxfun(x = tAUC, y = x, rule = 2, method = 'linear'))
AUCs <- sapply(X = interpAbsW, FUN = function(x) pracma::trapzfun(f = x, a = t0, b = tf))
if (verbose) {
cat(sprintf("Iteration %3d: \t J(w)= %006.4f change J(w): %6.2f%% \t alpha = %10.5f \n", i, J[i + 1], (1 - abs(J[i + 1] / J[i])) * 100, alpha))
}
if (plotEsti == TRUE) {
showEstimates(measureTimes, AUCs, input, alpha2, J, yNominal, SD)
}
if ((abs(J[i + 1] / J[i]) > 1 - (eps / 100))) {
break
}
}
if (missing(origAUC)) {
origAUC <- AUCs
}
greedySelection <- function(AUC, optW, origAUC) {
orderAUCs <- order(-do.call(cbind, as.list(origAUC[1,])))
tempOptW = rep(0, ncol(AUC))
if (sum(unlist(origAUC[1, ])) == sum(unlist(AUC[1, ]))) {
tempOptW[orderAUCs[1]] = 1
}
else {
tempOptW[orderAUCs[1:(sum(optW) + 1)]] = 1
}
return(tempOptW)
}
rmse <- function(measureTimes, input) {
y <- sapply(input$interpY, mapply, measureTimes)
yhat <- sapply(input$interpyHat, mapply, measureTimes)
y = apply(y, MARGIN = 2, FUN = function(X)(X - min(X)) / diff(range(X)))
yhat = apply(yhat, MARGIN = 2, FUN = function(X)(X - min(X)) / diff(range(X)))
y[is.nan(y)] <- 0
yhat[is.nan(yhat)] <- 0
return((colSums((yhat - y) ^ 2)) / nrow(yhat))
}
colnames(yHat) <- append('t', paste0('y', 1:(ncol(yHat) - 1)))
results <- list()
results$w <- cbind(Tp, w)
results$AUC <- do.call(cbind, AUCs[1,])
results$optW <- greedySelection(AUCs, optW, origAUC)
results$nomX <- solNominal
results$x <- solX
results$y <- yHat
results$rmse <- rmse(measureTimes, input)
lastJ = J[J > 0]
lastJ = lastJ[length(lastJ)]
results$J <- lastJ
results$totalJ <- J
return(results)
} |
NULL
dwnorm <- function(x, mean, covariance, log = FALSE) {
if (missing(mean)) mean <- 0
n <- if (is.matrix(x)) ncol(x) else length(x)
output <- -0.5 * (
n * log(2 * pi)
+ determinant(covariance, logarithm = TRUE)$modulus
+ mahalanobis(x, mean, covariance)
)
attributes(output) <- NULL
if (log) output else exp(output)
}
rwnorm <- function(n, mean, covariance) {
if (missing(mean)) mean <- 0
output <- sweep(
as.matrix(
.sample_Q(n, covariance@A)
+ covariance@X %*% .sample_Q(n, covariance@B)
),
1,
mean,
'+'
)
if (n == 1) output[, 1] else t(output)
}
.sample_Q <- function(n, Q) {
z <- matrix(stats::rnorm(n * nrow(Q)), nrow = nrow(Q))
if (is(Q, 'denseMatrix')) {
solve(chol(Q), z)
} else {
chol_Q <- Cholesky(Q, LDL = FALSE)
solve(chol_Q, solve(
chol_Q,
z,
system = 'Lt'
), system = 'Pt')
}
} |
test_that("get_vega_version works correctly", {
skip_on_cran()
vega_vers <- list(
vega_lite = "3.0.2",
vega = "5.3.2",
vega_embed = "4.0.0-rc1"
)
expect_identical(get_vega_version("3.0.2"), vega_vers)
})
test_that("vega_version() works correctly", {
vega_version <- vega_version()
expect_identical(
names(vega_version),
c("widget", "vega_lite", "vega", "vega_embed", "is_locked")
)
expect_identical(get_major(c("2.3.0", "3.2")), c("2", "3"))
expect_identical(get_major(TRUE), TRUE)
expect_identical(get_major("vl5"), "vl5")
})
test_that("vega_version_all() works correctly", {
vega_version_all <- vega_version_all()
expect_identical(
names(vega_version_all),
c("widget", "vega_lite", "vega", "vega_embed")
)
expect_s3_class(vega_version_all, 'data.frame')
})
test_that("vega_version_available() works correctly", {
vega_version_all <- vega_version_all()
vega_version <- vega_version()
vega_version_available <- vega_version_available()
expect_s3_class(vega_version_available, 'data.frame')
is_locked <- vw_env$is_locked
vw_lock_set(FALSE)
expect_identical(
vega_version_all(),
vega_version_available()
)
vw_lock_set(TRUE)
all <- vega_version_all()
expect_identical(
all[all[["widget"]] == vw_env[["widget"]], ],
vega_version_available()
)
vw_lock_set(is_locked)
})
test_that("get_candidate() works", {
exp_ca <- function(result, index, re_msg) {
expect_identical(result$index, index)
if (is.null(re_msg)) {
expect_null(result$message)
} else {
expect_match(result$message, re_msg)
}
}
exp_ca(get_candidate("5", c("5.2.0", "4.1.7")), 1L, NULL)
exp_ca(get_candidate("4", c("5.2.0", "4.1.7")), 2L, NULL)
exp_ca(get_candidate("6", c("5.2.0", "4.1.7")), 1L, "maximum")
exp_ca(get_candidate("3", c("5.2.0", "4.1.7")), 2L, "minimum")
exp_ca(get_candidate("5.21.0", c("5.21.0", "5.17.0")), 1L, NULL)
exp_ca(get_candidate("5.01.0", c("5.21.0", "5.17.0")), 1L, NULL)
exp_ca(get_candidate("5.22.0", c("5.21.0", "5.17.0")), 1L, NULL)
})
test_that("get_widget_string() works", {
library("tibble")
available <- tribble(
~widget, ~vega_lite, ~vega,
"vl5", "5.2.0", "5.21.0",
"vl4", "4.1.7", "5.17.0"
)
expect_identical(get_widget_string("vega-lite", "5", available), "vl5")
expect_identical(get_widget_string("vega", "5", available), "vl5")
expect_warning(
expect_identical(get_widget_string("vega-lite", "2", available), "vl4"),
"minimum"
)
expect_warning(
expect_identical(get_widget_string("vega-lite", "20", available), "vl5"),
"maximum"
)
}) |
pgfthomas <-
function(s,params) {
k<-s[abs(s)>1]
if (length(k)>0)
warning("At least one element of the vector s are out of interval [-1,1]")
if (length(params)<2) stop("At least one value in params is missing")
if (length(params)>2) stop("The length of params is 2")
lambda<-params[1]
theta<-params[2]
if (lambda<=0)
stop ("Parameter lambda must be positive")
if (theta<=0)
stop ("Parameter theta must be positive")
exp(lambda*(s*exp(theta*(s-1))-1))
} |
initialize.emul <-
function(mpars, moutput, par.reg, time.reg, kappa0, zeta0) {
m.par <- dim(mpars$par)[1]
p.par <- dim(mpars$par)[2]
n.par <- dim(moutput$out)[1]
nreg <- 1 + sum(par.reg) + sum(time.reg)
dmat <- design.mat(mpars, moutput, par.reg, time.reg)
Theta.mat <- dmat$Theta.mat
t.vec <- moutput$t
X.mat.df <- as.data.frame(dmat$X.mat)
beta.est <- lm(dmat$Y.mat ~ 0 + ., data=X.mat.df, offset=NULL)
beta.vec <- unname(beta.est$coefficients)
rho <- 0.9
par.min <- apply(Theta.mat, 2, min)
par.max <- apply(Theta.mat, 2, max)
phi.vec <- (par.max-par.min)/2
mu.vec <- dmat$X.mat%*%as.matrix(beta.vec)
vecC <- dmat$Y.mat - mu.vec
Sigma.mats <- sep.cov(Theta.mat, t.vec, rho, kappa0, phi.vec, zeta0)
Sigma.theta.Chol.mat <- chol(Sigma.mats$Sigma.theta.mat)
Sigma.theta.inv.mat <- chol2inv(Sigma.theta.Chol.mat)
init.emul <- list(Theta.mat=Theta.mat, t.vec=t.vec, Y.mat=dmat$Y.mat, X.mat=dmat$X.mat,
beta.vec=beta.vec, kappa=kappa0, phi.vec=phi.vec, zeta=zeta0, n=n.par,
rho=rho, p=p.par, vecC=vecC, par.reg=par.reg, time.reg=time.reg,
Sigma.mats=Sigma.mats, Sigma.theta.inv.mat=Sigma.theta.inv.mat)
init.emul
} |
require(Matrix)
work.blk.kriging2 <-
function(query,obs,fout,future=T,verbose=T,nmin=0,nmax=Inf,th=c(Inf,Inf))
{
tstamp <- matrix(obs[,3],ncol=1)
coords <- matrix(obs[,1:2],ncol=2)
z <- obs[,4]
vfs0 <- get(paste('v',fout$smodel,sep=''))
vf0t <- get(paste('v',fout$tmodel,sep=''))
Dmat <- dist(coords)
Tmat <- dist(tstamp)
Gd0 <- with(fout,as.vector(vfs0(Dmat,scoef[1],scoef[2],scoef[3])))
G0t <- with(fout,as.vector(vf0t(Tmat,tcoef[1],tcoef[2],tcoef[3])))
tmp <- Gd0 + G0t - fout$k * Gd0 * G0t
chk <- with(fout,(scoef[3]==0) & (tcoef[3]==0))
if(chk){
tmp <- tmp + 1e-5
}
fitGamma <- tritomat(tmp,length(z))
work.blk.kriging.nbr <- function(obs,query,nmax,th,fout){
return(0)
}
s0 <- query[,4]
t0 <- query[,3]
loc0 <- matrix(query[!duplicated(s0),1:2],ncol=2)
s.map <- match(s0,unique(s0))
tstamp0 <- query[!duplicated(t0),3]
t.map <- match(t0,unique(t0))
b0 <- query[,5]
dmat <- as.matrix(rdist(loc0,coords))
tmat0 <- outer(tstamp0,obs[,3],FUN="-")
tmat <- abs(tmat0)
gd0 <- with(fout,vfs0(dmat,scoef[1],scoef[2],scoef[3]))
g0t <- with(fout,vf0t(tmat,tcoef[1],tcoef[2],tcoef[3]))
tmp1 <- rowsum(gd0[s.map,]+g0t[t.map,]-fout$k*gd0[s.map,]*g0t[t.map,],b0)
r <- data.frame(table(b0))
fitgamma0 <- t(tmp1/r$Freq)
G <- rbind(cbind(fitGamma,1),c(rep(1,ncol(fitGamma)),0))
g <- rbind(fitgamma0,1)
lambda <- solve(G,g)
tmp <- lambda[-nrow(G),]
m <- lambda[nrow(G),]
zhat <- crossprod(tmp,z)
sigmasq <- m + apply(tmp * fitgamma0,2,sum)
sigmasq <- pmax(0,sigmasq)
r$krig <- as.vector(zhat)
r$se <- sqrt(sigmasq)
r
} |
getGenomeSet <-
function(db = "refseq",
organisms,
reference = FALSE,
release = NULL,
clean_retrieval = TRUE,
gunzip = TRUE,
update = FALSE,
path = "set_genomes") {
message(
"Starting genome retrieval of the following genomes: ",
paste0(organisms, collapse = ", "),
" ..."
)
if (!file.exists(path)) {
message("Generating folder ", path, " ...")
dir.create(path, recursive = TRUE)
}
if (!file.exists(file.path(path, "documentation")))
dir.create(file.path(path, "documentation"))
clean_names <- clean_species_names_helper(list.files(path), gunzip = gunzip)
message("\n")
if (length(clean_names) > 0) {
for (j in seq_len(length(clean_names))) {
if (file.exists(file.path(path, clean_names[j]))) {
if (!update) {
message("The file ", clean_names[j], " seems to exist already in ", path, ".",
"The existing file will be retained. Please specify 'update = TRUE' in case you wish to re-load the file.")
}
if (update) {
message("The file ", clean_names[j], " seems to exist already in ", path, ".",
"You specified 'update = TRUE', thus the file ", clean_names[j], " will be downloaded again.")
unlink(file.path(path, clean_names[j]), force = TRUE)
}
}
}
}
if (!update && (length(organisms) > 1)) {
organisms_short <- tidy_name2(organisms)
clean_names_short <- unlist(sapply(clean_names, function(x) unlist(stringr::str_split(x, "[.]"))))
organisms_short_setdiff <- as.character(as.vector(dplyr::setdiff(organisms_short, clean_names_short)))
if (length(organisms) > 0) {
organisms <- organisms[which(organisms_short %in% organisms_short_setdiff)]
}
}
if (length(organisms) > 0) {
paths <- vector("character", length(organisms))
message("\n")
for (i in seq_len(length(organisms))) {
paths[i] <- getGenome(db = db,
organism = organisms[i],
reference = reference,
release = release,
path = path)
message("\n")
}
meta_files <- list.files(path)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(path, meta_files), to = file.path(path, "documentation", meta_files))
doc_tsv_files <- file.path(path,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(path, "documentation", paste0(basename(path), "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all species has been stored at '",file.path(path, "documentation", paste0(basename(path), "_summary.csv")),"'.")
if (clean_retrieval) {
message("\n")
message("Cleaning file names for more convenient downstream processing ...")
}
if (clean_retrieval && gunzip)
clean.retrieval(paths, gunzip = TRUE)
if (clean_retrieval && !gunzip)
clean.retrieval(paths, gunzip = FALSE)
new_files <- list.files(path)
new_files <- new_files[-which(stringr::str_detect(new_files, "documentation"))]
return(file.path(path, new_files))
} else {
files <- file.path(path, list.files(path))
files <- files[-which(stringr::str_detect(files, "documentation"))]
return(files)
}
} |
predict0 <- function( mod, meig0, x0 = NULL, xgroup0 = NULL, offset0 = NULL,
weight0 = NULL, compute_quantile = FALSE ){
if( (class( mod ) !="resf")&(class( mod ) !="esf") ){
stop("Error: Input model must be an output from resf or esf function")
}
{
af <-function(par,y) par[1]+par[2]*y
sc <-function(par,y) (y-par[1])/par[2]
sa <-function(par,y) sinh(par[1]*asinh(y)-par[2])
bc <-function(par,y, jackup){
yy <- y + ifelse(jackup, abs( par[2] ), 0 )
if(par[1]==0){
res <- log(yy)
} else {
res <- ( yy^par[1] - 1 ) / par[1]
}
}
sal<-function(par,y, noconst=FALSE){
if(noconst==FALSE){
par[3]+ par[4]*sinh(par[1]*asinh(y)-par[2])
} else {
sinh(par[1]*asinh(y)-par[2])
}
}
d_af<-function(par,y) par[2]
d_sc <-function(par,y) 1/par[2]
d_sa<-function(par,y) par[1]*cosh(par[1]*asinh(y)-par[2])/sqrt(1+y^2)
d_bc<-function(par,y,jackup) (y + ifelse(jackup, abs( par[2] ), 0 ) )^(par[1]-1)
d_sal<-function(par,y,noconst=FALSE){
if(noconst==FALSE){
d_af(par=par[3:4],sa(par=par[1:2],y))*d_sa(par=par[1:2],y)
} else {
d_af(par=c(0, 1),sa(par=par[1:2],y))*d_sa(par=par[1:2],y)
}
}
i_af<-function(par,y) (y-par[1])/par[2]
i_sc <-function(par,y) par[1]+par[2]*y
i_sa<-function(par,y) sinh(1/par[1]*(asinh(y)+par[2]))
i_bc<-function(par,y,jackup){
if(par[1]==0){
exp(y) - ifelse(jackup, abs( par[2] ), 0 )
} else {
(par[1]*y + 1)^(1/par[1]) - ifelse(jackup, abs( par[2] ), 0 )
}
}
i_sal<-function(par,y,noconst=FALSE){
if(noconst==FALSE){
i_sa(par=par[1:2],i_af(par=par[3:4],y))
} else {
i_sa(par=par[1:2],i_af(par=c(0, 1),y))
}
}
d_sal_k <-function(par,y,k=2,noconst_last=TRUE,bc_par=NULL,y_ms=NULL,z_ms,jackup){
d <-1
if( !is.null( bc_par[1] ) ){
d <- d_bc(bc_par,y,jackup=jackup)*d
y <- bc(bc_par,y,jackup=jackup)
}
if(k>0){
d <- d_sc(par=y_ms,y)*d
y <- sc(par=y_ms,y)
for(kk in 1:k){
nc_dum<-ifelse((noconst_last==TRUE)&(kk==k),TRUE,FALSE)
d <-d_sal(par[[kk]],y,noconst=nc_dum)*d
y <- sal(par[[kk]],y,noconst=nc_dum)
}
}
d <-d_sc(par=z_ms,y)*d
return(d)
}
i_sal_k <-function(par,y,k=2,noconst_last=TRUE,bc_par=NULL,y_ms=NULL,z_ms, jackup){
y <-i_sc(par=z_ms,y)
if(k>0){
for(kk in k:1) {
nc_dum<-ifelse((noconst_last==TRUE)&(kk==k),TRUE,FALSE)
y <- i_sal(par[[kk]],y,noconst=nc_dum)
}
}
if( !is.null( y_ms ) ){
y <-i_sc(par=y_ms,y)
}
if( !is.null(bc_par[1]) ){
y <- i_bc(par=bc_par, y, jackup=jackup)
}
return(y)
}
sal_k <-function(par,y,k=2,noconst_last=TRUE,bc_par=NULL, jackup){
if( !is.null(bc_par[1]) ){
y <- bc(par=bc_par,y,jackup=jackup)
}
if( k > 0){
y_ms<- c( mean(y), sd(y) )
y <- sc(par=y_ms,y)
for(kk in 1:k) {
nc_dum<-ifelse((noconst_last==TRUE)&(kk==k),TRUE,FALSE)
y <- sal(par[[kk]],y,noconst=nc_dum)
}
} else {
y_ms<- NULL
}
z_ms <- c( mean(y), sd(y) )
y <- sc(par=z_ms,y)
return(list(y=y,y_ms=y_ms, z_ms=z_ms))
}
NLL_sal<-function(par,y,M,Minv,m0,k=2,noconst_last=TRUE,y_nonneg=FALSE,jackup){
n <-length(y)
par2<-list(NULL)
for(kk in 1:k){
if(noconst_last & (kk==k)){
par[(4*(kk-1)+1)]<- abs( par[(4*(kk-1)+1)] )
par2[[kk]] <- par[(4*(kk-1)+1):(4*(kk-1)+2)]
} else {
par[(4*(kk-1)+1)]<- abs( par[(4*(kk-1)+1)] )
par[(4*(kk-1)+4)]<- abs( par[(4*(kk-1)+4)] )
par2[[kk]] <- par[(4*(kk-1)+1):(4*(kk-1)+4)]
}
}
if(y_nonneg){
np_b <-length(par)
bc_par<-par[(np_b-1):np_b]
bc_par[2]<-abs(bc_par[2])
} else {
bc_par<-NULL
}
z0 <- sal_k(par=par2,y=y,k=k,noconst_last=noconst_last,bc_par=bc_par,jackup=jackup)
z <- z0$y
z_ms<- z0$z_ms
y_ms<- z0$y_ms
m <- t(m0)%*%z
b <- Minv%*%m
ee <- sum( z ^ 2 ) - 2 * t( b ) %*% m + t( b ) %*% M %*% b
d_abs<-abs( d_sal_k(par=par2,y,k=k,noconst_last=noconst_last,bc_par=bc_par,y_ms=y_ms,z_ms=z_ms,jackup=jackup) )
comp<- sum( log( d_abs ) )
nll <- ee/2 - comp
}
NLL_sal2<-function(par,y,M,Minv,m0,k=2,noconst_last=TRUE,y_nonneg=FALSE,jackup){
n <-length(y)
par2<-list(NULL)
for(kk in 1:k){
if(noconst_last & (kk==k)){
par[(4*(kk-1)+1)]<- abs( par[(4*(kk-1)+1)] )
par2[[kk]] <- par[(4*(kk-1)+1):(4*(kk-1)+2)]
} else {
par[(4*(kk-1)+1)]<- abs( par[(4*(kk-1)+1)] )
par[(4*(kk-1)+4)]<- abs( par[(4*(kk-1)+4)] )
par2[[kk]] <- par[(4*(kk-1)+1):(4*(kk-1)+4)]
}
}
if(y_nonneg){
np_b <-length(par)
bc_par<-par[(np_b-1):np_b]
bc_par[2]<-abs(bc_par[2])
} else {
bc_par<-NULL
}
z0 <- sal_k(par=par2,y=y,k=k,noconst_last=noconst_last,bc_par=bc_par,jackup=jackup)
z <- z0$y
z_ms<- z0$z_ms
y_ms<- z0$y_ms
m <- t(m0)%*%z
b <- Minv%*%m
ee <- sum( z ^ 2 ) - 2 * t( b ) %*% m + t( b ) %*% M %*% b
d_abs<-abs( d_sal_k(par=par2,y,k=k,noconst_last=noconst_last,bc_par=bc_par,y_ms=y_ms,z_ms=z_ms,jackup=jackup) )
comp<- sum( log( d_abs ) )
loglik<- ee/2 - comp
return(list(z=z, b=b, loglik=loglik,comp=comp,y_ms=y_ms,z_ms=z_ms))
}
NLL_bc <-function(par,y,M,Minv,m0,jackup){
par[2]<-abs(par[2])
z0 <- bc(par=par,y=y,jackup=jackup)
z_ms<- c(mean(z0),sd(z0))
z <- (z0-z_ms[1])/z_ms[2]
m <- t(m0)%*%z
b <- Minv%*%m
ee <- sum( z ^ 2 ) - 2 * t( b ) %*% m + t( b ) %*% M %*% b
d_abs<-abs( d_bc( par=par,y,jackup=jackup )*d_sc( par=z_ms,y ) )
comp<- sum( log( d_abs ) )
nll <- ee/2 - comp
}
NLL_bc2<-function(par,y, M, Minv,m0,jackup){
par[2]<-abs(par[2])
z0 <- bc(par=par,y=y,jackup=jackup)
z_ms<- c(mean(z0),sd(z0))
z <- (z0-z_ms[1])/z_ms[2]
m <- t(m0)%*%z
b <- Minv%*%m
ee <- sum( z ^ 2 ) - 2 * t( b ) %*% m + t( b ) %*% M %*% b
d_abs<-abs( d_bc( par=par,y,jackup=jackup )*d_sc( par=z_ms,y ) )
comp<- sum( log( d_abs ) )
loglik<- ee/2 - comp
return(list(z=z, b=b, loglik=loglik,comp=comp,z_ms=z_ms))
}
}
n <-length(mod$other$coords[,1])
nx <-mod$other$nx
eevSqrt <-mod$other$eevSqrt
if( mod$other$model == "esf" ){
if( is.null( dim( mod$r ) ) ){
sf_pred <- meig0$sf[ mod$other$sf_id] %*% c( mod$r[,1] )
} else {
sf_pred <- meig0$sf[ ,mod$other$sf_id ] %*% c( mod$r[,1] )
}
x0 <- as.matrix(x0)
b_g0 <- NULL
if( is.null( mod$other$x_id ) ){
xb_pred <- c( as.matrix( mod$b[ 1 ] ) )
pred <- xb_pred + sf_pred
} else {
if( is.null( x0 ) ){
message( " Note: Only spatial component (sf) is interpolated because x0 is missing")
pred <- sf_pred
} else {
if( is.numeric( x0 ) == FALSE ){
mode( x0 ) <- "numeric"
}
if( length( c(sf_pred)) ==1 ){
xb_pred <- c(1, x0[ ,mod$other$x_id ]) %*% mod$b[, 1 ]
} else {
xb_pred <- as.matrix( cbind( 1, x0[ ,mod$other$x_id ] ) ) %*% mod$b[, 1 ]
}
pred <- xb_pred + sf_pred
pred <- as.data.frame( cbind( pred, xb_pred, sf_pred ) )
names( pred )<- c( "pred", "xb", "sf_residual" )
}
}
c_vc <- cse_vc <- ct_vc <- cp_vc <- NULL
} else {
if( is.null( dim( mod$r ) ) ){
sf_pred <- meig0$sf %*% c( mod$r )
} else {
sf_pred <- meig0$sf %*% c( mod$r[, 1 ] )
}
n0 <- length( c(sf_pred) )
if( !is.null( x0 )){
if(dim( as.matrix( x0 ) )[2] != length( mod$other$res$other$xf_id )){
stop("x and x0 must have the same number of columns")
}
X1 <- as.matrix( mod$other$res$other$xconst )[,mod$other$res$other$xf_id]
X0 <- as.matrix( as.matrix( x0 )[,mod$other$res$other$xf_id] )
} else {
X0<-NULL
}
XX_0 <- list( NULL )
XX <- NULL
nvc <- mod$other$res$other$nvc_xconst
if( ( is.logical( nvc[ 1 ] ) ==FALSE )&( !is.null( x0 ) ) ){
X1_nvc<- as.matrix( X1 )[ , nvc ]
if( n0 == 1 ){
X0_nvc<- X0[ nvc ]
} else {
X0_nvc<- as.matrix( X0[ , nvc ] )
}
xxfname <- names( as.data.frame( X1 ) )[ nvc ]
nnxf <- length( xxfname )
X1 <- as.matrix( X1 )
X1_nvc <- as.matrix( X1_nvc )
np_xx <-apply( X1_nvc,2,function( x ) length( unique( x )))
np_xx <-ifelse( np_xx < mod$other$res$other$nvc_num/0.7, round( np_xx * 0.7 ) ,mod$other$res$other$nvc_num )
np_xx_max <-round( n/nnxf ) - 2
np_xx[ np_xx > np_xx_max ] <-np_xx_max
np_xx[ np_xx < 2 ] <- 2
B_c <-list(NULL)
for( ii in 1:dim( X1_nvc )[ 2 ] ){
if( np_xx[ ii ] <= 2 ){
B_c[[ii+1]] <- 0
np_xx[[ii]]<- 0
} else {
test<-TRUE
iiii<-0
while(test){
kkk <- np_xx[ ii ]-iiii
knots <-seq(min( X1_nvc[ ,ii ] ),max( X1_nvc[ ,ii ] ),len=kkk+2)[2:(kkk+1)]
testt<- try(XX1_00<- ns( X1_nvc[ , ii], knots = knots ), silent=TRUE)
test <- class(testt)[1] == "try-error"
iiii <- iiii+1
}
XX1_0 <- cbind( X1[,ii] , XX1_00)
if( n0 == 1 ){
XX0_0 <- c( X0_nvc[ii], predict( XX1_00, newx= X0_nvc[ii]) )
} else {
XX0_0 <- cbind( X0_nvc[,ii], predict( XX1_00, newx= X0_nvc[,ii]) )
}
if( !is.na( mod$other$res$other$sel_basis_c[[ ii ]][ 1 ] ) ){
XX1_0<- XX1_0[,mod$other$res$other$sel_basis_c[[ii]]]
if( n0 == 1){
XX0_0<- XX0_0[mod$other$res$other$sel_basis_c[[ii]]]
} else {
XX0_0<- XX0_0[,mod$other$res$other$sel_basis_c[[ii]]]
}
}
if( n0 == 1){
for( j in 1:length(XX0_0)){
XX0_0[j]<- ( XX0_0[j] - mean(XX1_0[,j]))/sd(XX1_0[,j])
}
} else {
for( j in 1:dim(XX0_0)[2]){
XX0_0[,j]<- ( XX0_0[,j] - mean(XX1_0[,j]))/sd(XX1_0[,j])
}
}
B_c[[ii]] <- XX0_0
}
}
}
if( is.null( mod$other$res$c_vc )|( is.null( x0 ) ) ){
c_vc <- cse_vc <- ct_vc <- cp_vc <- NULL
} else {
xc_vc <- 0
c_vc <- matrix(0, nrow = n0, ncol = nnxf )
cse_vc<- matrix(0, nrow = n0, ncol = nnxf )
ct_vc <- matrix(0, nrow = n0, ncol = nnxf )
cp_vc <- matrix(0, nrow = n0, ncol = nnxf )
for( i in 1:nnxf ){
evSqrts_c<- mod$other$res$other$evSqrts_c[[ i ]]
if(length( evSqrts_c ) == 1) evSqrts_c <- NULL
if( length( mod$other$res$other$evSqrts_c[[ i ]] ) <= 1 ){
c_vc[ , i ] <- mod$other$res$other$b_c[[ i ]][ 1 ]
cse_vc[ , i ] <- sqrt( mod$other$res$other$b_covs_c[[ i ]] )
ct_vc[ , i ] <- c_vc[ , i ] / cse_vc[ , i ]
cp_vc[ , i ] <- 2 - 2 * pt( abs( ct_vc[ , i ] ), df = n - mod$other$res$other$df )
} else {
if( n0 == 1 ){
c_vc[ , i ] <- mod$other$res$other$b_c[[ i ]][1] + c(B_c[[ i ]]) %*% c( mod$other$res$other$b_c[[ i ]][ -1 ])
sf2 <- t( B_c[[ i ]] * mod$other$res$other$evSqrts_c[[ i ]] )
} else {
c_vc[ , i ] <- mod$other$res$other$b_c[[ i ]][1] + B_c[[ i ]] %*% c( mod$other$res$other$b_c[[ i ]][ -1 ] )
sf2 <- t( t( B_c[[ i ]] ) * mod$other$res$other$evSqrts_c[[ i ]] )
}
if( n0 == 1){
x_sf <-t(as.matrix( c( 1, c( sf2 ) ) ))
cse_vc[ , i ] <- sqrt( x_sf %*% mod$other$res$other$b_covs_c[[ i ]] %*% t( x_sf ) )
} else {
x_sf <- as.matrix( cbind( 1, sf2 ) )
cse_vc[ , i ] <- sqrt( colSums( t( x_sf ) * ( mod$other$res$other$b_covs_c[[ i ]] %*% t( x_sf ) ) ) )
}
ct_vc[ , i ] <- c_vc[ , i ] / cse_vc[ , i ]
cp_vc[ , i ] <- 2 - 2 * pt( abs( ct_vc[ , i ] ), df = n - mod$other$res$other$df )
}
}
}
if( is.null( mod$b_g )==FALSE ){
if( is.null(xgroup0) ){
message( " Note: Group effects are ignored because xgroup0 is missing")
b_g0 <- NULL
} else {
ng <- length(mod$b_g)
xgroup0 <- data.frame( xgroup0 )
b_g0 <- xgroup0
for(ggid in 1:ng){
b_g_sub <- as.data.frame( mod$b_g[[ggid]] )
xg00_0 <- factor( xgroup0[ , ggid ] )
xg00_nam0 <- names( xgroup0 )[ ggid ]
xg00_nam <-ifelse( xg00_nam0 == "xgroup0", "xgroup", xg00_nam0 )
xgroup0_nam <- paste( xg00_nam, "_", xg00_0, sep = "" )
xgroup0_dat <- data.frame(id=1:length(xgroup0_nam),xg_nam=xgroup0_nam)
xgroup0_dat2 <- merge(xgroup0_dat, b_g_sub, by.x = "xg_nam", by.y = "row.names", all.x = TRUE )
b_g0[,ggid] <- xgroup0_dat2[order(xgroup0_dat2$id), "Estimate" ]
}
xg_names <- names( xgroup0 )
if( length( xg_names ) == 1 ){
xg_names <- ifelse( xg_names == "xgroup0", "xgroup", paste("xgroup_",xg_names,sep="" ) )
} else {
xg_names <- paste( "xgroup_", xg_names, sep = "" )
}
names(b_g0) <- xg_names
}
} else {
b_g0 <- NULL
}
if( is.null( mod$other$x_id ) ){
xb_pred <- c( mod$b$Estimate[1] )
pred <- xb_pred + sf_pred
pred <- data.frame( pred = pred, xb = xb_pred, sf_residual = sf_pred )
} else {
if( is.null( X0 ) ){
message( " Note: Trend term (xb) is ignored because x0 is missing")
pred <- data.frame(pred=NA, sf_residual=sf_pred)
} else {
if( is.numeric( X0 ) == FALSE ){
mode( X0 ) <- "numeric"
}
if( is.null( c_vc )){
if( n0 ==1 ){
xb_pred<- c( 1, X0[ mod$other$x_id ]) %*% mod$b[, 1 ]
} else {
xb_pred<- as.matrix( cbind( 1, X0[ ,mod$other$x_id ] ) ) %*% mod$b[, 1 ]
}
} else {
if( n0 == 1 ){
xb_pred<- sum( X0[ mod$other$x_id ] * c_vc ) + mod$b$Estimate[1]
} else {
xb_pred<- rowSums( X0[ ,mod$other$x_id ] * c_vc ) + mod$b$Estimate[1]
}
}
pred <- xb_pred + sf_pred
pred <- data.frame( pred = pred, xb = xb_pred, sf_residual = sf_pred )
}
}
if( is.null( b_g0 ) == FALSE ){
pred <- data.frame( pred, b_g0 )
na_b_g0 <- is.na( b_g0 )
if( sum( na_b_g0 ) > 0 ){
b_g0[ na_b_g0 ] <- 0
message( " Note: b_g = 0 is assumed for samples who does not belong to any groups in xgroup")
}
pred[ ,1 ]<- pred[ ,1 ] + rowSums( b_g0 )
}
y0 <- mod$other$y
tr_num <- mod$other$tr_num
y_nonneg <- mod$other$y_nonneg
y_type <- mod$other$y_type
tr_par <- mod$tr_par
tr_bpar <- mod$tr_bpar$Estimate
y_added <- mod$other$y_added
jackup <- mod$other$jackup
pred0 <- pred[,1]
pred_name <-names(pred)
noconst_last<-TRUE
if( tr_num > 0 ){
z0 <- sal_k(par=tr_par,y=y0,k=tr_num,noconst_last=noconst_last,bc_par=tr_bpar,jackup=jackup)
z_ms <- z0$z_ms
y_ms <- z0$y_ms
pred2 <- i_sal_k(par=tr_par,y=pred0,k=tr_num,noconst_last=noconst_last,
bc_par=tr_bpar,y_ms=y_ms,z_ms=z_ms,jackup=jackup) - y_added
if( y_nonneg ) pred2[ pred2 < 0 ] <- 0
if( y_type=="count" ){
pred2 <- exp( pred2 )
if( !is.null( mod$other$offset ) ){
if( is.null( offset0 ) ) stop( "offset0 is missing" )
pred2 <- pred2 * offset0
}
}
pred <- data.frame( pred= pred2, pred_transG=pred0, pred[,-1] )
names(pred)[-c(1:2)]<-pred_name[ -1 ]
} else if( y_nonneg ){
z0 <- bc(par=tr_bpar,y=y0,jackup=jackup)
pred2 <- i_bc(par=tr_bpar,y=pred0,jackup=jackup) - y_added
pred2[ is.nan( pred2 ) ] <- 0
pred2[pred2 < 0 ] <- 0
pred <- data.frame( pred = pred2, pred_transG=pred0, pred[,-1] )
names(pred)[-c(1:2)]<-pred_name[ -1 ]
} else if( y_type=="count" ){
pred2 <- exp( pred0 )
if( !is.null( mod$other$offset ) ){
if( is.null( offset0 ) ) stop( "offset0 is missing" )
pred2 <- pred2 * offset0
}
pred <- data.frame( pred = pred2, pred_transG=pred0, pred[,-1] )
names(pred)[-c(1:2)] <- pred_name[ -1 ]
}
res <- pred
pq_dat <- NULL
if( compute_quantile ==TRUE ){
if( mod$other$y_type == "count" ){
message("Note: 'compute_quantile' is currently not supported for count data")
} else {
if( mod$other$is_weight ==TRUE ){
if( is.null( weight0 ) ) stop( "Specify weight0 to compute quantile" )
} else {
weight0 <- NULL
}
if( !is.null( mod$other$x_id )&is.null( X0 ) ){
stop( "x0 is required to compute quantile" )
}
B_covs<-mod$other$B_covs
sig <-mod$other$sig
XX <- as.matrix( cbind( 1, X0, meig0$sf ) )
if( !is.null( mod$b_g ) ){
for( ggid in 1:ng ){
skip_id <-which(is.na(mod$b_g[[ggid]][,2]))
xg_levels <- mod$other$xg_levels[[ggid]][ -skip_id]
Xg <- matrix( 0, nrow =n0, ncol=length( xg_levels ) )
for( ggid2 in 1:length( xg_levels ) ) Xg[ ,ggid2 ][ xgroup0[, ggid ] == xg_levels[ ggid2 ] ]<-1
XX <-cbind(XX, Xg)
}
}
if( !is.null( mod$other$res$other$evSqrts_c[[1]] ) ){
for( i in 1:nnxf ){
evSqrts_n<- mod$other$res$other$evSqrts_c[[ i ]]
if( length( evSqrts_n ) == 1 ) evSqrts_n <- NULL
if( !is.null( evSqrts_n ) ){
XX<- cbind( XX, X0[ , i ] * B_c[[ i ]] )
}
}
}
if( is.null( weight0 ) ){
weight0 <- 1
} else {
weight0 <- weight0*mod$other$w_scale
}
X3 <- XX
X3[,-( 1:nx )]<- t(t(XX[,-( 1:nx )])* eevSqrt[eevSqrt > 0])
pred0_se<- sqrt( colSums( t( sqrt(weight0)*X3 ) * ( B_covs %*% t( sqrt(weight0)*X3 ) ) ) + sig )
pred0_se<- pred0_se/sqrt( weight0 )
if( sum(names( res ) %in% "pred_transG") == 0 ){
res_name<-names( res )
res <- data.frame( res[,1], pred_se = pred0_se, res[,-1] )
names( res ) <- c( res_name[1], "pred_se", res_name[ -1 ] )
} else {
res_name<-names( res )
res <- data.frame( res[,1:2], pred_se = pred0_se, res[,-(1:2)])
names( res ) <- c( res_name[1:2], "pred_transG_se", res_name[-(1:2)] )
}
pquant <- c(0.01, 0.025, 0.05, seq(0.1,0.9,0.1), 0.95, 0.975, 0.99)
pq_dat0 <- NULL
for(pq in pquant){
pq_dat0<-cbind(pq_dat0,qnorm(pq,pred0,pred0_se))
}
pq_dat0 <- as.data.frame(pq_dat0)
names(pq_dat0)<- paste("q",pquant,sep="")
if( tr_num > 0 ){
tr_bpar0 <-tr_bpar
z0 <- sal_k(par=tr_par,y=y0,k=tr_num,noconst_last=noconst_last,
bc_par=tr_bpar0,jackup=jackup)
z_ms <- z0$z_ms
y_ms <- z0$y_ms
pq_dat <- pq_dat0
for(pq in 1:ncol( pq_dat0 ) ){
ptest<-try(pq_pred<- i_sal_k( par=tr_par,y=pq_dat0[,pq],k=tr_num,noconst_last=noconst_last,
bc_par=tr_bpar0,y_ms=y_ms,z_ms=z_ms,jackup=jackup ) - y_added )
if(class(ptest)!="try-error"){
pq_dat[,pq] <-pq_pred
} else {
pq_dat[,pq] <-NA
}
}
} else if( y_nonneg ==TRUE ){
y <- bc(par=tr_bpar,y=y0,jackup=jackup)
pred <- i_bc(par=tr_bpar,y=pred0,jackup=jackup) - y_added
pred[ is.nan( pred ) ] <- 0
pred[pred < 0 ] <- 0
pq_dat <- pq_dat0
for(pq in 1:ncol(pq_dat0)){
ptest<-try(pq_pred<- i_bc(par=tr_bpar,y=pq_dat0[,pq],jackup=jackup) - y_added)
if(class(ptest)!="try-error"){
pq_pred[is.nan(pq_pred)&(pq_dat0[,pq] < 0)]<-0
pq_pred[pq_pred < 0 ] <- 0
pq_dat[,pq] <-pq_pred
} else {
pq_dat[,pq] <-NA
}
}
} else {
pq_dat <- pq_dat0
}
}
}
}
result <- list( pred = res, pred_quantile=pq_dat,
c_vc = c_vc, cse_vc =cse_vc, ct_vc = ct_vc, cp_vc = cp_vc )
return( result )
} |
expected <- eval(parse(text="6L"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(A = c(1, NA, 1), B = c(1.1, NA, 2), C = c(1.1+0i, NA, 3+0i), D = c(NA_integer_, NA_integer_, NA_integer_), E = c(FALSE, NA, TRUE), F = c(\"abc\", NA, \"def\")), .Names = c(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), class = \"data.frame\", row.names = c(\"1\", \"2\", \"3\")))"));
do.call(`length`, argv);
}, o=expected); |
moment_empirical_var <- function(model_matrices,N,n_d,n_o) {
wt <- model_matrices$wt
weight_as_indicator <- is.logical(wt[1])
if (weight_as_indicator) wt <- wt*1
const_global <- model_matrices$constants$global
const_intra <- model_matrices$constants$intra
const_intra_wt <- wt %|!|% lapply(const_intra, "*", wt)
order_keys <- c("D_","O_","I_")
X <- compact(model_matrices[order_keys])
wt_odi <- derive_weights_ODI(wt,n_d,n_o)[names(X)]
G_wt <- wt %|!|% lapply(model_matrices$G_, "*", wt)
alpha_blocks <- const_global %|!|% Reduce("cbind",list(
var_block_alpha(wt, N),
var_block_alpha_alpha_I(const_intra_wt %||% const_intra),
var_block_alpha_beta(X,wt_odi),
var_block_alpha_gamma(G_wt %||% model_matrices$G_)
))
if (!is.null(alpha_blocks))
rownames(alpha_blocks) <- "(Intercept)"
alpha_I_blocks <- const_intra %|!|% Reduce("cbind",list(
var_block_alpha_I(const_intra,const_intra_wt),
var_block_alpha_I_beta(const_intra_wt %||% const_intra,X),
var_block_alpha_I_gamma(const_intra_wt %||% const_intra,
model_matrices$G)
))
if (!is.null(alpha_I_blocks))
rownames(alpha_I_blocks) <- names(const_intra)
beta_blocks <- X %|!|% Reduce("cbind",list(
var_block_beta(X,wt_odi,wt),
var_block_beta_gamma(X, G_wt %||% model_matrices$G)
))
if (!is.null(beta_blocks))
rownames(beta_blocks) <- ulapply(X,"colnames")
gamma_block <- model_matrices$G %|!|% var_block_gamma(model_matrices$G, G_wt)
if (!is.null(gamma_block))
rownames(gamma_block) <- names(model_matrices$G)
combined_blocks <- list(alpha_blocks,alpha_I_blocks,beta_blocks,gamma_block)
combined_blocks <- rbind_fill_left(compact(combined_blocks))
combined_blocks <- make_symmetric(combined_blocks)
colnames(combined_blocks) <- rownames(combined_blocks)
return(combined_blocks)
}
var_block_alpha <- function(wt,N) {
if (is.null(wt)) N else sum(wt)
}
var_block_alpha_I <- function(const_intra, const_intra_wt) {
const_intra %|!|% crossproduct_mat_list(const_intra, const_intra_wt, TRUE)
}
var_block_beta <- function(X,wt_odi,wt) {
od_names <- c("D","O") %p% "_"
scalar_weights <- has_equal_elements(c(rapply(wt_odi, length),1))
if (scalar_weights) {
cross_prods <- Map("*", lapply(X, "crossprod"), wt_odi)
outer_prods <- tcrossprod(colSums(X$D_),colSums(X$O_))
intra_prods <- X$I_ %|!|% lapply(X[od_names], "crossprod", X$I_)
}
if (!scalar_weights) {
cross_prods <- Map("*", X, lapply(wt_odi,"sqrt"))
cross_prods <- lapply(cross_prods, "crossprod")
outer_prods <- crossprod(X$D_, wt) %*% X$O_
wt_XI <- X$I_ %|!|% wt_odi$I_ * X$I_
intra_prods <- wt_XI %|!|% lapply(X[od_names], "crossprod",wt_XI)
}
beta_block <- compact(list(
"D_" = cbind(cross_prods$D_,outer_prods,intra_prods$D_),
"O_" = cbind(cross_prods$O_,intra_prods$O_),
"I_" = cbind(cross_prods$I_)))
beta_block <- rbind_fill_left(beta_block)
beta_block <- as.matrix(forceSymmetric(beta_block, "U"))
return(beta_block)
}
var_block_gamma <- function(G,G_wt) {
G %|!|% crossproduct_mat_list(G, G_wt, TRUE)
}
var_block_alpha_alpha_I <- function(const_intra) {
const_intra %|!|% matrix(rapply(const_intra,sum), nrow = 1)
}
var_block_alpha_beta <- function(X, wt_odi) {
if (is.null(X))
return(NULL)
scalar_weights <- has_equal_elements(c(rapply(wt_odi, length),1))
if (scalar_weights) {
scaled_col_sums <- Map("*", wt_odi, lapply(X, "colSums2mat"))
scaled_col_sums <- Reduce("cbind", scaled_col_sums)
}
if (!scalar_weights) {
scaled_col_sums <- Map("%*%", wt_odi, X)
scaled_col_sums <- Reduce("cbind", scaled_col_sums)
}
return(scaled_col_sums)
}
var_block_alpha_gamma <- function(G) {
G %|!|% matrix(rapply(G,sum), nrow = 1)
}
var_block_alpha_I_beta <- function(const_intra,X) {
if (is.null(X) || is.null(const_intra))
return(NULL)
result <- Reduce("rbind", lapply(const_intra, "matrix_prod_ODI", X))
return(result)
}
var_block_alpha_I_gamma <- function(const_intra,G) {
if (is.null(G) || is.null(const_intra))
return(NULL)
block_alpha_I_gamma <- crossproduct_mat_list(const_intra,G)
return(block_alpha_I_gamma)
}
var_block_beta_gamma <- function(X,G) {
if (is.null(X) || is.null(G))
return(NULL)
result <- lapply(G, "matrix_prod_ODI", X)
result <- Reduce("cbind", lapply(result, "t"))
return(result)
}
moment_empirical_covar <- function(Y, model_matrices) {
order_keys <- c("D","O","I") %p% "_"
X <- compact(model_matrices[order_keys])
result <- Reduce("c", c(
cov_moment_alpha(Y) %T% (1 == model_matrices$constants$global),
cov_moment_alpha_I(Y, model_matrices$constants$intra),
cov_moment_beta(Y, X),
cov_moment_gamma(Y, model_matrices$G)
))
return(result)
}
cov_moment_alpha <- function(Y) {
Y %|!|% sum(Y)
}
cov_moment_alpha_I <- function(Y,const_intra) {
if (is.null(const_intra))
return(NULL)
block_Y_alpha_I <- sum(diag(Y))
if (length(const_intra) == 1)
return(block_Y_alpha_I)
block_Y_alpha_I <- c(
block_Y_alpha_I,
unlist(lapply(const_intra[-1], "hadamard_sum", Y))
)
return(block_Y_alpha_I)
}
cov_moment_beta <- function(Y, X) {
as.vector(matrix_prod_ODI(mat = Y,X = X))
}
cov_moment_gamma <- function(Y, G) {
G %|!|% unlist(lapply(G,hadamard_sum,Y))
}
derive_weights_ODI <- function(wt,n_o,n_d) {
if (is.null(wt))
return(list("D_" = n_o, "O_" = n_d, "I_" = 1))
return(list("D_" = rowSums(wt), "O_" = colSums(wt), "I_" = diag(wt)))
}
matrix_prod_ODI <- function(mat,X) {
if (is.null(X) || is.null(mat))
return(NULL)
result <- list(
X$D_ %|!|% (rowSums(mat) %*% X$D_),
X$O_ %|!|% (colSums(mat) %*% X$O_),
X$I_ %|!|% (diag(mat) %*% X$I_))
result <- Reduce("cbind", result)
return(result)
} |
turtle_x <- 0
turtle_y <- 0
turtle_direction <- 0
turtle_color <- "white"
turtle_drawing <- TRUE
turtle_init <- function(width = 100, height = 100,
mar = rep(0, 4), bg = "black", ...) {
par(mar = mar)
par(bg = bg)
plot(c(-width, width), c(-height, height), type = "n", xlab = "",
ylab = "", axes = FALSE, ...)
turtle_x <<- 0
turtle_y <<- 0
turtle_direction <<- 0
}
turtle_goto <- function(x, y) {
if (turtle_drawing) {
segments(turtle_x, turtle_y, x, y, col = turtle_color)
}
turtle_x <<- x
turtle_y <<- y
}
turtle_pen_up <- function() {
turtle_drawing <<- FALSE
}
turtle_pen_down <- function() {
turtle_drawing <<- TRUE
}
turtle_forward <- function(distance) {
x <- turtle_x + distance * cos(turtle_direction * pi/180)
y <- turtle_y + distance * sin(turtle_direction * pi/180)
turtle_goto(x, y)
}
turtle_turn_left <- function(degree) {
turtle_direction <<- (turtle_direction + degree)%%360
}
turtle_turn_right <- function(degree) {
turtle_direction <<- (turtle_direction - degree)%%360
}
turtle_set_color <- function(col) {
turtle_color <<- col
}
draw_turtle <- function() {
turtle_init()
turtle_set_color("brown")
turtle_forward(50)
turtle_turn_left(120)
turtle_forward(20)
turtle_turn_left(30)
turtle_forward(20)
turtle_turn_left(30)
turtle_forward(40)
turtle_turn_left(30)
turtle_forward(20)
turtle_turn_left(30)
turtle_forward(20)
turtle_turn_left(120)
turtle_forward(50)
turtle_set_color("pink")
turtle_pen_up()
turtle_goto(-20, 0)
turtle_pen_down()
turtle_turn_right(120)
turtle_forward(25)
turtle_turn_right(60)
turtle_forward(25)
turtle_goto(-30, 0)
turtle_turn_left(180)
turtle_pen_up()
turtle_goto(35, 0)
turtle_pen_down()
turtle_turn_right(90)
turtle_forward(20)
turtle_turn_right(60)
turtle_forward(20)
turtle_goto(25, 0)
turtle_turn_left(150)
turtle_pen_up()
turtle_goto(50, 0)
turtle_pen_down()
turtle_turn_left(30)
turtle_forward(30)
turtle_turn_left(60)
turtle_forward(10)
turtle_turn_left(60)
turtle_forward(10)
turtle_turn_left(30)
turtle_forward(10)
turtle_goto(45, 10)
turtle_pen_up()
turtle_goto(-45, 0)
turtle_pen_down()
turtle_forward(17)
turtle_turn_right(170)
turtle_forward(19)
}
draw_turtle() |
util_replace_codes_by_NA <- function(study_data, meta_data,
split_char = SPLIT_CHAR) {
sdf <- study_data
mdf <- meta_data
stopifnot(is.data.frame(sdf))
stopifnot(is.data.frame(mdf))
label_col <- VAR_NAMES
if (!is.null(attr(sdf, "label_col"))) {
label_col <- attr(sdf, "label_col")
}
for (code_name in c(MISSING_LIST, JUMP_LIST)) {
if (!(code_name %in% names(mdf)) || all(is.na(mdf[[code_name]]) |
trimws(mdf[[code_name]]) == "")) {
util_warning(
c("Meta data does not provide a filled column",
"called %s for replacing codes with NAs."),
dQuote(code_name),
applicability_problem = TRUE)
}
}
miss <- lapply(setNames(nm = names(sdf)), util_get_code_list,
MISSING_LIST, split_char,
mdf = mdf, label_col = label_col, warning_if_no_list = FALSE
)
jump <- lapply(setNames(nm = names(sdf)), util_get_code_list,
JUMP_LIST, split_char,
mdf = mdf, label_col = label_col, warning_if_no_list = FALSE
)
miss_n <- list()
jump_n <- list()
miss_n <- lapply(
mapply(`%in%`, sdf, miss, SIMPLIFY = FALSE, USE.NAMES = TRUE), sum,
na.rm = TRUE)
jump_n <- lapply(
mapply(`%in%`, sdf, jump, SIMPLIFY = FALSE, USE.NAMES = TRUE), sum,
na.rm = TRUE)
replace <- function(x, l) {
x[x %in% l] <- NA
x
}
environment(replace) <- parent.env(environment())
sdf[] <- mapply(replace, sdf, miss, SIMPLIFY = FALSE)
sdf[] <- mapply(replace, sdf, jump, SIMPLIFY = FALSE)
attr(sdf, "Codes_to_NA") <- TRUE
attr(sdf, "MAPPED") <- attr(study_data, "MAPPED")
return(list(study_data = sdf, list_N_MC_replaced = miss_n,
list_N_JC_replaced = jump_n))
} |
HKG <- function(level){
x <- NULL
if(level==1){
x1 <- github.cssegisanddata.covid19(country = "Hong Kong")
x2 <- ourworldindata.org(id = "HKG")
x <- full_join(x1, x2, by = "date")
}
return(x)
} |
set.max.replicates <- function (first = TRUE) {
value <- .cur.db@[email protected]$n
if (first == TRUE) {
cat("Number of (maximum) bootstrap replicates to perform \n")
if (is.null(value)) {
cat("The current value is NULL...\n")
}
else {
cat("The current number is", value, "...\n")
}
cat("\nPlease type the new number: ")
}
ans <- as.numeric(readline())
if (ans == "NULL" || ans == "null") {
Recall(first = FALSE)
} else {
if (ans > 0) {
.cur.db@[email protected]$n <- ans
c1 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter a numeric value larger than 0 ")
Recall(first = FALSE)
}
}
}
bootgam.conv.crit1 <- function() {
cat("\nType the critical value of the fluctuation ratio\n")
cat("you want to use (0 to exit)\n")
ans <- readline()
if (ans == 0) {
return()
}
if (ans < 1) {
cat("The number must be greater than 1\n")
Recall()
}
.cur.db@[email protected]$crit1.conv <- ans
c2 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c2)
invisible()
return()
}
bootgam.conv.crit2 <- function(skip=F) {
if(!skip) {
cat("\nType the lowest important relative inclusion frequency\n")
cat("or return for the default (0.2):")
ans <- readline()
if(ans == "") {
.cur.db@[email protected]$crit2.liif <- 0.2
} else if(ans < 0 || ans > 1) {
cat("The number must be greater than 0 and lower than 1\n")
Recall()
} else {
.cur.db@[email protected]$crit2.liif <- ans
}
}
cat("\nType the lowest absulute joint inclusion frequency\n")
cat("or return for the default (25):")
ans2 <- readline()
if(ans2 == "") {
.cur.db@[email protected]$crit2.ljif.conv <- 25
} else if(ans2 < 1) {
cat("The number must be greater than 1\n")
Recall(skip=T)
} else {
.cur.db@[email protected]$crit2.ljif.conv <- ans2
}
c3 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c3)
invisible()
return()
}
specify.start.model <- function () {
if (any(is.null(covs <- xvardef("covariates", .cur.db)))) {
cat("\nThe current data base has no covariates defined\n")
invisible()
return()
}
cat("\nThe following covariates are defined in the current data base:\n")
cat(covs, fill = 60)
cat("\nType the names of the covariates that should be included in the\n")
cat("\nmodel and end with a blank line:\n")
st.covs <- scan(what = character())
if(length(st.covs) == 0) {
st.covs <- NULL
}
.cur.db@[email protected]$start.mod <- st.covs
c4 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c4)
invisible()
return()
}
normalize.median <- function () {
if (.cur.db@[email protected]$median.norm == FALSE) {
.cur.db@[email protected]$median.norm <- TRUE
cat ("\nNormalize to median is now set to ON\n")
} else {
.cur.db@[email protected]$median.norm <- FALSE
cat ("\nNormalize to median is now set to OFF\n")
}
c5 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c5)
invisible()
return()
}
bg.conv.crit2 <- function(skip = FALSE) {
if(!skip) {
cat("\nType the lowest important relative inclusion frequency\n")
cat("or return for the default (0.2):")
ans <- readline()
if(ans == "") {
.cur.db@[email protected]$liif <- 0.2
} else if(ans < 0 || ans > 1) {
cat("The number must be greater than 0 and lower than 1\n")
Recall()
} else {
.cur.db@[email protected]$liif <- ans
}
}
cat("\nType the lowest absulute joint inclusion frequency\n")
cat("or return for the default (25):")
ans2 <- readline()
if(ans2 == "") {
.cur.db@[email protected]$ljif.conv <- 25
} else if(ans2 < 1) {
cat("The number must be greater than 1\n")
Recall(skip=T)
} else {
.cur.db@[email protected]$ljif.conv <- ans2
}
c6 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c6)
invisible()
return()
}
bg.conv.crit1 <- function() {
cat("\nType the critical value of the fluctuation ratio\n")
cat("you want to use (0 to exit)\n")
ans <- readline()
if(ans == 0) {
return()
}
if(ans < 1) {
cat("The number must be greater than 1\n")
Recall()
}
.cur.db@[email protected]$conv.value <- ans
c7 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c7)
invisible()
return()
}
change.conv.alg <- function () {
cat("\nSpecify the algorithm for convergence calculations\n")
choices <- c("Return to previous menu",
"Fluctuation ratio",
"Lowest absolute joint inclusion frequency"
)
pick <- menu(choices)
switch(pick,
return(),
{ .cur.db@[email protected]$algo <- "fluct.ratio"
c8 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c8)
bg.conv.crit1()
},
{ .cur.db@[email protected]$algo <- "liif"
c9 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c9)
bg.conv.crit2()
})
Recall()
return()
}
specify.start.check <- function () {
cat("\nType the iteration number at which you want to start checking\n")
cat("convergence (0 to exit):")
ans <- readline()
if(ans == 0) {
return()
}
if(ans < 0) {
cat("The number must be positive.\n")
Recall()
}
.cur.db@[email protected]$start.check <- ans
c10 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c10)
invisible()
return()
}
specify.interval <- function () {
cat("\nType the interval at which the convergence should be \n")
cat("checked (0 to exit):")
ans <- readline()
if (ans == 0) {
return()
}
if (ans < 0) {
cat ("The number must be positive.\n")
Recall()
}
.cur.db@[email protected]$check.interval <- ans
c11 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c11)
invisible()
return()
}
exclude.individuals <- function () {
cat("Please type the ID number of the individuals you want to exclude\n")
cat("from the bootgam analysis and finish with a blank line:\n")
inds <- scan(what = character())
if(length(inds) == 0) {
inds <- NULL
}
.cur.db@[email protected]$excluded.ids <- inds
c12 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c12)
invisible()
return()
}
set.seed.number <- function () {
cat ("Type a seed number between 1 and 1000 (return to exit):")
ans <- readline()
if (ans == "") {
return()
}
if (as.numeric(ans) >= 1 && as.numeric(ans) <= 1000) {
.cur.db@[email protected]$seed <- ans
} else {
cat("The number must be between 1 and 1000\n")
Recall()
}
c13 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c13)
}
bootgam.settings.menu <- function () {
choices <- c("Return to the previous menu ->",
"List current bootGAM settings",
"Set maximum number of bootstrap replicates",
"Change convergence algorithm",
"Specify iteration to start check convergence at",
"Specify at what interval to check the convergence",
"Set seed number",
"Exclude individuals",
"Specify starting model"
)
title = "\nBootGAM SETTINGS MENU\n \\main\\covariate model\\BootGAM\\settings for the BootGAM"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
list.bootgam.settings(eval(as.name(".cur.db"))),
set.max.replicates(),
change.conv.alg(),
specify.start.check(),
specify.interval(),
set.seed.number(),
exclude.individuals(),
specify.start.model()
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
list.bootgam.settings <- function (object) {
if (exists("object")) {
cat(paste("\nThe current run number is ", object@Runno, ".\n\n", sep = ""))
if (!any(is.null(object@Prefs@Xvardef$parms))) {
cat("\nMaximum number of bootstrap replicates: ", object@[email protected]$n)
cat(":", object@[email protected]$n)
cat("\nConvergence algorithm to use: ", object@[email protected]$algo)
if (object@[email protected]$algo == "fluct.ratio") {
cat("\nConvergence criterion: ", object@[email protected]$conv.value)
} else {
cat("\nLowest importan relative inclusion freq: ", object@[email protected]$liif)
cat("\nCritical value (ljif): ", object@[email protected]$ljif.conv)
}
cat("\nStarting model: ", object@[email protected]$n)
}
} else {
cat("The current run number is", object@Runno, "but no matching database was found.\n")
}
}
bootgam.menu <- function () {
choices <- c("Return to previous menu ->",
"Run a bootGAM",
"Summarize bootGAM",
"Plot bootGAM results ->",
"Settings for the BootGAM ->",
"Settings for the GAM ->")
title = "\nBootGAM MENU\n \\main\\covariate model\\BootGAM\n\n*** Note that the bootGAM also uses the settings from the GAM!\n Please go the GAM settings menu to alter these.\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
xp.bootgam (eval(as.name(".cur.db")), overwrite = FALSE),
bootgam.print(),
qx <- bootgam.plot.menu(),
qx <- bootgam.settings.menu(),
qx <- gam.settings.menu())
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootgam.plot.menu <- function () {
choices <- c("Return to previous menu",
"Inclusion frequencies",
"Most common 2-covariate combinations",
"Distribution of model size",
"Inclusion stability - covariates",
"Inclusion index of covariates",
"Inclusion index of covariates/individuals",
"Compare index of covariates/individuals"
)
title = "\nBootGAM plot MENU\n \\main\\covariate model\\BootGAM\\Plot"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
print(xp.inc.prob()),
print(xp.inc.prob.comb.2()),
print(xp.distr.mod.size()),
print(xp.inc.stab.cov()),
print(xp.incl.index.cov()),
print(xp.incl.index.cov.ind()),
print(xp.incl.index.cov.comp())
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootscm.plot.menu <- function ()
{
choices <- c("Return to previous menu ->",
"Inclusion frequencies",
"Most common 2-covariate combinations",
"Distribution of model size",
"Conditional inclusion index",
"Individual inclusion index",
"Compare index of covariates/individuals",
"Bias parameter estimates (hurricane plot)",
"Correlation in parameters covariate effects",
"Distribution of dOFV final models",
"dOFV versus model size final models",
"dAIC versus model size final models",
"Trace plots - parameter-covariates",
"Trace plots - conditional indices",
"Trace plots - indiv. conditional indices")
title = "\nBOOTSCM PLOT MENU\n \\main\\covariate model\\BootSCM\\Plot menu\n\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
print(xp.inc.prob()),
print(xp.inc.prob.comb.2()),
print(xp.distr.mod.size()),
print(xp.incl.index.cov()),
print(xp.incl.index.cov.ind()),
print(xp.incl.index.cov.comp()),
print(xp.boot.par.est()),
print(xp.boot.par.est.corr(ask.covs = TRUE)),
print(xp.dofv.plot()),
print(xp.dofv.npar.plot()),
print(xp.daic.npar.plot()),
print(xp.inc.stab.cov()),
print(xp.inc.cond.stab.cov()),
print(xp.inc.ind.cond.stab.cov()))
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootscm.menu <- function () {
choices <- c("Return to previous menu ->",
"Import bootSCM data (from PsN folder)",
"Summarize bootSCM",
"Plot menu"
)
title = "\nBOOTSCM MENU\n \\main\\covariate model\\BootSCM\n\nThe BootSCM is implemented in PsN. Xpose can import its output and\ngenerate plots similar to those for the BootGAM\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
bootscm.import(),
bootgam.print(),
qx <- bootscm.plot.menu()
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(pdfsearch)
file <- system.file('pdf', '1610.00147.pdf', package = 'pdfsearch')
result <- keyword_search(file,
keyword = c('measurement', 'error'),
path = TRUE)
head(result)
head(result$line_text, n = 2)
file <- system.file('pdf', '1610.00147.pdf', package = 'pdfsearch')
result <- keyword_search(file,
keyword = c('measurement', 'error'),
path = TRUE, surround_lines = 1)
head(result)
head(result$line_text, n = 2)
file <- system.file('pdf', '1610.00147.pdf', package = 'pdfsearch')
result_hyphen <- keyword_search(file,
keyword = c('measurement'),
path = TRUE, remove_hyphen = FALSE)
result_remove_hyphen <- keyword_search(file,
keyword = c('measurement'),
path = TRUE, remove_hyphen = TRUE)
nrow(result_hyphen)
nrow(result_remove_hyphen)
token_result <- convert_tokens(file, path = TRUE)[[1]]
head(token_result)
file <- system.file('pdf', '1501.00450.pdf', package = 'pdfsearch')
result <- keyword_search(file,
keyword = c('repeated measures', 'mixed effects'),
path = TRUE, surround_lines = 1)
result
directory <- system.file('pdf', package = 'pdfsearch')
result <- keyword_directory(directory,
keyword = c('repeated measures', 'mixed effects',
'error'),
surround_lines = 1, full_names = TRUE)
head(result) |
Sn_A = function(x,trunc.level){
v = c(2:(trunc.level))
dim0=dim(x)
n = dim0[1]
d = dim0[2]
cA = sum(choose(d,v))
out0 = .C("stats_nonserial",
as.double(x),
as.integer(n),
as.integer(d),
as.integer(trunc.level),
stats = double(cA),
cardA = double(cA),
M = double(n*n*cA),
Asets = double(d*cA),
Sn = double(1),
J = double(n*n),
PACKAGE = "MixedIndTests"
)
} |
context("absolute_path_linter")
test_that("unquote", {
f <- lintr:::unquote
expect_equal(f(character()), character())
expect_equal(f("foo"), "foo")
expect_equal(
f(c("'f", "\"f'", "\"f\""), q="\""),
c("'f", "\"f'", "f" ))
expect_equal(
f(c("\"f\"", "'f'", "`f`", "`'f'`"), q="'"),
c("\"f\"", "f", "`f`", "`'f'`"))
expect_equal(f("`a\\`b`", q=c("`")), "a`b")
x <- c("\"x\"", "\"\\n\"", "\"\\\\\"", "\"\\\\y\"", "\"\\ny\"", "\"\\\\ny\"", "\"\\\\\\ny\"",
"\"\\\\\\\\ny\"", "\"'\"", "\"\\\"\"", "\"`\"")
y <- c("x", "\n", "\\", "\\y", "\ny", "\\ny", "\\\ny", "\\\\ny", "'", "\"", "`")
expect_equal(f(x, q="\""), y)
})
test_that("unescape", {
f <- lintr:::unescape
expect_equal(f(character()), character())
expect_equal(f("n"), "n")
x <- c("x", "x\\n", "x\\\\", "x\\\\y", "x\\ny", "x\\\\ny", "x\\\\\\ny", "x\\\\\\\\ny")
y <- c("x", "x\n", "x\\", "x\\y", "x\ny", "x\\ny", "x\\\ny", "x\\\\ny")
expect_equal(f(x), y)
})
test_that("is_root_path", {
f <- lintr:::is_root_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c( "", "foo", "http://rseek.org/", "./", " /", "/foo", "'/'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c( "/", "//")
y <- c(TRUE, FALSE)
expect_equal(f(x), y)
x <- c( "~", "~/", "~//", "~bob2", "~foo_bar/")
y <- c(TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("c:", "C:\\", "D:/", "C:\\\\", "D://")
y <- c(TRUE, TRUE, TRUE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("\\\\", "\\\\localhost", "\\\\localhost\\")
y <- c( TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_absolute_path", {
f <- lintr:::is_absolute_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c( "/", "//", "/foo", "/foo/")
y <- c(TRUE, FALSE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c( "~", "~/foo", "~/foo/", "~'")
y <- c(TRUE, TRUE, TRUE, FALSE)
expect_equal(f(x), y)
x <- c("c:", "C:\\foo\\", "C:/foo/")
y <- c(TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("\\\\", "\\\\localhost", "\\\\localhost\\c$", "\\\\localhost\\c$\\foo")
y <- c( TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_relative_path", {
f <- lintr:::is_relative_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c( "/", "c:\\", "~/", "foo", "http://rseek.org/", "'./'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("/foo", "foo/", "foo/bar", "foo//bar", "./foo", "../foo")
y <- c( FALSE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("\\\\", "\\foo", "foo\\", "foo\\bar", ".\\foo", "..\\foo", ".", "..", "../")
y <- c( FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_path", {
f <- lintr:::is_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c( "", "foo", "http://rseek.org/", "foo\nbar", "'foo/bar'", "'/'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("c:", "..", "foo/bar", "foo\\bar", "~", "\\\\localhost")
y <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_valid_path", {
f <- lintr:::is_valid_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("C:/asdf", "C:/asd*f", "a\\s:df", "a\\\nsdf")
y <- c( TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("C:/asdf", "C:/asd*f", "a\\s:df", "a\\\nsdf")
y <- c( TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x, lax=TRUE), y)
x <- c("/asdf", "/asd*f", "/as:df", "/a\nsdf")
y <- c( TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("/asdf", "/asd*f", "/as:df", "/a\nsdf")
y <- c( TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x, lax=TRUE), y)
})
test_that("is_long_path", {
f <- lintr:::is_long_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("foo/", "/foo", "n/a", "Z:\\foo", "foo/bar", "~/foo", "../foo")
y <- c( FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("returns the correct linting", {
msg <- rex::escape("Do not use absolute paths.")
linter <- absolute_path_linter(lax=FALSE)
non_absolute_path_strings <- c(
"..",
"./blah",
encodeString("blah\\file.txt")
)
for(path in non_absolute_path_strings) {
expect_lint(single_quote(path), NULL, linter)
expect_lint(double_quote(path), NULL, linter)
}
expect_lint("\"'/'\"", NULL, linter)
absolute_path_strings <- c(
"/",
"/blah/file.txt",
encodeString("d:\\"),
"E:/blah/file.txt",
encodeString("\\\\"),
encodeString("\\\\server\\path"),
"~",
"~james.hester/blah/file.txt",
encodeString("/a\nsdf"),
"/as:df"
)
for (path in absolute_path_strings) {
expect_lint(single_quote(path), msg, linter)
expect_lint(double_quote(path), msg, linter)
}
linter <- absolute_path_linter(lax=TRUE)
unlikely_path_strings <- c(
"/",
encodeString("/a\nsdf/bar"),
"/as:df/bar"
)
for (path in unlikely_path_strings) {
expect_lint(single_quote(path), NULL, linter)
expect_lint(double_quote(path), NULL, linter)
}
}) |
mnis_mps_on_date <- function(date1 = Sys.Date(), date2 = NULL,
tidy = TRUE, tidy_style = "snake_case") {
date1 <- as.Date(date1)
if (is.null(date2) == FALSE) {
date2 <- as.Date(date2)
}
if (is.null(date2) == TRUE) {
date2 <- date1
}
date_vec <- c(date1, date2)
query <- paste0(base_url, "members/query/House=Commons|Membership=all|",
"commonsmemberbetween=", min(date_vec), "and",
max(date_vec), "/")
got <- mnis_query(query)
mps <- got$Members$Member
mps <- tibble::as_tibble(mps)
if (.Platform$OS.type == "windows") {
mps$MemberFrom <- stringi::stri_trans_general(mps$MemberFrom, "latin-ascii")
mps$MemberFrom <- gsub("Ynys MA\U00B4n", "Ynys M\U00F4n", mps$MemberFrom)
}
if (tidy == TRUE) {
mps <- mnis::mnis_tidy(mps, tidy_style)
}
mps
} |
feval <- function(file.name,...){
do.call(file.name,list(...))
} |
library(hamcrest)
assertThat(simplify2array(list(1,2,3)), identicalTo(c(1,2,3))) |
str_c. <- function(..., sep = "", collapse = NULL) {
paste(..., sep = sep, collapse = collapse)
}
str_detect. <- function(string, pattern, fixed = FALSE, perl = FALSE) {
grepl(pattern, string, fixed = fixed, perl = perl)
}
str_ends. <- function(string, pattern) {
endsWith(string, pattern)
}
str_extract. <- function(x, pattern, fixed = FALSE, perl = FALSE) {
regmatches(x, regexpr(pattern, x, fixed = fixed, perl = perl))
}
str_extract_all. <- function(x, pattern, fixed = FALSE, perl = FALSE) {
regmatches(x, gregexpr(pattern, x, fixed = fixed, perl = perl))
}
str_replace. <- function(string, pattern, replacement, fixed = FALSE, perl = FALSE) {
sub(pattern, replacement, string, fixed = fixed, perl = perl)
}
str_replace_all. <- function(string, pattern, replacement, fixed = FALSE, perl = FALSE) {
if (missing(replacement)) {
replacement <- unname(pattern)
pattern <- names(pattern)
} else if (length(pattern) != length(replacement)) {
if (length(pattern) > 1 & length(replacement) > 1) {
stop("replacement has to have the same length as pattern")
} else {
if (length(replacement) == 1) {
replacement <- rep(replacement, length(pattern))
} else {
pattern <- rep(pattern, length(replacement))
}
}
}
for (i in 1:length(pattern)) {
string <- gsub(pattern[[i]], replacement[[i]], string, perl = perl, fixed = fixed)
}
string
}
str_starts. <- function(string, pattern) {
startsWith(string, pattern)
} |
ctModeltoNumeric <- function(ctmodelobj){
domessage<-FALSE
sapply(names(ctmodelobj), function(x){
if(is.matrix(ctmodelobj[[x]])){
m <- ctmodelobj[[x]]
if(any(suppressWarnings(is.na(as.numeric(m))))){
domessage <<-TRUE
}
m[suppressWarnings(is.na(as.numeric(m)))] <- 0
ctmodelobj[[x]] <<- matrix(as.numeric(m),nrow=nrow(m), ncol=ncol(m))
}
})
if(domessage) message('Some free parameters in matrices set to zero!')
return(ctmodelobj)
}
ctGenerate<-function(ctmodelobj,n.subjects=100,burnin=0,dtmean=1,logdtsd=0,dtmat=NA,
wide=FALSE){
ctmodelobj <- ctModeltoNumeric(ctmodelobj)
m <- ctmodelobj
fullTpoints<-burnin+m$Tpoints
for(si in 1:n.subjects){
if(is.na(dtmat[1])) dtvec<- exp(rnorm(fullTpoints,log(dtmean),logdtsd))
if(!is.na(dtmat[1])) dtvec <- c(rep(1,burnin),dtmat[si,,drop=FALSE])
time=rep(0,fullTpoints)
for(t in 2:fullTpoints) time[t] = round(time[t-1] + dtvec[t-1],6)
if(m$n.TDpred > 0) {
tdpreds <- rbind(matrix(0,nrow=1+(burnin),ncol=m$n.TDpred)[-1,,drop=FALSE],
matrix(m$TDPREDMEANS + m$TDPREDVAR %*% rnorm(nrow(m$TDPREDVAR),0,1),ncol=m$n.TDpred))
}
sm=m
if(any(m$TRAITVAR != 0)) {
traits = m$TRAITVAR %*% rnorm(m$n.latent,0,1)
sm$CINT = m$CINT + traits
sm$T0MEANS = m$T0MEANS + m$T0TRAITEFFECT %*% traits
}
if(any(m$MANIFESTTRAITVAR != 0)) {
sm$MANIFESTMEANS = m$MANIFESTMEANS + m$MANIFESTTRAITVAR %*% rnorm(m$n.manifest,0,1)
}
if(m$n.TIpred > 0) {
tipreds <- m$TIPREDMEANS + m$TIPREDVAR %*% rnorm(m$n.TIpred,0,1)
sm$CINT = m$CINT + m$TIPREDEFFECT %*% tipreds
}
manifests<-matrix(NA,fullTpoints,m$n.manifest)
latents<-matrix(NA,fullTpoints,m$n.latent)
sdat <- cbind(si,time,manifests,
if(m$n.TDpred > 0) tdpreds,
if(m$n.TIpred > 0) matrix(tipreds,byrow=TRUE,nrow=fullTpoints,ncol=m$n.TIpred))
colnames(sdat) <- c('id','time',m$manifestNames,m$TDpredNames,m$TIpredNames)
sdat <- data.frame(sdat)
latents[1,] <- sm$T0MEANS+m$T0VAR %*% rnorm(m$n.latent)
Qinf <- fQinf(sm$DRIFT,sm$DIFFUSION)
for(i in 2:nrow(latents)){
dtA=expm::expm(sm$DRIFT * (sdat$time[i]-sdat$time[i-1]))
latents[i,] <- dtA %*% latents[i-1,] +
solve(sm$DRIFT,(dtA - diag(m$n.latent))) %*% sm$CINT +
t(chol(fdtQ(Qinf,dtA))) %*% rnorm(m$n.latent)
if(m$n.TDpred > 0) latents[i,] <- latents[i,] + sm$TDPREDEFFECT %*%
t(as.matrix(sdat[i,m$TDpredNames,drop=FALSE]))
}
for(i in 1:nrow(sdat)){
sdat[i,m$manifestNames] <- sm$LAMBDA %*% latents[i,] + sm$MANIFESTMEANS +
sm$MANIFESTVAR %*% rnorm(m$n.manifest)
}
sdat=sdat[(burnin+1):fullTpoints,]
sdat[,'time'] = sdat[,'time'] - sdat[1,'time']
if(si==1) datalong <- sdat else datalong <- rbind(datalong,sdat)
}
datalong<-as.matrix(datalong)
if(wide==FALSE) return(datalong) else {
datawide <- ctLongToWide(datalong = datalong,id = 'id',time = 'time',
manifestNames = m$manifestNames, TDpredNames = m$TDpredNames,TIpredNames = m$TIpredNames)
datawide <- ctIntervalise(datawide = datawide,Tpoints = m$Tpoints,n.manifest = m$n.manifest,n.TDpred = m$n.TDpred,n.TIpred = m$n.TIpred,
manifestNames=m$manifestNames,TDpredNames=m$TDpredNames,TIpredNames=m$TIpredNames)
return(datawide)
}
} |
test_propensity_calculation <- function(
comp_reac,
params,
state,
sim_time
) {
test_propensity_cpp(
comp_reac$function_pointers,
params,
comp_reac$buffer_size,
length(comp_reac$reaction_ids),
state,
sim_time
)
} |
install_anndata <- function(method = "auto", conda = "auto") {
reticulate::py_install("anndata>=0.7.5", method = method, conda = conda)
} |
lsm_l_para_sd <- function(landscape, directions = 8) {
landscape <- landscape_as_list(landscape)
result <- lapply(X = landscape,
FUN = lsm_l_para_sd_calc,
directions = directions)
layer <- rep(seq_along(result),
vapply(result, nrow, FUN.VALUE = integer(1)))
result <- do.call(rbind, result)
tibble::add_column(result, layer, .before = TRUE)
}
lsm_l_para_sd_calc <- function(landscape, directions, resolution = NULL){
para_patch <- lsm_p_para_calc(landscape,
directions = directions,
resolution = resolution)
if (all(is.na(para_patch$value))) {
return(tibble::tibble(level = "landscape",
class = as.integer(NA),
id = as.integer(NA),
metric = "para_sd",
value = as.double(NA)))
}
para_sd <- stats::sd(para_patch$value)
return(tibble::tibble(level = "landscape",
class = as.integer(NA),
id = as.integer(NA),
metric = "para_sd",
value = as.double(para_sd)))
} |
createMessage <- function(ID, path = NULL, outputData){
pathResult <- .pathTest(path)
if(pathResult[1] == FALSE){
stop(pathResult[2])
}
if(ID == 0){return("No InputFile In Path")}
CSS_Table <- "style='border: 1px solid black; width: 75%;'"
CSS_Cells <- "text-align:center; color: black; padding: 5px; border: 1px solid black;"
x <- ID
TableRows <- nrow(outputData)
O1 <- ListModels(path = path, SelectMDL = x)
O2 <- knitr::kable(
x = cbind(`Model ID`=x, outputData),
format = "html",
table.attr = CSS_Table)
O3 <- kableExtra::row_spec(kable_input = O2,
row = 0:TableRows,
extra_css = CSS_Cells )
msg <- paste("<h2 style='color:black;'>Model Selected</h2>",
paste0(O1, collapse = ""),"<br>",
"<h2 style='color:black;'>Model Results</h2>",
paste0(O3 , collapse = "")
)
return(msg)
} |
total.dista <- function(x,y,square = FALSE) {
.Call(Rfast_total_dista,t(x),t(y),square)
} |
importSAQN <- function(site = "gla4", year = 2009, pollutant = "all",
meta = FALSE, ratified = FALSE,
to_narrow = FALSE) {
aq_data <- importUKAQ(site = site, year = year, pollutant = pollutant,
meta = meta, ratified = ratified,
to_narrow = to_narrow,
source = "saqn")
return(aq_data)
} |
constellation_as_tibble_list <-
function(ct, include_role_playing = FALSE) {
UseMethod("constellation_as_tibble_list")
}
constellation_as_tibble_list.constellation <-
function(ct, include_role_playing = FALSE) {
tl <- list()
names <- c()
for (d in seq_along(ct$dimension)) {
tl <- c(tl, list(tibble::as_tibble(ct$dimension[[d]])))
names <- c(names, attr(ct$dimension[[d]], "name"))
}
names(tl) <- names
for (s in seq_along(ct$star)) {
tl <-
star_schema_as_tl(ct$star[[s]], tl, names, include_role_playing)
}
tl
} |
partialPlot <- function(x, ...) UseMethod("partialPlot")
partialPlot.default <- function(x, ...)
stop("partial dependence plot not implemented for this class of objects.\n")
partialPlot.RRF <-
function (x, pred.data, x.var, which.class, w, plot=TRUE, add=FALSE,
n.pt = min(length(unique(pred.data[, xname])), 51), rug = TRUE,
xlab=deparse(substitute(x.var)), ylab="",
main=paste("Partial Dependence on", deparse(substitute(x.var))),
...)
{
classRF <- x$type != "regression"
if (is.null(x$forest))
stop("The RRF object must contain the forest.\n")
x.var <- substitute(x.var)
xname <- if (is.character(x.var)) x.var else {
if (is.name(x.var)) deparse(x.var) else {
eval(x.var)
}
}
xv <- pred.data[, xname]
n <- nrow(pred.data)
if (missing(w)) w <- rep(1, n)
if (classRF) {
if (missing(which.class)) {
focus <- 1
}
else {
focus <- charmatch(which.class, colnames(x$votes))
if (is.na(focus))
stop(which.class, "is not one of the class labels.")
}
}
if (is.factor(xv) && !is.ordered(xv)) {
x.pt <- levels(xv)
y.pt <- numeric(length(x.pt))
for (i in seq(along = x.pt)) {
x.data <- pred.data
x.data[, xname] <- factor(rep(x.pt[i], n), levels = x.pt)
if (classRF) {
pr <- predict(x, x.data, type = "prob")
y.pt[i] <- weighted.mean(log(ifelse(pr[, focus] > 0,
pr[, focus], .Machine$double.eps)) -
rowMeans(log(ifelse(pr > 0, pr, .Machine$double.eps))),
w, na.rm=TRUE)
} else y.pt[i] <- weighted.mean(predict(x, x.data), w, na.rm=TRUE)
}
if (add) {
points(1:length(x.pt), y.pt, type="h", lwd=2, ...)
} else {
if (plot) barplot(y.pt, width=rep(1, length(y.pt)), col="blue",
xlab = xlab, ylab = ylab, main=main,
names.arg=x.pt, ...)
}
} else {
if (is.ordered(xv)) xv <- as.numeric(xv)
x.pt <- seq(min(xv), max(xv), length = n.pt)
y.pt <- numeric(length(x.pt))
for (i in seq(along = x.pt)) {
x.data <- pred.data
x.data[, xname] <- rep(x.pt[i], n)
if (classRF) {
pr <- predict(x, x.data, type = "prob")
y.pt[i] <- weighted.mean(log(ifelse(pr[, focus] == 0,
.Machine$double.eps, pr[, focus]))
- rowMeans(log(ifelse(pr == 0, .Machine$double.eps, pr))),
w, na.rm=TRUE)
} else {
y.pt[i] <- weighted.mean(predict(x, x.data), w, na.rm=TRUE)
}
}
if (add) {
lines(x.pt, y.pt, ...)
} else {
if (plot) plot(x.pt, y.pt, type = "l", xlab=xlab, ylab=ylab,
main = main, ...)
}
if (rug && plot) {
if (n.pt > 10) {
rug(quantile(xv, seq(0.1, 0.9, by = 0.1)), side = 1)
} else {
rug(unique(xv, side = 1))
}
}
}
invisible(list(x = x.pt, y = y.pt))
} |
argonRow <- function(..., center = FALSE) {
rowCl <- "row"
if (center) rowCl <- paste0(rowCl, " align-items-center justify-content-center")
htmltools::tags$div(class = rowCl, ..., htmltools::tags$br())
} |
library("NMOF")
library("tinytest")
sets <- function(x) {
ans <- NULL
for (i in 1:length(x)) {
x1 <- utils::combn(x, i)
ans <- c(ans, split(x1, col(x1)))
}
names(ans) <- NULL
ans
}
test_fun <- function(x) {
List1 <- x$c1
Num1 <- x$n1
Num2 <- x$n2
-length(List1) - Num1 - Num2
}
ans <- gridSearch(test_fun,
levels = list(c1 = sets(letters[1:5]),
n1 = 1:5,
n2 = 101:105),
asList = TRUE, keepNames = TRUE)
expect_equal(test_fun(ans$levels[[200]]), ans$values[[200]])
expect_error(ans <- gridSearch(test_fun,
levels = list(c1 = sets(letters[1:5]),
n1 = 1:5,
n2 = 101:105),
asList = FALSE, keepNames = TRUE))
testFun <- function(x)
x[[1L]] + x[[2L]]^2
res <- gridSearch(fun = testFun, levels = list(1:2, c(2, 3, 5)),
asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 2)))
levels <- list(a = 1:2, b = 1:3)
res <- gridSearch(testFun, levels, asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 1)))
lower <- 1; upper <- 3; npar <- 2
res <- gridSearch(testFun, lower = lower, upper = upper, npar = npar,
asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 1)))
lower <- 1; upper <- 3; npar <- 2; n <- 4
res <- gridSearch(testFun, lower = lower, upper = upper, npar = npar, n = n,
asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 1)))
expect_equal(length(res$levels), n^npar)
lower <- 1; upper <- 3; npar <- 5; n <- 5
res <- gridSearch(testFun, lower = lower, upper = upper, npar = npar, n = n,
asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 1)))
expect_equal(length(res$levels), n^npar)
lower <- c(1,1); upper <- c(3,3); n <- 4
res <- gridSearch(testFun, lower = lower, upper = upper, n = n,
asList = TRUE)
expect_equal(res$minfun, testFun(list(1, 1)))
expect_equal(length(res$levels), n^length(lower))
lower <- c(1,1); upper <- 3; n <- 4
res <- gridSearch(testFun, lower = lower, upper = upper, n = n)
expect_equal(res$minfun, testFun(list(1, 1)))
expect_equal(length(res$levels), n^length(lower)) |
f21hyper <-
function (a, b, c, z)
{
if ((length(a) != 1) | (length(b) != 1) | (length(c) != 1) |
(length(z) != 1))
stop("All function arguments need to be scalars")
if ((a < 0) | (b < 0) | (c < 0))
stop("Arguments a, b, and c need to be non-negative")
if ((z > 1) | (z <= (-1)))
stop("Argument z needs to be between -1 and 1")
nmx = max(100, 3 * floor(((a + b) * z - c - 1)/(1 - z)))
if (nmx > 10000)
warning("Power series probably does not converge")
serie = 0:nmx
return(1 + sum(cumprod((a + serie)/(c + serie) * (b + serie)/(1 +
serie) * z)))
} |
par(ask=TRUE)
library(coin)
score <- c(40, 57, 45, 55, 58, 57, 64, 55, 62, 65)
treatment <- factor(c(rep("A",5), rep("B",5)))
mydata <- data.frame(treatment, score)
t.test(score~treatment, data=mydata, var.equal=TRUE)
oneway_test(score~treatment, data=mydata, distribution="exact")
UScrime <- transform(UScrime, So = factor(So))
wilcox_test(Prob ~ So, data=UScrime, distribution="exact")
library(multcomp)
set.seed(1234)
oneway_test(response~trt, data=cholesterol,
distribution=approximate(B=9999))
library(coin)
library(vcd)
Arthritis <- transform(Arthritis,
Improved = as.factor(as.numeric(Improved)))
set.seed(1234)
chisq_test(Treatment~Improved, data=Arthritis,
distribution=approximate(B=9999))
states <- as.data.frame(state.x77)
set.seed(1234)
spearman_test(Illiteracy ~ Murder, data=states,
distribution=approximate(B=9999))
library(coin)
library(MASS)
wilcoxsign_test(U1 ~ U2, data=UScrime, distribution="exact")
library(lmPerm)
set.seed(1234)
fit <- lmp(weight ~ height, data=women, perm="Prob")
summary(fit)
library(lmPerm)
set.seed(1234)
fit <- lmp(weight ~ height + I(height^2), data=women, perm="Prob")
summary(fit)
library(lmPerm)
set.seed(1234)
states <- as.data.frame(state.x77)
fit <- lmp(Murder ~ Population + Illiteracy+Income+Frost,data=states, perm="Prob")
summary(fit)
library(lmPerm)
library(multcomp)
set.seed(1234)
fit <- lmp(response ~ trt, data=cholesterol, perm="Prob")
anova(fit)
library(lmPerm)
set.seed(1234)
fit <- lmp(weight ~ gesttime + dose, data=litter, perm="Prob")
anova(fit)
library(lmPerm)
set.seed(1234)
fit <- lmp(len ~ supp*dose, data=ToothGrowth, perm="Prob")
anova(fit)
rsq <- function(formula, data, indices) {
d <- data[indices,]
fit <- lm(formula, data=d)
return(summary(fit)$r.square)
}
library(boot)
set.seed(1234)
results <- boot(data=mtcars, statistic=rsq,
R=1000, formula=mpg~wt+disp)
print(results)
plot(results)
boot.ci(results, type=c("perc", "bca"))
bs <- function(formula, data, indices) {
d <- data[indices,]
fit <- lm(formula, data=d)
return(coef(fit))
}
library(boot)
set.seed(1234)
results <- boot(data=mtcars, statistic=bs,
R=1000, formula=mpg~wt+disp)
print(results)
plot(results, index=2)
boot.ci(results, type="bca", index=2)
boot.ci(results, type="bca", index=3) |
setClass("ProbitSpatial",
slots= list(beta ="numeric",
rho ="numeric",
lambda ="numeric",
coeff ="numeric",
loglik ="numeric",
formula ="formula",
nobs ="integer",
nvar ="integer",
y ="numeric",
X ="matrix",
time ="numeric",
DGP ="character",
method ="character",
varcov ="character",
W ="Matrix",
M ="ANY",
iW_CL ="numeric",
iW_FL ="numeric",
iW_FG ="numeric",
reltol ="numeric",
prune ="numeric",
env ="environment",
message ="numeric")
)
coef.ProbitSpatial <- function(object,...)
{
return(object@coeff)
}
effects_ProbitSpatial <- function(object)
{
idx1 <- match(c("(Intercept)","Intercept","(intercept)","intercept"),colnames(object@X))
if (any(!is.na(idx1))) {
nvar <- object@nvar-1
X <- object@X[,-idx1[!is.na(idx1)]]
beta <- object@beta[-idx1[!is.na(idx1)]]
} else {
nvar <- object@nvar
X <- object@X
beta <- object@beta
}
if (object@DGP == "SEM"){
ME <- rep(0,nvar)
dfit <- dnorm(fitted(object,type="link"))
for (i in 1:nvar){ME[i] <- mean(beta[i]*dfit)}
ME <- data.frame(ME,row.names=names(beta))
names(ME) <- c("average marginal effetcs")
} else {
ME <- matrix(0,nvar,3)
dfit <- dnorm(fitted(object,type="link"))
D <- Matrix::diag(dfit)
iW <- ApproxiW(object@W,object@rho,object@iW_CL)
P <- D %*% iW
for (i in 1:nvar){
dPdi <- P %*% Matrix::diag(beta[i],object@nobs)
ME[i,3] <- (1-object@rho)^-1*mean(dfit)*beta[i]
ME[i,1] <- mean(Matrix::diag(dPdi))
ME[i,2] <- ME[i,3]-ME[i,1]
}
ME <- data.frame(ME,row.names=names(beta))
names(ME) <- c("direct","indirect","total")
}
return(ME)
}
fitted.ProbitSpatial<-function(object,type=c("link","response","binary"),cut=0.5,...)
{
type <- match.arg(type)
if (object@DGP %in% c("SAR","SARAR")){
iW <- ApproxiW(object@W,object@rho,object@iW_CL)
f <- iW %*% (object@X %*% object@beta)
} else {
f <- (object@X %*% object@beta) }
if (type=="link") {f<-as.numeric(f)}
if (type=="response") {f<-pnorm(as.numeric(f))}
if (type=="binary") {f<-(pnorm(as.numeric(f)) >= cut)*1}
return(f)
}
names.ProbitSpatial <- function(x,...){return(slotNames(x))}
predict.ProbitSpatial <- function(object,X,type=c("link","response","binary"),cut=0.5,oos=FALSE,WSO=NULL,...)
{
if(oos==FALSE){
if (ncol(X) != object@nvar) {stop("number of columns of X does not match
the number of variables of the model")}
if (nrow(X) != object@nobs) {stop("number of observations of X does not
match the one expected by the model.
Consider out-of-sample predictions.")}
type <- match.arg(type)
if (object@DGP == "SAR"){
iW <- ApproxiW(object@W,object@rho,object@iW_CL)
f <- iW %*% (X %*% object@beta)} else { f <- (X %*% object@beta) }
if (type=="link") {f<-as.numeric(f)}
if (type=="response") {f<-pnorm(as.numeric(f))}
if (type=="binary") {f<-(pnorm(as.numeric(f))>=cut)*1}
return(f) } else {
type <- match.arg(type)
if (object@DGP == "SAR"){
n<-dim(WSO)[1]
ns<-object@nobs
no<-n-ns
XSO<-X
Q<-Matrix::crossprod(Matrix::Diagonal(n,1)-object@rho * WSO)
QOO<-Q[(ns+1):n,(ns+1):n]
QOS<-Q[(ns+1):n,1:ns]
iW <- ApproxiW(WSO,object@rho,object@iW_CL)
f <- iW %*% (XSO %*% object@beta)
re<-Matrix::solve(QOO,QOS)%*%(object@y-f[1:ns])
f[(ns+1):n]<-f[(ns+1):n]-re
} else {f <- (X %*% object@beta)}
if (type=="link") {f<-as.numeric(f)}
if (type=="response") {f<-pnorm(as.numeric(f))}
if (type=="binary") {f<-(pnorm(as.numeric(f))>=cut)*1}
return(f)}
}
residuals.ProbitSpatial <- function(object,...)
{ object@y - fitted(object,type="response") }
ProbitSpatialFit<-function(formula,data,W,DGP='SAR',method="conditional",varcov="varcov",M=NULL,control=list()){
con <- list(iW_CL=6,iW_FL=0,iW_FG=0,reltol=1e-05,prune=1e-4,silent=TRUE)
nmsC <- names(con)
con[(namc <- names(control))] <- control
if (length(noNms <- namc[!namc %in% nmsC]))
warning("unknown names in control: ", paste(noNms, collapse = ", "))
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
Y <- model.extract(mf, "response")
Y <- as.numeric(Y>0)
X <- model.matrix(mt, mf)
idx1<-match(c("(Intercept)","Intercept","(intercept)","intercept"),colnames(X))
if (any(!is.na(idx1))) { colnames(X)[idx1[!is.na(idx1)]] <- "(Intercept)"}
myenv <- new.env()
try(rm(myenv),silent =TRUE)
myenv <- new.env()
myenv[["appiWCL"]] <- con$iW_CL
myenv[["appiWFL"]] <- con$iW_FL
myenv[["appiNFG"]] <- con$iW_FG
myenv[["eps"]] <- con$prune
if(is.null(W) | any(abs(Matrix::rowSums(W)-1)>1e-12)) stop('W must be a valid row normalized spatial weight matrix')
if(class(W)=="matrix") W <- Matrix::Matrix(W)
myenv[["WW"]] <- W
myenv[["MM"]] <- M
myenv[["ind"]] <- X
myenv[["de"]] <- Y
myenv[["reltol"]] <- con$reltol
message <- 0
if(varcov=='precision') method_sigma='UP' else method_sigma='UC'
if (DGP=="SAR" ){DGP_1='SAR'}
if (DGP=="SEM" ){DGP_1='SEM'}
if (DGP=="SARAR"){DGP_1='SARAR'}
lik <- get(paste('conditional',DGP_1,method_sigma,sep='_'))
llik <- get(paste('lik',DGP_1,method_sigma,sep='_'))
init_cond <- Sys.time()
out <- suppressWarnings(lik(myenv))
fint_cond <- Sys.time()
tim_cond <- as.numeric(difftime(fint_cond,init_cond,units='secs'))
mycoef_cond <- unlist(out$par)
myenv$l_cond <- out$l
if (DGP_1 == 'SARAR') {second_place=c("rho","lambda")
} else {second_place='rho'}
names(mycoef_cond) <- c(colnames(X),second_place)
retourcond=1
if(method == "full-lik" && DGP %in% c("SAR","SEM"))
{ retourcond=0
if (con$prune==0) method_grad <- "FG" else method_grad <- "AG"
ggrad <- get(paste('grad',DGP,method_sigma,method_grad,sep='_'))
init_FL <- Sys.time()
out = optim(mycoef_cond,llik,ggrad,myenv,method = "BFGS",control = list(reltol = myenv$reltol))
fint_FL <- Sys.time()
tim_FL <- as.numeric(difftime(fint_FL,init_FL,units='secs'))
if(!is.list(out)) {
retourcond=1
cat('Convergence failed with Full Maximum Likelihood: try to increase iW_FL and/or decrease prune (in case of approximate gradients) and/or stick to the results of conditional likelihood estimation')
message=1
} else {
mycoef_FL=unlist(out$par)
names(mycoef_FL) <- c(colnames(X),'rho')
myenv$l_FL=out$value
}
}
if (retourcond==1){mycoef <- mycoef_cond
lhat<-myenv$l_cond} else {
mycoef <- mycoef_FL
lhat <- myenv$l_FL}
k <- ncol(X)
beta <- mycoef[1:k]
rho <- mycoef[k+1]
if (DGP=="SARAR") lambda <- mycoef[k+2]
if (con$silent==FALSE){
iW <- ApproxiW(W,rho,con$iW_CL)
if (DGP %in% c("SAR","SARAR")) {
xstar <- iW %*% X
} else {xstar <- X}
if (DGP %in% c("SAR","SEM")) {
v <- sqrt(Matrix::diag(Matrix::tcrossprod(iW)))
} else {
iM <- ApproxiW(M,lambda,con$iW_CL)
v <- sqrt(Matrix::diag(Matrix::tcrossprod(iW %*% iM)))
}
xb <- as.numeric(xstar %*% beta)/v
p <- pnorm(xb)
p[which(p==1)] <- 0.9999
p[which(p==0)] <- 0.0001
g <- (dnorm(xb)^2)/(p * (1 - p))
gmat <- as.matrix((sqrt(g)/v) * xstar)
vmat1 <- Matrix::solve(Matrix::crossprod(gmat))
semat1 <- sqrt(Matrix::diag(vmat1))
Beta0 <- coef(glm.fit(X, Y,family=binomial(link='probit')))
if (DGP=="SARAR"){
LR_rho<-2*(llik(c(Beta0,0,lambda),myenv)-lhat)
LR_lambda<-2*(llik(c(Beta0,rho,0),myenv)-lhat)
LR <- c(LR_rho,LR_lambda)
} else {
LR <- 2*(llik(c(Beta0,0),myenv)-lhat)}
cat("St. dev. of beta conditional on rho and Lik-ratio of rho", "\n")
if (DGP=="SARAR") {fin_res<-c(beta,rho,lambda)} else {fin_res<-c(beta,rho)}
outmat <- cbind(fin_res, c(semat1,LR*NA), c(beta/semat1,LR),
c(2 * (1 - pnorm(abs(beta)/semat1)),pchisq(LR, 1, lower.tail = FALSE)))
colnames(outmat) <- c("Estimate", "Std. Error", "z-value",
"Pr(>|z|)")
if (DGP_1 == 'SARAR') {
second_place=c("rho","lambda")
} else {second_place='rho'}
rownames(outmat) <- c(colnames(X),second_place)
}
out <- new("ProbitSpatial",
beta = mycoef[1:k],
rho = mycoef[1+k],
lambda = ifelse(DGP=="SARAR",mycoef[2+k],0),
coeff = mycoef,
loglik = ifelse(retourcond==1,myenv$l_cond,myenv$l_FL),
formula = formula,
nobs = ncol(W),
nvar = k,
y = Y,
X = X,
time = ifelse(retourcond==1,tim_cond,tim_FL),
DGP = DGP,
method = method,
varcov = varcov,
W = W,
M = M,
iW_CL = con$iW_CL,
iW_FL = con$iW_FL,
iW_FG = con$iW_FG,
reltol = con$reltol,
prune = con$prune,
env = myenv,
message = message)
return(out)
}
"_PACKAGE"
conditional_SAR_UC <- function(myenv)
{
logl <- function(rho) {
-lik_SAR_UC_conditional(rho,myenv)$l}
rho = optimize(logl, lower = -1, upper = 1, tol= myenv$reltol)
out <- list(lik_SAR_UC_conditional(rho$minimum,myenv)$beta,rho$minimum)
names(out) <- c("beta", "rho")
return(list(par=out,l=rho$objective))}
conditional_SAR_UP <- function(myenv)
{
logl <- function(rho) {
-lik_SAR_UP_conditional(rho,myenv)$l}
rho = optimize(logl, lower = -1, upper = 1, tol= myenv$reltol)
out <- list(lik_SAR_UP_conditional(rho$minimum,myenv)$beta,rho$minimum)
names(out) <- c("beta", "rho")
return(list(par=out,l=rho$objective))}
conditional_SEM_UC <- function(myenv)
{ logl <- function(rho) {
-lik_SEM_UC_conditional(rho,myenv)$l}
rho = optimize(logl, lower = -1, upper = 1, tol= myenv$reltol)
out <- list(lik_SEM_UC_conditional(rho$minimum,myenv)$beta,rho$minimum)
names(out) <- c("beta", "rho")
return(list(par=out,l=rho$objective))}
conditional_SEM_UP <- function(myenv)
{ logl <- function(rho) {
-lik_SEM_UP_conditional(rho,myenv)$l}
rho = optimize(logl, lower = -1, upper = 1, tol= myenv$reltol)
out <- list(lik_SEM_UP_conditional(rho$minimum,myenv)$beta,rho$minimum)
names(out) <- c("beta", "rho")
return(list(par=out,l=rho$objective))}
conditional_SARAR_UC <- function(myenv)
{
logl <- function(par) { -lik_SARAR_UC_conditional(par,myenv)$l}
inipar<-c(0,0)
Ui<-matrix(c(1,0,-1,0,0,1,0,-1),4,2)
bvec <- c(-0.99, -0.99, -0.99,-0.99)
res<-constrOptim(inipar,logl,NULL,ui=Ui,ci=bvec, control=list(reltol=1e-4))
out<-list(par=c(lik_SARAR_UC_conditional(res$par,myenv)$beta,
res$par[1],res$par[2]),res$value)
names(out) <- c("par","l")
return(out)
}
conditional_SARAR_UP <- function(myenv)
{
logl <- function(par) { -lik_SARAR_UP_conditional(par,myenv)$l}
inipar<-c(0,0)
Ui<-matrix(c(1,0,-1,0,0,1,0,-1),4,2)
bvec <- c(-0.99, -0.99, -0.99,-0.99)
res<-constrOptim(inipar,logl,NULL,ui=Ui,ci=bvec, control=list(reltol=1e-4))
out<-list(par=c(lik_SARAR_UP_conditional(res$par,myenv)$beta,
res$par[1],res$par[2]),res$value)
names(out) <- c("par","l")
return(out)
}
generate_W <-function(n,nneigh,seed=123)
{
set.seed(seed)
coord <- cbind(runif(n,0,1),runif(n,0,1))
k=nneigh+1
nb1 <- RANN::nn2(as.matrix(coord), k=k ,treetype = c("bd"))
W <- Matrix::sparseMatrix(i=rep(seq_along(rep(k,n)),rep(k,n)),j=t(nb1$nn.idx),x=1/k)
diag(W) <- 0
if(class(W)=='matrix') W <- Matrix::Matrix(W)
ret <- Matrix::summary(as(W, "dgCMatrix") )
ti <- tapply(ret$x,ret$i,function(x) sum(x,na.rm=TRUE))
ret$x <- as.numeric(ret$x/ti[match(ret$i,as.numeric(names(ti)))])
W <- Matrix::sparseMatrix(i = ret$i, j = ret$j,x= ret$x,dims=dim(W))
Matrix::drop0(W)
W
}
sim_binomial_probit<-function(W,X,beta,rho,model="SAR",M=NULL,lambda=NULL,
sigma2=1,ord_iW=6,seed=123){
set.seed(seed)
k <- length(beta)
n <- dim(W)[1]
iW <- ApproxiW(W, rho, ord_iW)
if (!is.null(M)){ iM <- ApproxiW(M, lambda, ord_iW) }
if (dim(X)[1] != dim(W)[1]) (cat("X and W need to have the same number of rows"))
if (dim(X)[2] != length(beta))(cat("the number of columns of X has to equal to the length of beta"))
e_sim <- rnorm(n,0,sigma2)
if (model=="SAR"){z <- iW%*%(X %*% beta + e_sim)}
if (model=="SEM"){z <- (X %*% beta + iW%*%e_sim)}
if (model=="SARAR"){z <- iW%*%(X %*% beta + iM%*%e_sim)}
Y_sim <- as.double(z >= 0)
return(Y_sim)
}
summary.ProbitSpatial <- function(object,covar=FALSE,...) {
cat("-- Univariate conditional estimation of spatial probit --\n\n")
cat("Sample size = ", object@nobs,"\n")
cat("Number of covariates = ",object@nvar,"\n")
cat("DGP = ", object@DGP,"\n")
cat("estimation method = ", object@method,"\n")
vc<-ifelse(object@varcov=="varcov", "Var-Covar Matrix", "Precision Matrix")
cat("Variance covariance = ", vc,"\n" )
if (object@iW_CL>0) {cat("order of approx. of iW in the conditional step = ", object@iW_CL,"\n")}
if (object@method=="full-lik"){
if (object@iW_FL>0) {cat("order of approximation of iW in the likelihood function = ", object@iW_FL,"\n")}
if (object@iW_FG>0) {cat("order of approximation of iW in the gradient function = ", object@iW_FG,"\n")}
if (object@prune>0) {cat("pruning in the gradient functions = ", object@prune,"\n")}
}
cat("Execution time = ", object@time,"\n\n")
cat("-----------------------------------------------\n\n")
mod_covar <- ifelse(object@varcov=='varcov',"UC","UP")
if (covar == TRUE){
mycoef <- object@coeff
lik <- get(paste('lik',object@DGP,mod_covar, sep='_'))
H <- numDeriv::hessian(lik,x=mycoef,env=object@env)
se <- sqrt(diag(abs(solve(H))))
outmat <- cbind(mycoef, se, mycoef/se, 2 * (1 - pnorm(abs(mycoef)/se)))
colnames(outmat) <- c("Estimate", "Std. Error", "z-value", "Pr(>z)")
rownames(outmat) <- names(mycoef)
cat("Unconditional standard errors with variance-covariance matrix\n\n")
} else { lik<-get(paste('conditional',object@DGP,mod_covar, sep='_'))
llik<-get(paste('lik',object@DGP, mod_covar,sep='_'))
env1 <- object@env
Beta0 <- suppressWarnings(coef(glm.fit(object@X,object@y,intercept=FALSE,family=binomial(link='probit'))))
if (object@DGP=="SARAR"){
LR_rho=-2*(llik(c(Beta0,0,object@lambda),env1)-object@loglik)
LR_lambda=-2*(llik(c(Beta0,object@rho,0),env1)-object@loglik)
LR <- c(LR_rho,LR_lambda)
} else { LR=-2*(llik(c(Beta0,0),env1)-object@loglik) }
LR_beta <- c()
for(i in 1:object@nvar){
XX <- env1$ind
env1$ind <- as.matrix(XX[,-i])
lc=lik(env1)
env1$ind <- as.matrix(XX)
LR_beta <- c(LR_beta,-2*(lc$l-object@loglik))}
LRtheta <- abs(as.numeric(c(LR_beta,LR)))
outmat <- cbind(object@coeff, LRtheta, pchisq(LRtheta, 1, lower.tail = FALSE))
colnames(outmat) <- c("Estimate", "LR test", "Pr(>z)")
if(object@DGP=="SARAR"){rownames(outmat)<-c(colnames(object@X),'rho','lambda')
} else { rownames(outmat) <- c(colnames(object@X),'rho') }
cat("Unconditional standard errors with likelihood-ratio test\n")
}
print(outmat)
cat("\n-----------------------------------------------\n")
f<-fitted(object,type="binary")
y<-object@y
TP <- sum(f==1 & y==1)
TN <- sum(f==0 & y==0)
FP <- sum(f==1 & y==0)
FN <- sum(f==0 & y==1)
conf_matrix<-matrix(c(TP,FN,FP,TN),2,2)
colnames(conf_matrix) <- c("pred 1","pred 0")
rownames(conf_matrix) <- c("true 1","true 0")
cat("Confusion Matrix:\n")
print(conf_matrix)
cat("Accuracy:\t", (TP+TN)/(TP+TN+FP+FN), "\n")
cat("Sensitivity:\t", (TP)/(TP+FN), "\t Specificity:\t",(TN)/(FP+TN),"\n")
cat("Pos Pred Value:\t", (TP)/(TP+FP), "\t Neg Pred Value:",(TN)/(TN+FN),"\n")
}
"Katrina"
setMethod("$",
signature(x = "ProbitSpatial"),
function (x, name)
{
slot(x,name)
}
) |
context("Player Name Lookup")
cols <- c(
"name_first", "name_last", "name_given", "name_suffix",
"name_nick", "birth_year", "mlb_played_first",
"key_mlbam", "key_retro", "key_bbref", "key_fangraphs"
)
test_that("Player Name Lookup", {
skip_on_cran()
x <- playername_lookup("kaaihki01")
expect_equal(colnames(x), cols)
expect_s3_class(x, "data.frame")
}) |
filter_activity_instance <- function(eventlog,
activity_instances,
reverse) {
UseMethod("filter_activity_instance")
}
filter_activity_instance.eventlog <- function(eventlog,
activity_instances = NULL,
reverse = FALSE){
if(!reverse)
filter(eventlog, (!!activity_instance_id_(eventlog)) %in% activity_instances)
else
filter(eventlog, !((!!activity_instance_id_(eventlog)) %in% activity_instances))
}
filter_activity_instance.grouped_eventlog <- function(eventlog,
activity_instances = NULL,
reverse = FALSE) {
grouped_filter(eventlog, filter_activity_instance, cases, reverse)
}
ifilter_activity_instance <- function(eventlog) {
ui <- miniPage(
gadgetTitleBar("Filter Activity Instances"),
miniContentPanel(
fillRow(flex = c(10,1,8),
selectizeInput("selected_cases", label = "Select activity instances:", choices = eventlog %>% pull(!!as.symbol(activity_instance_id(eventlog))) %>%
unique, selected = NA, multiple = T), " ",
radioButtons("reverse", "Reverse filter: ", choices = c("Yes","No"), selected = "No")
)
)
)
server <- function(input, output, session){
observeEvent(input$done, {
filtered_log <- filter_activity_instance(eventlog,
activity_instances = input$selected_cases,
reverse = ifelse(input$reverse == "Yes", T, F))
stopApp(filtered_log)
})
}
runGadget(ui, server, viewer = dialogViewer("Filter Activity instances", height = 400))
} |
promaxQ <- function(R = NULL,
urLoadings = NULL,
facMethod = "fals",
numFactors = NULL,
power = 4,
standardize = "Kaiser",
epsilon = 1e-4,
maxItr = 15000,
faControl = NULL) {
if ( is.null(R) & is.null(urLoadings) ) {
stop("Either the 'R' or 'urLoadings' arguments must be specified.")
}
if ( is.null(urLoadings) & is.null(numFactors) ) {
stop("An unrotated factor matrix is not provided, please specify the number of factors to extract to generate this loadings matrix.")
}
if ( is.null(faControl) ) {
cnFA <- list(treatHeywood = TRUE,
nStart = 10,
maxCommunality = .995,
epsilon = 1e-4,
communality = "SMC",
maxItr = 15000)
faControl <- cnFA
}
if ( is.null(urLoadings) ) {
faOut <- faX(R = R,
numFactors = numFactors,
facMethod = facMethod,
faControl = faControl)
urLoadings <- faOut$loadings[]
}
stnd <- faStandardize(method = standardize,
lambda = urLoadings)
lambda <- stnd$lambda
VarimaxOutput <-
GPArotation::Varimax(L = lambda,
normalize = FALSE,
eps = epsilon,
maxit = maxItr)
convergence <- VarimaxOutput$convergence
VarimaxOutput$loadings[] <- stnd$DvInv %*% VarimaxOutput$loadings[]
VMaxDisc <- min( VarimaxOutput$Table[, 2] )
VMaxLoadings <- Loadings <- VarimaxOutput$loadings[]
signTarget <- sign(Loadings)
ObliqueTarg <- abs(Loadings)^power * signTarget
TMatrix <- solve( t(Loadings) %*% Loadings ) %*% t(Loadings) %*% ObliqueTarg
D2 <- diag( solve( t(TMatrix) %*% TMatrix ) )
Dmat <- diag(sqrt(D2))
rescaledTMatrix <- TMatrix %*% Dmat
PromaxLoadings <- Loadings %*% rescaledTMatrix
Phi <- solve( t(rescaledTMatrix) %*% rescaledTMatrix )
facOrder <- orderFactors(Lambda = PromaxLoadings,
PhiMat = Phi,
salient = .25,
reflect = TRUE)
PromaxLoadings <- facOrder$Lambda
Phi <- facOrder$PhiMat
list(loadings = PromaxLoadings,
vmaxLoadings = VMaxLoadings,
rotMatrix = rescaledTMatrix,
Phi = Phi,
vmaxDiscrepancy = VMaxDisc,
convergence = convergence,
Table = VarimaxOutput$Table,
rotateControl = list(power = power,
standardize = standardize,
epsilon = epsilon,
maxItr = maxItr))
} |
MeasErrorRandom <- function(substitute,
variance) {
if (missing(substitute))
stop("'substitute' in the MeasErrorRandom object is missing")
if (!is.vector(substitute))
stop("'substitute' in the MeasErrorRandom object is not a vector")
if (any(is.na(substitute)) == TRUE)
stop("'substitute' in the MeasErrorRandom object cannot contain missing values")
if (!is.numeric(variance)) {
stop("'variance' in the MeasErrorRandom object is not numeric")
}
out <- list(substitute = substitute,
variance = variance)
input <- c(substitute = as.list(match.call())$substitute)
attr(out, "input") <- input
attr(out, "call") <- match.call()
class(out) <- c("MeasErrorRandom", "list")
out
} |
plotGenomeLabel <- function(chrom, chromstart = NULL, chromend = NULL,
assembly = "hg38", fontsize = 10,
fontcolor = "black", linecolor = "black",
margin = unit(1, "mm"),
scale = "bp", commas = TRUE, sequence = TRUE,
boxWidth = 0.5, axis = "x", at = NULL,
tcl = 0.5, x, y, length,
just = c("left", "top"),
default.units = "inches", params = NULL, ...) {
errorcheck_plotGenomeLabel <- function(scale, ticks, object, axis) {
if (!scale %in% c("bp", "Kb", "Mb")) {
stop("Invalid \'scale\'. Options are \'bp\', \'Kb\', or \'Mb\'.",
call. = FALSE
)
}
if (!is.null(ticks)) {
if (is.null(object$chrom)) {
stop("Cannot add tick marks to a genome label of entire ",
"genome assembly.", call. = FALSE)
}
if (range(ticks)[1] < object$chromstart |
range(ticks)[2] > object$chromend) {
stop("Given tick locations do not fall within ",
"the genomic range.",
call. = FALSE
)
}
}
if (!axis %in% c("x", "y")) {
stop("Invalid \'axis\'. Options are \'x\' or \'y\'.", call. = FALSE)
}
}
genomeLabelInternal <- parseParams(
params = params,
defaultArgs = formals(eval(match.call()[[1]])),
declaredArgs = lapply(match.call()[-1], eval.parent, n = 2),
class = "genomeLabelInternal"
)
additionalParams <- list(...)
if ("space" %in% names(additionalParams)) {
genomeLabelInternal$space <- additionalParams$space
}
genomeLabelInternal$gp <- gpar(
fontsize = genomeLabelInternal$fontsize,
col = genomeLabelInternal$linecolor,
fontcolor = genomeLabelInternal$fontcolor,
lineend = "butt"
)
genomeLabelInternal$gp <- setGP(
gpList = genomeLabelInternal$gp,
params = genomeLabelInternal, ...
)
genomeLabelInternal$just <-
justConversion(genomeLabelInternal$just)
genomeLabel <- structure(list(
chrom = genomeLabelInternal$chrom,
chromstart = genomeLabelInternal$chromstart,
chromend = genomeLabelInternal$chromend,
assembly = genomeLabelInternal$assembly,
x = genomeLabelInternal$x,
y = genomeLabelInternal$y,
width = NULL, height = NULL,
just = genomeLabelInternal$just,
grobs = NULL
), class = "genomeLabel")
if (is.null(genomeLabel$x)) stop("argument \"x\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(genomeLabel$y)) stop("argument \"y\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(genomeLabel$chrom)) stop("argument \"chrom\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(genomeLabelInternal$length)) {
stop("argument \"length\" is missing, ",
"with no default.",
call. = FALSE
)
}
if (base::length(genomeLabel$chrom) == 1) {
if (is.null(genomeLabel$chromstart)) stop("argument \"chromstart\" ",
"is missing, with no ",
"default.", call. = FALSE)
if (is.null(genomeLabel$chromend)) stop("argument \"chromend\" ",
"is missing, with no ",
"default.", call. = FALSE)
} else {
if (is.null(genomeLabelInternal$space)) {
genomeLabelInternal$space <- 0.01
}
}
check_page(error = paste("Cannot plot a genome label without",
"a `plotgardener` page."))
errorcheck_plotGenomeLabel(
scale = genomeLabelInternal$scale,
ticks = genomeLabelInternal$at,
object = genomeLabel,
axis = genomeLabelInternal$axis
)
genomeLabel$assembly <-
parseAssembly(assembly = genomeLabel$assembly)
genomeLabel$x <- misc_defaultUnits(value = genomeLabel$x,
name = "x",
default.units =
genomeLabelInternal$default.units)
genomeLabel$y <- misc_defaultUnits(
value = genomeLabel$y,
name = "y",
default.units = genomeLabelInternal$default.units)
genomeLabelInternal$length <- misc_defaultUnits(
value = genomeLabelInternal$length,
name = "length",
default.units = genomeLabelInternal$default.units)
genomeLabelInternal$margin <- misc_defaultUnits(
value = genomeLabelInternal$margin,
name = "margin",
default.units = genomeLabelInternal$default.units)
genomeLabelInternal$margin <-
convertHeight(genomeLabelInternal$margin,
unitTo = get("page_units", envir = pgEnv)
)
genomeLabelInternal$tgH <- convertHeight(heightDetails(textGrob(
label = genomeLabelInternal$scale,
x = 0.5, y = 0.5,
default.units = "npc",
gp = genomeLabelInternal$gp
)),
unitTo = get("page_units", envir = pgEnv)
)
if (!is.null(genomeLabelInternal$at)) {
genomeLabelInternal$tick_height <-
genomeLabelInternal$tgH * (genomeLabelInternal$tcl)
genomeLabelInternal$depth <-
convertHeight(genomeLabelInternal$tgH +
genomeLabelInternal$tick_height +
0.5 * genomeLabelInternal$tgH +
genomeLabelInternal$margin,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
} else {
genomeLabelInternal$tick_height <- NULL
genomeLabelInternal$depth <-
convertHeight(genomeLabelInternal$tgH +
genomeLabelInternal$margin,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
}
if (base::length(genomeLabel$chrom) == 1){
vp_name <- plotChromGenomeLabel(genomeLabel = genomeLabel,
genomeLabelInternal = genomeLabelInternal,
...)
} else {
vp_name <- plotManhattanGenomeLabel(genomeLabel = genomeLabel,
genomeLabelInternal = genomeLabelInternal)
}
genomeLabel$grobs <- get("genomeLabel_grobs", envir = pgEnv)
grid.draw(genomeLabel$grobs)
genomeLabel$width <- genomeLabelInternal$length
genomeLabel$height <- genomeLabelInternal$depth
if (genomeLabelInternal$axis == "y") {
genomeLabel$width <- genomeLabelInternal$depth
genomeLabel$height <- genomeLabelInternal$length
}
message("genomeLabel[", vp_name, "]")
invisible(genomeLabel)
}
plotChromGenomeLabel <- function(genomeLabel,
genomeLabelInternal, ...){
comma_labels <- function(object, commas, fact, ...) {
digits <- list(...)$digits
if (is.null(digits)){
if (fact == 1){
digits <- rep(0, 2)
} else {
digits <- rep(1, 2)
}
}
if (length(digits) == 1){
digits <- rep(digits, 2)
}
roundedStart <- round(object$chromstart / fact, digits[1])
if ((roundedStart * fact) != object$chromstart) {
roundedStart <- paste0("~", roundedStart)
warning("Start label is rounded.", call. = FALSE)
}
roundedEnd <- round(object$chromend / fact, digits[2])
if ((roundedEnd * fact) != object$chromend) {
roundedEnd <- paste0("~", roundedEnd)
warning("End label is rounded.", call. = FALSE)
}
if (commas == TRUE) {
chromstartlabel <- formatC(roundedStart,
format = "f",
big.mark = ",", digits = digits[1]
)
chromendlabel <- formatC(roundedEnd,
format = "f",
big.mark = ",", digits = digits[2]
)
} else {
chromstartlabel <- roundedStart
chromendlabel <- roundedEnd
}
return(list(chromstartlabel, chromendlabel))
}
chrom_viewport <- function(object, length, depth, seqType,
vp_name, seqHeight, just, axis){
convertedPageCoords <- convert_page(object = structure(list(
width = length,
height = unit(
depth,
get("page_units", envir = pgEnv)
),
x = object$x,
y = object$y
),
class = "genomeLabelInternal"
))
convertedPageCoords$length <- convertedPageCoords$width
convertedPageCoords$depth <- convertedPageCoords$height
convertedViewport <- viewport(
width = convertedPageCoords$length,
height = convertedPageCoords$depth,
x = convertedPageCoords$x,
y = convertedPageCoords$y, just = just
)
if (!is.null(seqType)) {
topLeftViewport <- vp_topLeft(viewport = convertedViewport)
seq_height <- unit(seqHeight, get("page_units", envir = pgEnv))
vp1 <- viewport(
width = convertedPageCoords$width,
height = unit(depth, get("page_units", envir = pgEnv)),
x = topLeftViewport[[1]],
y = topLeftViewport[[2]] - seq_height,
just = c("left", "top"),
name = paste0(vp_name, "_01"),
xscale = c(object$chromstart, object$chromend),
yscale = c(0, depth)
)
vp2 <- viewport(
width = convertedPageCoords$width,
height = seq_height,
x = topLeftViewport[[1]],
y = topLeftViewport[[2]],
just = c("left", "top"),
name = paste0(vp_name, "_02"),
clip = "on",
xscale = c(object$chromstart, object$chromend)
)
vp <- vpList(vp1, vp2)
} else {
if (axis == "y") {
convertedViewport <- viewport(
width = convertedPageCoords$depth,
height = convertedPageCoords$length,
x = convertedPageCoords$x,
y = convertedPageCoords$y,
just = just
)
bottomRightViewport <-
vp_bottomRight(viewport = convertedViewport)
vp <- viewport(
width = convertedPageCoords$length,
height = convertedPageCoords$depth,
x = bottomRightViewport[[1]] -
convertedPageCoords$depth,
y = bottomRightViewport[[2]],
just = c("left", "top"),
name = vp_name,
xscale = c(object$chromstart, object$chromend),
yscale = c(0, depth),
angle = 90
)
} else {
vp <- viewport(
width = convertedPageCoords$width,
height = convertedPageCoords$height,
x = convertedPageCoords$x,
y = convertedPageCoords$y,
just = just,
name = vp_name,
xscale = c(object$chromstart, object$chromend),
yscale = c(0, depth)
)
}
}
return(vp)
}
chrom_grobs <- function(ticks, seqType, scale, chromLabel,
startLabel, endLabel, object, vp,
yaxis) {
margin <- convertHeight(object$margin,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
height <- convertHeight(object$depth,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
if (!is.null(seqType)) {
assign("genomeLabel_grobs", gTree(), envir = pgEnv)
chrom_vp <- vp[[1]]
if (!is.null(ticks)) {
tgH <- convertHeight(object$tgH,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
tick_height <- convertHeight(object$tick_height,
unitTo = get("page_units",
envir = pgEnv),
valueOnly = TRUE
)
x_coords <- ticks
y0_coord <- height
y1_coords <- rep(height - tick_height, length(ticks))
yLabel <- unit(height - (tick_height + margin), "native")
tickGrobs <- segmentsGrob(
x0 = x_coords,
y0 = rep(y0_coord, length(ticks)),
x1 = x_coords,
y1 = y1_coords,
vp = chrom_vp,
gp = object$gp,
default.units = "native"
)
line <- segmentsGrob(
x0 = unit(0, "npc"),
x1 = unit(1, "npc"),
y0 = y0_coord,
y1 = y0_coord,
vp = chrom_vp,
gp = object$gp,
default.units = "native"
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale),
x = unit(0, "npc"), y = yLabel,
just = c("left", "top"),
vp = chrom_vp,
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale),
x = unit(1, "npc"), y = yLabel,
just = c("right", "top"),
vp = chrom_vp,
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel,
x = unit(0.5, "npc"), y = yLabel,
vp = chrom_vp,
gp = object$gp, just = c("center", "top")
)
assign("genomeLabel_grobs",
setChildren(get("genomeLabel_grobs", envir = pgEnv),
children = gList(
line, chromLab, startLab,
endLab, tickGrobs
)
),
envir = pgEnv
)
} else {
yLabel <- unit(height - margin, "native")
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = height, y1 = height,
vp = chrom_vp,
gp = object$gp, default.units = "native"
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale, sep = " "),
x = unit(0, "npc"), y = yLabel,
vp = chrom_vp,
just = c("left", "top"),
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale, sep = " "),
x = unit(1, "npc"), y = yLabel,
vp = chrom_vp,
just = c("right", "top"),
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel, x = unit(0.5, "npc"),
y = yLabel,
vp = chrom_vp,
gp = object$gp,
just = c("center", "top")
)
assign("genomeLabel_grobs",
setChildren(get("genomeLabel_grobs", envir = pgEnv),
children = gList(
line, chromLab,
startLab, endLab
)
),
envir = pgEnv
)
}
} else {
assign("genomeLabel_grobs", gTree(vp = vp), envir = pgEnv)
if (!is.null(ticks)) {
tgH <- convertHeight(object$tgH,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
tick_height <- convertHeight(object$tick_height,
unitTo = get("page_units",
envir = pgEnv),
valueOnly = TRUE
)
x_coords <- ticks
if (yaxis == TRUE) {
y0_coord <- 0
y1_coords <- rep(tick_height, length(ticks))
yLabel <- unit(tick_height + margin, "native")
tickGrobs <- segmentsGrob(
x0 = x_coords,
y0 = rep(y0_coord, length(ticks)),
x1 = x_coords, y1 = y1_coords,
gp = object$gp, default.units = "native"
)
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = y0_coord, y1 = y0_coord,
gp = object$gp, default.units = "native"
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale),
x = unit(0, "npc"), y = yLabel,
just = c("left", "bottom"),
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale),
x = unit(1, "npc"), y = yLabel,
just = c("right", "bottom"),
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel,
x = unit(0.5, "npc"), y = yLabel,
gp = object$gp, just = c("center", "bottom")
)
} else {
y0_coord <- height
y1_coords <- rep(height - tick_height, length(ticks))
yLabel <- unit(height - (tick_height + margin), "native")
tickGrobs <- segmentsGrob(
x0 = x_coords,
y0 = rep(y0_coord, length(ticks)),
x1 = x_coords, y1 = y1_coords,
gp = object$gp, default.units = "native"
)
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = y0_coord, y1 = y0_coord,
gp = object$gp, default.units = "native"
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale),
x = unit(0, "npc"),
y = unit(tgH + 0.25 * tgH, "native"),
just = c("left", "top"),
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale),
x = unit(1, "npc"),
y = unit(tgH + 0.25 * tgH, "native"),
just = c("right", "top"),
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel, x = unit(0.5, "npc"),
y = unit(tgH + 0.25 * tgH, "native"),
gp = object$gp, just = c("center", "top")
)
}
assign("genomeLabel_grobs",
setChildren(get("genomeLabel_grobs", envir = pgEnv),
children = gList(
line, chromLab, startLab,
endLab, tickGrobs
)
),
envir = pgEnv
)
} else {
if (yaxis == TRUE) {
yLabel <- unit(margin, "native")
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = unit(0, "npc"), y1 = unit(0, "npc"),
gp = object$gp
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale, sep = " "),
x = unit(0, "npc"), y = yLabel,
just = c("left", "bottom"),
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale, sep = " "),
x = unit(1, "npc"), y = yLabel,
just = c("right", "bottom"),
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel, x = unit(0.5, "npc"),
y = yLabel,
gp = object$gp,
just = c("center", "bottom")
)
} else {
yLabel <- unit(height - margin, "native")
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = height, y1 = height,
gp = object$gp, default.units = "native"
)
object$gp$col <- object$gp$fontcolor
startLab <- textGrob(
label = paste(startLabel, scale, sep = " "),
x = unit(0, "npc"), y = yLabel,
just = c("left", "top"),
gp = object$gp
)
endLab <- textGrob(
label = paste(endLabel, scale, sep = " "),
x = unit(1, "npc"), y = yLabel,
just = c("right", "top"),
gp = object$gp
)
object$gp$fontface <- "bold"
chromLab <- textGrob(
label = chromLabel, x = unit(0.5, "npc"),
y = yLabel,
gp = object$gp,
just = c("center", "top")
)
}
assign("genomeLabel_grobs",
setChildren(get("genomeLabel_grobs", envir = pgEnv),
children = gList(
line, chromLab,
startLab, endLab
)
),
envir = pgEnv
)
}
}
}
seq_grobs <- function(object, seqHeight, seqType, assembly, chromLabel, vp,
boxWidth, gparParams) {
bsgenome <- eval(parse(text = paste0(as.name(object$assembly$BSgenome),
"::",
as.name(object$assembly$BSgenome))))
sequence <- strsplit(as.character(BSgenome::getSeq(
bsgenome,
GenomicRanges::GRanges(
seqnames = chromLabel,
ranges = IRanges::IRanges(
start = object$chromstart,
end = object$chromend
)
)
)),
split = ""
)
dfSequence <- data.frame(
"nucleotide" = unlist(sequence),
"pos" = seq(object$chromstart, object$chromend),
"col" = "grey"
)
invisible(tryCatch(dfSequence[which(
dfSequence$nucleotide == "A"
), ]$col <- "
error = function(e) {}
))
invisible(tryCatch(dfSequence[which(
dfSequence$nucleotide == "T"
), ]$col <- "
error = function(e) {}
))
invisible(tryCatch(dfSequence[which(
dfSequence$nucleotide == "G"
), ]$col <- "
error = function(e) {}
))
invisible(tryCatch(dfSequence[which(
dfSequence$nucleotide == "C"
), ]$col <- "
error = function(e) {}
))
seq_vp <- vp[[2]]
if (seqType == "letters") {
seqGrobs <- textGrob(
label = dfSequence$nucleotide, x = dfSequence$pos,
y = unit(0.5, "npc"), just = "center",
vp = seq_vp,
default.units = "native",
gp = gpar(
col = dfSequence$col,
fontsize = gparParams$gp$fontsize - 2
)
)
} else if (seqType == "boxes") {
seqGrobs <- rectGrob(
x = dfSequence$pos, y = unit(1, "npc"),
width = boxWidth,
height = unit(
seqHeight - 0.05 * seqHeight,
get("page_units", envir = pgEnv)
),
just = c("center", "top"),
vp = seq_vp,
default.units = "native",
gp = gpar(col = NA, fill = dfSequence$col)
)
}
assign("genomeLabel_grobs",
addGrob(
gTree = get("genomeLabel_grobs", envir = pgEnv),
child = seqGrobs
),
envir = pgEnv
)
}
if (genomeLabelInternal$scale == "bp") {
fact <- 1
}
if (genomeLabelInternal$scale == "Mb") {
fact <- 1000000
}
if (genomeLabelInternal$scale == "Kb") {
fact <- 1000
}
commaLabels <- comma_labels(
object = genomeLabel,
commas = genomeLabelInternal$commas,
fact = fact, ...
)
chromstartlabel <- commaLabels[[1]]
chromendlabel <- commaLabels[[2]]
seq_height <- heightDetails(textGrob(
label = "A",
x = 0.5, y = 0.5,
default.units = "npc",
gp = gpar(fontsize = genomeLabelInternal$gp$fontsize - 2)
))
seq_height <- convertHeight(seq_height + 0.05 * seq_height,
unitTo = get("page_units", envir = pgEnv)
)
seqType <- NULL
if (genomeLabelInternal$sequence == TRUE) {
if (genomeLabelInternal$axis == "x") {
labelWidth <- convertWidth(genomeLabelInternal$length,
unitTo = "inches",
valueOnly = TRUE
)
bpWidth <- convertWidth(widthDetails(textGrob(
label = "A",
x = 0.5, y = 0.5,
default.units = "npc",
gp = gpar(fontsize = genomeLabelInternal$gp$fontsize - 2)
)),
unitTo = "inches",
valueOnly = TRUE
)
seqRange <- genomeLabel$chromend - genomeLabel$chromstart
seqWidth <- bpWidth * seqRange
if (seqWidth <= labelWidth) {
seqType <- "letters"
} else if (seqWidth / labelWidth <= 9) {
seqType <- "boxes"
}
}
}
if (!is.null(seqType)) {
if (!is.null(genomeLabel$assembly$BSgenome)) {
if (!requireNamespace(genomeLabel$assembly$BSgenome,
quietly = TRUE)){
bsChecks <- FALSE
warning("`", genomeLabel$assembly$BSgenome,
"` not available. ",
"Sequence information will not be displayed.",
call. = FALSE)
} else {
bsChecks <- TRUE
}
if (bsChecks == FALSE) {
seqType <- NULL
}
} else {
warning("No `BSgenome` package found for the input assembly. ",
"Sequence information cannot be displayed.", call. = FALSE)
seqType <- NULL
}
}
if (!is.null(seqType)) {
seq_height <- convertHeight(seq_height,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
genomeLabelInternal$depth <- unit(
genomeLabelInternal$depth + seq_height,
get("page_units", envir = pgEnv)
)
} else {
genomeLabelInternal$depth <- unit(
genomeLabelInternal$depth,
get("page_units", envir = pgEnv)
)
}
currentViewports <- current_viewports()
vp_name <- paste0(
"genomeLabel",
base::length(grep(
pattern = "genomeLabel",
x = currentViewports
)) + 1
)
vp <- chrom_viewport(
object = genomeLabel,
length = genomeLabelInternal$length,
depth = genomeLabelInternal$depth,
seqType = seqType,
seqHeight = seq_height,
vp_name = vp_name, just = genomeLabel$just,
axis = genomeLabelInternal$axis
)
chrom_grobs(
ticks = genomeLabelInternal$at,
seqType = seqType,
scale = genomeLabelInternal$scale,
chromLabel = genomeLabel$chrom,
startLabel = chromstartlabel, endLabel = chromendlabel,
object = genomeLabelInternal, vp = vp,
yaxis = (genomeLabelInternal$axis == "y")
)
if (!is.null(seqType)) {
seq_grobs(
object = genomeLabel, seqHeight = seq_height,
seqType = seqType, assembly = genomeLabel$assembly,
chromLabel = genomeLabel$chrom, vp = vp,
boxWidth = genomeLabelInternal$boxWidth,
gparParams = genomeLabelInternal
)
}
return(vp_name)
}
plotManhattanGenomeLabel <- function(genomeLabel, genomeLabelInternal){
manhattan_viewport <- function(object, length, depth,
vp_name, just, axis, space){
convertedPageCoords <- convert_page(object = structure(list(
width = length,
height = unit(
depth,
get("page_units", envir = pgEnv)
),
x = object$x,
y = object$y
),
class = "genomeLabelInternal"
))
convertedPageCoords$length <- convertedPageCoords$width
convertedPageCoords$depth <- convertedPageCoords$height
convertedViewport <- viewport(
width = convertedPageCoords$length,
height = convertedPageCoords$depth,
x = convertedPageCoords$x,
y = convertedPageCoords$y, just = just
)
if (is(object$assembly$TxDb, "TxDb")) {
txdbChecks <- TRUE
} else {
if (!requireNamespace(object$assembly$TxDb, quietly = TRUE)){
txdbChecks <- FALSE
warning("`", object$assembly$TxDb, "` not available. Please ",
"install to label genome.", call. = FALSE)
} else {
txdbChecks <- TRUE
}
}
if (txdbChecks == TRUE) {
if (is(object$assembly$TxDb, "TxDb")) {
tx_db <- object$assembly$TxDb
} else {
tx_db <- eval(parse(text = paste0(as.name(object$assembly$TxDb),
"::",
as.name(object$assembly$TxDb))))
}
assembly_data <- as.data.frame(setDT(as.data.frame(
GenomeInfoDb::seqlengths(tx_db)
),
keep.rownames = TRUE
))
colnames(assembly_data) <- c("chrom", "length")
assembly_data <- assembly_data[which(assembly_data[, "chrom"] %in%
object$chrom), ]
offsetAssembly <- spaceChroms(
assemblyData = assembly_data,
space = space
)
cumsums <- cumsum(as.numeric(assembly_data[, "length"]))
spacer <- cumsums[length(cumsum(
as.numeric(assembly_data[, "length"])
))] * space
xscale <- c(0, max(offsetAssembly[, "end"]) + spacer)
} else {
xscale <- c(0, 1)
}
if (axis == "y") {
convertedViewport <- viewport(
width = convertedPageCoords$depth,
height = convertedPageCoords$length,
x = convertedPageCoords$x,
y = convertedPageCoords$y, just = just
)
bottomRightViewport <-
vp_bottomRight(viewport = convertedViewport)
vp <- viewport(
width = convertedPageCoords$length,
height = convertedPageCoords$depth,
x = bottomRightViewport[[1]] - convertedPageCoords$depth,
y = bottomRightViewport[[2]],
just = c("left", "top"),
name = vp_name,
xscale = c(object$chromstart, object$chromend),
yscale = c(0, depth),
angle = 90
)
} else {
vp <- viewport(
width = convertedPageCoords$width,
height = convertedPageCoords$height,
x = convertedPageCoords$x,
y = convertedPageCoords$y,
just = just,
name = vp_name,
xscale = xscale,
yscale = c(0, depth)
)
}
return(vp)
}
genome_grobs <- function(object, vp, gp, space) {
assign("genomeLabel_grobs", gTree(vp = vp), envir = pgEnv)
if (is(object$assembly$TxDb, "TxDb")) {
txdbChecks <- TRUE
} else {
if (!requireNamespace(object$assembly$TxDb, quietly = TRUE)){
txdbChecks <- FALSE
} else {
txdbChecks <- TRUE
}
}
if (txdbChecks == TRUE) {
if (is(object$assembly$TxDb, "TxDb")) {
tx_db <- object$assembly$TxDb
} else {
tx_db <- eval(parse(text =
paste0(as.name(object$assembly$TxDb),
"::",
as.name(object$assembly$TxDb))))
}
assembly_data <- as.data.frame(setDT(as.data.frame(
GenomeInfoDb::seqlengths(tx_db)
),
keep.rownames = TRUE
))
colnames(assembly_data) <- c("chrom", "length")
assembly_data <- assembly_data[which(assembly_data[, "chrom"] %in%
object$chrom), ]
offsetAssembly <- spaceChroms(
assemblyData = assembly_data,
space = space
)
chromCenters <- (offsetAssembly[, "start"] +
offsetAssembly[, "end"]) / 2
margin <- convertHeight(object$margin,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
line <- segmentsGrob(
x0 = unit(0, "npc"), x1 = unit(1, "npc"),
y0 = unit(1, "npc"), y1 = unit(1, "npc"), gp = gp
)
gp$col <- gp$fontcolor
labels <- textGrob(
label = gsub("chr", "", offsetAssembly[, 1]),
x = chromCenters,
y = unit(1, "npc") - unit(margin, "native"),
just = c("center", "top"),
gp = gp,
default.units = "native"
)
assign("genomeLabel_grobs",
setChildren(get("genomeLabel_grobs", envir = pgEnv),
children = gList(line, labels)
),
envir = pgEnv
)
}
}
currentViewports <- current_viewports()
vp_name <- paste0(
"genomeLabel",
base::length(grep(
pattern = "genomeLabel",
x = currentViewports
)) + 1
)
vp <- manhattan_viewport(
object = genomeLabel,
length = genomeLabelInternal$length,
depth = genomeLabelInternal$depth,
vp_name = vp_name, just = genomeLabel$just,
axis = genomeLabelInternal$axis,
space = genomeLabelInternal$space
)
genome_grobs(
object = genomeLabelInternal, vp = vp,
gp = genomeLabelInternal$gp,
space = genomeLabelInternal$space
)
return(vp_name)
} |
pscoast <- function(cmd, file=getOption("gmt.file"))
{
if(is.null(file))
stop("please pass a valid 'file' argument, or run gmt(file=\"myfile\")")
owd <- setwd(dirname(file)); on.exit(setwd(owd))
gmt.system(paste("gmt pscoast",cmd), file=file)
invisible(NULL)
} |
iterationPlot <- function(model.fit){
UseMethod("iterationPlot")
}
iterationPlot.list <- function(model.fit) {
history <- model.fit$item.log
nitems <- model.fit$nitems
ncat <- model.fit$ncat
nless <- model.fit$nless
ItemNames <- model.fit$ItemNames
Maxnphi <- model.fit$Maxnphi
PhiNames <- model.fit$PhiNames
model.type <- model.fit$model.type
phi.log <- model.fit$phi.log
ok.models <- c("nominal", "gpcm")
"%notin%"<- Negate("%in%")
if (model.type %notin% ok.models) {
stop("Iteration plot only applies to nominal and gpcm models")
}
oldpar <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(oldpar))
graphics::par(mfrow=c(1,2))
get.names <- as.data.frame(history[[1]])
lambda.names <- names(get.names[3:(2+nless)])
if (model.type=="nominal") {
nu.names <- names(get.names[(2+ncat):(ncat+ncat)])
} else {
nu.names <- names(get.names[(1+ncat)])
}
histry <- get.names[, lambda.names]
lam.min<- min(histry)
lam.max <- max(histry)
histry <- get.names[, nu.names]
nu.min<- min(histry)
nu.max <- max(histry)
for (item in 2:nitems) {
histry <- as.data.frame(history[[item]] )
histry <- histry[2:nrow(histry),]
lmin <- min(histry[ , lambda.names])
if (lmin < lam.min){ lam.min <- lmin }
lmax <- max(as.matrix(histry[ , lambda.names]))
if (lmax > lam.max){ lam.max <- lmax}
nmin <- min(as.matrix(histry[ , nu.names]))
if (nmin < nu.min) { nu.min <- nmin }
nmax <- max(as.matrix(histry[ , nu.names]))
if (nmax > nu.max){ nu.max <- nmax }
}
for (item in 1:nitems) {
histry <- as.data.frame(history[[item]] )
histry <- histry[2:nrow(histry),]
iter <- seq(1:nrow(histry))
plot(iter, histry[,1] , type='n',
main= paste("Lambda: ","item= ", ItemNames[item]),
ylab= "Estimated Lambda",
xlab= "Iteration",
ylim=c(lam.min,lam.max),
)
for (j in 1:nless) {
graphics::lines(iter, histry[ , lambda.names[j]], lty=j, lwd=2, col=j)
}
if (model.type == "nominal") {
plot(iter, histry[,1] , type='n',
main= paste("Nu: ","item= ", ItemNames[item]),
ylab= "Estimated Nu",
xlab= "Iteration",
ylim=c(nu.min, nu.max)
)
for (j in 1:nless) {
graphics::lines(iter, histry[ , nu.names[j]], lty=j, lwd=2, col=j)
}
} else {
plot(iter, histry[ , nu.names[1]], type='l', lty=1, lwd=2, col=1,
main= paste("a: ","item= ", ItemNames[item]),
ylab= "Estimated Nu",
xlab= "Iteration",
ylim=c(nu.min, nu.max)
)
}
}
if (Maxnphi > 1) {
phi.log <- as.data.frame(phi.log)
iter <- 1:nrow(phi.log)
for (p in 1:Maxnphi) {
plot(iter[2:length(iter)], phi.log[2:length(iter) , PhiNames[p]] ,
type="l", lwd=2,
main= PhiNames[p],
ylim=c(0,1),
xlab="Iteration",
ylab=expression(paste("Estimated ", phi)))
}
}
} |
library(sf)
library(spData)
u = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson"
earthquakes = read_sf(u)
print(paste0(nrow(earthquakes), " significant earthquakes happened last month"))
plot(st_geometry(world), border = "grey")
plot(st_geometry(earthquakes), cex = earthquakes$mag, add = TRUE)
title(paste0(
"Location of significant (mag > 5) Earthquakes in the month to ",
Sys.Date(),
"\n(circle diameter is proportional to magnitude)"
)) |
.longtoint <- function(k){
limit = 2000000000
k1 = as.integer(k/limit)
k2 = k - k1*limit
return(c(k1, k2))
}
depth.simplicialVolume <- function(x, data, exact = F, k = 0.05, mah.estimate = "moment", mah.parMcd = 0.75, seed = 0){
if (seed!=0) set.seed(seed)
if (!is.matrix(x)
&& is.vector(x)){
x <- matrix(x, nrow=1)
}
if (!(is.matrix(data) && is.numeric(data)
|| is.data.frame(data) && prod(sapply(data, is.numeric)))
|| ncol(data) < 2){
stop("Argument \"data\" should be a numeric matrix of at least 2-dimensional data")
}
if (!is.numeric(x)){
stop("Argument \"x\" should be numeric")
}
if (ncol(x) != ncol(data)){
stop("Dimensions of the arguments \"x\" and \"data\" should coincide")
}
if (ncol(data) + 1 > nrow(data)){
stop("To few data points")
}
if (!exact) if (k <= 0) stop("k must be positive")
else if (k < 1) k = choose(nrow(data), ncol(data))*k
if(toupper(mah.estimate) == "NONE"){
useCov <- 0
covEst <- diag(ncol(data))
} else if(toupper(mah.estimate) == "MOMENT"){
useCov <- 1
covEst <- cov(data)
} else if(toupper(mah.estimate) == "MCD"){
useCov <- 2
covEst <- covMcd(data, mah.parMcd)$cov
} else {stop("Wrong argument \"mah.estimate\", should be one of \"moment\", \"MCD\", \"none\"")}
points <- as.vector(t(data))
objects <- as.vector(t(x))
ds <- .C("OjaDepth",
as.double(points),
as.double(objects),
as.integer(nrow(data)),
as.integer(nrow(x)),
as.integer(ncol(data)),
as.integer(seed),
as.integer(exact),
as.integer(.longtoint(k)),
as.integer(useCov),
as.double(as.vector(t(covEst))),
depths=double(nrow(x)))$depths
return (ds)
}
depth.space.simplicialVolume <- function(data, cardinalities, exact = F, k = 0.05, mah.estimate = "moment", mah.parMcd = 0.75, seed = 0){
if (!(is.matrix(data) && is.numeric(data)
|| is.data.frame(data) && prod(sapply(data, is.numeric)))
|| ncol(data) < 2){
stop("Argument \"data\" should be a numeric matrix of at least 2-dimensional data")
}
if (!is.vector(cardinalities, mode = "numeric")
|| is.na(min(cardinalities))
|| sum(.is.wholenumber(cardinalities)) != length(cardinalities)
|| min(cardinalities) <= 0
|| sum(cardinalities) != nrow(data)){
stop("Argument \"cardinalities\" should be a vector of cardinalities of the classes in \"data\" ")
}
if (sum(cardinalities < ncol(data) + 1) != 0){
stop("Not in all classes sufficiently enough objetcs")
}
if (toupper(mah.estimate) == "NONE"){
useCov <- 0
} else if (toupper(mah.estimate) == "MOMENT"){
useCov <- 1
} else if (toupper(mah.estimate) == "MCD"){
useCov <- 2
} else {stop("Wrong argument \"mah.estimate\", should be one of \"moment\", \"MCD\", \"none\"")}
depth.space <- NULL
for (i in 1:length(cardinalities)){
pattern <- data[(1 + sum(cardinalities[0:(i - 1)])):sum(cardinalities[1:i]),]
pattern.depths <- depth.simplicialVolume(data, pattern, exact, k, mah.estimate, mah.parMcd, seed)
depth.space <- cbind(depth.space, pattern.depths, deparse.level = 0)
}
return (depth.space)
} |
RCplot <-
function(x, r2 = residuals(x, "deviance")^2,
alphabet = x$alpha, lab.horiz = k <= 20, do.call = TRUE,
cex.axis = if(k <= 20) 1 else if(k <= 40) 0.8 else 0.6,
y.fact = if(.Device == "postscript") 1.2 else 0.75,
col = "gray70", xlab = "Context", main = NULL,
med.pars = list(col = "red", pch = 12, cex= 1.25 * cex.axis),
ylim = range(0, r2, finite=TRUE), ...)
{
namx <- deparse(substitute(x))
if(!is.vlmc(x)) stop("'x' must be a fitted VLMC object")
fID <- id2ctxt(predict(x, type="id"), alpha = alphabet)
ok <- fID != "NA"
fID <- as.factor(fID[ok])
r2 <- r2[ok]
tfID <- table(fID)
k <- length(tfID)
if(is.null(main))
main <- paste(if(!do.call)"VLMC", "Residuals vs. Context")
labs <- c("
if(!lab.horiz && missing(ylim)) {
op <- par(xaxs = "i"); plot.new(); plot.window(xlim=ylim, ylim=0:1)
y0 <- y.fact * max(strwidth(labs, cex=cex.axis))
ylim[1] <- min(ylim[1], - 1.4 * y0)
par(op)
}
op <- par(cex.axis = cex.axis)
on.exit(par(op))
rp <- plot(fID, r2, varwidth = TRUE, xlab = xlab, main = main,
ylab = paste("residuals(",namx,", \"deviance\") ^ 2", sep=""),
ylim = ylim, col = col, las = if(lab.horiz) 0 else 2, ...)
abline(h = 0, lty = 3)
if(any(i0 <- abs(meds <- rp$stats[3,]) < 1e-3))
do.call("points", c(list(x=which(i0), y= meds[i0]), med.pars))
if(lab.horiz)
text(c(.2, 1:k), -.1, labs, xpd=FALSE, cex=cex.axis)
else {
text(c((par("usr")[1]+1)/2, 1:k), -0.3*y0, labs,
xpd=NA, srt = 90, adj = c(1, 0.5), cex=cex.axis)
}
if(do.call) mtext(deparse(x$call))
invisible(list(k = k, fID = fID, rp = rp))
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(tidyLPA)
library(dplyr)
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
single_imputation() %>%
estimate_profiles(3)
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
single_imputation() %>%
scale() %>%
estimate_profiles(3) %>%
plot_profiles()
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
single_imputation() %>%
estimate_profiles(1:3,
variances = c("equal", "varying"),
covariances = c("zero", "varying")) %>%
compare_solutions(statistics = c("AIC", "BIC"))
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
estimate_profiles(3,
variances = "varying",
covariances = "varying")
m3 <- pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
estimate_profiles(3)
get_estimates(m3)
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
scale() %>%
estimate_profiles(4) %>%
plot_profiles()
pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
poms() %>%
estimate_profiles(4) %>%
plot_profiles()
get_data(m3)
m4 <- pisaUSA15[1:100, ] %>%
select(broad_interest, enjoyment, self_efficacy) %>%
single_imputation() %>%
estimate_profiles(c(3, 4))
get_data(m4)
get_fit(m4) |
lsem_group_moderator <- function( data, type, moderator.grid,
moderator, residualize, h )
{
moderator.grouped <- NULL
if (type=="MGM"){
G1 <- length(moderator.grid)
moderator.grouped <- data.frame( "min"=moderator.grid[-G1],
"max"=moderator.grid[-1] )
moderator.grouped$mid <- rowMeans( moderator.grouped)
v1 <- data[, moderator ]
v2 <- moderator.grouped$mid[1]
for (gg in 2:G1){
v2 <- ifelse( v1 > moderator.grouped$max[gg-1],
moderator.grouped$mid[gg], v2 )
}
data[,moderator] <- v2
h <- 1E-5
moderator.grid <- moderator.grouped$mid
}
res <- list( data=data, moderator.grouped=moderator.grouped,
residualize=residualize, h=h,
moderator.grid=moderator.grid )
return(res)
}
lsem.group.moderator <- lsem_group_moderator |
rm(list=ls());library(tidyverse);library(SEERaBomb)
load("~/data/SEER/mrgd/popsae.RData")
(p=popsae%>%count(race,sex,age,year,wt=py)%>%rename(py=n))
load("~/data/SEER/mrgd/cancDef.RData")
canc$cancer=fct_collapse(canc$cancer,AML=c("AML","AMLti","APL"))
secs=c("CML","AML","ALL")
(d=canc%>%filter(sex=="Female",cancer%in%c("breast",secs)))
pf=seerSet(d,p,Sex="Female")
pf=mk2D(pf,secondS=secs)
trts=c("rad.chemo","rad.noChemo","noRad.chemo","noRad.noChemo")
pf=csd(pf,brkst=c(0,1,2,3,5,10),brksa=c(0,60),trts=trts,firstS="breast")
(D=pf$DF%>%filter(ageG=="(0,60]"))
D=D%>%mutate(cancer2=fct_relevel(cancer2,"AML"))
D$t=D$t+c(0,0.075,0.15)
myt=theme(legend.title=element_blank(),legend.margin=margin(0,0,0,0))
myth=theme(legend.direction="horizontal",legend.key.height=unit(.25,'lines'))
myth=myt+myth+theme(legend.position=c(.25,.95))
g=ggplot(aes(x=t,y=RR,col=cancer2),data=D)+geom_point()+geom_line()+myth+
labs(x="Years Since Breast Cancer Diagnosis",y="Relative Risk of Leukemia")
g=g+facet_grid(rad~chemo)+geom_abline(intercept=1,slope=0)
g+geom_errorbar(aes(ymin=rrL,ymax=rrU),width=0.05)+coord_cartesian(ylim=c(0,25))
ggsave("~/Results/tutorial/breast2leu.pdf",width=4,height=2.5) |
plotSimmap<-function(tree,colors=NULL,fsize=1.0,ftype="reg",lwd=2,
pts=FALSE,node.numbers=FALSE,mar=NULL,add=FALSE,offset=NULL,direction="rightwards",
type="phylogram",setEnv=TRUE,part=1.0,xlim=NULL,ylim=NULL,nodes="intermediate",
tips=NULL,maxY=NULL,hold=TRUE,split.vertical=FALSE,lend=2,asp=NA,outline=FALSE,
plot=TRUE){
if(inherits(tree,"multiPhylo")){
par(ask=TRUE)
for(i in 1:length(tree)) plotSimmap(tree[[i]],colors=colors,fsize=fsize,
ftype=ftype,lwd=lwd,pts=pts,node.numbers=node.numbers,mar,add,offset,
direction,type,setEnv,part,xlim,ylim,nodes,tips,maxY,hold,split.vertical,
lend,asp,outline,plot)
} else {
if(!inherits(tree,"phylo")) stop("tree should be object of class \"phylo\"")
if(is.null(tree$maps)) stop("tree should contain mapped states on edges.")
ftype<-which(c("off","reg","b","i","bi")==ftype)-1
if(!ftype) fsize=0
if(is.null(colors)){
st<-sort(unique(unlist(sapply(tree$maps,names))))
colors<-palette()[1:length(st)]
names(colors)<-st
if(length(st)>1){
cat("no colors provided. using the following legend:\n")
print(colors)
}
}
tree$tip.label<-gsub("_"," ",tree$tip.label)
if(is.null(mar)) mar=rep(0.1,4)
if(hold) null<-dev.hold()
if(type=="phylogram"){
if(direction%in%c("upwards","downwards")){
if(outline){
fg<-par()$fg
par(fg="transparent")
black<-colors
black[]<-fg
updownPhylogram(tree,colors=black,fsize,ftype,lwd=lwd+2,pts,
node.numbers,mar,add,offset,direction,setEnv,xlim,ylim,nodes,
tips,split.vertical,lend,asp,plot)
par(fg=fg)
}
updownPhylogram(tree,colors,fsize,ftype,lwd,pts,node.numbers,mar,
add=if(outline) TRUE else add,offset,direction,setEnv,xlim,ylim,nodes,
tips,split.vertical,lend,asp,plot)
} else {
if(outline){
fg<-par()$fg
par(fg="transparent")
black<-colors
black[]<-fg
plotPhylogram(tree,colors=black,fsize,ftype,lwd=lwd+2,pts,
node.numbers,mar,add,offset,direction,setEnv,xlim,ylim,nodes,
tips,split.vertical,lend,asp,plot)
par(fg=fg)
}
plotPhylogram(tree,colors,fsize,ftype,lwd,pts,node.numbers,mar,
add=if(outline) TRUE else add,offset,direction,setEnv,xlim,ylim,nodes,
tips,split.vertical,lend,asp,plot)
}
} else if(type=="fan"){
if(outline){
fg<-par()$fg
par(fg="transparent")
black<-colors
black[]<-fg
plotFan(tree,colors=black,fsize,ftype,lwd=lwd+2,mar,add,part,setEnv,
xlim,ylim,tips,maxY,lend,plot,offset)
par(fg=fg)
}
plotFan(tree,colors,fsize,ftype,lwd,mar,add=if(outline) TRUE else add,part,
setEnv,xlim,ylim,tips,maxY,lend,plot,offset)
} else if(type=="cladogram"){
if(outline){
fg<-par()$fg
par(fg="transparent")
black<-colors
black[]<-fg
plotCladogram(tree,colors=black,fsize,ftype,lwd=lwd+2,mar,add,offset,
direction,xlim,ylim,nodes,tips,lend,asp,plot)
par(fg=fg)
}
plotCladogram(tree,colors,fsize,ftype,lwd,mar,add=if(outline) TRUE else add,
offset,direction,xlim,ylim,nodes,tips,lend,asp,plot)
}
if(hold) null<-dev.flush()
}
}
updownPhylogram<-function(tree,colors,fsize,ftype,lwd,pts,node.numbers,mar,
add,offset,direction,setEnv,xlim,ylim,placement,tips,split.vertical,lend,
asp,plot){
if(split.vertical&&!setEnv){
cat("split.vertical requires setEnv=TRUE. Setting split.vertical to FALSE.\n")
spit.vertical<-FALSE
}
offsetFudge<-1.37
cw<-reorderSimmap(tree)
pw<-reorderSimmap(tree,"postorder")
n<-Ntip(cw)
m<-cw$Nnode
Y<-matrix(NA,m+n,1)
if(is.null(tips)) Y[cw$edge[cw$edge[,2]<=n,2]]<-1:n
else Y[cw$edge[cw$edge[,2]<=n,2]]<-if(is.null(names(tips)))
tips[sapply(1:Ntip(cw),function(x,y) which(y==x),y=cw$edge[cw$edge[,2]<=n,2])]
else tips[gsub(" ","_",cw$tip.label)]
nodes<-unique(pw$edge[,1])
for(i in 1:m){
if(placement=="intermediate"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="centered"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="weighted"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
n1<-desc[which(Y[desc]==min(Y[desc]))]
n2<-desc[which(Y[desc]==max(Y[desc]))]
v1<-pw$edge.length[which(pw$edge[,2]==n1)]
v2<-pw$edge.length[which(pw$edge[,2]==n2)]
Y[nodes[i]]<-((1/v1)*Y[n1]+(1/v2)*Y[n2])/(1/v1+1/v2)
} else if(placement=="inner"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
mm<-which(abs(Y[desc]-median(Y[1:Ntip(pw)]))==min(abs(Y[desc]-
median(Y[1:Ntip(pw)]))))
if(length(mm>1)) mm<-mm[which(Y[desc][mm]==min(Y[desc][mm]))]
Y[nodes[i]]<-Y[desc][mm]
}
}
H<-nodeHeights(cw)
par(mar=mar)
if(is.null(offset)) offset<-0.2*lwd/3+0.2/3
if(!add) plot.new()
if(is.null(ylim)){
pp<-par("pin")[2]
sw<-fsize*(max(strwidth(cw$tip.label,units="inches")))+
offsetFudge*fsize*strwidth("W",units="inches")
alp<-optimize(function(a,H,sw,pp) (a*1.04*max(H)+sw-pp)^2,H=H,sw=sw,pp=pp,
interval=c(0,1e6))$minimum
ylim<-if(direction=="downwards") c(min(H)-sw/alp,max(H)) else c(min(H),max(H)+sw/alp)
}
if(is.null(xlim)) xlim=range(Y)
if(direction=="downwards") H<-max(H)-H
plot.window(xlim=xlim,ylim=ylim,asp=asp)
if(plot){
if(!split.vertical){
for(i in 1:m) lines(Y[cw$edge[which(cw$edge[,1]==nodes[i]),2]],
H[which(cw$edge[,1]==nodes[i]),1],
col=colors[names(cw$maps[[match(nodes[i],
cw$edge[,1])]])[1]],lwd=lwd)
}
for(i in 1:nrow(cw$edge)){
x<-H[i,1]
for(j in 1:length(cw$maps[[i]])){
if(direction=="downwards")
lines(c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),c(x,x-cw$maps[[i]][j]),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
else lines(c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),c(x,x+cw$maps[[i]][j]),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
if(pts) points(c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),c(x,x+cw$maps[[i]][j]),
pch=20,lwd=(lwd-1))
x<-x+if(direction=="downwards") -cw$maps[[i]][j] else cw$maps[[i]][j]
j<-j+1
}
}
if(node.numbers){
symbols(mean(Y[cw$edge[cw$edge[,1]==(Ntip(cw)+1),2]]),
if(direction=="downwards") max(H) else 0,
rectangles=matrix(c(1.2*fsize*strwidth(as.character(Ntip(cw)+1)),
1.4*fsize*strheight(as.character(Ntip(cw)+1))),1,2),inches=FALSE,
bg="white",add=TRUE)
text(mean(Y[cw$edge[cw$edge[,1]==(Ntip(cw)+1),2]]),
if(direction=="downwards") max(H) else 0,Ntip(cw)+1,
cex=fsize)
for(i in 1:nrow(cw$edge)){
x<-H[i,2]
if(cw$edge[i,2]>Ntip(cw)){
symbols(Y[cw$edge[i,2]],x,
rectangles=matrix(c(1.2*fsize*strwidth(as.character(cw$edge[i,2])),
1.4*fsize*strheight(as.character(cw$edge[i,2]))),1,2),inches=FALSE,
bg="white",add=TRUE)
text(Y[cw$edge[i,2]],x,cw$edge[i,2],cex=fsize)
}
}
}
if(direction=="downwards") pos<-if(par()$usr[3]>par()$usr[4]) 2 else 4
if(direction=="upwards") pos<-if(par()$usr[3]>par()$usr[4]) 2 else 4
for(i in 1:n){
shift<-offset*fsize*strwidth("W")*(diff(par()$usr[3:4])/diff(par()$usr[1:2]))
if((direction=="downwards"&&diff(par()$usr[3:4])>0) ||
(direction=="upwards"&&diff(par()$usr[3:4])<0)) shift<--shift
if(ftype){
text(labels=cw$tip.label[i],Y[i],
H[which(cw$edge[,2]==i),2]+shift,
pos=pos,offset=0,cex=fsize,font=ftype,
srt=if(direction=="downwards") 270 else 90)
}
}
}
if(setEnv){
PP<-list(type="phylogram",use.edge.length=TRUE,node.pos=1,
show.tip.label=if(ftype) TRUE else FALSE,show.node.label=FALSE,
font=ftype,cex=fsize,adj=0,srt=0,no.margin=FALSE,label.offset=offset,
x.lim=xlim,y.lim=ylim,
direction=direction,tip.color="black",Ntip=Ntip(cw),Nnode=cw$Nnode,
edge=cw$edge,xx=Y[,1],yy=sapply(1:(Ntip(cw)+cw$Nnode),
function(x,y,z) y[match(x,z)],y=H,z=cw$edge))
assign("last_plot.phylo",PP,envir=.PlotPhyloEnv)
}
if(plot) if(split.vertical) splitEdgeColor(cw,colors,lwd)
}
plotPhylogram<-function(tree,colors,fsize,ftype,lwd,pts,node.numbers,mar,
add,offset,direction,setEnv,xlim,ylim,placement,tips,split.vertical,lend,
asp,plot){
if(split.vertical&&!setEnv){
cat("split.vertical requires setEnv=TRUE. Setting split.vertical to FALSE.\n")
spit.vertical<-FALSE
}
offsetFudge<-1.37
cw<-reorderSimmap(tree)
pw<-reorderSimmap(tree,"postorder")
n<-Ntip(cw)
m<-cw$Nnode
Y<-matrix(NA,m+n,1)
if(is.null(tips)) Y[cw$edge[cw$edge[,2]<=n,2]]<-1:n
else Y[cw$edge[cw$edge[,2]<=n,2]]<-if(is.null(names(tips)))
tips[sapply(1:Ntip(cw),function(x,y) which(y==x),y=cw$edge[cw$edge[,2]<=n,2])]
else tips[gsub(" ","_",cw$tip.label)]
nodes<-unique(pw$edge[,1])
for(i in 1:m){
if(placement=="intermediate"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="centered"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="weighted"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
n1<-desc[which(Y[desc]==min(Y[desc]))]
n2<-desc[which(Y[desc]==max(Y[desc]))]
v1<-pw$edge.length[which(pw$edge[,2]==n1)]
v2<-pw$edge.length[which(pw$edge[,2]==n2)]
Y[nodes[i]]<-((1/v1)*Y[n1]+(1/v2)*Y[n2])/(1/v1+1/v2)
} else if(placement=="inner"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
mm<-which(abs(Y[desc]-median(Y[1:Ntip(pw)]))==min(abs(Y[desc]-
median(Y[1:Ntip(pw)]))))
if(length(mm>1)) mm<-mm[which(Y[desc][mm]==min(Y[desc][mm]))]
Y[nodes[i]]<-Y[desc][mm]
}
}
H<-nodeHeights(cw)
par(mar=mar)
if(is.null(offset)) offset<-0.2*lwd/3+0.2/3
if(!add) plot.new()
if(is.null(xlim)){
pp<-par("pin")[1]
sw<-fsize*(max(strwidth(cw$tip.label,units="inches")))+
offsetFudge*fsize*strwidth("W",units="inches")
alp<-optimize(function(a,H,sw,pp) (a*1.04*max(H)+sw-pp)^2,H=H,sw=sw,pp=pp,
interval=c(0,1e6))$minimum
xlim<-if(direction=="leftwards") c(min(H)-sw/alp,max(H)) else c(min(H),max(H)+sw/alp)
}
if(is.null(ylim)) ylim=range(Y)
if(direction=="leftwards") H<-max(H)-H
plot.window(xlim=xlim,ylim=ylim,asp=asp)
if(plot){
if(!split.vertical){
for(i in 1:m) lines(H[which(cw$edge[,1]==nodes[i]),1],
Y[cw$edge[which(cw$edge[,1]==nodes[i]),2]],col=colors[names(cw$maps[[match(nodes[i],
cw$edge[,1])]])[1]],lwd=lwd)
}
for(i in 1:nrow(cw$edge)){
x<-H[i,1]
for(j in 1:length(cw$maps[[i]])){
if(direction=="leftwards")
lines(c(x,x-cw$maps[[i]][j]),c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
else lines(c(x,x+cw$maps[[i]][j]),c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
if(pts) points(c(x,x+cw$maps[[i]][j]),c(Y[cw$edge[i,2]],Y[cw$edge[i,2]]),
pch=20,lwd=(lwd-1))
x<-x+if(direction=="leftwards") -cw$maps[[i]][j] else cw$maps[[i]][j]
j<-j+1
}
}
if(node.numbers){
symbols(if(direction=="leftwards") max(H) else 0,
mean(Y[cw$edge[cw$edge[,1]==(Ntip(cw)+1),2]]),
rectangles=matrix(c(1.2*fsize*strwidth(as.character(Ntip(cw)+1)),
1.4*fsize*strheight(as.character(Ntip(cw)+1))),1,2),inches=FALSE,
bg="white",add=TRUE)
text(if(direction=="leftwards") max(H) else 0,
mean(Y[cw$edge[cw$edge[,1]==(Ntip(cw)+1),2]]),Ntip(cw)+1,
cex=fsize)
for(i in 1:nrow(cw$edge)){
x<-H[i,2]
if(cw$edge[i,2]>Ntip(cw)){
symbols(x,Y[cw$edge[i,2]],
rectangles=matrix(c(1.2*fsize*strwidth(as.character(cw$edge[i,2])),
1.4*fsize*strheight(as.character(cw$edge[i,2]))),1,2),inches=FALSE,
bg="white",add=TRUE)
text(x,Y[cw$edge[i,2]],cw$edge[i,2],cex=fsize)
}
}
}
if(direction=="leftwards") pos<-if(par()$usr[1]>par()$usr[2]) 4 else 2
if(direction=="rightwards") pos<-if(par()$usr[1]>par()$usr[2]) 2 else 4
for(i in 1:n) if(ftype) text(H[which(cw$edge[,2]==i),2],Y[i],cw$tip.label[i],pos=pos,
offset=offset,cex=fsize,font=ftype)
}
if(setEnv){
PP<-list(type="phylogram",use.edge.length=TRUE,node.pos=1,
show.tip.label=if(ftype) TRUE else FALSE,show.node.label=FALSE,
font=ftype,cex=fsize,adj=0,srt=0,no.margin=FALSE,label.offset=offset,
x.lim=xlim,y.lim=ylim,
direction=direction,tip.color="black",Ntip=Ntip(cw),Nnode=cw$Nnode,
edge=cw$edge,xx=sapply(1:(Ntip(cw)+cw$Nnode),
function(x,y,z) y[match(x,z)],y=H,z=cw$edge),yy=Y[,1])
assign("last_plot.phylo",PP,envir=.PlotPhyloEnv)
}
if(plot) if(split.vertical) splitEdgeColor(cw,colors,lwd)
}
plotFan<-function(tree,colors,fsize,ftype,lwd,mar,add,part,setEnv,xlim,ylim,tips,maxY,lend,plot,offset){
if(!plot) cat("plot=FALSE option is not permitted for type=\"fan\". Tree will be plotted.\n")
if(is.null(offset)) offset<-1
cw<-reorder(tree)
pw<-reorder(tree,"pruningwise")
n<-Ntip(cw)
m<-cw$Nnode
Y<-vector(length=m+n)
if(is.null(tips)) tips<-1:n
if(part<1.0) Y[cw$edge[cw$edge[,2]<=n,2]]<-0:(n-1)
else Y[cw$edge[cw$edge[,2]<=n,2]]<-tips
nodes<-unique(pw$edge[,1])
for(i in 1:m){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
}
if(is.null(maxY)) maxY<-max(Y)
Y<-setNames(Y/maxY*2*pi,1:(n+m))
Y<-part*cbind(Y[as.character(cw$edge[,2])],Y[as.character(cw$edge[,2])])
R<-nodeHeights(cw)
x<-R*cos(Y)
y<-R*sin(Y)
par(mar=mar)
offsetFudge<-1.37
OFFSET<-0
pp<-par("pin")[1]
sw<-fsize*(max(strwidth(cw$tip.label,units="inches")))+
offsetFudge*OFFSET*fsize*strwidth("W",units="inches")
alp<-optimize(function(a,H,sw,pp) (2*a*1.04*max(H)+2*sw-pp)^2,H=R,sw=sw,pp=pp,
interval=c(0,1e6))$minimum
if(part<=0.25) x.lim<-y.lim<-c(0,max(R)+sw/alp)
else if(part>0.25&&part<=0.5){
x.lim<-c(-max(R)-sw/alp,max(R)+sw/alp)
y.lim<-c(0,max(R)+sw/alp)
} else x.lim<-y.lim<-c(-max(R)-sw/alp,max(R)+sw/alp)
if(is.null(xlim)) xlim<-x.lim
if(is.null(ylim)) ylim<-y.lim
if(!add) plot.new()
plot.window(xlim=xlim,ylim=ylim,asp=1)
jj<-which(cw$edge[,1]==(Ntip(cw)+1))
if(length(jj)==2){
m.left<-cumsum(cw$maps[[jj[1]]])/sum(cw$maps[[jj[1]]])
xx.left<-c(x[jj[1],1],x[jj[1],1]+(x[jj[1],2]-x[jj[1],1])*m.left)
yy.left<-c(y[jj[1],1],y[jj[1],1]+(y[jj[1],2]-y[jj[1],1])*m.left)
m.right<-cumsum(cw$maps[[jj[2]]])/sum(cw$maps[[jj[2]]])
xx.right<-c(x[jj[2],1],x[jj[2],1]+(x[jj[2],2]-x[jj[2],1])*m.right)
yy.right<-c(y[jj[2],1],y[jj[2],1]+(y[jj[2],2]-y[jj[2],1])*m.right)
xx<-c(xx.left[length(xx.left):1],xx.right[2:length(xx.right)])
yy<-c(yy.left[length(yy.left):1],yy.right[2:length(yy.right)])
col<-colors[c(names(m.left)[length(m.left):1],names(m.right))]
segments(xx[2:length(xx)-1],yy[2:length(yy)-1],xx[2:length(xx)],yy[2:length(yy)],
col=col,lwd=lwd,lend=lend)
} else jj<-NULL
for(i in 1:nrow(cw$edge)){
if(i%in%jj==FALSE){
maps<-cumsum(cw$maps[[i]])/sum(cw$maps[[i]])
xx<-c(x[i,1],x[i,1]+(x[i,2]-x[i,1])*maps)
yy<-c(y[i,1],y[i,1]+(y[i,2]-y[i,1])*maps)
for(i in 1:(length(xx)-1)) lines(xx[i+0:1],yy[i+0:1],col=colors[names(maps)[i]],
lwd=lwd,lend=lend)
}
}
for(i in 1:m+n){
r<-R[match(i,cw$edge)]
a1<-min(Y[which(cw$edge==i)])
a2<-max(Y[which(cw$edge==i)])
draw.arc(0,0,r,a1,a2,lwd=lwd,col=colors[names(cw$maps[[match(i,cw$edge[,1])]])[1]])
}
for(i in 1:n){
ii<-which(cw$edge[,2]==i)
aa<-Y[ii,2]/(2*pi)*360
adj<-if(aa>90&&aa<270) c(1,0.25) else c(0,0.25)
tt<-if(aa>90&&aa<270) paste(cw$tip.label[i],paste(rep(" ",offset),
collapse=""),sep="") else paste(paste(rep(" ",offset),collapse=""),
cw$tip.label[i],sep="")
aa<-if(aa>90&&aa<270) 180+aa else aa
if(ftype) text(x[ii,2],y[ii,2],tt,srt=aa,adj=adj,cex=fsize,font=ftype)
}
if(setEnv){
PP<-list(type="fan",use.edge.length=TRUE,node.pos=1,
show.tip.label=if(ftype) TRUE else FALSE,show.node.label=FALSE,
font=ftype,cex=fsize,adj=0,srt=0,no.margin=FALSE,label.offset=offset,
x.lim=xlim,y.lim=ylim,direction="rightwards",tip.color="black",
Ntip=Ntip(cw),Nnode=cw$Nnode,edge=cw$edge,
xx=c(x[sapply(1:n,function(x,y) which(x==y)[1],y=cw$edge[,2]),2],x[1,1],
if(m>1) x[sapply(2:m+n,function(x,y) which(x==y)[1],y=cw$edge[,2]),2] else c()),
yy=c(y[sapply(1:n,function(x,y) which(x==y)[1],y=cw$edge[,2]),2],y[1,1],
if(m>1) y[sapply(2:m+n,function(x,y) which(x==y)[1],y=cw$edge[,2]),2] else c()))
assign("last_plot.phylo",PP,envir=.PlotPhyloEnv)
}
}
plotCladogram<-function(tree,colors=NULL,fsize=1.0,ftype="reg",lwd=2,mar=NULL,
add=FALSE,offset=NULL,direction="rightwards",xlim=NULL,ylim=NULL,
nodes="intermediate",tips=NULL,lend=2,asp=NA,plot=TRUE){
placement<-nodes
offsetFudge<-1.37
cw<-reorderSimmap(tree)
pw<-reorderSimmap(tree,"postorder")
n<-Ntip(cw)
m<-cw$Nnode
Y<-matrix(NA,m+n,1)
if(is.null(tips)) Y[cw$edge[cw$edge[,2]<=n,2]]<-1:n
else Y[cw$edge[cw$edge[,2]<=n,2]]<-if(is.null(names(tips)))
tips[sapply(1:Ntip(cw),function(x,y) which(y==x),y=cw$edge[cw$edge[,2]<=n,2])]
else tips[gsub(" ","_",cw$tip.label)]
nodes<-unique(pw$edge[,1])
for(i in 1:m){
if(placement=="intermediate"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="centered"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
} else if(placement=="weighted"){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
n1<-desc[which(Y[desc]==min(Y[desc]))]
n2<-desc[which(Y[desc]==max(Y[desc]))]
v1<-pw$edge.length[which(pw$edge[,2]==n1)]
v2<-pw$edge.length[which(pw$edge[,2]==n2)]
Y[nodes[i]]<-((1/v1)*Y[n1]+(1/v2)*Y[n2])/(1/v1+1/v2)
} else if(placement=="inner"){
desc<-getDescendants(pw,nodes[i])
desc<-desc[desc<=Ntip(pw)]
mm<-which(abs(Y[desc]-median(Y[1:Ntip(pw)]))==min(abs(Y[desc]-
median(Y[1:Ntip(pw)]))))
if(length(mm>1)) mm<-mm[which(Y[desc][mm]==min(Y[desc][mm]))]
Y[nodes[i]]<-Y[desc][mm]
}
}
H<-nodeHeights(cw)
par(mar=mar)
if(is.null(offset)) offset<-0.2*lwd/3+0.2/3
if(!add) plot.new()
if(is.null(xlim)){
pp<-par("pin")[1]
sw<-fsize*(max(strwidth(cw$tip.label,units="inches")))+
offsetFudge*fsize*strwidth("W",units="inches")
alp<-optimize(function(a,H,sw,pp) (a*1.04*max(H)+sw-pp)^2,H=H,sw=sw,pp=pp,
interval=c(0,1e6))$minimum
xlim<-if(direction=="leftwards") c(min(H)-sw/alp,max(H)) else c(min(H),max(H)+sw/alp)
}
if(is.null(ylim)) ylim=range(Y)
if(direction=="leftwards") H<-max(H)-H
plot.window(xlim=xlim,ylim=ylim,asp=asp)
if(plot){
for(i in 1:nrow(cw$edge)){
x<-H[i,1]
y<-Y[cw$edge[i,1]]
m<-(Y[cw$edge[i,2]]-Y[cw$edge[i,1]])/(H[i,2]-H[i,1])
if(is.finite(m)){
for(j in 1:length(cw$maps[[i]])){
if(direction=="leftwards")
lines(c(x,x-cw$maps[[i]][j]),c(y,y-cw$maps[[i]][j]*m),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
else lines(c(x,x+cw$maps[[i]][j]),c(y,y+cw$maps[[i]][j]*m),
col=colors[names(cw$maps[[i]])[j]],lwd=lwd,lend=lend)
x<-x+if(direction=="leftwards") -cw$maps[[i]][j] else cw$maps[[i]][j]
y<-y+if(direction=="leftwards") -m*cw$maps[[i]][j] else m*cw$maps[[i]][j]
j<-j+1
}
} else {
lines(rep(x,2),Y[cw$edge[i,]],col=colors[names(cw$maps[[i]])[1]],lwd=lwd,
lend=lend)
}
}
if(direction=="leftwards") pos<-if(par()$usr[1]>par()$usr[2]) 4 else 2
if(direction=="rightwards") pos<-if(par()$usr[1]>par()$usr[2]) 2 else 4
for(i in 1:n) if(ftype) text(H[which(cw$edge[,2]==i),2],Y[i],cw$tip.label[i],pos=pos,
offset=offset,cex=fsize,font=ftype)
}
PP<-list(type="phylogram",use.edge.length=TRUE,node.pos=1,
show.tip.label=if(ftype) TRUE else FALSE,show.node.label=FALSE,
font=ftype,cex=fsize,adj=0,srt=0,no.margin=FALSE,label.offset=offset,
x.lim=xlim,y.lim=ylim,
direction=direction,tip.color="black",Ntip=Ntip(cw),Nnode=cw$Nnode,
edge=cw$edge,xx=sapply(1:(Ntip(cw)+cw$Nnode),
function(x,y,z) y[match(x,z)],y=H,z=cw$edge),yy=Y[,1])
assign("last_plot.phylo",PP,envir=.PlotPhyloEnv)
}
add.simmap.legend<-function(leg=NULL,colors,prompt=TRUE,vertical=TRUE,...){
if(hasArg(shape)) shape<-list(...)$shape
else shape<-"square"
if(prompt){
cat("Click where you want to draw the legend\n")
x<-unlist(locator(1))
y<-x[2]
x<-x[1]
} else {
if(hasArg(x)) x<-list(...)$x
else x<-0
if(hasArg(y)) y<-list(...)$y
else y<-0
}
if(hasArg(fsize)) fsize<-list(...)$fsize
else fsize<-1.0
if(is.null(leg)) leg<-names(colors)
h<-fsize*strheight(LETTERS[1])
w<-par()$mfcol[2]*h*abs(diff(par()$usr[1:2])/diff(par()$usr[3:4]))
flipped<-par()$usr[1]>par()$usr[2]
if(vertical){
y<-y-0:(length(leg)-1)*1.5*h
x<-rep(x+w/2,length(y))
text(x + if(flipped) -w else w,y,leg,pos=4,cex=fsize/par()$cex)
} else {
sp<-abs(fsize*max(strwidth(leg)))
x<-x + if(flipped) w/2-0:(length(leg)-1)*1.5*(sp+w) else -w/2+0:(length(leg)-1)*1.5*(sp+w)
y<-rep(y+w/2,length(x))
text(x,y,leg,pos=4,cex=fsize/par()$cex)
}
if(shape=="square") symbols(x,y,squares=rep(w,length(x)),bg=colors,add=TRUE,inches=FALSE)
else if(shape=="circle") nulo<-mapply(draw.circle,x=x,y=y,col=colors,
MoreArgs=list(nv=200,radius=w/2))
else stop(paste("shape=\"",shape,"\" is not a recognized option.",sep=""))
}
plotTree<-function(tree,...){
if(hasArg(color)) color<-list(...)$color
else color<-NULL
if(hasArg(fsize)) fsize<-list(...)$fsize
else fsize<-1.0
if(hasArg(ftype)) ftype<-list(...)$ftype
else ftype<-"reg"
if(hasArg(lwd)) lwd<-list(...)$lwd
else lwd<-2
if(hasArg(pts)) pts<-list(...)$pts
else pts<-FALSE
if(hasArg(node.numbers)) node.numbers<-list(...)$node.numbers
else node.numbers<-FALSE
if(hasArg(mar)) mar<-list(...)$mar
else mar<-NULL
if(hasArg(add)) add<-list(...)$add
else add<-FALSE
if(hasArg(offset)) offset<-list(...)$offset
else offset<-NULL
if(hasArg(type)) type<-list(...)$type
else type<-"phylogram"
if(hasArg(direction)) direction<-list(...)$direction
else direction<-"rightwards"
if(hasArg(setEnv)) setEnv<-list(...)$setEnv
else setEnv<-TRUE
if(hasArg(part)) part<-list(...)$part
else part<-1.0
if(hasArg(xlim)) xlim<-list(...)$xlim
else xlim<-NULL
if(hasArg(ylim)) ylim<-list(...)$ylim
else ylim<-NULL
if(hasArg(nodes)) nodes<-list(...)$nodes
else nodes<-"intermediate"
if(hasArg(tips)) tips<-list(...)$tips
else tips<-NULL
if(hasArg(maxY)) maxY<-list(...)$maxY
else maxY<-NULL
if(hasArg(hold)) hold<-list(...)$hold
else hold<-TRUE
if(hasArg(lend)) lend<-list(...)$lend
else lend<-2
if(hasArg(asp)) asp<-list(...)$asp
else asp<-NA
if(hasArg(plot)) plot<-list(...)$plot
else plot<-TRUE
if(inherits(tree,"multiPhylo")){
par(ask=TRUE)
if(!is.null(color)) names(color)<-"1"
for(i in 1:length(tree)) plotTree(tree[[i]],color=color,fsize=fsize,ftype=ftype,
lwd=lwd,pts=pts,node.numbers=node.numbers,mar=mar,add=add,offset=offset,
direction=direction,type=type,setEnv=setEnv,part=part,xlim=xlim,ylim=ylim,
nodes=nodes,tips=tips,maxY=maxY,hold=hold,lend=lend,asp=asp,plot=plot)
} else {
if(is.null(tree$edge.length)) tree<-compute.brlen(tree)
tree$maps<-as.list(tree$edge.length)
for(i in 1:length(tree$maps)) names(tree$maps[[i]])<-c("1")
if(!is.null(color)) names(color)<-"1"
plotSimmap(tree,colors=color,fsize=fsize,ftype=ftype,lwd=lwd,pts=pts,
node.numbers=node.numbers,mar=mar,add=add,offset=offset,direction=direction,
type=type,setEnv=setEnv,part=part,xlim=xlim,ylim=ylim,nodes=nodes,tips=tips,maxY=maxY,
hold=hold,lend=lend,asp=asp,plot=plot)
}
}
plot.simmap<-function(x,...) plotSimmap(x,...)
plot.multiSimmap<-function(x,...) plotSimmap(x,...)
splitEdgeColor<-function(tree,colors,lwd=2){
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
for(i in 1:tree$Nnode+Ntip(tree)){
daughters<-tree$edge[which(tree$edge[,1]==i),2]
cols<-vector()
for(j in 1:length(daughters)){
jj<-which(tree$edge[,2]==daughters[j])
cols[j]<-if(tree$maps[[jj]][1]==0&&length(tree$maps[[jj]])>1) colors[names(tree$maps[[jj]])[2]]
else colors[names(tree$maps[[jj]])[1]]
}
ii<-order(obj$yy[c(i,daughters)])
jj<-order(obj$yy[daughters])
x0<-x1<-rep(obj$xx[i],length(daughters))
y0<-obj$yy[c(i,daughters)][ii][1:length(daughters)]
y1<-obj$yy[c(i,daughters)][ii][2:(length(daughters)+1)]
cols<-cols[jj]
for(j in 1:length(x0)) segments(x0[j],y0[j],x1[j],y1[j],col=cols[j],lwd=lwd,lend=2)
}
} |
cpsurv <- function(time, event, cpmax, intwd, cpmin = 0,
censoring = c("random", "type1", "no"), censpoint = NULL,
biascorrect = FALSE, parametric = FALSE, B.correct = 49,
opt.start = c(0.1, 50), boot.ci = FALSE,
B = 999, conf.level = 0.95, norm.riskset = TRUE, seed = NULL,
parallel = TRUE, cores = 4L){
if (!is.null(seed)) {
if(parallel) RNGkind(kind = "L'Ecuyer-CMRG")
set.seed(as.integer(seed))
}
is_single_num <- function(x, lower = -Inf, upper = Inf){
if(is.na(x) || !is.numeric(x) || (length(x) != 1)){
stop("Argument '", substitute(x), "' is not a single numeric value.")
}
if(x < lower) stop("Value for argument '", substitute(x), "' too low.")
if(x > upper) stop("Value for argument '", substitute(x), "' too high.")
}
stopifnot(is.numeric(time),
all(sapply(time, function(z) z >= 0)),
length(time) >= 1)
if(missing(event))
event <- rep.int(1, length(time))
stopifnot(is.numeric(event), length(event) >= 1)
if(!all(sapply(event, function(z) z %in% c(0,1)))){
stop("Argument 'event' has to be binary.")
}
is_single_num(cpmax, lower = 1L)
is_single_num(cpmin, lower = 0L, upper = cpmax)
if(!is.null(censpoint)) is_single_num(censpoint, lower = 0L, upper = max(time))
is_single_num(B.correct, lower = 1L)
is_single_num(B, lower = 1L)
is_single_num(conf.level, lower = 0L, upper = 1L)
is_single_num(cores, lower = 1L)
if(missing(intwd)) intwd <- ceiling(cpmax / 20)
is_single_num(intwd, lower = 1L)
stopifnot(!is.na(norm.riskset), is.logical(norm.riskset), length(norm.riskset) == 1,
!is.na(biascorrect), is.logical(biascorrect), length(biascorrect) == 1,
!is.na(parametric), is.logical(parametric), length(parametric) == 1,
!is.na(boot.ci), is.logical(boot.ci), length(boot.ci) == 1,
!is.na(parallel), is.logical(parallel), length(parallel) == 1)
if((cpmax%%intwd) != 0){
cpmax <- cpmax + (cpmax %% intwd)
warning("'cpmax' is not a multiple of 'intwd'; cpmax corrected to ", cpmax)
}
censoring <- match.arg(censoring)
if(!identical(length(time), length(event)))
stop("Vectors 'time' and 'event' must be of equal length.")
if(sum(event[time > cpmax] == 1) == 0){
stop("No events with 'time' > 'cpmax'; ",
"choose lower value for 'cpmax'.")
}
if(!is.vector(opt.start) || !length(opt.start) == 2 || !all(opt.start > 0)){
stop("Invalid 'opt.start' argument. See documentation.")
}
if(all(event %in% 1)){
censoring <- "no"
}
if(censoring == "type1" && is.null(censpoint)){
censpoint <- min(time[sapply(seq_along(time), function(i)
all(event[time >= time[i]] == 0))])
warning("point for Type I censoring missing; 'censpoint' was set to ", censpoint)
}
nobs <- length(time)
check.integer <- function(x){
x == round(x)
}
if(all(sapply(time, check.integer))){
times.int <- TRUE
} else{
times.int <- FALSE
}
cp <- cpest(time = time, event = event, intwd = intwd, cpmax = cpmax,
cpmin = cpmin, norm.riskset = norm.riskset)
changeP <- cp$cp
if(biascorrect){
bcresult <- bootbiascorrect(changeP = changeP, time = time, event = event,
censoring = censoring, censpoint = censpoint,
intwd = intwd, opt.start = opt.start,
cpmax = cpmax, cpmin = cpmin,
norm.riskset = norm.riskset,
B.correct = B.correct, parametric = parametric,
times.int = times.int)
if(is.na(bcresult$bc)){
if(parametric == TRUE){
warning("Parametric bootstrap bias correction not possible;",
"maybe times are not Weibull distributed")
} else{
warning("Nonparametric bootstrap bias correction not possible",
"(no events above 'cpmax' in simulated data)")
}
}
cp$cp.bc <- bcresult$bc
if(parametric){
cp$ml.shape <- bcresult$shape
cp$ml.scale <- bcresult$scale
}
if(bcresult$oob[1] == TRUE){
warning("bias corrected change point out of bounds; it was set to 'cpmin'")
} else if(bcresult$oob[2] == TRUE){
warning("bias corrected change point out of bounds; it was set to 'cpmax'")
}
}
if(boot.ci){
bootstrap <- function(x){
boot.out <- NA
while(is.na(boot.out)){
samp <- sample(1:nobs, size = nobs, replace=T)
cp.tmp <- cpest(time = time[samp], event = event[samp], intwd = intwd,
cpmax = cpmax, cpmin = cpmin, norm.riskset = norm.riskset)$cp
if(biascorrect){
boot.out <- bootbiascorrect(changeP = cp.tmp, time = time[samp],
event = event[samp], censoring = censoring,
censpoint = censpoint, intwd = intwd,
cpmax = cpmax, cpmin = cpmin,
norm.riskset = norm.riskset, B.correct = B.correct,
parametric = parametric, times.int = times.int,
opt.start = opt.start)$bc
} else{
boot.out <- cp.tmp
}
}
boot.out
}
if(parallel){
if(parallel::detectCores() < cores) cores <- parallel::detectCores()
if(.Platform$OS.type != "windows") {
cpboot <- parallel::mclapply(1:B, FUN = bootstrap, mc.cores = cores)
} else{
cl <- parallel::makePSOCKcluster(rep("localhost", cores))
parallel::clusterExport(cl = cl, varlist = c("bootbiascorrect",
"neg.loglik.WeibExp", "cpest", "sim.survdata",
"km.sim.survtimes", "nobs", "time", "event", "intwd", "cpmax",
"cpmin", "norm.riskset", "censoring", "censpoint", "biascorrect", "B.correct",
"parametric", "times.int", "opt.start"),
envir = environment())
if(!is.null(seed)) parallel::clusterSetRNGStream(cl)
cpboot <- parallel::parLapply(cl, 1:B, fun = bootstrap)
parallel::stopCluster(cl)
}
cpboot <- unlist(cpboot)
} else{
cpboot <- vapply(1:B, bootstrap, FUN.VALUE = numeric(1L))
}
cp$cp.boot <- cpboot
sd_boot <- sd(cpboot)
cp$sd <- sd_boot
quant <- (1 + c(-conf.level, conf.level))/2
if(biascorrect){
ci.normal <- c(cp$cp.bc - qnorm(quant[2]) * sd_boot,
cp$cp.bc + qnorm(quant[2]) * sd_boot)
} else{
ci.normal <- c(changeP - qnorm(quant[2]) * sd_boot,
changeP + qnorm(quant[2]) * sd_boot)
}
if(ci.normal[1] < 0){
ci.normal[1] <- 0
warning("lower bound of confidence interval was set to 0")
}
if(ci.normal[2] > cpmax){
ci.normal[2] <- cpmax
warning("upper bound of confidence interval was set to 'cpmax'")
}
cp$ci.normal <- ci.normal
perc <- (B + 1) * quant
ptrunc <- trunc(perc)
cpsort <- sort(cpboot)
percint <- numeric(2L)
percint[1] <- ifelse(ptrunc[1] == 0, cpsort[1L], cpsort[ptrunc[1]])
percint[2] <- ifelse(ptrunc[2] == B, cpsort[B], cpsort[ptrunc[2]])
if(ptrunc[1] == 0 || ptrunc[2] == B){
warning("extreme order statistics used as endpoints for percentile interval")
}
cp$ci.percent <- percint
cp$conf.level <- conf.level
cp$B <- B
}
structure(c(cp, list(time = time, event = event, cpmax = cpmax, intwd = intwd,
call = match.call())), class = "cpsurv")
} |
markTime <- function(x,times,nlost,pch,col,...){
mtimeList=lapply(1:length(x),function(i){
who=nlost[[i]]>0 & !is.na(nlost[[i]])
mark.x=times[who]
mark.y=x[[i]][who]
if (length(col)<length(x)) mcol=col[1] else mcol=col[i]
if (length(pch)<length(x)) mpch=pch[1] else mpch=pch[i]
points(x=mark.x,y=mark.y,col=mcol,pch=mpch,...)
invisible(NULL)
})
} |
library(rmr)
csvtextinputformat = function(line) keyval(NULL, unlist(strsplit(line, "\\,")))
deptdelay = function (input, output) {
mapreduce(input = input,
output = output,
textinputformat = csvtextinputformat,
map = function(k, fields) {
if (!(identical(fields[[1]], "Year")) & length(fields) == 29) {
deptDelay <- fields[[16]]
if (!(identical(deptDelay, "NA"))) {
keyval(c(fields[[9]], fields[[1]], fields[[2]]), deptDelay)
}
}
},
reduce = function(keySplit, vv) {
keyval(keySplit[[2]], c(keySplit[[3]], length(vv), keySplit[[1]], mean(as.numeric(vv))))
})
}
from.dfs(deptdelay("/data/airline/", "/dept-delay-month-orig")) |
dots_sample_slab_function = function(
df, input, limits = NULL, quantiles = NA, orientation = NA,
trans = scales::identity_trans(), na.rm = FALSE, ...
) {
x = switch(orientation,
y = ,
horizontal = "x",
x = ,
vertical = "y"
)
if (is.null(quantiles) || is.na(quantiles)) {
input = df[[x]]
} else {
input = quantile(df[[x]], ppoints(quantiles, a = 1/2), type = 5, na.rm = na.rm)
}
data.frame(
.input = trans$inverse(input),
.value = 1,
n = length(input)
)
}
dots_dist_slab_function = function(
df, input, quantiles = 100, trans = scales::identity_trans(), ...
) {
pmap_dfr_(df, function(dist, ...) {
if (is.null(dist) || anyNA(dist)) {
return(data.frame(.input = NA, .value = NA))
}
args = c(
list(ppoints(quantiles, a = 1/2)),
args_from_aes(...)
)
quantile_fun = distr_quantile(dist)
input = do.call(quantile_fun, args)
data.frame(
.input = input,
.value = 1,
n = length(input)
)
})
}
stat_dotsinterval = function(
mapping = NULL,
data = NULL,
geom = "dotsinterval",
position = "identity",
...,
quantiles = NA,
point_interval = median_qi,
na.rm = FALSE,
show.legend = c(size = FALSE),
inherit.aes = TRUE
) {
layer(
data = data,
mapping = mapping,
stat = StatDotsinterval,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
quantiles = quantiles,
slab_function = dots_sample_slab_function,
slab_args = list(),
point_interval = point_interval,
na.rm = na.rm,
...
)
)
}
StatDotsinterval = ggproto("StatDotsinterval", StatSlabinterval,
extra_params = c(
StatSlabinterval$extra_params,
"quantiles"
),
default_params = defaults(list(
quantiles = NA,
slab_function = dots_sample_slab_function,
point_interval = median_qi
), StatSlabinterval$default_params),
setup_params = function(self, data, params) {
params = ggproto_parent(StatSlabinterval, self)$setup_params(data, params)
params$slab_args = list(
quantiles = params$quantiles %||% self$default_params$quantiles
)
params
}
)
stat_dots = function(
mapping = NULL,
data = NULL,
geom = "dots",
position = "identity",
...,
show.legend = NA,
inherit.aes = TRUE
) {
layer(
data = data,
mapping = mapping,
stat = StatDots,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
show_point = FALSE,
show_interval = FALSE,
...
)
)
}
StatDots = ggproto("StatDots", StatDotsinterval,
default_params = defaults(list(
show_point = FALSE,
show_interval = FALSE
), StatDotsinterval$default_params)
)
StatDots$default_aes$size = NULL
stat_dist_dotsinterval = function(
mapping = NULL,
data = NULL,
geom = "dotsinterval",
position = "identity",
...,
quantiles = 100,
na.rm = FALSE,
show.legend = c(size = FALSE),
inherit.aes = TRUE
) {
layer(
data = data,
mapping = mapping,
stat = StatDistDotsinterval,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
quantiles = quantiles,
limits_function = NULL,
slab_function = dots_dist_slab_function,
slab_args = list(),
interval_function = dist_interval_function,
interval_args = list(),
point_interval = NULL,
na.rm = na.rm,
...
)
)
}
StatDistDotsinterval = ggproto("StatDistDotsinterval", StatDistSlabinterval,
extra_params = c(
StatDistSlabinterval$extra_params,
"quantiles"
),
default_params = defaults(list(
quantiles = 100,
limits_function = NULL,
slab_function = dots_dist_slab_function,
interval_function = dist_interval_function
), StatDistSlabinterval$default_params),
setup_params = function(self, data, params) {
params = defaults(params, self$default_params)
params$flipped_aes = get_flipped_aes(data, params,
main_is_orthogonal = FALSE, range_is_orthogonal = TRUE, group_has_equal = TRUE, main_is_optional = TRUE
)
params$orientation = get_orientation(params$flipped_aes)
params = ggproto_parent(StatSlabinterval, self)$setup_params(data, params)
params$slab_args = list(
quantiles = params$quantiles %||% self$default_params$quantiles
)
params
}
)
stat_dist_dots = function(
mapping = NULL,
data = NULL,
geom = "dots",
position = "identity",
...,
show.legend = NA,
inherit.aes = TRUE
) {
layer(
data = data,
mapping = mapping,
stat = StatDistDots,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
show_point = FALSE,
show_interval = FALSE,
...
)
)
}
StatDistDots = ggproto("StatDistDots", StatDistDotsinterval,
default_params = defaults(list(
show_point = FALSE,
show_interval = FALSE
), StatDistDotsinterval$default_params)
)
StatDistDots$default_aes$size = NULL |
context("TaskClust")
test_that("Basic ops on usarrests task", {
task = tsk("usarrests")
expect_task(task)
expect_task_clust(task)
expect_identical(task$target_names, character(0))
})
test_that("0 feature task", {
b = as_data_backend(data.table(ids = 1:30))
task = TaskClust$new(id = "zero_feat_task", b)
expect_output(print(task))
b = task$backend
expect_backend(b)
expect_task(task)
expect_task_clust(task)
expect_data_table(task$data(), ncols = 1L)
lrn = lrn("clust.featureless")
lrn$param_set$values = list(num_clusters = 3L)
p = lrn$train(task)$predict(task)
expect_prediction(p)
}) |
norm.vect <- function(vector1) {
norm <- sqrt(sum(vector1^2))
return(norm)
} |
.datatable.aware <- TRUE
setnames <- `names<-`
setclass <- `class<-`
ndots <- function(dots) {
any(nzchar(dots))
}
is.formula <- function(expr) {
inherits(expr, "formula") || (is.call(expr) && .subset2(expr, 1L) == "~")
}
is.side_effect <- function(expr) {
is.formula(expr) &&
(length(expr) == 2L ||
length(expr) == 3L &&
Recall(.subset2(expr, 2L)))
} |
require(RgoogleMaps)
markerdata = read.csv(system.file('extdata', 'Napoleon.csv', package = 'MSG'))
boundingbox = qbbox(lon = markerdata[, 'lon'], lat = markerdata[, 'lat'])
NPMap = GetMap.bbox(boundingbox$lonR, boundingbox$latR, destfile = tempfile(),
maptype = 'map', zoom = 6, size = c(640, 370))
lwd_m = rep(1e-04, nrow(markerdata) - 1)
lwd_m[1:5] = (15:11) * 1e-5
color = c('
tmp = c(16, 35, 41, 43, 46)
n = 1
PlotOnStaticMap(
NPMap, FUN = lines,
lon = markerdata$lon[1:2], lat = markerdata$lat[1:2],
lwd = lwd_m[1] * markerdata$size[1], col = color[1], verbose = 0
)
for (i in 2:(nrow(markerdata) - 1)) {
if (!(i %in% tmp)) {
PlotOnStaticMap(
NPMap, FUN = lines,
lon = markerdata$lon[i:(i + 1)], lat = markerdata$lat[i:(i + 1)],
lwd = lwd_m[i] * markerdata$size[i], col = color[n], add = TRUE, verbose = 0
)
} else {
n = ifelse(n == 1, 2, 1)
}
} |
test_that('vacuum_cleaner validates input arguments', {
expect_warning(vacuum_cleaner(matrix(c('a', 1:3), nrow = 2)), 'argument "x" must be convertable to a numeric matrix')
expect_warning(vacuum_cleaner(matrix(1:6, nrow = 2)), 'argument "x" must have at least 3 rows and columns')
}) |
time_windows <- function(r0=NULL,
dist_param=NULL,
m=NULL,
imm_frac=NULL,
hosp_rate=NULL,
recov_hosp=NULL,
icu_rate=NULL,
death_rate=NULL,
window_length=NULL,
start_dates=NULL,
end_dates=NULL,
daily=NULL)
{
is.Date <- function(obj) inherits(obj, "Date")
if (is.null(r0)) stop("Parameter r0 cannot be omitted.")
if (is.null(dist_param)) stop("Parameter dist_param cannot be omitted.")
if (is.null(m)) stop("Parameter m cannot be omitted.")
if (is.null(imm_frac)) stop("Parameter imm_frac cannot be omitted.")
if (class(r0) != "list") {
temp_r0 <- r0
r0 <- list()
r0[[1]] <- temp_r0
}
n_pop <- length(r0)
total_windows <- length(r0[[1]])
if (is.null(window_length) && is.null(start_dates) && is.null(daily)) stop("You must provide one of the following options: window_length, start_dates with end_dates, or daily.")
if ((!is.null(window_length) && (!is.null(start_dates) || !is.null(end_dates) || !is.null(daily))) ||
(!is.null(daily) && (!is.null(start_dates) || !is.null(end_dates) || !is.null(window_length))) ||
(!is.null(start_dates) && (!is.null(window_length) || !is.null(daily))))
{
stop("You may provide only one of the following options: window_length, start_dates with end_dates, or daily.")
}
if (!is.null(start_dates) && is.null(end_dates)) stop("You must provide end_dates with start_dates.")
if (is.null(daily) && (!is.null(hosp_rate) || !is.null(recov_hosp) || !is.null(icu_rate) || !is.null(death_rate))) stop("You may only provide hosp_rate, recov_hosp, icu_rate, death_rate when using daily time windows.")
if (!all(dist_param >= 0)) stop("Values of dist_param must be greater than or equal to zero.")
if (!all(m >= 0)) stop("Values of m must be greater than or equal to zero.")
if (!all(imm_frac >= 0)) stop("Values of imm_frac must be greater than zero.")
if (!all(imm_frac <= 1)) stop("Values of imm_frac must be less than or equal to one.")
if (total_windows != length(dist_param)) stop("Length of R0 does not match length of dist_param.")
if (total_windows != length(m)) stop("Length of R0 does not match length of m.")
if (total_windows != length(imm_frac)) stop("Length of R0 does not match length of imm_frac.")
if (!is.null(window_length) && (total_windows != length(window_length))) stop("Length of R0 does not match length of window_length.")
for (this_pop in 1:n_pop) {
if (!all(r0[[this_pop]] >= 0)) stop("Values of r0 must be greater than or equal to zero.")
if (length(r0[[this_pop]]) != total_windows) {stop("The lengths of R0 in each population must be the same.")}
}
if (!is.null(start_dates))
{
if (!is.Date(start_dates)) stop("Vector start_dates does not contain valid Dates.")
if (!is.Date(end_dates)) stop("Vector end_dates does not contain valid Dates.")
if (length(start_dates) != length(end_dates)) stop("The lengths of start_dates and end_dates do not match.")
if (total_windows != length(start_dates)) stop("Length of R0 does not match the length of start_dates and end_dates.")
}
if (!is.null(daily))
{
if (!is.Date(daily)) stop("Vector daily does not contain valid Dates.")
if (total_windows != length(daily)) stop("Length of R0 does not match length of daily.")
}
if (!is.null(daily))
{
for (index in 2:length(daily))
{
difference <- as.numeric(daily[index] - daily[index - 1])
if (difference == 0) stop(paste("Daily entry at daily[", index, "] overlaps with the previous entry."))
if (difference > 1) stop(paste("There is a gap between daily[", index, "] and daily[", (index - 1), "]."))
if (difference < 0) stop(paste("The entry at daily[", index, "] is not sequential."))
}
window_length <- c(rep(1, length(daily)))
}
if (!is.null(start_dates))
{
for (index in 1:length(start_dates))
{
if (index > 1)
{
difference <- as.numeric(start_dates[index] - end_dates[index - 1])
if (difference > 1) stop(paste("There is a gap between start_dates[", index, "] and end_dates[", (index - 1), "]."))
if (difference < 1) stop(paste("The entry at start_dates[", index, "] overlaps with the previous entry."))
}
window_length <- append(window_length, as.numeric(end_dates[index] - start_dates[index] + 1))
}
}
checkIfInZeroToOne <- function(parameter, name)
{
if ((!all(parameter > 0)) || (!all(parameter <= 1))) stop(paste("Error: The values of ", name, " must be within the range (0, 1]."))
}
checkIfGreaterThanZero <- function(parameter, name)
{
if (!all(parameter >= 0)) stop(paste0("Error: The value of ", name, " must be greater than or equal to zero."))
if (!all(parameter <= 1)) warning(paste0("Warning: The value of ", name, ", is greater than one and unusual. Are you sure you want this?"))
}
if (is.null(hosp_rate)) {
hosp_rate <- rep(0.175, total_windows)
} else {
if (total_windows != length(hosp_rate)) stop("Length of R0 does not match length of hosp_rate.")
checkIfInZeroToOne(hosp_rate, "hosp_rate")
}
if (is.null(recov_hosp)) {
recov_hosp <- rep(1/7.0, total_windows)
} else {
if (total_windows != length(recov_hosp)) stop("Length of R0 does not match length of recov_hosp.")
checkIfGreaterThanZero(recov_hosp, "recov_hosp")
}
if (is.null(icu_rate)) {
icu_rate <- rep(0.20, total_windows)
} else {
if (total_windows != length(icu_rate)) stop("Length of R0 does not match length of icu_rate.")
checkIfInZeroToOne(icu_rate, "icu_rate")
}
if (is.null(death_rate)) {
death_rate <- rep(0.60, total_windows)
} else {
if (total_windows != length(death_rate)) stop("Length of R0 does not match length of death_rate.")
checkIfInZeroToOne(death_rate, "death_rate")
}
t_max <- sum(window_length)
value <- list(r0 = r0,
dist_param = dist_param,
m = m,
imm_frac = imm_frac,
hosp_rate = hosp_rate,
recov_hosp = recov_hosp,
icu_rate = icu_rate,
death_rate = death_rate,
window_length = window_length,
total_windows = total_windows,
t_max = t_max)
attr(value, "class") <- "time_windows"
value
} |
meteSAR <- function(spp, abund, row, col, x, y, S0 = NULL, N0 = NULL,
Amin, A0, upscale=FALSE, EAR=FALSE) {
if(!upscale) {
areaInfo <- .findAreas(
spp=if(missing(spp)) NULL else spp,
abund=if(missing(abund)) NULL else abund,
row=if(missing(row)) NULL else row,
col=if(missing(col)) NULL else col,
x=if(missing(x)) NULL else x,
y=if(missing(y)) NULL else y,
Amin=if(missing(Amin)) NULL else Amin,
A0=if(missing(A0)) NULL else A0)
areas <- areaInfo$areas
row <- areaInfo$row
col <- areaInfo$col
nrow <- areaInfo$nrow
ncol <- areaInfo$ncol
Amin <- areaInfo$Amin
A0 <- areaInfo$A0
}
if(upscale & EAR) stop('upscaling EAR not currently supported')
if(!missing(spp) & !missing(abund)) {
S0 <- length(unique(spp))
N0 <- sum(abund)
}
if(is.null(S0) | is.null(N0)) stop('must provide spp and abund data or state variables S0 and N0')
thisESF <- meteESF(S0=S0, N0=N0)
if(!missing(spp) & !missing(abund)) {
eSAR <- empiricalSAR(spp, abund, row=row, col=col, Amin=Amin, A0=A0, EAR=EAR)
} else {
eSAR <- NULL
}
if(upscale) {
thrSAR <- upscaleSAR(thisESF, Amin, A0, EAR)
} else {
thrSAR <- downscaleSAR(thisESF, areas*Amin, A0, EAR)
}
out <- list(obs=eSAR, pred=thrSAR)
class(out) <- 'meteRelat'
return(out)
}
empiricalSAR <- function(spp, abund, row, col, x, y, Amin, A0, EAR=FALSE) {
areaInfo <- .findAreas(
spp=if(missing(spp)) NULL else spp,
abund=if(missing(abund)) NULL else abund,
row=if(missing(row)) NULL else row,
col=if(missing(col)) NULL else col,
x=if(missing(x)) NULL else x,
y=if(missing(y)) NULL else y,
Amin=if(missing(Amin)) NULL else Amin,
A0=if(missing(A0)) NULL else A0)
areas <- areaInfo$areas
row <- areaInfo$row
col <- areaInfo$col
nrow <- areaInfo$nrow
ncol <- areaInfo$ncol
Amin <- areaInfo$Amin
A0 <- areaInfo$A0
out <- lapply(areas, function(a) {
nspp <- .getSppInGroups(spp, abund, row, col, .getNeighbors(a, nrow, ncol), EAR)
data.frame(A=a*Amin, S=nspp)
})
out <- do.call(rbind, out)
attr(out, 'source') <- 'empirical'
attr(out, 'type') <- ifelse(EAR, 'ear', 'sar')
class(out) <- 'sar'
return(out)
}
downscaleSAR <- function(x, A, A0, EAR=FALSE) {
n0 <- 1:x$state.var['N0']
if(EAR) {
piFun <- function(a) .getPin0(n0, a, A0)
} else {
piFun <- function(a) 1 - .getPi0(n0, a, A0)
}
getspp <- function(a) {
probs <- piFun(a) *
with(x,
metePhi(n0, La[1], La[2], Z,
state.var['S0'], state.var['N0'],
ifelse(is.na(state.var['E0']), state.var['N0']*10^3, state.var['E0'])))
return(x$state.var['S0'] * sum(probs))
}
nspp <- sapply(A, getspp)
out <- data.frame(A=A, S=nspp)
attr(out, 'source') <- 'theoretical'
attr(out, 'type') <- ifelse(EAR, 'ear', 'sar')
class(out) <- 'sar'
return(out)
}
upscaleSAR <- function(x, A0, Aup, EAR=FALSE) {
Aups <- A0 * 2^(0:ceiling(log(Aup/A0)/log(2)))
N0s <- x$state.var['N0'] * 2^(0:ceiling(log(Aup/A0)/log(2)))
S0s <- numeric(length(Aups))
S0s[1] <- x$state.var['S0']
termcodes <- numeric(length(Aups))
for(i in 2:length(Aups)) {
S0s[i] <- .solveUpscale(S0s[i-1], N0s[i-1])
}
out <- data.frame(A=Aups, S=S0s)
attr(out, 'source') <- 'theoretical'
attr(out, 'type') <- ifelse(EAR, 'ear', 'sar')
class(out) <- 'sar'
return(out)
} |
context("get_wq")
test_that("get_wq works", {
vcr::use_cassette("get_wq_works", {
x <- get_wq(station_id = c("FLAB08", "FLAB09"),
date_min = "2011-03-01", date_max = "2012-05-01",
test_name = "CHLOROPHYLL-A, SALINE")
})
expect_is(x, "data.frame")
})
vcr::use_cassette("get_wq_fails_well", {
test_that("get_wq fails well", {
expect_message(get_wq(station_id = c("FLAB08", "FLAB09"),
date_min = "1990-03-01", date_max = "1992-05-01",
test_name = "CHLOROPHYLL-A, SALINE"),
"No data found")
expect_message(get_wq(station_id = "ROOK467", date_min = "2012-07-19",
date_max = "2016-04-27", test_name = "AMMONIA-N"),
"No data found")
expect_message(get_wq("FLAB01", "1983-09-14", "1986-09-18",
"NITRATE+NITRITE-N", raw = TRUE),
"No data found")
})
})
vcr::use_cassette("get_wq_nonchar_dates", {
test_that("non-character dates are handled", {
expect_error(get_wq(station_id = c("FLAB08", "FLAB09"), date_min = 1990-03-01,
date_max = 1992-05-01, test_name = "CHLOROPHYLL-A, SALINE"),
"Enter dates as quote-wrapped character strings in YYYY-MM-DD format")
})
})
vcr::use_cassette("get_wq_mdl_handling", {
test_that("mdl_handling inputs are sane", {
expect_error(clean_wq(get_wq("FLAB01", "2014-09-14", "2014-09-18",
"NITRATE+NITRITE-N", raw = TRUE), mdl_handling = "crazy"),
"mdl_handling must be one of 'raw', 'half', or 'full'")
})
})
test_that("mdl handling occurs when get_wq raw is TRUE", {
vcr::use_cassette("get_mdl_handling_raw", {
yes_raw <- get_wq("FLAB01", "2014-09-14", "2014-09-18", "NITRATE+NITRITE-N",
raw = TRUE, mdl_handling='half')$Value
no_raw <- get_wq("FLAB01", "2014-09-14", "2014-09-18", "NITRATE+NITRITE-N",
raw = FALSE, mdl_handling='half')[,2]
})
expect_equal(yes_raw, no_raw)
})
test_that("multiple stations return correct num of columns", {
vcr::use_cassette("get_wq_multiple_stations", {
x <- ncol(get_wq(station_id = c("FLAB08","FLAB09"),
date_min = "2011-03-01", date_max = "2012-05-01",
test_name = "CHLOROPHYLL-A, SALINE"))
})
expect_equal(x, 3)
}) |
httpget_tmp <- function(requri){
check.enabled("api.tmp");
prefix <- "x0";
reqhead <- utils::head(requri, 1);
reqtail <- utils::tail(requri, -1);
if(!length(reqhead)){
res$checkmethod();
res$checktrail();
allfiles <- list.files(ocpu_store(), pattern=paste("^", prefix, sep=""));
res$sendlist(allfiles);
}
if(grepl("::", reqhead, fixed = TRUE)){
parts <- strsplit(reqhead, "::", fixed = TRUE)[[1]]
reqhead <- parts[1]
reqtail <- c("R", parts[2], reqtail)
}
sessionpath <- file.path(ocpu_store(), reqhead);
res$setcache("tmp");
httpget_session(sessionpath, reqtail);
} |
get_shot_locs <- function(game_ids) {
if(any(is.na(game_ids))) {
error("game_ids missing with no default")
}
n <- length(game_ids)
for(i in 1:n) {
message(paste("Getting Shots for Game", i, "of", n))
url = paste0('http://www.espn.com/mens-college-basketball/playbyplay?gameId=', game_ids[i])
date <- get_date(game_ids[i])
away_team_name <-
stringr::str_replace_all(xml2::read_html(url) %>%
rvest::html_nodes(".away h3") %>%
rvest::html_text(), "[\r\n\t]" , "")
if(length(away_team_name) == 0){
message("No shot location data available for this game.")
}else{
away_shot_text <- xml2::read_html(url) %>%
rvest::html_nodes(".away-team li") %>%
rvest::html_text()
away_shot_style <- xml2::read_html(url) %>%
rvest::html_nodes(".away-team li") %>%
xml2::xml_attr("style")
away_color <- gsub("^.*border-color:\\s*|\\s*;.*$", "", away_shot_style[1])
home_team_name <- stringr::str_replace_all(xml2::read_html(url) %>% rvest::html_nodes(".home h3") %>% rvest::html_text(), "[\r\n\t]" , "")
home_shot_text <- xml2::read_html(url) %>% rvest::html_nodes(".home-team li") %>% rvest::html_text()
home_shot_style <- xml2::read_html(url) %>% rvest::html_nodes(".home-team li") %>% xml2::xml_attr("style")
home_color <- gsub("^.*border-color:\\s*|\\s*;.*$", "", home_shot_style[1])
away_df <- data.frame(
team_name = away_team_name,
shot_text = away_shot_text,
shot_style = away_shot_style,
color = away_color,
stringsAsFactors = F
)
home_df <- data.frame(
team_name = home_team_name,
shot_text = home_shot_text,
shot_style = home_shot_style,
color = home_color,
stringsAsFactors = F
)
total_df = rbind(away_df, home_df)
total_df <-total_df %>%
mutate(
"date" = date,
"outcome" = ifelse(grepl("made", shot_text), "made", "missed"),
"shooter" = stripwhite(gsub("made.*", "", shot_text)),
"shooter" = stripwhite(gsub("missed.*", "", shooter)),
"assisted" = stripwhite(gsub(".{1}$", "", gsub(".*Assisted by", "", shot_text))),
"assisted" = stripwhite(ifelse(grepl("made", assisted) |
grepl("missed", assisted), NA, assisted)),
"three_pt" = grepl("Three Point", shot_text),
"x" = as.numeric(gsub('^.*top:\\s*|\\s*%;.*$', '', total_df$shot_style)) * 0.5,
"y" = as.numeric(gsub('^.*left:\\s*|\\s*%;top.*$', '', total_df$shot_style)) * .94
) %>% select(-shot_style)
total_df$game_id <- game_ids[i]
if(!exists("total_df_all")) {
total_df_all <- total_df
}else{
total_df_all <- rbind(total_df_all, total_df)
}
}
}
if(!exists("total_df_all")) {
return(NULL)
}
return(total_df_all)
} |
require(NMOF)
resample <- function(x, ...) x[sample.int(length(x), ...)]
na <- dim(fundData)[2L]
ns <- dim(fundData)[1L]
winf <- 0.0
wsup <- 0.05
data <- list(R = t(fundData),
RR = crossprod(fundData),
na = na,
ns = ns,
eps = 0.5/100,
winf = winf,
wsup = wsup)
neighbour <- function(w, data){
eps <- runif(1) * data$eps
toSell <- w > data$winf
toBuy <- w < data$wsup
i <- resample(which(toSell), size = 1L)
j <- resample(which(toBuy), size = 1L)
eps <- min(w[i] - data$winf, data$wsup - w[j], eps)
w[i] <- w[i] - eps
w[j] <- w[j] + eps
w
}
OF1 <- function(w, data) {
Rw <- crossprod(data$R,w)
crossprod(Rw)
}
OF2 <- function(w, data) {
aux <- crossprod(data$RR,w)
crossprod(w,aux)
}
w0 <- runif(na); w0 <- w0/sum(w0)
algo <- list(x0 = w0,
neighbour = neighbour,
nS = 2000L,
nT = 10L,
nD = 5000L,
q = 0.20)
system.time(res <- TAopt(OF1,algo,data))
100*sqrt(crossprod(fundData %*% res$xbest)/ns)
system.time(res <- TAopt(OF2,algo,data))
100*sqrt(crossprod(fundData %*% res$xbest)/ns)
require(quadprog)
covMatrix <- crossprod(fundData)
A <- rep(1, na); a <- 1
B <- rbind(-diag(na),
diag(na))
b <- rbind(array(-data$wsup, dim = c(na,1)),
array( data$winf, dim = c(na,1)))
system.time({
result <- solve.QP(Dmat = covMatrix,
dvec = rep(0,na),
Amat = t(rbind(A,B)),
bvec = rbind(a,b),
meq = 1)
})
wqp <- result$solution
100 * sqrt( crossprod(fundData %*% wqp)/ns )
100 * sqrt( crossprod(fundData %*% res$xbest)/ns )
min(res$xbest); max(res$xbest); sum(res$xbest)
min(wqp); max(wqp); sum(wqp) |
library(HH) |
"laptop_urry" |
MG <- function(units, ame_out, multiple = FALSE,
id_only = FALSE, index_only) {
if (!missing(index_only)) {
stop('Argument `index_only` is defunct and will be removed in a later',
'release; please use `id_only` instead.')
}
if (multiple && !ame_out$info$replacement) {
stop(paste('Multiple matched groups cannot be queried if',
ame_out$info$algo, 'was run without replacement.'))
}
if (any(!(units %in% as.numeric(rownames(ame_out$data))))) {
stop('Supplied a unit not in the matched data.')
}
units <- match(units, rownames(ame_out$data))
if (id_only & !multiple) {
return(lapply(ame_out$MGs[units], function(z) {
if (is.null(z)) {
NULL
}
else {
rownames(ame_out$data)[z]
}
}))
}
outcome_name <- ame_out$info$outcome
treated_name <- ame_out$info$treatment
col_names <- colnames(ame_out$data)
cov_inds <-
which(!(col_names %in%
c(treated_name, outcome_name, 'weight', 'matched', 'MG', 'CATE')))
all_MGs <- vector('list', length(units))
all_MGs <- lapply(all_MGs, function(x) x <- vector('list', 1))
for (i in seq_along(units)) {
if (is.null(ame_out$MGs[[units[i]]])) {
next
}
if (!multiple) {
MGs_to_return <- units[i]
}
else {
in_MG <-
which(vapply(ame_out$MGs, function(x) units[i] %in% x, logical(1)))
MGs_to_return <- in_MG[!duplicated(ame_out$MGs[in_MG])]
}
for (j in seq_along(MGs_to_return)) {
if (id_only) {
all_MGs[[i]][[j]] <-
rownames(ame_out$data)[ame_out$MGs[[MGs_to_return[j]]]]
next
}
MG_all_cols <-
ame_out$data[ame_out$MGs[[MGs_to_return[j]]], , drop = FALSE]
for (cov_set in ame_out$cov_sets) {
matched_on <- setdiff(col_names[cov_inds], cov_set)
data <- data.matrix(MG_all_cols[, matched_on, drop = FALSE])
tmp <- colSums(sweep(data, 2, data[1, ]) ^ 2)
if (any(is.na(tmp))) {
next
}
if (all(tmp == 0)) {
all_MGs[[i]][[j]] <-
MG_all_cols[, c(matched_on, treated_name, outcome_name)]
break
}
}
}
}
if (!multiple) {
all_MGs <- lapply(all_MGs, `[[`, 1)
}
return(all_MGs)
}
CATE <- function(units, ame_out) {
if (any(!(units %in% as.numeric(rownames(ame_out$data))))) {
stop('Supplied a unit not in the matched data.')
}
units <- match(units, rownames(ame_out$data))
if (ame_out$info$outcome_type != 'continuous') {
stop('CATEs and their variance estimates can only be computed for ',
'continuous outcomes.')
}
CATE_mat <- matrix(nrow = length(units), ncol = 2,
dimnames = list(units, c('Mean', 'Variance')))
Tr <- ame_out$data[[ame_out$info$treatment]]
Y <- ame_out$data[[ame_out$info$outcome]]
n <- length(Y)
for (unit in units) {
mg <- ame_out$MGs[[unit]]
if (is.null(mg)) {
next
}
control <- mg[Tr[mg] == 0]
treated <- mg[Tr[mg] == 1]
CATE_mat[as.character(unit), 'Mean'] <- mean(Y[treated]) - mean(Y[control])
CATE_mat[as.character(unit), 'Variance'] <-
var(Y[treated]) / length(treated) +
var(Y[control]) / length(control)
}
return(CATE_mat)
}
ATE <- function(ame_out) {
.Deprecated(msg = paste('`ATE` is now deprecated, as ATE, ATT, and ATC mean',
'and variance estimates are now computed in the',
'`summary.ame` method'))
if (ame_out$info$estimate_CATEs &&
ame_out$info$outcome_type == 'continuous') {
return(mean(ame_out$data$CATE, na.rm = TRUE))
}
return(get_average_effects(ame_out)['All', 'Mean'])
}
ATT <- function(ame_out) {
.Deprecated(msg = paste('`ATT` is now deprecated, as ATE, ATT, and ATC mean',
'and variance estimates are now computed in the',
'`summary.ame` method'))
if (ame_out$info$estimate_CATEs &&
ame_out$info$outcome_type == 'continuous') {
return(mean(ame_out$data$CATE[ame_out$data[[ame_out$info$treatment]] == 1],
na.rm = TRUE))
}
return(get_average_effects(ame_out)['Treated', 'Mean'])
}
ATC <- function(ame_out) {
.Deprecated(msg = paste('`ATC` is now deprecated, as ATE, ATT, and ATC mean',
'and variance estimates are now computed in the',
'`summary.ame` method'))
if (ame_out$info$estimate_CATEs &&
ame_out$info$outcome_type == 'continuous') {
return(mean(ame_out$data$CATE[ame_out$data[[ame_out$info$treatment]] == 0],
na.rm = TRUE))
}
return(get_average_effects(ame_out)['Control', 'Mean'])
} |
NULL
dplyr::vars
param_range <- function(prefix, range, vars = NULL) {
if (!is.null(vars) && !is.character(vars)) {
abort("'vars' must be NULL or a character vector.")
}
nms <- paste0(prefix, "[", range, "]")
param_matches <- match(nms, vars %||% tidyselect::peek_vars())
param_matches[!is.na(param_matches)]
}
param_glue <- function(pattern, ..., vars = NULL) {
if (!is.null(vars) && !is.character(vars)) {
abort("'vars' must be NULL or a character vector.")
}
dots <- as.list(expand.grid(...))
nms <- as.character(glue::glue_data(dots, pattern))
param_matches <- match(nms, vars %||% tidyselect::peek_vars())
param_matches[!is.na(param_matches)]
}
tidyselect_parameters <- function(complete_pars, pars_list) {
helpers <- tidyselect::vars_select_helpers
pars_list <- lapply(pars_list, rlang::env_bury, !!! helpers)
selected <- tidyselect::vars_select(.vars = complete_pars, !!! pars_list)
if (!length(selected)) {
abort("No parameters were found matching those names.")
}
unname(selected)
} |
covid19Explorer <- function(locn=NULL) {
c19Dashboard <- covid19dashboard(locn=locn)
ui <- c19Dashboard[[1]]
server <- c19Dashboard[[2]]
capture.output(shinyApp(ui = ui, server = server))
} |
hli <- function(x, check = TRUE, force.hemisphere = c("none", "southern", "northern")) {
if (!inherits(x, "RasterLayer")) stop("x must be a RasterLayer object")
if(check) {
if (is.na(sp::proj4string(x))) stop("Projection must be defined")
if (length(grep("longlat", sp::proj4string(x))) <= 0) {
geo.prj = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
e <- as(raster::extent(x), "SpatialPolygons")
sp::proj4string(e) <- sp::proj4string(x)
e <- sp::spTransform(e, geo.prj )
l = sp::coordinates(e)[2]
} else {
e <- as(raster::extent(x), "SpatialPolygons")
l = sp::coordinates(e)[2]
}
} else {
e <- as(raster::extent(x), "SpatialPolygons")
l = sp::coordinates(e)[2]
}
if(l < 0) hemisphere = "southern" else hemisphere = "northern"
l = abs(l) * 0.017453293
cl = cos(l)
sl = sin(l)
tmp1 <- raster::terrain(x, opt="slope", unit="degrees") * 0.017453293
tmp2 <- raster::terrain(x, opt="aspect", unit="degrees") * 0.017453293
if(hemisphere == "northern" | force.hemisphere[1] == "northern"){
message("Using folded aspect equation for Northern hemisphere")
tmp3 <- raster::calc(tmp2, fun=function(x) { abs(3.141593 - abs(x - 3.926991)) } )
} else if(hemisphere == "southern" | force.hemisphere[1] == "southern") {
message("Using folded aspect equation for Southern hemisphere")
tmp3 <- raster::calc(tmp2, fun=function(x) { abs(3.141593 - abs(x - 5.497791)) } )
}
tmp4 <- raster::calc(tmp1, fun = cos)
tmp5 <- raster::calc(tmp1, fun = sin)
tmp6 <- raster::calc(tmp3, fun = cos)
tmp7 <- raster::calc(tmp3, fun = sin)
h <- exp( -1.467 + 1.582 * cl * tmp4 - 1.5 * tmp6 * tmp5 * sl - 0.262 *
sl * tmp5 + 0.607 * tmp7 * tmp5)
if(cellStats(h,"max") > 1){
h <- ( h / cellStats(h, "max", asSample=FALSE) )
}
return( h )
} |
if(!require("GNE"))stop("this test requires package GNE.")
dimx <- c(2, 2, 3)
grfullob <- function(x, i, j)
{
x <- x[1:7]
if(i == 1)
{
grad <- 3*(x - 1:7)^2
}
if(i == 2)
{
grad <- 1:7*(x - 1:7)^(0:6)
}
if(i == 3)
{
s <- x[5]^2 + x[6]^2 + x[7]^2 - 5
grad <- c(1, 0, 1, 0, 4*x[5]*s, 4*x[6]*s, 4*x[7]*s)
}
grad[j]
}
hefullob <- function(x, i, j, k)
{
x <- x[1:7]
if(i == 1)
{
he <- diag( 6*(x - 1:7) )
}
if(i == 2)
{
he <- diag( c(0, 2, 6, 12, 20, 30, 42)*(x - 1:7)^c(0, 0:5) )
}
if(i == 3)
{
s <- x[5]^2 + x[6]^2 + x[7]^2
he <- rbind(rep(0, 7), rep(0, 7), rep(0, 7), rep(0, 7),
c(0, 0, 0, 0, 4*s+8*x[5]^2, 8*x[5]*x[6], 8*x[5]*x[7]),
c(0, 0, 0, 0, 8*x[5]*x[6], 4*s+8*x[6]^2, 8*x[6]*x[7]),
c(0, 0, 0, 0, 8*x[5]*x[7], 8*x[6]*x[7], 4*s+8*x[7]^2) )
}
he[j,k]
}
dimlam <- c(1, 2, 2)
g <- function(x, i)
{
x <- x[1:7]
if(i == 1)
res <- sum( x^(1:7) ) -7
if(i == 2)
res <- c(sum(x) + prod(x) - 14, 20 - sum(x))
if(i == 3)
res <- c(sum(x^2) + 1, 100 - sum(x))
res
}
grfullg <- function(x, i, j)
{
x <- x[1:7]
if(i == 1)
{
grad <- (1:7) * x ^ (0:6)
}
if(i == 2)
{
grad <- 1 + sapply(1:7, function(i) prod(x[-i]))
grad <- cbind(grad, -1)
}
if(i == 3)
{
grad <- cbind(2*x, -1)
}
if(i == 1)
res <- grad[j]
if(i != 1)
res <- grad[j,]
as.numeric(res)
}
hefullg <- function(x, i, j, k)
{
x <- x[1:7]
if(i == 1)
{
he1 <- diag( c(0, 2, 6, 12, 20, 30, 42) * x ^ c(0, 0, 1:5) )
}
if(i == 2)
{
he1 <- matrix(0, 7, 7)
he1[1, -1] <- sapply(2:7, function(i) prod(x[-c(1, i)]))
he1[2, -2] <- sapply(c(1, 3:7), function(i) prod(x[-c(2, i)]))
he1[3, -3] <- sapply(c(1:2, 4:7), function(i) prod(x[-c(3, i)]))
he1[4, -4] <- sapply(c(1:3, 5:7), function(i) prod(x[-c(4, i)]))
he1[5, -5] <- sapply(c(1:4, 6:7), function(i) prod(x[-c(5, i)]))
he1[6, -6] <- sapply(c(1:5, 7:7), function(i) prod(x[-c(6, i)]))
he1[7, -7] <- sapply(1:6, function(i) prod(x[-c(7, i)]))
he2 <- matrix(0, 7, 7)
}
if(i == 3)
{
he1 <- diag(rep(2, 7))
he2 <- matrix(0, 7, 7)
}
if(i != 1)
return( c(he1[j, k], he2[j, k]) )
else
return( he1[j, k] )
}
z <- rexp(sum(dimx) + sum(dimlam))
n <- sum(dimx)
m <- sum(dimlam)
x <- z[1:n]
lam <- z[(n+1):(n+m)]
resphi <- funSSR(z, dimx, dimlam, grobj=grfullob, constr=g, grconstr=grfullg, compl=phiFB)
check <- GNE:::funSSRcheck(z, dimx, dimlam, grobj=grfullob, constr=g, grconstr=grfullg, compl=phiFB)
cat("\n\n________________________________________\n\n")
print(cbind(check, res=as.numeric(resphi))[1:length(x), ])
print(cbind(check, res=as.numeric(resphi))[(length(x)+1):length(z), ])
if(sum(abs(check - resphi)) > .Machine$double.eps^(2/3))
stop("wrong result")
resjacphi <- jacSSR(z, dimx, dimlam, heobj=hefullob, constr=g, grconstr=grfullg,
heconstr=hefullg, gcompla=GrAphiFB, gcomplb=GrBphiFB)
checkjac <- GNE:::jacSSRcheck(z, dimx, dimlam, heobj=hefullob, constr=g, grconstr=grfullg,
heconstr=hefullg, gcompla=GrAphiFB, gcomplb=GrBphiFB)
cat("\n\n________________________________________\n\n")
cat("\n\npart A\n\n")
print(resjacphi[1:n, 1:n] - checkjac[1:n, 1:n])
cat("\n\n________________________________________\n\n")
cat("\n\npart B\n\n")
print(resjacphi[1:n, (n+1):(n+m)] - checkjac[1:n, (n+1):(n+m)])
cat("\n\n________________________________________\n\n")
cat("\n\npart C\n\n")
print(resjacphi[(n+1):(n+m), 1:n] - checkjac[(n+1):(n+m), 1:n])
cat("\n\n________________________________________\n\n")
cat("\n\npart D\n\n")
print(resjacphi[(n+1):(n+m), (n+1):(n+m)] - checkjac[(n+1):(n+m), (n+1):(n+m)])
if(sum(abs(checkjac - resjacphi)) > .Machine$double.eps^(2/3))
stop("wrong result") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.